text:
Q: How do I link javascript to an express application? On my node server, I receive "GET /json 404" when I start it using npm start. How do I fix this? I am making a basic express/mongodb app by following this article:
https://zellwk.com/blog/crud-express-and-mongodb-2/
Adding items to the database has worked so far using post requests on a form element. But now I am trying to use update and delete requests through the javascript file main.js (not through the html form like the post request). However, now that I am doing that, the requests are not working. The page still renders, but when I click on the buttons, they don't perform any javascript. Here is my file structure:
bin
node_modules
public
    images
    javascripts
    stylesheets
    main.js
routes
    index.js
    quotes.js
    users.js
views
    error.ejs
    index.ejs
app.js
package.json

I suspect I am doing something wrong with linking the javascript to the index.ejs file, but I have tried every possible way of linking it in the script tag. I have done:

And also did each version of those with the js file in the "javascripts" folder. I think it is a linking issue, but I really don't know what the problem is.
Here is the code for my app.js file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/quotes', (err, database) => {
        if (err) throw err;
    db = database;
});

var index = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.post('/quotes', (req, res) => {
    db.collection('quotes').save(req.body, (err, result) => {
        if (err) return console.log(err);

        console.log('saved to database');
        res.redirect('/');
    });
});

app.get('/', (req, res) => {
  var cursor = db.collection('quotes').find().toArray(function(err, result) {
    if (err) return console.log(err);

    res.render('index.ejs', {quotes: result});
  });
});

app.put('/quotes', (req, res) => {
  db.collection('quotes').findOneAndUpdate({name: 'Yoda'}, {
    $set: {
      name: req.body.name,
      quote: req.body.quote
    }
  }, {
    sort: {_id: -1},
    upsert: true
  }, (err, result) => {
    if (err) return res.send(err);
    res.send(result);
  });
});

app.delete('/quotes', (req, res) => {
  db.collection('quotes').findOneAndDelete({name:
    req.body.name},
    (err, result) => {
      if (err) return res.send(500, err);
        res.send({message: 'A darth vadar quote got deleted'});
    });
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  console.log("The problem is: " + err);
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Here is the index.ejs file:
<!DOCTYPE html>

        <title>quotes</title>

        May Node and Express be with you.

            <% for(var i=0; i<quotes.length; i++) {%>

                    <%= quotes[i].name %> once said: "<%= quotes[i].quote %>."

            <% } %>

        <form action="/quotes" method="POST">
            <input type="text" placeholder="name" name="name">

            <input type="text" placeholder="quote" name="quote">

            <button type="submit">Submit</button>
        </form>

Replace last quote written by Master Yoda with a quote written by Darth Vadar.

            <button id="update"> Darth Vadar invades! </button>

Delete Darth Vadar's first quote

            <button id="delete"> Delete first Darth Vadar quote
            </button>

And here is the main.js file:
var update = document.getElementById('update');

update.addEventListener('click', function() {
    fetch('quotes', {
        method: 'put',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'name': 'Darth Vader',
            'quote': 'I find your lack of faith disturbing'
        })
    }).then(res => {
    if (res.ok) return res.json();
  }).then(data => {
    console.log(data);
    window.location.reload(true);
  });
});

var del = document.getElementById('delete');

del.addEventListener('click', function() {
    fectch('quotes', {
        method: 'delete',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            'name': 'Yoda'
        })
    })
    .then(res => {
        if (res.ok) return res.json();
    }).then(data => {
        console.log(data);
        window.location.reload(true);
    });
});


text:
Q: How can I capture the last group in a multiline file using a regular expression? I'm trying to use a regular expression to grab parts of a subtitle file. They come in this format:
1
00:00:38,505 --> 00:00:40,438
<i>I'm not gonna bullshit you.</i>

...

1029
01:37:20,223 --> 01:37:23,023
No thanks.

The text can take up multiple lines.
Here's what I'm currently using:
(\d+?)\r\n(\d+?):(\d+?):(\d+?),(\d+?) --> (\d+?):(\d+?):(\d+?),(\d+?)\r\n(?<content>(.+)(\r\n)*\D*)[\r\n|$]*?

It's capturing all the groups properly, but it's leaving out the last match. So if there are 1029 subtitles in the text file, it's finding 1028 of them. The file ends after the </i> in the example I provided. It's the only group that is not being captured.
Can anyone help me with this? I thought that since it wasn't specified as multiline that "$" would act as "End of File", but I seem to be wrong there.

A: You may use
(?sm)^(\d+)\r?\n(\d+?):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)\r?\n(?<content>.*?)(?=\r?\n\d+\r?$|\z)

See the regex demo.
Details

*

*(?sm) - enable anchors matching at the start and end of each line (with m) and dot matching newline (with s)

*^ - start of a line

*(\d+) - Group 1: one or more digits

*\r?\n - a CRLF or LF ending

*(\d+):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+) - 1+ digits (Group 2), :, 1+ digits (Group 3), :, 1+ digits (Group 4), ,, 1+ digits (Group 5), --> enclosed with 1 space, 1+ digits (Group 6), :, 1+ digits (Group 7), :, 1+ digits (Group 8), ,, 1+ digits (Group 9)

*\r?\n - a CRLF or LF ending

*(?<content>.*?) - Group "content" that matches any 0+ chars as few as possible up to the first

*(?=\r?\n\d+\r?$|\z) - CRLF or LF ending, 1+ digits and end of line or end of string.

C# code snippet:
var matches = Regex.Matches(text, @"(?sm)^(\d+)\r?\n(\d+?):(\d+):(\d+),(\d+) --> (\d+):(\d+):(\d+),(\d+)\r?\n(?<content>.*?)(?=\r?\n\d+\r?$|\z)");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Отсортировать массив по названию страны и по названию города (если страны равны) в порядке возрастания function sortCitiesArray(arr) {
  let newArr = [];
  newArr[0] = arr[0];
  return arr.reduce(function(prev, current, i) {
    if (current.country <= newArr[0].country) {
      newArr.unshift(current);
    }
    newArr.reduce(function(prev, current) {
      if (current.country > arr[i].country) {
        newArr.splice(i - 1, 0, current);

      }
      return newArr;
    })
    return newArr;
  })
}

Можно использовать только .map или .reduce
 *    [
 *      { country: 'Russia',  city: 'Moscow' },
 *      { country: 'Belarus', city: 'Minsk' },
 *      { country: 'Poland',  city: 'Warsaw' },
 *      { country: 'Russia',  city: 'Saint Petersburg' },
 *      { country: 'Poland',  city: 'Krakow' },
 *      { country: 'Belarus', city: 'Brest' }
 *    ]
 *                      =>
 *    [
 *      { country: 'Belarus', city: 'Brest' },
 *      { country: 'Belarus', city: 'Minsk' },
 *      { country: 'Poland',  city: 'Krakow' },
 *      { country: 'Poland',  city: 'Warsaw' },
 *      { country: 'Russia',  city: 'Moscow' },
 *      { country: 'Russia',  city: 'Saint Petersburg' }


text:
Q: How to pass data from one HTML page to another HTML page using JQuery? I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
    type: "POST",
    url: get_data_from_database_url,
    async:false,
    data: params,
    success: function(json)
    {
        json_send_my_data(json);
    }
});

function json_send_my_data(json)
{
    //pass the json object to the other page and load it
}

I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.

A: session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?

A: You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

A: Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
    if (window.location.href.indexOf('?') === (-1)) {
        return {};
    }
    var qparts = window.location.href.split('?')[1].split('&'),
        qmap   = {};
    qparts.map(function (part) {
        var kvPair = part.split('='),
            key    = decodeURIComponent(kvPair[0]),
            value  = kvPair[1];

        //handle params that lack a value: e.g. &delayed=
        qmap[key] = (!value) ? '' : decodeURIComponent(value);
    });
    return qmap;
}

Next, inside your success handler function:
success: function(json) {
    //please really convert the server response to a json
    //I don't see you instructing jQuery to do that yet!
    //handleAs: 'json'

    var qstring = '?';
    for(key in json) {
        qstring += '&' + key + '=' + json[key];
        qstring = qstring.substr(1); //removing the first redundant &
    }
    var urlTarget = 'abc.html';
    var urlTargetWithParams = urlTarget + qstring;

    //will go to abc.html?key1=value1&key2=value2&key2=value2...
    window.location.href = urlTargetWithParams;
}

On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt

Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).

A: Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.

A: Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
    $(this).find('a').bind('click', function () {
        $.mobile.changePage(this.href, {
            reloadPage : true,
            type       : 'post',
            data       : { myKey : 'myVal' }
        });
        return false;
    });
});

Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page


text:
Q: Solving alternate infinite series Suppose we have an alternating series of the form $$\sum_{n=2}^{\infty} \frac{(-1)^{f(n)}}{n^2} \text{ where }
 f(n) = \begin{cases}1 & \text{n is prime} \\
0 & \text{otherwise}\end{cases}$$.
How would one go about proving that this series converges or not? Does this series have a closed form solution?


text:
Q: Android Manifest Merger failed, says android:exported is required, but I already have it As the title says, my android test build is failing with the error "Manifest merger failed". It says "android:exported needs to be explicitly specified for "
The problem is, I already have android:exported set. Does anyone know what I can do here?
I have tried adding android:exported="true" to every one of my activities, but that had no affect.
I'm not sure if it's relevant, but the app runs and builds without issue normally. I only get this error when trying run Instrumented Tests
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fyp.launcher">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Launcher">
        <activity
            android:name=".Activity_Home"
            android:theme="@style/Theme.Launcher"
            android:launchMode="singleTask"
            android:stateNotNeeded="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Activity_AllApps"
            android:theme="@style/Theme.Launcher">
        </activity>
        <activity
            android:name=".settings.Activity_Settings"
            android:theme="@style/Theme.Launcher">
        </activity>
        <activity
            android:name=".settings.Activity_Theme"
            android:theme="@style/Theme.Launcher">
        </activity>
        <activity
            android:name=".settings.Activity_Favourites"
            android:theme="@style/Theme.Launcher">
        </activity>
        <activity
            android:name=".settings.Activity_Font"
            android:theme="@style/Theme.Launcher">
        </activity>
    </application>

    <permission android:name="android.permission.QUERY_ALL_PACKAGES" />
    <uses-permission android:name="android.permission.VIBRATE"/>

    <queries>
        <intent>
            <action android:name="android.intent.action.MAIN" />
        </intent>
    </queries>
</manifest>


text:
Q: Meteor reactive maps don't work as should I am using two brilliant packages named dburles:google-maps and mdg:geolocation. What I nee is to add a marker and change map's zoom automatically when I get user's geolocation data (after he allows it to share).
Inside Template.onCreated I have the following code:
Template.dealersMap.onCreated(function() {
    Tracker.autorun(() => {
       this.latLng = new ReactiveVar(Geolocation.latLng());
    })
});

Then in onRendered I do the following:
Template.dealersMap.onRendered(function() {
  navigator.geolocation.getCurrentPosition((position) => {
    GoogleMaps.ready('exampleMap', (map) => {
      let marker;

      if(!this.latLng.get())
        console.log('Didn\'t get the location..');

      if(!marker) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(
              this.latLng.get().lat,
              this.latLng.get().lng
          ),
          map: map.instance
        });
      } else {
        marker.setPosition(this.latLng.get());
      }
      map.instance.setCenter(marker.getPosition());
      map.instance.setZoom(11);
    }, () => {
      console.log('deny');
    });
  })
});

As result after user allows me to get his geodata nothing happens. But if user changes at least one step map zoom — everything works.
The question is — how to make this code work without letting user change map zoom?

A: I just removed navigator.geolocation.getCurrentPosition and now everything works fine. Here is the successful code:
Template.dealersMap.onCreated(function() {
  this.latLng = new ReactiveVar();
  Tracker.autorun(() => {
    this.latLng.set(Geolocation.latLng());
  })
});

Template.dealersMap.onRendered(function() {

  this.autorun(() => {
    GoogleMaps.ready('exampleMap', (map) => {
      console.log('map is ready');

      let marker;

      if(!this.latLng.get()) {
        console.log('Didn\'t get the location..');
      } else {
        if(!marker) {
          marker = new google.maps.Marker({
            position: new google.maps.LatLng(
              this.latLng.get()
              .lat,
              this.latLng.get()
              .lng
            ),
            map: map.instance
          });
        } else {
          marker.setPosition(this.latLng.get());
        }
      }
      map.instance.setCenter(marker.getPosition());
      map.instance.setZoom(11);
    })
  })
});

A: You can use Tracker to rerun the once the dta is changed like, once uses share his/her location, the marker is triggered. Here is the example code:
Template.dealersMap.onRendered(function() {
var self=this;
navigator.geolocation.getCurrentPosition((position) => {
GoogleMaps.ready('exampleMap', (map) => {
  self.autorun(function() {   //tracker function
  let marker;

  if(!this.latLng.get())
    console.log('Didn\'t get the location..');

  if(!marker) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(
          this.latLng.get().lat,
          this.latLng.get().lng
      ),
      map: map.instance
    });
  } else {
    marker.setPosition(this.latLng.get());
  }
  map.instance.setCenter(marker.getPosition());
  map.instance.setZoom(11);
}, () => {
  console.log('deny');
}
});
})
});


text:
Q: How do I add a link to a Title/Caption in LightBox 2 Gallery I would like to add a link to a title/Caption on the last image in of a Lightbox 2 gallery to point to the next physical page of this particular gallery.
I tried the code below but it didn't work and only displayed the link code above the image in the page.
<a href="images/galleries/bath/21.jpg" rel="lightbox[ed]" title="Click HERE to continue viewing Gallery">

If you go to http://revdesigndev.com/rc/gallery-bathroom-update.html and click on the last image in the gallery you will see the caption I would like to link from.
Any way to do this?

A: I can't claim credit for this one, but the answer is already on StackOverflow.  You need to edit the if statement as Zenpoy suggests.
turning caption into a link doesn't work in Lightbox 2.51


text:
Q: how to get value from input in angular.js I am working with angular date picker directive. I would like to get the value of the date that is entered via date picker and console.log it. But somehow everything I have tried so far does not work.
My code:
HTML:
 <input class="form-control"
       ng-model="ctrl.input"
       ng-model-options="{ updateOn: 'blur' }"
       placeholder="Select a date..."
       moment-picker="ctrl.input" id='date'>

    <button ng-model='ctrl.input' ng-click="onclick()">submit</button>

JS
angular
  .module('Demo', ['moment-picker'])
  .controller('DemoCtrl', ['$scope', function ($scope) {
    $scope.onclick = function(){
      console.log(angular.element(document).find('#date').val());
    }

  }]);

plunker

A: its not like jquery where you select the value out of the dom.
Setting
  ng-model="ctrl.input"

sets up the two way data binding already.
What you want to do is change the js to the following
angular
  .module('Demo', ['moment-picker'])
  .controller('DemoCtrl', ['$scope', function ($scope) {
    var ctrl = this;
    $scope.onclick = function(){
      console.log(ctrl.input);
    }

  }]);

A: This will console log the input.
 <!DOCTYPE html>
    <html ng-app="Demo">
      <head>
    <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Angular Moment Picker - Basic demo</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link href="//rawgit.com/indrimuska/angular-moment-picker/master/dist/angular-moment-picker.css" rel="stylesheet">
  </head>
  <body ng-controller="DemoCtrl as ctrl" style="margin:30px;" ng-cloak>

    <input class="form-control"
       ng-model="ctrl.input"
       ng-model-options="{ updateOn: 'blur' }"
       placeholder="Select a date..."
       moment-picker="ctrl.input" id='date'>

    <button  ng-click="onclick()">submit</button>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment-with-locales.js"></script>
    <script src="//rawgit.com/indrimuska/angular-moment-picker/master/dist/angular-moment-picker.js"></script>
    <script src="script.js"></script>
  </body>
</html>

angular.module('Demo', ['moment-picker']).controller('DemoCtrl', ['$scope',function ($scope) {
  $scope.onclick = function(){
  console.log($scope.ctrl.input);
  }
}]);

A: *

*You're using controller-as syntax in your HTML but you haven't defined your controller as such.  You're controller is still using the older $scope-as-controller syntax.

*Also you had another ng-model pointing to ctrl.input on your submit button which could interfere with things so removed that.

*As another person stated you were trying to access something via angular.element.  That's not recommended for view controllers because you have access to the DOM bindings already via the controller properties.  angular.element should be reserved for use in directives, and only in special cases.
I'd suggest going with controller-as like in your HTML and then fixing your controller like so:
angular
.module('Demo', ['moment-picker'])
.controller('DemoCtrl', ['$scope', function ($scope) {
   var ctrl = this
   ctrl.onclick = function(){
      console.log(ctrl.input);
   }
}]);

updated plunker - https://plnkr.co/edit/j1RTh7NlxADieVEnwx1q?p=preview


text:
Q: How can i show progress in horizontal progressbar when downloading data using ksoap library in android application? How can i show progress in horizontal progressbar when downloading data using ksoap in android application?
Here i am using AsyncTask for fetching datas from server. And at the same time i need to show a horizontal progressbar progresses according to the data transfered vs datas going to transfer.
private class SyncIncoData extends AsyncTask<String, Void, String> {
        ProgressBar pb;
        LinearLayout all;
        @Override
        protected String doInBackground(String... urls) {
            try {
                incodata=si.GetSoapData();
                db=new SqlConnector(con);
                datacheckerInco(incodata);
            } catch (Exception e) {

                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            all=(LinearLayout)findViewById(R.id.linearLayoutall);
            all.setEnabled(false);
            pb=(ProgressBar)findViewById(R.id.progressBarsync4);
            pb.setVisibility(View.VISIBLE);
            back=false;
            saleto.setClickable(false);
            shipto.setClickable(false);
            mate.setClickable(false);
            inco.setClickable(false);
            off.setClickable(false);
            tv4.setText("Synchronizing");
            //im4.setVisibility(View.INVISIBLE);
        }

        @Override
        protected void onPostExecute(String result) {
            all=(LinearLayout)findViewById(R.id.linearLayoutall);
            all.setEnabled(true);
            pb=(ProgressBar)findViewById(R.id.progressBarsync4);
            pb.setVisibility(View.INVISIBLE);
            back=true;
            saleto.setClickable(true);
            shipto.setClickable(true);
            mate.setClickable(true);
            inco.setClickable(true);
            off.setClickable(true);
            tv4.setText("Completed");
            //im4.setVisibility(View.VISIBLE);
        }
    }

A: Take a look at this: https://sites.google.com/site/androidhowto/how-to-1/create-a-custom-progress-bar-using-asynctask


text:
Q: Files created in /var/www/website.com/public_html contain 600 permissions I have created a virtual hosts configuration and the file permissions are not inheriting correctly. I have set the permissions as follows:
/var/www

/var/www/example.com

/var/www/example.com/public_html

/var/www/example.com/public_html/index.html

Note: index.php is generated with 600 file permissions and not 775 permissions like its parent. I have attempted to delete all folders and files all the way down to var/www and re-establish permissions to ensure steps properly and the files are still being generated with 600 permissions.

EDIT > SOLUTION:
Because new files were being created via FTP, this issue was not related to the files folder permissions but rather VSFTPD's configuration and how it was assigning new files permissions generated via FTP.  All the credit goes to gurcanozturk's answer on this question for the commands and pointing me in the correct direction. Below are the few steps for this specific scenario.
Open VSFTPD configuration file
sudo nano /etc/vsftpd.conf

Near the top, add (0755 being questionable)
file_open_mode=0755

And uncomment out
local_umask=022


text:
Q: Propose asking draft questions on other SEs While authoring a question, I get a list of "similar questions" from the current SE site. It would be really nice if it would also be able to say:

Out ML model think this question has a high chance of being closed on this site for reason $X. The model thinks that it would be more on-topic/less-likely-to-be-closed on these other SE sites.

(Well, I think the phrasing would be better using different words, but that's what I expect it would end up actual checking.)


text:
Q: Int numbers appearing as 0x00000000 For some reason all my numbers appear as 0x00000000, 0x00000001, 0x00000002 when I hover over them.
Is this some kind of setting I've accidently turned on or does anyone have any idea what's going on?

A: Hover over the variable -> right click -> uncheck hexadecimal display
Actually, Roman R. comment is even better, never saw it before :)


text:
Q: Optional ignored arguments in Ruby's nil#rationalize I was perusing through the NilClass documentation, and I found a method rationalize that, when called on nil, "returns zero as a rational":
nil.rationalize
#=> 0/1

What's strange is that the documentation also states that "The optional argument eps is always ignored".
Thus,
nil.rationalize(5)
#=> 0/1

nil.rationalize("monkey")
#=> 0/1

nil.rationalize(false)
#=> 0/1

What is the purpose of the eps argument, and why have an optional argument that is always ignored?

A: Given that .rationalize is also available on Float, Integer, Complex and Rational, the parameter is probably accepted for compatibility reasons. It might not be used for NilClass, but this way it's argument-compatible with the rest.


text:
Q: Composition of two differential operators . Laplacian operator. I have a question with the composition of two operators.
To contextualize. Let $p_1 = p_1 (x,D_x):= 1-\partial_ {x}^2 $ be the operator $ p_1: D(p_1)\subset L^2 \to L^2 $ where
$$ D(p_1) = \left\{u \in L^2: p_1u\in L^2\right\}$$
It can be verified that $p_1u(x) = \mathcal {F}^{-1}((1+ \xi^2)\widehat {u}(\xi))(x)$
and if $p_2 = p_2 (x, D_x)u(x): = p_1(x, D_x)^{-1}u(x)$ ($p_2$ the resolvent) , it can be proved that $p_2u(x)=\mathcal {F}^{-1} ((1+\xi^2)^{-1}\widehat{u}(\xi))(x)$.
Since $p_1\circ p_2 u(x)=u(x)$, that is, $p_1\circ p_2 = Id$, the identity operator symbol is $1$ (I suppose this is true since $Id(u(x)) = u(x)$ does not appear any differentiation operator).
My doubt leaves now. In general, if $p_1$ and $p_2$ are two operators, the symbols of the composition $p_1\circ p_2$ is given by
$$(p_1\#p_2) (x, \xi): = \int \int e^{-ix'\xi'} p_1 (x, \xi + \xi ') p_2 (x + x' , \xi) dx'd \xi'$$ (as you can see in, for example, Pseudo differential and singular integral operators by the author Abels).
Given the above, it should happen that
$$\int \int e^{-ix '\xi'} (1 + (\xi + \xi ')^2) (1+ \xi)^{-1} dx'd \xi' = 1$$
This is true?


text:
Q: SKScene Won't Present When SubView Is Added To View Controller I tried to add a subview to my GameViewController (because I want to add a banner ad at the bottom). I created it as follows:
    if let view = self.view as! SKView? {
        let subView = SKView(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 415, height: 685)))
        view.addSubview(subView)
        if let scene = SKScene(fileNamed: "GameScene") {
            scene.scaleMode = SKSceneScaleMode.aspectFit
            subView.presentScene(scene)
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
            view.showsDrawCount = false
            addBannerViewToView(bannerView)
        }
    }

This works initially - it presents my GameScene. But later, I ask my GameScene to present another subclass of SKScene that I created, which I call Shop, using the following code:
func initializeShop() {
    let shop = Shop(size: self.size)
    let transition = SKTransition.fade(withDuration: 0.1)
    self.view?.presentScene(shop!, transition: transition)
}

And it simply does not present. It remains on the current view.
This works completely fine if I do NOT add a subview to the initial view in the GameViewController, i.e.
   if let view = self.view as! SKView? {
        if let scene = SKScene(fileNamed: "GameScene") {
            scene.scaleMode = SKSceneScaleMode.aspectFit
            view.presentScene(scene)
            view.ignoresSiblingOrder = true
            view.showsFPS = false
            view.showsNodeCount = false
            view.showsDrawCount = false
        }
    }

So it seems like there is some property of the GameViewController's default SKView that allows presentation, but not a subview. But I can't find any documentation that says that - from what I can tell, all SKViews should be able to present SKScenes.
Any help would be much appreciated.


text:
Q: Filter and Unique array of object in javascript with underscore.js based on two property In my application i have an array like this :
var arr=[
 {id:1,name:"mohammmad",deny:false},
 {id:1,name:"mohammmad",deny:false},
 {id:1,name:"mohammmad",deny:true},
 {id:2,name:"ali",deny:false},
 {id:3,name:"reza",deny:true},
 {id:2,name:"ali",deny:true}
];

now I want to return unique collection of this array based on id of object but if collection have true value for deny it must return the object that have deny=true. for example :
 {id:1,name:"mohammmad",deny:false},
 {id:1,name:"mohammmad",deny:false},
 {id:1,name:"mohammmad",deny:true},

it filter with id=1 but return the object that have deny=true.
i also create a jsbin here .

A: Using underscore:
_.chain(arr)
  .sortBy(function(d) { return !d.deny })
  .uniq(function(d) { return d.id })
  .value()

Sort by deny (with true values first), then uniq on id. Underscore's implementation of uniq keeps the first matching value for each key. Therefore, if a given id had a value with deny: true, that value will be kept. If it didn't, it keeps first value with any value of deny.
JSFiddle


text:
Q: Java Swing - Simulate process run Selection sort I have a final project:
Simulate process selection sort similar to this video:
https://www.youtube.com/watch?v=RWET645TK88

But I don't know how to make the code in jList run like in the video. Someone advised me to user Timer! But I still don't understand what I must do!
When I click button "Start", the array is sorted immediately, it does not run slowly like in the video.
Here is it:

and here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Timer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }
    int b[];
    Timer timer;
    int n;
    javax.swing.JLabel []a;
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton2.setText("Create");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Insert Code");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Set min to index 0");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Start");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jList2);

        jTextField1.setText("10");

        jLabel1.setText("Amount:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGap(20, 20, 20)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4))
                    .addComponent(jScrollPane2))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(62, 62, 62))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(74, 74, 74))
        );

        pack();
    }// </editor-fold>

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        n=Integer.parseInt(jTextField1.getText());
        b=new int[n];
        a= new javax.swing.JLabel[n];
        int x=5, y=40;
        for (int i=0; i< n; i++)
        {
            int random = (int )(Math.random()*20 + 1);
            b[i]=random;
            a[i]= new javax.swing.JLabel();
            a[i].setText(random+ "");
            a[i].setSize(20, 30);
            x=x +20;
            a[i].setBorder( BorderFactory.createRaisedBevelBorder());
            a[i].setLocation(x, y);
 //           setLayout(new java.awt.GridBagLayout());
            add(a[i], new java.awt.GridBagConstraints());
            a[i].setVisible(true);

        }
        this.repaint();
        jButton2.setVisible(false);
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        jList1.setListData(new String [0]);
        String[] strings = { "int min, i, j,temp;", "for(i = 0; i < n-1; i++){", "   min = i;", "   for(j = i+1; j < n; j++)", "         if(a[j] < a[min])","           min = j;","    if(min != i){","       temp=a[i];","       a[i]=a[j];","       a[j]=temp;","    }","}" };
        jList1.setListData(strings);

    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        int min=b[0],x=0,temp1;
        for (int i=1;i<n;i++){
            if (b[i]<min) min=b[i];
        }
        for (int i=0;i<n;i++){
            if (b[i]==min) x=i;
        }
        temp1=b[x];
        b[x]=b[0];
        b[0]=temp1;
        a[x].setText(b[x]+"");
        a[0].setText(b[0]+"");
        jButton3.setVisible(false);
        DefaultListModel s=new DefaultListModel();
        s.addElement("Selection sort: - Set the smallest element in first index!");
        jList2.setModel(s);
    }

    ActionListener al=new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

//    timer = new Timer(10, al);
//    timer.start();
//    for (int k=0;k<10;k++){
//        a[k].setText(b[k]+ "");
//    }
        }
    };

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        int min,temp2, i, j; //min là chỉ số phần tử nhỏ nhất
             for(i = 1; i < n-1; i++)
             {
                   min = i;
                   for(j = i+1; j < n; j++){
                      if(b[j] < b[min])
                         min = j; //tìm min trong các phần tử còn lại
                   }
                       temp2=b[i];
                       b[i]=b[min];
                       b[min]=temp2;
                       a[min].setText(b[min]+"");
                       a[i].setText(b[i]+"");
                      //đổi chỗ nếu tìm thấy min
             }
        a[0].setBorder(BorderFactory.createLoweredBevelBorder());
        //jButton4.addActionListener(al);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws InterruptedException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });

    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

A: Just update jButton4ActionPerformed method :
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    new Thread(new Runnable() {
        @Override
        public void run() {

            int min, temp2, i, j; //min là chỉ số phần tử nhỏ nhất
            for (i = 0; i < n; i++) {
                min = i;
                for (j = i + 1; j < n; j++) {
                    if (b[j] < b[min]) {
                        min = j; //tìm min trong các phần tử còn lại
                    }
                }
                temp2 = b[i];
                b[i] = b[min];
                b[min] = temp2;
                a[min].setText(b[min] + "");
                a[i].setText(b[i] + "");
                a[i].setBorder(BorderFactory.createLoweredBevelBorder());
                a[i].repaint();
                if (i > 0) {
                    a[i - 1].setBorder(BorderFactory.createRaisedBevelBorder());
                    a[i - 1].repaint();
                }
                try {
                    //đổi chỗ nếu tìm thấy min
                    Thread.sleep(500);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }

            a[i - 1].setBorder(BorderFactory.createRaisedBevelBorder());
            a[i - 1].repaint();
        }
    }).start();

    //jButton4.addActionListener(al);
}


text:
Q: LDAP Acount Manager (LAM) can not use SSH public key module / OpenLDAP CentOS 6.4 SSL setup I set up openLDAP server + client on a virtual machine running CentOS 6.4.
I config openLDAP with SSL and I can create user in LDAP Account Manager - LAM.
Then I try to add the SSH public key module for user.
When I try to create a new user LAM returned:
Was unable to create DN: cn=test,ou=People,dc=local,dc=host.
Invalid syntax

Then I checked with Schema test then it shows up that SSH public key did not work with my LDAP server:
SSH public key XXX The object class ldapPublicKey is not supported by your LDAP server.

I know that openssh-lpk has integrated default in CentOS.
I installed openssh-ldap and tried to include openssh-lpk-openldap.schema path in /etc/openldap/slapd.conf:
include /usr/share/doc/openssh-ldap-5.3p1/openssh-lpk-openldap.schema

But it did work.
So what should I do next?
Thank you.

A: I found that I have to remove the config file generated by slaptest in /etc/openldap/slapd.d
and then rerun the slaptest command again to generate the template with openssh-lpk schema. It worked.


text:
Q: How to serve static default content under each subfolder wIth ktor I have a static route that works fine, but I would like to add a default document for any/all sub folders - default seems to only be able to take a fixed file to serve, with no way of asking it to look in the request directory.
The following will serve any static file under the "/export" directory when "/export/..." is requested, but if not found then the file "/index.html" is always returned instead of "export/.../index.html".
static("export") {
    files("export")
    default("index.html")
}

Is there any way to define this? It seems like a standard feature for a web server, so I may have just missed something obvious...

A: default() handles only the top-level folder, for whatever reason. You can replace the files() and default() pair with a custom extension, looking like this:
fun Route.filesWithDefaultIndex(dir: File) {
  val combinedDir = staticRootFolder?.resolve(dir) ?: dir
  get("{static_path...}") {
    val relativePath = call.parameters
      .getAll("static_path")
      ?.joinToString(File.separator) ?: return@get
    val file = combinedDir.combineSafe(relativePath)
    val fallbackFile = file.combineSafe("index.html")

    val localFile = when {
      file.isFile -> file
      file.isDirectory && fallbackFile.isFile -> fallbackFile
      else -> return@get
    }

    call.respond(LocalFileContent(localFile, ContentType.defaultForFile(localFile)))
  }
}

Basically, this resolves the local file matching the requested path, serves it if it's a regular file, or serves its index.html (if present) if it's a directory. Otherwise, it delegates the error handling to Ktor (likely returning a 404).
I wrote up a slightly longer explanation of this solution here as well.


text:
Q: Get events history from a table that holds events and their old versions at the same time I have a table with events "events" that holds all events and their older versions. I have these columns:

*

*"id" primary,

*"origin_id" here I keep the ID of the original event,

*"date_added" DATETIME column.

When I first add an event its "origin_id" get its "id" value. When I change this event I create a new event with the same "origin_id" as the first one, new auto-incremented "id" and new "date_added" of course.
How to get a list with all current events from table, without their old versions ordered by the starting date "start" - a DATETIME column again?
So if I have a 3 events and each of them has several revisions/updates I want to get only the last update for each of them.

A: Amm I think I got it on my own :)
SELECT *
FROM events WHERE id
IN (
SELECT MAX( id )
FROM events
GROUP BY origin_id
)
ORDER BY start ASC

A: What about this?
SELECT MAX(id), origin_id, MAX(date_added), start
FROM events
GROUP BY origin_id, start
ORDER BY start ASC

It is certainly not the same as your own solution, so I think you are free to accept yours if mine doesn't work for you and if nothing better turns up.


text:
Q: Algorithm to push/insert to stack Newbie to C here and following online book tutorials. (I have been attempting linked-lists but little complex for now, will return to these later.) I have the following algorithm:
Algorithm: PUSH (STACK, ITEM)
[STACK is an array of MAXSIZE and ITEM is an item to be pushed onto
stack]
1. [Check for stack overflow]
If TOP = MAXSIZE - 1 then
a) Print: Overflow
b) Return
2. [Increase top by 1]
Set TOP = TOP + 1
3. [Insert item in new top position]
Set STACK[TOP] = ITEM
4. Return

However, I cannot understand step 1, for Top, how would I go about initialising this, because Top should indicate some pre-existing value? For example:
(My attempt)
#include <stdlib.h>
#include <stdio.h>

int push(int item, int(*stack)[item]){
    int top;
    if(top == sizeof(*stack)/sizeof(*stack[0])-1){
        printf("Overflow");
        return -1;
    }
    top++;
    *stack[top] = item;
    return **stack;
}

int main(void){
    int arr[4] = {0 , 1, 2, 3};
    int itm = 2;
    int result;
    result = push(itm, &arr);
    printf("\nResult: %i", result);
    return 0;
}

Would always produce an overflow

A: You will simply need to store the current value of top and send it along with the stack everywhere. You should define a struct, like so:
typedef struct Stack {
    int stack[16]; // Replace 16 with desired capacity.
    int top;
} Stack;

Create a new stack like this:
Stack s = { .top = -1 };

Now all your functions should receive a pointer to this stack, and functions like push should update the value of top.


text:
Q: Prove $\mathbb P\{\sup_{t\geq 0}W_t=+\infty \}=1$ where $(W_t)$ is a Brownian motion. Let $(W_t)_t$ a Brownian motion. How can I prove that $$\mathbb P(\sup_{t\geq 0}W_t=+\infty )=1\ \ ?$$
Attempts
Set $Z=\sup_{t\geq 0}W_t$. I know that $Z\sim cZ$ for all $c>0$, and thus $$\mathbb P(Z=\infty) =\mathbb P\left(\bigcap_{n\in N^*}(Z\geq n)\right)=\lim_{n\to \infty }\mathbb P(Z\geq n)=P(Z>0)$$
because for all $c>0$, $$\mathbb P(Z>n)=\mathbb P(Z>\frac{n}{c})\underset{c\to 0}{\to} \mathbb P(Z>0).$$
Question
Since $W_0=0$, we have that $\mathbb P(Z\geq 0)=1$, and thus $\mathbb P(Z=0)+\mathbb P(Z=\infty )=1$. But, how can I prove that $\mathbb P(Z=0)=0$ ? I know that it mean that $W_t\leq 0$ for all $t$, but I don't see how to prove that this is $0$.

A: Let $Z_t:=\sup_{0\le s\le t}B_s$. By the reflection principle, $Z_t\overset{d}{=}|B_t|$, so that $\mathsf{P}(Z\le 0)\le \mathsf{P}(Z_1\le 0)=0$.


text:
Q: How to create a non single-shot timer in C? I need to use a non single shot Timer (such as QTimer from the Qt library) in a C code for embedded Linux (by no single shot Timer I mean one that triggers once ever x seconds indefinitely till a "stop timer" is called, not one that triggers only once or one that blocks the code while it's counting).
Some libraries that are available to me do implement such a timer using signal handlers, but I would like to avoid using such a system (I learned that is not the best solution). I know I can emulate what I want with single shot Timers by restarting the timer (calling it again) once it's finished, and that is an acceptable solution (actually the libraries I talked about work that way), but I don't know how to implement that without blocking the running code till the timer is triggered.
And one more thing: I need to be capable of implementing more then just one of them (here is where signal handlers stop being a viable solution AFAIK).
So how could I do such a solution? The closes to what Qt's QTimer has to offer, the better!

A: If you do need an unspecified number of triggers at varying intervals/times, a dedicated timer thread (as described by nneonneo in another answer) has the least number of pitfalls in my experience.
Timers are a limited resource (the number of timers available is configurable, and varies from system to system, so you cannot make any sweeping statements like "I'm sure there's enough for my purposes").
Signals interrupt blocking syscalls unless SA_RESTART flag is used; even then there are a few exceptions (see man 7 signal, Interruption of system calls and library functions by signal handlers chapter for details).

A dedicated timer thread is built around two components:

*

*A queue, list, tree, or heap holding all timer events
A typical implementation only needs to know when the next event occurs, so a min-heap or a priority queue works quite well. I've found a min-heap to be simple and robust to implement, and efficient enough (O(log N) time complexity for both inserts and deletes); using absolute times (using CLOCK_MONOTONIC in Linux) for the events as keys.
Note that if you use the timer events as timeouts, you'll also need to make sure cancelling an event is efficient. In normal operation, timeouts are rare, so something like a web server is likely to cancel just about all the timeouts it sets, without any of them actually ever triggering.

*A thread that waits for either the next event, or another thread inserting a new timer event
Personally, I use an array to hold the min-heap of events, protected by a pthread_mutex_t, with a pthread_cond_t for other threads to signal on after adding a new event. Then, it's a simple matter to use pthread_cond_timedwait() to wait/sleep for either the specified time, or until a thread notifies of a new event, whichever happens sooner.
When the next event occurs -- note that due to scheduling, you might find more than one separate event to occur, so you might not wish to sleep at all (but you might still check if new events were added) --, you perform the event. If the event is periodic, you reinsert it into the heap/queue, too, primed for the next time.
Choosing how events are performed is very important, and really, the only truly tricky bit. You can use flags -- switching from zero to nonzero is safe in practice, even if the change is not atomic, as long as you don't rely on any specific nonzero value --; you can cause a condition variable to be signaled or broadcast on; you can post a semaphore; you can raise a specific signal in a specific thread (even an empty signal handler will cause blocking I/O calls to interrupt, if the handler is installed without SA_RESTART flag; I've used this as an I/O timeout quite successfully); you can even use __atomic or __sync to modify a value atomically if using GCC (or Intel CC, Pathscale, or Portland Group C compilers); and so on.
If you need a specific function to be called, I recommend using a separate thread (or, if most of the work in the application/program/game is done in these timer events, a thread pool) to execute the events. This keeps the timer thread simple and precise, while keeping all resource use easily controlled. The worker thread or thread pool should simply have a FIFO queue of events protected by a mutex and a condition variable, so that the timer thread can add each event to the queue and then signal on the condition variable to notify the (next) worker thread that work is available.
Indeed, in the couple of instances I used other event action models, I now believe the function worker model would have been easier. Especially if you make the worker functions to take a pointer (to a structure), defined by the caller, so that they all have the same signature, this interface becomes quite straightforward to implement, but extremely powerful and versatile.
There is one downside to the timer-thread plus worker-thread(s) approach, and that is the (minimal) added latency. The worker thread will not get the work at the appointed time, but a short while afterwards. However, if you have the worker thread get the current time, compare to the (un-adjusted) target time, and use that as a statistic to trigger the events correspondingly prior to the target time, you can typically take care of this issue. (I have not verified, but I do believe both Qt and GTK+ toolkits do continuously estimate this latency in a similar if not same manner.)
Questions?

A: You have several options, none of which require any libraries beyond the standard C and POSIX libraries.

*

*POSIX timers API, e.g. timer_create and friends. These have flexible notification scheme based on sigev, which allows you to specify how you want to be notified (signal to a specific thread, creation of a new thread, or arbitrary signal). By specifying that the signal goes to a specific thread, you can set that thread up to be ready for async signals, and use sig_atomic_t to signal work to be done by the thread. The most interesting notification option is to use the creation of a brand new thread, but note that this can get expensive if the timer fires frequently.

*Linux timerfd API, e.g. timerfd_create. These create timers that you can poll with poll or epoll, enabling you to add the timers to a low-level event loop, as well as operate on them in a perfectly thread-safe and signal-safe way.

*alarm. This uses the SIGALRM asynchronous signal, so again you'll want to use sig_atomic_t and a signal-processing thread to handle the timer.

*select, poll, or nanosleep on a dedicated timer thread: This is what QTimer usually does under the covers. You simply create a dedicated timer thread and have the thread repeatedly sleep. To keep the timer on schedule, you adjust the sleep time based on the length of each processing cycle.

The last option is the most portable, but also basically the most work (since you're implementing the timer yourself). The upshot is that you get to customize the "timer" completely since you're implementing it on top of a sleep primitive.


text:
Q: In connect to server, there is no server type option in Ubuntu 14.04 I want to mount my box.com webdav into my Ubuntu 14.04, but when I clicked the "connect to server" option in my home folder, I guess there is supposed to be an option for the type of server I want to connect to, as there was on previous versions. Where is that option now?

A: In the 'Connect to Server' dialog window, use 'davs://dav.box.com/dav' in the server address field and click on connect button, then, it would ask you to enter your box.com's username and password. Hope this helps..


text:
Q: Windsor Performance Counter miss in PerfMon I would like to add the performance counter of windsor in my Performance Monitor...
I have configured Windsor as indicated in the docs :
var diagnostic = LifecycledComponentsReleasePolicy.GetTrackedComponentsDiagnostic(container.Kernel);
var counter = LifecycledComponentsReleasePolicy.GetTrackedComponentsPerformanceCounter(new PerformanceMetricsFactory());
container.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy(diagnostic, counter);

Then I run my Web Api application, and I run the performance Monitor. But when I try to add a new counter I do not find the "Castle Windsor" section.

What's wrong in what am  I doing?
PS.: I am using windsor 4

A: It is likely Windsor doesn't have permission to create the performance counter category and counter (i.e. write to the registry) and is swallowing the SecurityException in PerformanceMetricsFactory.Initialize.
Run your application or Visual Studio elevated as administrator, you will only need to do this once.


text:
Q: ASP.NET MVC Controller Result return to view I'm working in ASP MVC & C#, and what i'm trying to do is something similar to the following.
public JsonResult SendMessage(SMSTestViewModel model)
{
    if (//logic here)
    {
        string phonenumber = model.phone.ToString();
        string derp = string.Empty;
        //SMS.SendSMS(phonenumber, "testing heheheheh", derp);
        var result = new { Success = "True", Message = "Good Job" };
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    var result = new { Success = "False", Message = "Didn't work" };
    return Json(result, JsonRequestBehavior.AllowGet);
}

That's the code block in my controller, and now I'm trying to reference this in my View with the following

Please enter your phone number

    Phone Number
     <input id = "phone" type ="text" name= "phone" />

<input type="button" value="Submit" id="sendMSG">

For some reason the alerts wont show up. And It's quite confusing to me.
I'm really new to JSON, JQuery and Javascript so any help or recommendations would be greatly appreciated.
Thanks
EDIT:
Changed the html code block to the following:
<input type="button" value="Submit" id="sendMSG">

A: Most likely, the URL in your $.getJSON call is incorrect. You have it relative to whatever URL you're currently looking at.
Try changing that line to be:
$.getJSON('@Url.Action("SendMessage", "SMSTestController")', function (data) {

This way, MVC generates an absolute URL to your action.
Edit:
Your jQuery selector of your button is wrong.
$('sendMSG')

Since you're searching for it by id, use:
$('#sendMSG')

A: Changing the url to the following should make it work
'/SMSTestController/SendMessage'

However, the better solution is as Matt had mentioned
'@Url.Action("SendMessage", "SMSTestController")'

Also, Have a look at this Fiddle http://jsfiddle.net/Ukuyc/


text:
Q: Parent-Child relations in angular 4 This is my db.json after submit i want
{
    "id": 0,
    "code": "string",
    "name": "string",
    "isActive": true,
    "questionerdetails":[
        {
            "id":0,
            "questiondetail": "string",
            "isActive": true
        }
    ]
}

This is my method in questioner.component.ts
formSubmits() {
    this.validate = true;
    this.preProcessConfigurations();
    let questioner = this.questionerForm.value;
    let question = this.questions;

    this.allquestionare.forEach(obj => {

      question.push({ 'questiondetail': '' })
    })

    console.log(questioner);
    this.questionareService.getAllQuestioner()
      .subscribe(questionerss => {

        this.questionareService.createQuestioner(questioner)
          .subscribe(successCode => {
            this.statuscode = successCode;
            this.questionerForm.reset();
            alert("Success");

          },
          errorCode => this.statuscode = errorCode
          );
      });

  }

please help--
i got stuck in method form submits, to push the child class questionerdetails into parent class

A: I had the similar requirement. I have used the approach like, I have created two models. In your situation say Questionnaire and QuestionnaireDetails. Into Questionnaire there will be the array of  QuestionnaireDetails. You can use constructor or setter/getters to set/get data.
Check example given below,
Questionnaire Model
export class Questionnaire {

    private id: number;
    private code: string;
    private name: string;
    private isActive;
    private questionerdetails: QuestionnaireDetails[];

    constructor(){
    }
}

QuestionnaireDetails Model
export class QuestionnaireDetails {

    private id: number;
    private questionnairedetail: string;
    private isActive;

    constructor(){
   }
}


text:
Q: Qt web engine get history I am reading a Qt book, which may not be so good, that is giving me some troubles. I need to get the history from a QWebEngineView* webview; I have written this code following the book:
 QWebEngineHistory* h = QWebEnginePage::history();

This is how I should retrieve the history and then I can access it using h->items();. The problem is that the above code produces

call to non-static member function without an object argument

How can I fix this? I need to get the history of the navigated pages

I have then tried this
QWebEngineHistory* h = webview->history();

But now I am not able to call h->items(). How can I fix this? I need to access items().
Header file
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QWebEngineView>
#include <QWebEnginePage>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow() override;
    virtual void paintEvent(QPaintEvent* event) override;

private slots:
    void on_pushButton_2_clicked();
    void on_pushButton_3_clicked();
    void on_pushButton_clicked();
    void on_pushButton_4_clicked();
    void on_url_input_returnPressed();
    void on_pushButton_5_clicked();
    void on_pushButton_7_clicked();

    void on_pushButton_6_clicked();

private:
    Ui::MainWindow *ui;
    QWebEngineView* webview;
    void loadPage() const;
};

#endif // MAINWINDOW_H

Implementation
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow) {

    ui->setupUi(this);

    webview = new QWebEngineView(ui->webViewFrame);
    loadPage();
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::on_pushButton_2_clicked() {
    webview->back();
}

void MainWindow::on_pushButton_3_clicked() {
    webview->forward();
}

void MainWindow::on_pushButton_clicked() {
    webview->reload();
}

void MainWindow::on_pushButton_4_clicked() {
    loadPage();
}

void MainWindow::loadPage() const {
    QString url = ui->url_input->text();

    if (url.length() == 0)
        url = "http://www.google.it";

    if (!url.startsWith("http://") && !url.startsWith("https://"))
        url = "http://" + url;

    ui->url_input->setText(url);
    ui->listWidget->addItem(url);
    webview->load(QUrl(url));
}

void MainWindow::on_url_input_returnPressed() {
    loadPage();
}

void MainWindow::paintEvent(QPaintEvent* event) {
    QMainWindow::paintEvent(event);
    webview->resize(ui->webViewFrame->size());
}

void MainWindow::on_pushButton_5_clicked() {
    QWebEngineHistory* h = webview->history();
    auto x = h->items(); //error here!!

    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::on_pushButton_7_clicked() {
    ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::on_pushButton_6_clicked() {
    ui->listWidget->clear();
}

A: I'm not that big expert for Qt. But I think your book has a mistake in this case. Your second approch
QWebEngineHistory* h = webview->history();

is perferctly correct. Because you want to retrieve the history from your web engine (object webview).
From the Qt documentation history() is a non-static function. (That's why your first code produces the specified error.) If history() would be a static function, what history should it return? It hasn't any connection to a web view.
Edit (requested by scopchanov): In qwebenginepage.h QWebEngineHistory is only forward declared, hence you need to #include <QWebEngineHistory> to access items() (or any other method for that matter).


text:
Q: CSS parsing libraries for iPhone I'm looking for some static library or open source project (in obj-c, released under some permissive license) to parse CSS in iPhone. Any recommendations?

A: OK, I found good library for parsing CSS - libCSS from the NetSurf web browser project. Released under MIT license, can be used without problems for commercial iPhone applications distributed via the AppStore.
It requires some code for the programmer to write (e.g. you need to provide your own DOM hierarchy handlers), and there are no examples available... but people from the NetSurf dev mailing lists are very helpful. In case of problems you can search the list for my questions.
libCSS
NetSurf dev mailing list

A: I would recommend htmlcxx. It's pretty actively maintained, written in C++ and you can use it to parse HTML and CSS.
Of course, since it's written in C++, you can use it in your iPhone application with no problems at all.

A: I've taken this project and made it easy to add to your iOS or OSX projects. Clone my github project and add the html (and or css) folder to your project. There is an Xcode project too - so you can build and run the simple test provided by the original authors


text:
Q: How to visualize large graph? I am trying to create a graph where number of nodes is more than 400 which is not visualizing in a proper way.
import networkx as nx
G=nx.MultiGraph()
G.add_nodes_from(freqItemSet)
G.add_edges_from([edge])
plt.figure(figsize=(10000,10000))
nx.draw(G)

I was using the above code. Is there any other way to visualize in a proper way.
Thank you

A: You can use a tool called "Gephi" which is free and has good UI.
You can export the file from networkx as "*.gexf" format


text:
Q: When is a sum of consecutive squares equal to a square? We have the sum of squares of $n$ consecutive positive integers: $$S=(a+1)^2+(a+2)^2+ ... +(a+n)^2$$ Problem was to find the smallest $n$ such, that $S=b^2$ will be square of some positive integer. I found an example for $n=11$. Now, I'm trying to prove, that if $2<n<11$ there is't any solution. So I need some help with this: If $n,a,b \in \mathbb{N}$ and $n<11$ prove that equation
$$
n\cdot a^2 + n(n+1)\cdot a + \frac{1}{6}n(n+1)(2n+1)=b^2
$$
can't be solved. Or if I'm wrong, find counterexample.
The only idea I have is: to consider the remains $\operatorname{Mod}[b^2,n]$ and $\operatorname{Mod}[\frac{1}{6}n(n+1)(2n+1),n]$. For each $2<n<11$, but it is very long.

A: Below is a reasonable (but not very illuminating) proof. Put $S_n(x)=\sum_{k=1}^{n} (x+k)^2$. Note that it is also true that for $2<n<11$, $S_n(x)$ is never a square modulo $n^2$, and $S_n(x)$ is also never a square modulo $900$. Perhaps this will inspire others to produce more intelligent proofs.
Here it goes :
$$
\begin{array}{ccll}
S_3(x) & \equiv & 3x^2+12x+14 \equiv 2 & {\sf mod} \  3 \\
S_4(x) & \equiv & 4x^2+20x+30 \equiv 2 & {\sf mod} \  4 \\
S_5(x) & \equiv & 5x^2+30x+55 \equiv 2 \ \text{or} \ 3 & {\sf mod} \  4 \\
S_6(x) & \equiv & 6x^2+42x+91 \equiv 3 & {\sf mod} \  4 \\
S_7(x) & \equiv & 7x^2+56x+140 \equiv 3,8,11 \ \text{or} \ 12 & {\sf mod} \  16 \\
S_8(x) & \equiv & 8x^2+72x+204 \equiv 2,5,6 \ \text{or} \ 8 & {\sf mod} \  9 \\
S_9(x) & \equiv & 9x^2+90x+285 \equiv 6 & {\sf mod} \  9 \\
S_{10}(x) & \equiv & 10x^2+110x+385 \equiv 5,10 \ \text{or} \ 20& {\sf mod} \ 25  \\
\end{array}
$$
Each time, we see that $S_n(x)$ is never a square for the given modulus.

A: In general, there are $n$ consecutive squares that add to a square if and only if the following Diophantine equation has solutions:
$$x^2-ny^2=\frac{n(n-1)(n+1)}{3}$$
with the added parity condition that $y$ and $n$ are different parities. The value $y$ is just the sum of the first and last element of the sequence, so $$\frac{y-n+1}{2}$$ is the beginning of the sequence.
When $n$ is not  square, then the nice thing about Pell-like equations is that if there is one solution with the above parity condition, there are infinitely many. In particular, then there is always a sequence of consecutive positive numbers if there is any consecutive sequence of integers.
If $n$ is a perfect square, then there is a solution if and only if $(n,6)=1$. It is not always the case that you can find consecutive squares of positive numbers in this case. But we can get a solution $m,m+1,\dots,m+n-1$ with $m=\frac{(n+1)(n-25)}{48}$ when $n$ a perfect square, which gives positive solutions except when $n=1$ and $n=25$.  But $n=1$ obviously has positive solutions, so the only problem case is $n=25$. There is no positive solution when $n=25$, only a non-negative solution: $0^2+1^2\dots+24^2$ is a square.
When $n$ is not a perfect square, this condition gets harder, but the Pell-like nature of the equation gives us a way to find some solutions. For exmaple, $u^2-nv^2=n(n-1)$ has a trivial solution, so if $n+1$ is divisible by $3$ then we can find a solution to the above equation of $w^2-nz^2 = \frac{n+1}{3}$ yields a solution to the above, and it turns out you can easily show in that case that the solution satisfies the parity condition. In particular, if $n=3w^2-1$, then $(w,z)=(w,0)$ is a solution, so we know we have infinitely many non-square values of $n$, and, in particular, $n=11$ when $w=2$.
Necessary conditions when $n$  is not a square:
A. Factor $n=a^{2}b$, with $b$ square-free, then:

*

*If $2 \mid a$, then $2 \mid b$

*If $3 \mid a$, then $3 \mid b$

*$3$ is a square $\pmod{b}$. (Alternatively, the only primes that divide
 $b$ are $2$,  $3$, and primes of the form $12k \pm 1$.)

*If $3 \mid b$, then $b \equiv 6 \pmod{9}$

B.

*

*If $3 \mid n+1$, then $\frac{n+1}{3}$ is the sum of two perfect squares

*If $3 \nmid n+1$, then $n+1$ is the sum of two perfect squares

These can be used to exclude $n=3,...,10$:

*

*$3$ violates $A.4.$

*$4$ is a square and $(4,6)\neq 1$

*$5$ violates $A.3.$.

*$6$ violates $B.2$.

*$7$ violates $A.3.$

*$8$ violates $B.1.$

*$9$ is a square not relatively prime to $6$.

*$10$ violates $B.2.$

See here for some more details and some ways to explicitly construct such $n$.
I don't have sufficient conditions.  The smalles number that satisfies the above conditions but for which there is no solution is $n=842$.
It is easier to come up with necessary and sufficient conditions for the question of whether there exists an arithmetic progression of length $n$ such that the sum of the squares is a square. Indeed, if $y$ and $n$ are the same parity in the above equation, that amounts to a sequence of $n$ consecutive odd numbers whose squares add up to a square.

A: There is a solution for n=2, namely:
n=2; a=2,b=5.
since 3 squared + 4 squared = 5 squared,
proof: 9+16=25.
However I noticed n=2 was excluded in the equality stating n less than 11. It is not clear to me why n=2 is excluded.


text:
Q: Is it possible to implement always_false in the C++ standard library? There are cases where one uses an always_false helper to e.g. cause unconditional static_assert failure if instantiation of some template is attempted:
template <class... T> struct always_false : std::false_type {};

template<class T>
struct UsingThisShouldBeAnError {
  static_assert(always_false<T>::value, "You should not use this!");
};

This helper is necessary because a template definition must (at least theoretically) have at least one set of template parameters for which a valid specialization can be produced in order for the program to be well-formed:

[temp.res]/8: The program is ill-formed, no diagnostic required, if:

*

*no valid specialization can be generated for a template [...] and the template is not instantiated, or

[...]

(Writing static_assert(false, "You should not use this!"); above would thus be ill-formed and a compiler could always fire the static assert, even without the template being instantiated, which is not the intention.)
Here is a quick sampling of questions involving this pattern (including further explanation):

*

*Forbids functions with `static_assert`

*Are static_asserts to be evaluated if a member template isn't instantiated?

*Conditional compilation of templates
It might be useful to have always_false as a tool in the standard library so we don't have to constantly write it again. However, the answer to the following question makes me wonder whether this is even possible:
Dependent non-type parameter packs: what does the standard say?
There the argument is made (also with respect to [temp.res]/8) that std::enable_if_t<T> is always either void or not a type and that it is illegal for anyone to specialize it further. Therefore, a template that relies on the theoretical "specializability" of std::enable_if to avoid the [temp.res]/8 clause actually causes the program to be ill-formed, no diagnostic required.
Coming back to my question: If the standard provided always_false, it would have to forbid library users from specializing it as usual (for obvious reasons). But by the above reasoning, that would defeat the whole point of always_false (namely that it could theoretically be specialized to something other than std::false_type) - with respect to [temp.res]/8 it would be the same as using std::false_type directly.
Am I wrong in this reasoning? Or is it actually impossible for the standard library to provide always_false in a meaningful/useful way (without core language changes)?

A: All such attempts result in a program that is ill-formed, no diagnostic required.
The clauses that block you from using static_assert(false) make your program ill-formed, no diagnostic required based on the actual possibility of making an actual instantiation, not based on if the compiler can work it out.
These tricks simply make it harder for the compiler to detect the fact your program is ill-formed.  The diagnostic they issue is not required, and your ability to bypass the diagnostic being issued just means you made the compiler produce an ill-formed program for which the standard places no restrictions on its behavior.

(Writing static_assert(false, "You should not use this!"); above would thus be ill-formed and a compiler could always fire the static assert, even without the template being instantiated, which is not the intention.)

The exact same conclusion holds for your
template <class... T> struct always_false : std::false_type {};

template<class T>
struct UsingThisShouldBeAnError {
  static_assert(always_false<T>::value, "You should not use this!");
};

I claim there is no valid instantiation of UsingThisShouldBeAnError in the above program.
http://eel.is/c++draft/temp.res#6.1

The program is ill-formed, no diagnostic required, if:
(6.1) no valid specialization can be generated for a template [...]"

No valid specialization can be generated for this template.
To avoid this trap, your program must have
template <> struct always_false<SomeListOfTypes> : std::true_type {};

and if an always_false is specified in the standard for which this cannot occur, using always_false from the standard doesn't help you at all.
because the standard requires that the specialization "can be generated".
If the only way to instantiate your template is within an ill-formed program, then that is a huge stretch on the word "can".  So using reserved or magic types you aren't allowed to use within the true_type specialization is not really plausible.
Stepping back, the purpose of the "ill-formed, ndr" there is because the standard writers want to permit diagnostics of broken code, but don't want to mandate it.  Detecting such broken code in general is a halt-hard problem, but simple cases can be detected.  And optimizing around the assumption that the code isn't broken can be useful.
All attempts to inject static_assert(false, "message") are working around the intention that C++ code is intended to be valid.
We have a construct for a function for whom successful lookup is an error already in the language.
template<class T>
void should_never_be_found(tag<T>) = delete;

the hole, of course, is the lack of a diagnostic message here.
template<class T>
void should_never_be_found(tag<T>) = delete("Provide an custom ADL overload!");

also, the inability to =delete template specializations.
What you appear to want is:
template<class T>
struct UsingThisShouldBeAnError = delete("You should not use this");

which is direct, intentional, and consistent with how other =delete cases work.
The static_assert bypass requires magic and "tricking" the compiler to bypass parts of the standard explicitly written to prevent you from doing what you want to do.
This =delete("string") and =delete syntax on template classes is missing from the language.

A: In C++20, with lambda, you might do something like:
template <class... T> struct always_false : std::false_type {};

// To have true, but for a type that user code can't reuse as lambda types are unique.
template <> struct always_false<decltype([](){})> : std::true_type{};

After reflection, I think it is not possible: enclosing template might have other restrictions that the hypothetical type(s) for the specialization should fulfill:
With static_assert(is_enum_v<T> && always_false_v<T>), that type should be an enum.
And even more constrained, with static_assert(is_same_v<T, int> && always_false_v<T>), it is for int.

A: To paraphrase Jarod's idea, It could be something like
template <class... T> struct always_false : std::false_type {};

template <> struct always_false</* implementation defined */> : std::true_type{};

Where /* implementation defined */ can be filled by std::_ReservedIdentifer. User code can't access it, since the identifier is reserved to the library, but there exists a specialization that is true. That should avoid questions about the ODR and lambdas in specializations.

A: just use option -fdelayed-template-parsing


text:
Q: How to restrict anyone (Root user also) to modify file in Linux? I am developing one security base software for LINUX platform using C and CPP. I want to restrict all users even ROOT user also to modify the file. i.e No one can modify the file.
Modifying means No one can - write into the file, move the file or remove the file etc.

*

*More precisely ---
I have a file named as a.txt in directory /home/ and I want to do something to this file so that no one can write into this file , remove this file or move this file.
But can read the file.
I tried chattr command -

chattr +i /home/a.txt

It solved my problem for other users but when I switched to superuser i.e ROOT user into terminal and I fired command --

chattr -i /home/a.txt

So /home/a.txt file become mutable.
So ROOT user can change file immutable to mutable. So problem is not solved for ROOT user.
So I want to do something to this file, so even root user can't modify this file. I hope my question is clear to you all. I am trying for this from last one month, but didn't got anything. Any suggestion and solution is appreciated.

A: On a general purpose operating system, there is always a super user account that can ultimately do and undo anything (otherwise, you can't mitigate/clean a compromised system).

*

*The immutable attribute (chattr +i) is a good option to avoid mistake

*Mounting the filessytem as readonly is unpractical and ineffective (easy to undo)

*creating and using read-only filesystem is easy to override (overlay FS, or just use bind mount to another filesystem)

*Mandatory access control system (like SELinux) is the closest to what you want: a root shell in (staff role can't do perform some actions, but there's also a (sysadm role with more privileges)

*Even on the most paranoid system, the security will boil down to who have physical access to the system... to modify the kernel boot command like (this applies to Android devices)

A: A solution can be create a partition with luks that is encrypted with a password.
EDIT:
Another approach can be use IPFS to store the file.


text:
Q: how to get all information of wkt polygon when i click on it? I get the data from MSsql server 2012 in json format, i get just WKT string to convert for showing on the map using ol.format.WKT() .
I want to show the ID and the name of the polygon when i click, on popup.
How can i recognize in which polygon am i clicking?
How can i know the map in which polygon I click and get me the data of that polygon?
for (var i = 0; i < geometries.length; i++) {

    var feature = wktReader.readFeature(geometries[i].GeomCol1.Geometry.WellKnownText);

    feature.getGeometry().transform('EPSG:4326', 'EPSG:3857');

    if (feature.getGeometry().getType() == 'Polygon') {
        feature.setStyle(new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
            }),
            fill: new ol.style.Fill({
                color: 'rgba(0, 0, 255, 0.1)'
            })
       }));
       featureCollection.push(feature);
    }
}

this is a part how i get just wkt string.

These are the polygons that i have shown, and i want to show a popup with the informations of the polygon which i click

This is a picture of how i have stored the spatial data in my MSsql server
Thanks

A: forEachFeatureAtPixel (api doc) can get you all the features on a certain position. Admittedly, it can be confusing to use. The callback you pass to that function is called for every layer. If the callback returns a truthy value, it stops and then forEachFeatureAtPixel returns whatever your callback returned. This makes it perfect to select a specific feature.

var count = 2000;
var features = new Array(count);
var e = 4500000;
for (var i = 0; i < count; ++i) {
  var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
  features[i] = new ol.Feature({
    geometry: new ol.geom.Point(coordinates),
    myHappyAttribute: ('you are beautiful ' + i)
  });
}

var source = new ol.source.Vector({
  features: features
});

var layer = new ol.layer.Vector({source: source});

const view = new ol.View({
  center: [2500000, 0], zoom: 5
});
const map = new ol.Map({
  layers: [
    new ol.layer.Tile({
        source: new ol.source.OSM()
    }),
    layer
  ],
  target: 'map',
  view
});

map.on('singleclick', function(evt) {
  const pixel = map.getEventPixel(evt.originalEvent);
  const feature = map.forEachFeatureAtPixel(
    pixel,
    someFeature => someFeature, // return first element
    {
      hitTolerance: 2 // how far off the click can be
    }
  );
  if (feature) {
    const attr = feature.get('myHappyAttribute');
    console.log('clicked on feature with attr:', attr);
  } else {
    console.log('not clicked on a feature');
  }
});
<link href="https://openlayers.org/en/v4.6.5/css/ol.css" rel="stylesheet"/>


text:
Q: Brew error: Could not symlink, path is not writable When I try to install a library with homebrew (brew install aLibrary), I got the following error:
Could not symlink lib/pkgconfig/aFile
/usr/local/lib/pkgconfig is not writable.

What should I do?
There are several questions and answers (1,2,etc.) concerning this brew error, this is an attempt to make a general question as suggested here.

A: Use the following.
$ brew doctor

message will display error links to prune. If any found, run next option.
$ brew prune

once these are removed, proceed to link them agian
$ brew link python

A: I uninstalled brew, re-installed, then the issues went away.

A: You should simply give the permission to your account by running this command on terminal.
sudo chown -R $(whoami) (path)
In your case:
sudo chown -R $(whoami) lib/pkgconfig/aFile /usr/local/lib/pkgconfig

A: As explained here by Rick:
Start with brew doctor which will show you errors with your brew setup.
You might see something like this: "Warning: /usr/local/lib/pkgconfig isn't writable."
It will give you the advice that: "You should probably chown /usr/local/lib/pkgconfig".
This means:   sudo chown -R $(whoami) /usr/local/lib/pkgconfig
Then you will need to link the files with this: brew link yourLibrary
If this does not work hopefully the output of brew doctor will give you enough to continue the search.

A: Giant Elk had a great suggestion and this is how I fixed my issue, which in my opinion is the cleanest. Users should not change permissions unless they know the ramifications.

*

*Output your installed packages (via brew) to a text file:
brew list > brewlist.txt

*Uninstall brew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

*Re-install brew:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

*Re-install previous packages (edit list if you do not need all packages):
brew install $(< brewlist.txt )


text:
Q: R convert string to vector tokenize using " " I have a string :
string1 <- "This is my string"

I would like to convert it to a vector that looks like this:
vector1
"This"
"is"
"my"
"string"

How do I do this?  I know I could use the tm package to convert to termDocumentMatrix and then convert to a matrix but it would alphabetize the words and I need them to stay in the same order.

A: As a supplement, we can also use unlist() to produce a vector from a given list structure:
string1 <- "This is my string"  # get a list structure
unlist(strsplit(string1, "\\s+"))  # unlist the list
#[1] "This"   "is"     "my"     "string"

A: If you're simply extracting words by splitting on the spaces, here are a couple of nice alternatives.
string1 <- "This is my string"

scan(text = string1, what = "")
# [1] "This"   "is"     "my"     "string"

library(stringi)
stri_split_fixed(string1, " ")[[1]]
# [1] "This"   "is"     "my"     "string"
stri_extract_all_words(string1, simplify = TRUE)
#      [,1]   [,2] [,3] [,4]
# [1,] "This" "is" "my" "string"
stri_split_boundaries(string1, simplify = TRUE)
#      [,1]    [,2]  [,3]  [,4]
# [1,] "This " "is " "my " "string"

A: You can use strsplit to accomplish this task.
string1 <- "This is my string"
strsplit(string1, " ")[[1]]
#[1] "This"   "is"     "my"     "string"

A: Slightly different from Dason, but this will split for any amount of white space including newlines:
string1 <- "This   is my
string"
strsplit(string1, "\\s+")[[1]]

A: Try:
library(tm)
library("RWeka")
library(RWekajars)
NGramTokenizer(source1, Weka_control(min = 1, max = 1))

It is an over engineered solution for your problem. strsplit using Sacha's approach is generally just fine.


text:
Q: How can I connect webdriver to an instance of Edge on Android to run test scripts? When running msedgedriver --help I get the following output:
Usage: C:\Users\Ian\.bin\msedgedriver.exe [OPTIONS]

Options
  --port=PORT                     port to listen on
  --adb-port=PORT                 adb server port
  --log-path=FILE                 write server log to file instead of stderr, increases log level to INFO
  --log-level=LEVEL               set log level: ALL, DEBUG, INFO, WARNING, SEVERE, OFF
  --verbose                       log verbosely (equivalent to --log-level=ALL)
  --silent                        log nothing (equivalent to --log-level=OFF)
  --append-log                    append log file instead of rewriting
  --replayable                    (experimental) log verbosely and don't truncate long strings so that the log can be replayed.
  --version                       print the version number and exit
  --url-base                      base URL path prefix for commands, e.g. wd/url
  --readable-timestamp            add readable timestamps to log
  --enable-chrome-logs            show logs from the browser (overrides other logging options)
  --allowed-ips                   comma-separated allowlist of remote IP addresses which are allowed to connect to MSEdgeDriver

The --adb-port option suggests in can connect to an ADB server for debugging on Android.
I'm using the OpenQA Edge driver and trying to specify the ADB server port like this:
        // Initialize edge driver
        var options = new EdgeOptions
        {
            PageLoadStrategy = PageLoadStrategy.Normal
        };
        options.AddArgument("adb-server-port=5037");

        _driver = new EdgeDriver(options);

When I try to connect it opens a desktop browser instead. What am I missing?


text:
Q: Question about König's Theorem for bipartite graphs Does König's Theorem imply that the independence number of a bipartite graph is equal to the minimum number of cliques that cover all vertices?
König's Theorem states that the size of a maximum matching in a bipartite graph $G$ is equal to the size of a minimum vertex cover of $G$. I know that the complement of a minimum vertex cover is a maximum independent set, but is there a relationship between minimum number of cliques that cover all vertices and the size of a maximum matching?
It seems to me that for bipartite graphs, there can only be two-vertex cliques, and so a clique would be equivalent to a matching. Is this correct?

A: You're right about biparte graphs having at most $2$ vertices in a clique.
Proof:
Suppose that there is a clique of at least $3$ elements, $u_i$ ($i\in[3]$) then $u_1u_2u_3u_1$would be a cycle of odd length, which can't happen in biparte graphs.
Now, as you mentioned, there is an easy bijection between a matching $M\subseteq E(G)$ and $2$-cliques. However sometimes you need $1$-cliques to cover all the vertices, namely when $G$ doesn't have a perfect matching (e.g take $V=\{1,3\}\cup\{2\}$, $E=\{(1,2), (3,2)\}$). In general you can have an arbitrary amount of $1$-cliques needed to cover the vertices in a biparte graph.
Let the size of the minimum vertex covering be $\tau(G)$, the size of the maximum matching be $a_E(G)$, the minimum number of cliques that cover all vertices be $\theta(G)$ and the independence number be $a(G)$.
König tells us that $\tau(G) = a_E(G)$ and you mentioned that $\tau(G)+a(G) = |G|$. We noticed that $\theta(G) = a_E(G) + r(G)$, where $r(G)$ is the number of $1$-cliques in the minimum clique vertex cover.
Notice that $|G| - \theta(G) = a_E(G)$ (there are $2$ nodes for every $2$-clique and $1$ node for $1$-cliques, so the latter cancels out in the subtraction and we are left with the count of $2$-cliques). This equation uncovers the result
\begin{align}
|G| - \theta(G) = a_E(G) &\iff |G|-a_E(G) = \theta(G) \\
&\iff |G|-\tau(G) = \theta(G) \\
&\iff a(G) = \theta(G)
\end{align}


text:
Q: Using sprites within a div of 100% I am attempting to use sprites for the first time... It took a minute or two to wrap my head around it, but I got the basic implementation of it. However, I am attempting to use the sprite to replace

which you can see a live example of here. The problem I am having is I have a footer set up like so:
 footer{
    width: 100%;
    height: 11%;
    position: fixed
    bottom: 0px;
 }

And each image occupies a percentage width of the foot. For example,
.head{
   width: 18%
   height: 100%;
}

So that, as the browser window is made larger or smaller, the images scale with it... (Note: From 1150 pixels or larger then other media queries handle.)
Now I have figured out how to replace all the images in the footer with a single sprite.
Like so, just to make sure I do get it:
 /* html*/

 /*css */

 .moneda-logo, .logo_head_thumb, .Swix-logo-thumb, .scotiaMcleod, .POC-logo1,
 .alpine-canada-logo-thumb, .cowboy-logo, .Love, .maddy, .gray, .delsorbo, .bietz{
    background: url('https://s3.amazonaws.com/benjaminthomsen.images/sprites.png') no- repeat;
 }
.logo_head_thumb{
    background-position: 0 -210px ;
    width: 300px;
    height: 60px;
    padding-right: 100%;
    padding-bottom:16%;
}
#head-hover{
   float:left;
   height: 100%;
   width: 15.9%;
}

(A little tweaking still needed but more or less), but you can see my attempt thus far over here ... originally done with a footer width of 1920 pixles.
The problem is, as it scales down the width of each div, as it's a percentage also scales (div of width 300 pixels becomes 200 pixels, for example) and the total sprite image does not scale or fit in the new space.
Is there some easy way that I can have the new footer bar with sprites act like the one that is currently on the live site?
Without having to resize the sprite .png image along with rewriting all of the CSS within media queries every 20 or 30 pixels (as this is currently the only way I see possible) or perhaps there is a jQuery script that can be utilized or am I actually not grasping how to properly use sprites at all. I would really like to save the extra 14 or so HTTP requests that using a sprite would alleviate, but I don't care to modify the user interface of the current site.

A: Here is an example using inline-block (it could be shorterer achieved with table/table-cell):
ul , body{
  margin: 0;
  padding: 0;
}
img {width: 100%;}
ul {
  width: 100%;
  font-size: 0;}
ul:before {
  content: '';
  display: inline-block;
  padding-top: 5%;
  vertical-align: top;
}
li {
  display: inline-block;
  vertical-align: top;
  text-align: center;
  background-size: auto 100%;
  background: url(http://i.stack.imgur.com/2xDHJ.png);
}
li:before {
  content: '';
  display: inline-block;
  vertical-align: middle;
}
li a {
  display: inline-block;
  font-size: 32px;
  font-size: 2rem;
  vertical-align: middle;
  line-height: 5vw;
  height: 5vw;
  width: 8vw;
  /* To show them for tst */
  color: turquoise;
  text-shadow: 0 0 0.5em lime;
}
#sp1 {
  width:9%;
  background-size: auto 100%;
}
#sp1:before {
  padding-top: 59%;
}
#sp2 {
  width: 15%;
  background-size: auto 100%;
  background-position: 10.5% 0;
}
#sp2:before {
  padding-top: 35%;
}
#sp3 {
  width:17%;
  background-size: auto 100%;
  background-position: 29% 0;
}
#sp3:before {
  padding-top: 31%;
}
#sp4 {
  width: 15%;
  background-size: auto 100%;
  background-position: 48% 0;
}
#sp4:before {
  padding-top: 35%;
}
#sp5 {
  width: 19%;
  background-size: auto 100%;
  background-position: 69% 0;
}
#sp5:before {
  padding-top: 28%;
}
#sp6 {
  width: 14%;
  background-size: auto 100%;
  background-position: 88% 0;
}
#sp6:before {
  padding-top: 38%;
}
#sp7 {
  width:11%;
  background-size: auto 100%;
  background-position: 100% 0;
}
#sp7:before {
  padding-top: 48%;
}

See and play with result here :) - http://codepen.io/gc-nomade/pen/Hezro