text:
Q: How to parse the string to array I have following value in a table column is there any option to get the sandbox value and merchant_email like array ? I know using explode and loop is works but any other smart options
 ?
something like $result->sandbox
 paypal_merchant_email="sample@ymail.com"|paypal_verified_only="0"|payment_currency=""|sandbox="1"|sandbox_merchant_email="sample@ymail.com"|payment_logos=""|debug="0"|status_pending="W"|status_success="O"|status_canceled="D"|countries=""|min_amount="0"|max_amount="0"|secure_post=""|ipn_test=""|no_shipping="0"|address_override="0"|cost_per_transaction="0"|cost_percent_total="0"|tax_id=0|

Thanks in advance!

A: $string = 'paypal_merchant_email="sample@ymail.com"|paypal_verified_only="0"|payment_currency=""|sandbox="1"|sandbox_merchant_email="sample@ymail.com"|payment_logos=""|debug="0"|status_pending="W"|status_success="O"|status_canceled="D"|countries=""|min_amount="0"|max_amount="0"|secure_post=""|ipn_test=""|no_shipping="0"|address_override="0"|cost_per_transaction="0"|cost_percent_total="0"|tax_id=0|';

$result = array();
$string = preg_split('/\|/', $string);
foreach($string as $key => $value)
{
    $value = str_replace('"', '', $value);
    $value = preg_split('/=/', $value);
    if(strlen($value[0])> 0)
    {
       $result[$value[0]] = array_key_exists(1, $value) ? $value[1] : NULL;
    }
}

echo "<pre>";
print_r($result);
echo "</pre>";

Output
Array
(
    [paypal_merchant_email] => sample@ymail.com
    [paypal_verified_only] => 0
    [payment_currency] =>
    [sandbox] => 1
    [sandbox_merchant_email] => sample@ymail.com
    [payment_logos] =>
    [debug] => 0
    [status_pending] => W
    [status_success] => O
    [status_canceled] => D
    [countries] =>
    [min_amount] => 0
    [max_amount] => 0
    [secure_post] =>
    [ipn_test] =>
    [no_shipping] => 0
    [address_override] => 0
    [cost_per_transaction] => 0
    [cost_percent_total] => 0
    [tax_id] => 0
    [] =>
)

A: Little benchmark magic:
<?php
// explode
$start = microtime(TRUE);
$data = array();
foreach (explode('|', $result->sandbox) as $item)
{
    if (empty($item)) continue;
    list($key, $value) = explode("=", $item);
    $data[$key] = str_replace('"', '', $value);
}
print_r($data);
$stop = microtime(TRUE);
$timeResult = $stop - $start;
echo $timeResult, "\n";

//preg_split
$start = microtime(TRUE);
$data = array();
foreach (preg_split('/\|/', $result->sandbox) as $item)
{
    if (empty($item)) continue;
    list($key, $value) = preg_split('/=/', $item);
    $data[$key] = str_replace('"', '', $value);
}
print_r($data);
$stop = microtime(TRUE);
$timeResult = $stop - $start;
echo $timeResult, "\n";

//preg_match_all
$start = microtime(TRUE);
$data = array();
preg_match_all('/([^=]+)="([^"]+)?"\|/', $result->sandbox, $result);
$data = array_combine($result[1], $result[2]);
print_r($data);
$stop = microtime(TRUE);
$timeResult = $stop - $start;
echo $timeResult, "\n";

Result:
Array
(
    [paypal_merchant_email] => sample@ymail.com
    [paypal_verified_only] => 0
    [payment_currency] =>
    [sandbox] => 1
    [sandbox_merchant_email] => sample@ymail.com
    [payment_logos] =>
    [debug] => 0
    [status_pending] => W
    [status_success] => O
    [status_canceled] => D
    [countries] =>
    [min_amount] => 0
    [max_amount] => 0
    [secure_post] =>
    [ipn_test] =>
    [no_shipping] => 0
    [address_override] => 0
    [cost_per_transaction] => 0
    [cost_percent_total] => 0
    [tax_id] => 0
)
0.00029397010803223

Array
(
    [paypal_merchant_email] => sample@ymail.com
    [paypal_verified_only] => 0
    [payment_currency] =>
    [sandbox] => 1
    [sandbox_merchant_email] => sample@ymail.com
    [payment_logos] =>
    [debug] => 0
    [status_pending] => W
    [status_success] => O
    [status_canceled] => D
    [countries] =>
    [min_amount] => 0
    [max_amount] => 0
    [secure_post] =>
    [ipn_test] =>
    [no_shipping] => 0
    [address_override] => 0
    [cost_per_transaction] => 0
    [cost_percent_total] => 0
    [tax_id] => 0
)
0.00031495094299316

Another:
Array
(
    [paypal_merchant_email] => sample@ymail.com
    [paypal_verified_only] => 0
    [payment_currency] =>
    [sandbox] => 1
    [sandbox_merchant_email] => sample@ymail.com
    [payment_logos] =>
    [debug] => 0
    [status_pending] => W
    [status_success] => O
    [status_canceled] => D
    [countries] =>
    [min_amount] => 0
    [max_amount] => 0
    [secure_post] =>
    [ipn_test] =>
    [no_shipping] => 0
    [address_override] => 0
    [cost_per_transaction] => 0
    [cost_percent_total] => 0
    [tax_id] => 0
)
0.00026917457580566

Array
(
    [paypal_merchant_email] => sample@ymail.com
    [paypal_verified_only] => 0
    [payment_currency] =>
    [sandbox] => 1
    [sandbox_merchant_email] => sample@ymail.com
    [payment_logos] =>
    [debug] => 0
    [status_pending] => W
    [status_success] => O
    [status_canceled] => D
    [countries] =>
    [min_amount] => 0
    [max_amount] => 0
    [secure_post] =>
    [ipn_test] =>
    [no_shipping] => 0
    [address_override] => 0
    [cost_per_transaction] => 0
    [cost_percent_total] => 0
    [tax_id] => 0
)
0.00028419494628906

A: There is a function parse_str() but it is for & delimiter:
http://php.net/manual/en/function.parse-str.php
Or you can impress somebody with knowledge or PHP functions:
$str = 'a=13|b="string"|';

$rawarray = preg_split('/\|/', $str, -1, PREG_SPLIT_NO_EMPTY);
$keys = array_map(create_function('$a', '$r = preg_split("/=/", $a); return $r[0];'), $rawarray);
$values = array_map(create_function('$a', '$r = preg_split("/=/", $a, 2); return eval("return $r[1];");'), $rawarray);
$result = array_combine($keys, $values);

print_r($result);

A: If you need just one or two values, use regular expressions:
function get_value_from_string($key, $str) {
    return preg_match('/\|'.$key.'=([^\|]*)/', '|'.$str, $matches) ? eval("return $matches[1];") : null;
}

A: Here's possibly a more elegant solution using str_getcsv, array_walk, use, parse_str and the venerable each (to extract the key / value pairs). With your data:
$string = 'paypal_merchant_email="sample@ymail.com"|paypal_verified_only="0"|payment_currency=""|sandbox="1"|sandbox_merchant_email="sample@ymail.com"|payment_logos=""|debug="0"|status_pending="W"|status_success="O"|status_canceled="D"|countries=""|min_amount="0"|max_amount="0"|secure_post=""|ipn_test=""|no_shipping="0"|address_override="0"|cost_per_transaction="0"|cost_percent_total="0"|tax_id=0|';

Idea is to first use str_getcsv to parse the |-separated line, then traverse it using fast PHP functions.
$t = str_getcsv( $string, "|" );

At this point, $t is a simple array containing broken up "key=value" pairs.
$new = array();
array_walk( $t, function( &$a ) use (&$new) {
    parse_str( $a, $b);            # parses each line, returns key-value
    $c = each( $b );               # need to obtain key-value from above
    $new[$c["key"]] = $c["value"]; # simple assignment
});

This requires PHP > 5.3.0 since it uses namespaces (use) in the anonymous function. However, if you made it this far,
print_r( $new ); gives you this:
Array (
    [paypal_merchant_email] => "sample@ymail.com"
    [paypal_verified_only] => "0"
    [payment_currency] => ""
    ...

A: Here is the very compact solution for you:
preg_match_all('/\|(.*?)="(.*?)"/', '|'.$string, $matches);
$result = array_combine($matches[1], $matches[2]);

Test it here: https://3v4l.org/rfBuc


text:
Q: How to navigate (ctrl+click) to .env and config/file.php from env() and config() helpers respectively* I'm using VS Code on Windows 10 (WSL 2.0: Ubuntu) with the Intelephense extension for PHP.
Navigating between classes, methods, properties, functions, and variables works exactly as one would expect ie. Ctrl+click navigates to the declaration of the said construct.
I'm looking for an extension or any other way integrated into VS Code, that would achieve the same functionality for env() and config() helpers.
Let's say I have the following code:
$middleware = new OAuthGuzzleMiddleware(
    client: new Client([
        'base_uri' => config('keycloak.url')
            . '/auth/admin/realms/' . config('keycloak.realm'),
        'verify' => config('keycloak.verify_ssl'),
    ]),
    cache: $this->app->make('cache')->store(),
    tokenUrl: config('keycloak.jwks_url'), // Example will follow from this line
    clientId: config('keycloak.client_id'),
    clientSecret: config('keycloak.client_secret'),
);

I would like to be able to Ctrl+click on keycloak.jwks_url in config('keycloak.jwks_url') so I would find myself in /config/keycloak.php on line with:
'jwks_url' => env('KEYCLOAK_JWKS_URL'),

Then Ctrl+click on KEYCLOAK_JWKS_URL would navigate to /.env to line with:
KEYCLOAK_JWKS_URL="${KEYCLOAK_URL}auth/realms/${KEYCLOAK_REALM_NAME}/protocol/openid-connect/certs"

In the first part, it would of course be even better if I could Ctrl+click on keycloak and jwks_url separately, where the first would navigate to the top of the file and the second the same as above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL insert_id always returns zero I'm working on editing an old project from php 5.3 to php 7+.
Unpleasant work, but I have to do it with minimal changes to the code.
I came across the following problem.
The insert_id always returns 0.
I have read that this may be because I do not have an auto_increment key on the table or the last query wasn't an INSERT or UPDATE statement but my problem is not due to this. The request successfully inputs information into the database.
This is the code:
class DBTable{

 function connection(){
    $mysqli = new mysqli('localhost', 'username', 'pass', 'db');

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    if (!$mysqli->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
    }
    return $mysqli;
  }

  function addrow_id($row){
    $query="some INSERT query";
    $res = $this->connection()->query($query);
    if ($res) $response = $this->connection()->insert_id; //always returns zero
    return $response;
  }
}

I am quite aware that this is not a good PHP but I can not start the project from a new one and my task is just to do it to work with PHP 7+

A: $this->connection() returns a new connection every time. Insert ids are specific to the connection, otherwise you'd get interference from parallel clients. You need to reuse your connection object:
$query="some INSERT query";
$con = $this->connection();
$res = $con->query($query);
if ($res) $response = $con->insert_id;

Preferably you'd do $this->con = $this->connection() once in __construct and reuse the same connection throughout your object; or, better, you inject one connection you have established globally as dependency when instantiating your object:
$con = new mysqli(...);
$db = new DBTable($con);

Otherwise you have a lot of overhead establishing and tearing down connections constantly. Not to mention testability and so on with a hardcoded connection.

A: I directly used the code from your post, though the answer above is great too.

<?php
class DBTable{
  private $dbcon;

  function __construct() {  //this constructor is called when you do $var = new DBTable() to instantiate your object

    //create the connection and assign it to the dbcon var
    $this->dbcon = new mysqli('localhost', 'username', 'password', 'db');

    //throw connection error and die
    if ($this->dbcon->connect_error) {
        printf("Connect failed: %s\n", $this->$dbcon->connect_error);
        exit();
    }

    //throw mysql error and die
    if (!$this->dbcon->set_charset("utf8")) {
        printf("Error loading character set utf8: %s\n", $this->$dbcon->error);
        exit();
    }
  }

  //I add a row and return an ID
  function addrow_id(){
    //create your query string
    $query="INSERT INTO TEST() VALUES()";
    //run the query
    $res = $this->dbcon->query($query);
    if ($res){  //if this value evaluates to zero, we want to throw an error
      $response = $this->dbcon->insert_id;
    } else {  //throw an error, because the query came back with a negative val
      $error = 'When adding a row, I got no results or a value that php interpolates as negative';
      throw new Exception($error);
    }
    //return the new id
    return $response;
  }
}
//instantiate your object/class
$dbTable = new DBTable();
//dump the outcome of your adding a row
var_dump($dbTable->addrow_id());
?>


text:
Q: Refresh image after JSlider is used to change image I have a program which will change threshold in a img but i do not know how to refresh image. It will create two JFrame windows one for slider and one for image. I do get value from a slider to go to threshold. But how do I Refresh changed image. Sorry for posting whole code but I can't figure this out.
import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;

import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;

import java.awt.image.BufferedImage;
import  java.awt.image.DataBufferByte;
import java.lang.Math;
import java.util.ArrayList;
import java.util.List;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.CvType;
import org.opencv.core.MatOfDouble;

public class Draw extends JFrame{

    JSlider slider;
    JLabel label;
    JLabel test1;
    int Actual;
    int value = 100;
    public Draw(){

        setLayout(new FlowLayout());

        slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 100);
        add(slider);

        label = new JLabel();
        add(label);

        test1 = new JLabel();
        add(test1);

        event e = new event();
        slider.addChangeListener(e);

    }
     public class event implements ChangeListener {

         public void stateChanged(ChangeEvent e){
              value = slider.getValue();
              label.setText("Current Value " + value);

         }
     }

     public static void main(String agrs[]){

         System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
         Draw sl = new Draw();
         sl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         sl.setSize(300,100);
         sl.setVisible(true);
         sl.setTitle("Slider Bar");
         sl.converter();
         sl.repaint();
         sl.revalidate();

     }

 public void converter(){

         Mat imageInMat = Imgcodecs.imread("C:/Users/ja/workspace/imgtomath/bin/imgtomath/bowl.jpg",0);
         if(imageInMat.empty()== true)
             {System.out.println("Error no image found!!");}
         else
             System.out.println("Image loaded");

         Mat thresh = new Mat();
        Imgproc.threshold(imageInMat, thresh, value, 250, Imgproc.THRESH_BINARY_INV);

        BufferedImage bufImage = Mat2BufferedImage(thresh);
        displayImage(bufImage);
        }

 public BufferedImage Mat2BufferedImage(Mat m){
        //source: http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui/
        //Fastest code
        //The output can be assigned either to a BufferedImage or to an Image

         int type = BufferedImage.TYPE_BYTE_GRAY;
         if ( m.channels() > 1 ) {
             type = BufferedImage.TYPE_3BYTE_BGR;
         }
         int bufferSize = m.channels()*m.cols()*m.rows();
         byte [] b = new byte[bufferSize];
         m.get(0,0,b); // get all the pixels
         BufferedImage image = new BufferedImage(m.cols(),m.rows(), type);
         final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
         System.arraycopy(b, 0, targetPixels, 0, b.length);
         return image;
        }

 public void displayImage(Image img2)
    {
    //BufferedImage img=ImageIO.read(new File("/HelloOpenCV/lena.png"));
    ImageIcon icon=new ImageIcon(img2);
    JFrame frame=new JFrame();

    frame.setLayout(new FlowLayout());

    frame.setSize(img2.getWidth(null)+50, img2.getHeight(null)+50);

    JLabel lbl=new JLabel();
    lbl.setIcon(icon);
    frame.add(lbl);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

A: I understand that the problem is that if you call converter() from stateChanged(), it will create a new JFrame every time you change the value on the slider?
Here's a simple proposal to prevent that:
stateChanged:
public void stateChanged(ChangeEvent e){
  value = slider.getValue();
  label.setText("Current Value " + value);
  converter();
}

displayImage:
 private JFrame frame = new JFrame("Image JFrame");
 JLabel lbl = null;

 public void displayImage(Image img2){

    if(lbl==null){
       lbl = new JLabel();

       frame.setLayout(new FlowLayout());
       frame.setSize(img2.getWidth(null)+50, img2.getHeight(null)+50);

       frame.add(lbl);
       frame.setVisible(true);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    ImageIcon icon=new ImageIcon(img2);
    lbl.setIcon(icon);

}

Also: You should create your Swing components on the Event thread from your main method, as described in: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html


text:
Q: Sending data / payload to the Google Chrome Push Notification with Javascript I'm working on the Google Chrome Push Notification and I'm trying to send the payload to the google chrome worker but, I have no idea how I receive this payload.
I have an API to create and save the notifications in my database and I need send the values through the https://android.googleapis.com/gcm/send and receive on the worker.js
This is my worker.js
    self.addEventListener('push', function(event) {
      var title = 'Yay a message.';
      var body = 'We have received a push message.';
      var icon = '/images/icon-192x192.png';
      var tag = 'simple-push-demo-notification-tag';

      event.waitUntil(
        self.registration.showNotification(title, {
          body: body,
          icon: icon,
          tag: tag
        })
      );
    });

And this is how I'm calling the GCM
curl --header "Authorization: key=AIzaSyDQjYDxeS9MM0LcJm3oR6B7MU7Ad2x2Vqc" --header  "Content-Type: application/json" https://android.googleapis.com/gcm/send -d "{ \"data\":{\"foo\":\"bar\"}, \"registration_ids\":[\"APA91bGqJpCmyCnSHLjY6STaBQEumz3eFY9r-2CHTtbsUMzBttq0crU3nEXzzU9TxNpsYeFmjA27urSaszKtA0WWC3yez1hhneLjbwJqlRdc_Yj1EiqLHluVwHB6V4FNdXdKb_gc_-7rbkYkypI3MtHpEaJbWsj6M5Pgs4nKqQ2R-WNho82mnRU\"]}"

I tried to get event.data but, this is undefined.
Does anyone have any idea or sugestion?

A: I just ran into this problem. Newer versions of firefox and chrome( version 50+) support payload transferring. The dev docs here details the implementation on how this works. An important thing to note is that google GCM or possibly client/chome (I dont know which one) will actually ignore the payload entirely if it is not encrypted.
This website has both client/server implementations of how to do the push and retrieval through service workers. The push library that examples use is merely a wrapper around a normal REST call
service worker example implementation:
self.addEventListener('push', function(event) {
var payload = event.data ? event.data.text() : 'no payload';

event.waitUntil(
   self.registration.showNotification('ServiceWorker Cookbook', {
     body: payload,
   })
 );
});

Server example implementation:
var webPush = require('web-push');

webPush.setGCMAPIKey(process.env.GCM_API_KEY);

module.exports = function(app, route) {
 app.post(route + 'register', function(req, res) {
 res.sendStatus(201);
});

app.post(route + 'sendNotification', function(req, res) {
  setTimeout(function() {
   webPush.sendNotification(req.body.endpoint, {
     TTL: req.body.ttl,
     payload: req.body.payload,
     userPublicKey: req.body.key,
     userAuth: req.body.authSecret,
   }).then(function() {
    res.sendStatus(201);
   });
  }, req.body.delay * 1000);
 });
};

Client side javascript implementation example of printing out the the required fields.
navigator.serviceWorker.register('serviceWorker.js')
.then(function(registration) {

    return registration.pushManager.getSubscription()
        .then(function(subscription) {
            if (subscription) {
                return subscription;
            }
            return registration.pushManager.subscribe({
                userVisibleOnly: true
            });
        });
}).then(function(subscription) {
    var rawKey = subscription.getKey ? subscription.getKey('p256dh') : '';
    key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : '';
    var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : '';
    authSecret = rawAuthSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : '';
    endpoint = subscription.endpoint;
    console.log("Endpoint: " + endpoint);
    console.log("Key: " + key);
    console.log("AuthSecret: " + authSecret);
});

A: Unfortunately it seems like an intended behavior:

A downside to the current implementation of the Push API in Chrome is
  that you can't send a payload with a push message. Nope, nothing. The
  reason for this is that in a future implementation, payload will have
  to be encrypted on your server before it's sent to a push messaging
  endpoint. This way the endpoint, whatever push provider it is, will
  not be able to easily view the content of the push payload. This also
  protects against other vulnerabilities like poor validation of HTTPS
  certificates and man-in-the-middle attacks between your server and the
  push provider. However, this encryption isn't supported yet, so in the
  meantime you'll need to perform a fetch request to get information
  needed to populate a notification.

As stated above, the workaround is to contact back your backend after receiving the push and fetch the stored data on the 3rd party server.

A: To retrieve that data, you need to parse "event.data.text()" to a JSON object. I'm guessing something was updated since you tried to get this to work, but it works now. Unlucky!
However, since I made it to this post when searching for a solution myself, others would probably like a working answer. Here it is:
// Push message event handler
self.addEventListener('push', function(event) {

  // If true, the event holds data
  if(event.data){

    // Need to parse to JSON format
    // - Consider event.data.text() the "stringify()"
    //   version of the data
    var payload = JSON.parse(event.data.text());
    // For those of you who love logging
    console.log(payload);

    var title = payload.data.title;
    var body  = payload.data.body;
    var icon  = './assets/icons/icon.ico'
    var tag   = 'notification-tag';

    // Wait until payload is fetched
    event.waitUntil(
      self.registration.showNotification(title, {
        body: body,
        icon: icon,
        tag: tag,
        data: {} // Keeping this here in case I need it later
      })
    );

  } else {
    console.log("Event does not have data...");
  }

}); // End push listener

// Notification Click event
self.addEventListener('notificationclick', function(event) {
  console.log("Notification Clicked");
}); // End click listener

Personally, I will be creating a "generic" notification in case my data is funky, and will also be using try/catch. I suggest doing the same.

A: @gauchofunky's answer is correct. With some guidance from the folks on the Chromium dev slack channel and @gauchofunky I was able to piece something together. Here's how to work around the current limitations; hopefully my answer becomes obsolete soon!
First figure out how you're going to persist notifications on your backend. I'm using Node/Express and MongoDB with Mongoose and my schema looks like this:
var NotificationSchema = new Schema({
  _user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  subscriptionId: String,
  title: String,
  body: String,
  sent: { type: Boolean, default: false }
});

Be sure to add an icon if you'd like to alter the icon. I use the same icon every time so mine's hardcoded in the service worker.
Figuring out the correct REST web service took some thought. GET seemed like an easy choice but the call to get a notification causes side effects, so GET is out. I ended up going with a POST to /api/notifications with a body of {subscriptionId: <SUBSCRIPTION_ID>}. Within the method we basically perform a dequeue:
var subscriptionId = req.body.subscriptionId;

Notification
.findOne({_user: req.user, subscriptionId: subscriptionId, sent: false})
.exec(function(err, notification) {
  if(err) { return handleError(res, err); }
  notification.sent = true;
  notification.save(function(err) {
    if(err) { return handleError(res, err); }
    return res.status(201).json(notification);
  });
});

In the service worker we need to for sure get the subscription before we make the fetch.
self.addEventListener('push', function(event) {
  event.waitUntil(
    self.registration.pushManager.getSubscription().then(function(subscription) {
      fetch('/api/notifications/', {
        method: 'post',
        headers: {
          'Authorization': 'Bearer ' + self.token,
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(subscription)
      })
      .then(function(response) { return response.json(); })
      .then(function(data) {
        self.registration.showNotification(data.title, {
          body: data.body,
          icon: 'favicon-196x196.png'
        });
      })
      .catch(function(err) {
        console.log('err');
        console.log(err);
      });
    })
  );
});

It's also worth noting that the subscription object changed from Chrome 43 to Chrome 45. In Chrome 45 the subscriptionId property was removed, just something to look out for - this code was written to work with Chrome 43.
I wanted to make authenticated calls to my backend so I needed to figure out how to get the JWT from my Angular application to my service worker. I ended up using postMessage. Here's what I do after registering the service worker:
navigator.serviceWorker.register('/service-worker.js', {scope:'./'}).then(function(reg) {
  var messenger = reg.installing || navigator.serviceWorker.controller;
  messenger.postMessage({token: $localStorage.token});
}).catch(function(err) {
  console.log('err');
  console.log(err);
});

In the service worker listen for the message:
self.onmessage.addEventListener('message', function(event) {
  self.token = event.data.token;
});

Strangely enough, that listener works in Chrome 43 but not Chrome 45. Chrome 45 works with a handler like this:
self.addEventListener('message', function(event) {
  self.token = event.data.token;
});

Right now push notifications take quite a bit of work to get something useful going - I'm really looking forward to payloads!

A: Actually, payload should be implemented in Chrome 50 (release date - April 19, 2016). In Chrome 50 (and in the current version of Firefox on desktop) you can send some arbitrary data along with the push so that the client can avoid making the extra request. All payload data must be encrypted.
Here is the the encryption details from developer : https://developers.google.com/web/updates/2016/03/web-push-encryption?hl=en

A: Follow these steps to achieve this:
In the browser:
You need to get the subscription object and save it, so your server has access to it: Read more about it
navigator.serviceWorker.ready.then(serviceWorkerRegistration => {
            serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
              .then(subscription => {
                  //save subscription.toJSON() object to your server
    })});

In the server:
install web-push npm package
And send a web push like this:
    const webpush = require('web-push');

    setImmediate(async () => {

      const params = {
        payload: {title: 'Hey', body: 'Hello World'}
      };
      //this is the subscription object you should get in the browser. This is a demo of how it should look like
      const subscription = {"endpoint":"https://android.googleapis.com/gcm/send/deC24xZL8z4:APA91bE9ZWs2KvLdo71NGYvBHGX6ZO4FFIQCppMsZhiTXtM1S2SlAqoOPNxzLlPye4ieL2ulzzSvPue-dGFBszDcFbSkfb_VhleiJgXRA8UwgLn5Z20_77WroZ1LofWQ22g6bpIGmg2JwYAqjeca_gzrZi3XUpcWHfw","expirationTime":null,"keys":{"p256dh":"BG55fZ3zZq7Cd20vVouPXeVic9-3pa7RhcR5g3kRb13MyJyghTY86IO_IToVKdBmk_2kA9znmbqvd0-o8U1FfA3M","auth":"1gNTE1wddcuF3FUPryGTZOA"}};

      if (subscription.keys) {
        params.userPublicKey = subscription.keys.p256dh;
        params.userAuth      = subscription.keys.auth;
      }

// this key you should take from firebase console for example
// settings -> cloud messaging -> Server key
webpush.setGCMAPIKey('AAAASwYmslc:APfA91bGy3tdKvuq90eOvz4AoUm6uPtbqZktZ9dAnElrlH4gglUiuvereTJJWxz8_dANEQciX9legijnJrxvlapI84bno4icD2D0cdVX3_XBOuW3aWrpoqsoxLDTdth86CjkDD4JhqRzxV7RrDXQZd_sZAOpC6f32nbA');

      try {
        const r = await webpush.sendNotification(subscription, JSON.stringify(params));
        console.log(r);
      }
      catch (e) {
        console.error(e);
      }
    });


text:
Q: How do I turn my CSV formatting into a automatic "drag & drop" BAT file? I'm outputting raw EDL files from Avid Media Composer which is essentially just text that needs re-formatting into the appropriate columns so it's easy to digest for the person receiving it. For security reasons the machines we use do not have internet connection so I'm trying to understand how I can achieve this without the use of third party tools or websites from the net.
The Raw .EDL file when opened in Notepad looks like this:

It's basically just a summary of the cuts used on the timeline and a the In/Out source and destination time codes involved. The example above is very small in size as a full EDL can have up to 1000 cuts (each numbered line being a cut).
I managed to format this manually with the use of comma separators. I achieved this by adding comma's and quotations so it looks like so:

The end result when importing this into Excel is this:

I've also been trying to explore the idea of using Powershell by using Get-Content to try and parse the data i need into specific rows/columns but I'm a complete novice in this field so I'm not sure what i'm doing:
$Content = Get-Content "C:\TEST EDIT DECISION LIST.EDL"
$Content | Foreach {

If ($_ -match '[0-9]{1,6}$')

So i've managed to have Get-Content read the EDL file and the text within is retrieved fine. I then tried to apply the match operator to get it to identify the 6 digit numerical (000001) and the goal is to figure out how to send that to column 1 row 1 (but it doesn't want to run). I then need to get the operator to identify the next entry (GUIDE_VO) which would be alpha-numeric-symbolic with a maximum 32 character limit etc, so as to adhere to the formatting I've created manually for the rest of the line. I would need Powershell to rinse and repeat process this through every line in the EDL and compile a CSV for me.
My question is, how would I go about getting this EDL file to output to the CSV as per the manual formatting I've done? I'd like to make this possible a with a "drag and drop" bat file or similar workflow. The entries that appear in the raw edl are always in that specific order, with only the clip names and source files varying in what they say throughout all the data. The entry numbers also incrementally go up with every new line of data as well.
This is the raw text from the EDL File itself:
TITLE:   Untitled Sequence.01
000001  GUIDE_VO                         A     C        12:36:54:21 12:37:06:19 01:00:00:00 01:00:11:23
*FROM CLIP NAME:  SFX CLIP 1
*SOURCE FILE: GUIDE VO
000002  HORROR.COPY.01.MP3               A     C        01:00:00:00 01:00:22:10 01:00:11:23 01:00:34:08
*FROM CLIP NAME:  SFX CLIP 2
*SOURCE FILE: HORROR.COPY.01.MP3
000003  93_HORROR_DRONE.MP3              A     C        01:00:04:15 01:00:08:08 01:00:34:08 01:00:38:01
*FROM CLIP NAME:  SFX CLIP 3
*SOURCE FILE: 93 HORROR DRONE.MP3

Many Thanks in Advance for any help or suggestions from this amazing community!

A: *

*Ctrl+H

*Find what: ^(\S+)\h+(\S+)\h+(\S+)\h+(\S+)\h+(\S+)\h+(\S+)\h+(\S+)\h+(\S+)\h+\R\*FROM CLIP NAME:\h*(.+?)\h*\R.+

*Replace with: $1,$2,$4,$3,$5,$6,$7,$8,"$9"

*check Wrap around

*check Regular expression

*UNCHECK . matches newline

*Replace all
Explanation:
^               # beginning of line
    (\S+)\h+    # group 1, 1 or more non spaces, then 1 or more horizontal spaces
    (\S+)\h+    # group 2, idem
    ...         # idem until
    (\S+)\h+    # group 8
    \R          # any kind of linebreak
    \*          # asterisk
    FROM CLIP NAME:\h*  # literally FROM CLIP NAME: followed by 0 or more horizontal spaces
    (.+?)       # group 9, 1 or more any character but newline, not greeedy
    \h*         # 0 or more horizontal spaces
    \R          # any kind of linebreak
    .+          # 1 or more any character but newline

Replacement:
$1,                 # content of group 1 plus a comma
$2,                 # content of group 2 plus a comma
$4,$3,$5,$6,$7,$8,  # idem
"$9"                # content of group 9 surounded by double quote

Result for given example:
TITLE:   Untitled Sequence.01
000001,GUIDE_VO,C,A,12:36:54:21,12:37:06:19,01:00:00:00,01:00:11:23,"SFX CLIP 1"
000002,HORROR.COPY.01.MP3,C,A,01:00:00:00,01:00:22:10,01:00:11:23,01:00:34:08,"SFX CLIP 2"
000003,93_HORROR_DRONE.MP3,C,A,01:00:04:15,01:00:08:08,01:00:34:08,01:00:38:01,"SFX CLIP 3"

A: if your source is
000001  GUIDE_VO                         A     C        12:36:54:21 12:37:06:19 01:00:00:00 01:00:11:23
*FROM CLIP NAME:  SFX CLIP 1
*SOURCE FILE: GUIDE VO
000002  HORROR.COPY.01.MP3               A     C        01:00:00:00 01:00:22:10 01:00:11:23 01:00:34:08
*FROM CLIP NAME:  SFX CLIP 2
*SOURCE FILE: HORROR.COPY.01.MP3
000003  93_HORROR_DRONE.MP3              A     C        01:00:04:15 01:00:08:08 01:00:34:08 01:00:38:01
*FROM CLIP NAME:  SFX CLIP 3
*SOURCE FILE: 93 HORROR DRONE.MP3

you could apply
mlr --skip-comments-with "*" --inidx --ifs ' ' --ocsv --repifs cat inputFile.txt

and have
1,2,3,4,5,6,7,8
000001,GUIDE_VO,A,C,12:36:54:21,12:37:06:19,01:00:00:00,01:00:11:23
000002,HORROR.COPY.01.MP3,A,C,01:00:00:00,01:00:22:10,01:00:11:23,01:00:34:08
000003,93_HORROR_DRONE.MP3,A,C,01:00:04:15,01:00:08:08,01:00:34:08,01:00:38:01

mlr is an opensource utility, also fow Windows, and you can run it via prompt. The last win exe is here (mlr.exe) https://github.com/johnkerl/miller/releases/tag/5.4.0


text:
Q: Using the built in dynamic values I have written an extension to generate a custom authentication string (getting it to actually work would improve our team's performance significantly).
The issue: our custom authentication string requires a HMAC to be computed, which also requires an MD5 hash. I tried requiring modules in a Nodejs fashion but it does not work. I noticed that the HMAC and MD5 functions I need are already built-in in the application.
The question: Is there any way to re-use the built in functions in custom extensions? - Having this possibility would make the whole process so much easier.
If the above is not possible; how could I do something like: var crypto = require('crypto'); in order to use Nodejs' default cryptography module?
Any feedback would be highly appreciated.

A: Yeah there's a way to create and compute dynamic values from the JavaScript code, but it isn't documented yet. Here are the 2 functions you need implemented using dynamic values:
function hmac(key, input){
  return DynamicValue('com.luckymarmot.HMACDynamicValue', {
    algorithm: 0, // for HMAC-MD5
    input: input,
    key: key
  }).getEvaluatedString();
};

function md5(input){
  return DynamicValue('com.luckymarmot.HashDynamicValue', {
    hashType: 2, // for MD5
    input: input
  }).getEvaluatedString();
};

And and example of use in a custom dynamic value:
function evaluate(context){
  var a = md5("MyStringToHash");
  var b = hmac("MyHMACKey", "String to sign");
  return a + ':' + b;
};

A: For the time being, I managed to decode the base64 and re-encode it to hex, this is not the cleanest way of doing this, but until extra features are made available this might help people with similar issues. The AuthenticationHeaderDynamicValue function can be adjusted to do whatever you need it to do.
(function() {

var request,
    url,
    md5 = function (input) {
        return DynamicValue('com.luckymarmot.HashDynamicValue', {
            hashType: 2,
            input: input
        }).getEvaluatedString();
    },
    hmac = function (key, input) {
        return DynamicValue('com.luckymarmot.HMACDynamicValue', {
            algorithm: 3,
            input: input,
            key: key
        }).getEvaluatedString();
    },
    base64Decode = function (input) {
        var a,
            b = 0,
            c,
            e = {},
            loop = 0,
            result = '';

        for (var i = 0; i < 64; i++) {
            e['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(i)] = i;
        }

        for (var x = 0; x < input.length; x++) {
            c = e[input.charAt(x)];
            b = (b << 6) + c;
            loop += 6;

            while (loop >= 8) {
                (( a = (b >>> (loop -= 8)) &0xff ) || ( x < (input.length - 2))) && ( result += String.fromCharCode(a));
            }
        }

        return result;
    },
    recode = function (input) {

        var decodedString = base64Decode(input),
            recodedString = '';

        // Encode binary to hex
        for (var i = 0; i < decodedString.length; i++) {
            var hex = decodedString.charCodeAt(i).toString(16);
            recodedString += ('000' + hex).slice(-2);
        }

        return recodedString;
    },
    AuthenticationHeaderDynamicValue = function () {
        this.computeString = function (context) {
            request = context.getCurrentRequest();
            url = request.getUrl(true).components[1];

            var time = Math.round(+new Date() / 1000),
                md5Checksum = md5(request.jsonBody ? JSON.stringify(request.jsonBody) : url),
                signature = hmac(this.secretKey, md5Checksum);

            return recode(signature);
        };

        this.evaluate = function(context) {
            if (this.secretKey) {
                return this.computeString(context);
            }
        };

        this.title = function() {
            return "Authentication header";
        };

        this.text = function() {
            return;
        };
    };

AuthenticationHeaderDynamicValue.identifier = "com.test.PawExtensions.AuthenticationHeaderDynamicValue";
AuthenticationHeaderDynamicValue.title = "AuthenticationHeader";
AuthenticationHeaderDynamicValue.inputs = [
    DynamicValueInput("publicKey", "Public key", "String"),
    DynamicValueInput("secretKey", "Secret key", "String")
];

registerDynamicValueClass(AuthenticationHeaderDynamicValue);

}).call(this);


text:
Q: How to build-up chopped information from serial This is kind of a follow-up question of this one: Get inline data from serial
Just to make it clear, I have a TerminalPanel class which has the OnSerialRead method:
def OnSerialRead(self, event):
    """Handle input from the serial port."""
    text = event.data
    self.text_ctrl_output.AppendText(text)
    self.GetParent().graphics_panel.get_data(text)

So far so good.  It acquires everything I'm expecting from the serial port (as I see it in my text_ctrl_outout.AppendText(text).
Nonetheless, I want to pass that information, that looks something like this:

2014-11-25 20:19:57 0 2 2 393

to my GraphicsPanel class through the get_data method:
def get_data(self, text):
    self.mario = text
    print self.mario

My problem is that what I get on my terminal is this:

20

14-1

1-25

20:

19:5

7 0

2 2

393

Even though I've been using the accepted solution, it only helps me to pretty print it.  I want to be able to use the last four columns (i.e., to remove the timestamp) so I can graph these values.
How can I get them?

A: If the whole line ends with line break "\n" you need to store your text in buffer (string) until it appears in incoming text. It easier to concat and split it
def __init__(self, ... ):
   self.buffer=""

def OnSerialRead(self, event):
    """Handle input from the serial port."""
    lines = (self.buffer + event.data).split('\n')
    self.buffer= lines[-1]  #anything after last line break store in buffer
    for text in lines[:-1]: #work for 0 or more lines
        self.text_ctrl_output.AppendText(text)
        columns= text.split()
        data=' '.join( columns[-4:] )
        self.GetParent().graphics_panel.get_data(data)

If it is serial communication you might clear the buffer after some time without any read. You simply need to create timer and restart each time in this function.


text:
Q: Showing intervals as Range rather than Upper Value using ArcGIS Pro I'm trying to show my point data with intervals but in ArcGIS Pro I only get "Upper value" which I don't want.
In ArcMap it looks like this:

but in ArcGIS Pro it looks like this:

How can I list the point data with intervals like I can in ArcMap?

I am using ArcGIS Pro 2.4.0 and it seems that this issue is fixed in later updates.

A: You do not say what version of ArcGIS Pro you are using but I think it must be earlier than 2.7 because there is an ArcGIS Idea named ArcGIS Pro - more Intuitive Default Legend Labels that I believe was implemented at 2.7 to address it.
I just did a quick test at ArcGIS Pro 2.8 and got this as my result (with no manual intervention):


text:
Q: Diagonalize an unknown matrix given only its eigenvectors and eigenvalues The question is the following:
The only way I can think of in doing this question would be for me to set variables for all values of A, and then using the given Eigenvectors and values to solve for the whole thing (every value in A).
The solution given here: Construct matrix given eigenvalues and eigenvectors is a little confusing, and I'm not entirely sure how to apply it.

A: If$$P=\begin{bmatrix}1&1&0\\0&1&1\\0&0&1\end{bmatrix}$$(the columns of $P$ are the entries of the three vectors), then$$P^{-1}AP=\begin{bmatrix}-1&0&0\\0&-3&0\\0&0&-4\end{bmatrix}$$and therefore$$P^{-1}A^5P=\begin{bmatrix}(-1)^5&0&0\\0&(-3)^5&0\\0&0&(-4)^5\end{bmatrix}.$$Can you take it from here?


text:
Q: Do time-based workflow rules cause triggers to fire? I am wondering if time-based workflow rules cause triggers to fire.  The use-case is I use a trigger to look for a field to be checked and then send an email out via a trigger (workflow rule is not an option because it requires BCC addresses).  The email also looks for a particular attachment in the notes and attachments section of the opportunity.  This attachment is automatically uploaded via a third-party, but it takes a few seconds for it to show up... currently, the email gets sent out before the attachment is uploaded.
I am wondering if a time-based workflow rule to update a field on the opportunity will still cause the trigger to fire.  If so, I believe this would solve my issue of the email being sent out before the attachment is there.

A: Any field update from a Workflow Rule/Process Builder/Apex Trigger will cause update triggers on affected records to fire.


text:
Q: Finding duration/number of frames of WebM using FFMPEG/libavformat I'm trying to retrieve the duration and number of frames from a WebM file using FFMPEG and libavformat. I'm adapting some code that was initially written to work with MP4s, and when passing an MP4 it seems to work fine.
I have FFMPEG 2.1 compiled with the vp8 parser and decoder and the matroska demuxer.
I have an AVStream pointer to the video stream, *video_st. The code looks for the number of frames in video_st->nb_frames, and for the duration in video_st->duration. These both appear to be 0.
The API docs for for video_st->duration (https://ffmpeg.org/doxygen/trunk/structAVStream.html#a4e04af7a5a4d8298649850df798dd0b) say that "If a source file does not specify a duration, but does specify a bitrate, this value will be estimated from bitrate and file size." I can confirm that that this file does specify a duration and a bitrate (as I tested it on my desktop with ffmpeg -i). So it seems odd that this is returning 0. Perhaps my FFMPEG build configuration is incorrect?
As for nb_frames, the docs say "number of frames in this stream if known or 0". Is there anything I can do if this returns 0? Again, ffmpeg -i does return an estimate for fps; that would be good enough, as I could estimate the number of frames with that and the duration.
Thanks!

A: Why is nb_frames 0?
Mp4 files can have complete indices of all frames in the stream, which allows you to exactly know the number of frames. AVI does this too. WebM allows indices of only frames-of-interest, e.g. keyframes, which means the index is smaller (i.e. smaller file), but it also means you don't know the number of frames unless you parse the whole file.
How to get the duration?
AVStream.duration is the per-stream duration. For many file types, including WebM, only the duration of the entire file is specified in the header, not the duration per-stream. Thus, use AVFormatContext.duration, which is in AV_TIME_BASE units (microseconds). To get an approximate FPS, use AVStream.avg_frame_rate, and then nb_frames can be approximated from there.


text:
Q: WebAPI Routing Assistance Learning a lot about MapRouting and have spent WAY too much time trying to get what I need done, so I'm hoping someone can help out. :)
I'm looking to do the following:
/api/Entities/1 <- Views the details entity with id of 1 (this is a string, not int)
/api/Entities/1/Action <- Calls a particular action on the entity with the id of 1.
/api/Entities <- Views the entities set.
/api/Entities/Action <- Calls the particular action on the entities set.
The problem I'm encountering is the last one.  That is currently being intercepted by the first case, as the id is a string.
Any assistance would be greatly appreciated!

A: A very good reference is here
Without using Attribute based routing the answer is somewhat long winded as the RPC style (Action) and Rest methods do not co-exist nicely if you are matching to the same verb. As you have noticed the GET() and DOSOMETHING() are seen as duplicate method signatures on the same controller. To get around this you could try use two controllers:
So I would recommend using attribute based routing; however, it is possible with normal methods:
Using standard routing...
Set your routes like so
        config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        config.Routes.MapHttpRoute(
            name: "ActionDefaultApi",
            routeTemplate: "api/entities/{action}/{actionId}",
            defaults: new
                          {
                              //Add more as needed
                              action = "(|dosomething|dosomethingelse)",
                              actionId = RouteParameter.Optional,
                              controller = "EntitiesRpc"
                          });

Controller 1:
public class EntitiesController : ApiController
{
    public string Get()
    {
        return "http://server/api/Entities";
    }

    public string Get(string id)
    {
        return string.Format("http://server/api/Entities/{0}", id);
    }
}

Controller 2:
public class EntitiesRpcController : ApiController
{
    [HttpGet]
    public string DoSomething()
    {
        return "http://server/api/Entities/doSomething";
    }

    [HttpGet]
    public string DoSomething(string actionId)
    {
        return string.Format("http://server/api/Entities/doSomething/{0}", actionId);
    }

    [HttpGet]
    public string DoSomethingElse()
    {
        return "http://server/api/Entities/doSomethingelse";
    }

    [HttpGet]
    public string DoSomethingElse(string actionId)
    {
        return string.Format("http://server/api/Entities/doSomethingelse/{0}", actionId);
    }
}

Now assumming you used attribute based routing you could go back to one controller and use something like this:
public class EntitiesController : ApiController
{
    [Get("Entities")]
    public string Get()
    {
        return "http://server/api/Entities";
    }

    [Get("Entities/{id}")]
    public string Get(string id)
    {
        return string.Format("http://server/api/Entities/{0}", id);
    }

    [Get("Entities/doSomething")]
    public string DoSomething()
    {
        return "http://server/api/Entities/doSomething";
    }

    [Get("Entities/doSomething/{actionId}")]
    public string DoSomething(string actionId)
    {
        return string.Format("http://server/api/Entities/doSomething/{0}", actionId);
    }

    [Get("Entities/doSomethingelse")]
    public string DoSomethingElse()
    {
        return "http://server/api/Entities/doSomethingelse";
    }

    [Get("Entities/doSomethingelse/{actionId}")]
    public string DoSomethingElse(string actionId)
    {
        return string.Format("http://server/api/Entities/doSomethingelse/{0}", actionId);
    }
}


text:
Q: CM elliptic curves and isogeny Q: Show that any two CM elliptic curves with the same endomorphism algebra (say $K$) are
isogenous.
I was thinking of the following:
Let $E_1\simeq \mathbb{C}/L_1$ and $E_2\simeq \mathbb{C}/L_2$, then since both elliptic curves have CM by $K$, we know $L_1\otimes \mathbb{Q} = L_2\otimes \mathbb{Q}=K$. WLOG we may assume $L_1\subseteq L_2$, then $L_1\cap L_2$ is also a lattice and has finite index in both $L_1$ and $L_2$ (this is where we probably use CM but I am unsure of the details, in fact is it even okay to assume the containment?). From here we conclude that there is an isogeny $\varphi: \mathbb{C}/L_1 \rightarrow \mathbb{C}/L_2$; indeed, since the map is surjective and kernel=$L_2/L_1$ is finite.
What happens for the case of non-CM elliptic curves?

A: Non-CM elliptic curves over the complexes all have endomorphism ring $\Bbb Z$. Up to isomorphism, there are only countably many curves isogenous to
a given curve, but there are uncountably many curves (consider the $j$-invariants) so there are uncountably man isogeny classes of non-CM elliptic curves.


text:
Q: How do I compile a GitHub project? I've tried for few hours.. and failed. i can't seem to get it to work. ( in NetBeans)
I've added libraries that creator pointed out, source and nbproject - I get errors.
Can someone tell me what to do step by step? Thank you in advance.
LINK TO GITHUB: https://github.com/lucidexploration/JonBot-NG
(   i've tried adding it - I downloaded the zip from github then I created new project in netbeams (selected as just Java) then I went to "files" tab and dragged and dropped down src folder from zip i downloaded from GitHub then nbproject and the rest. I've got an JAVADOC error. )

A: Step 1 : Install git into your system
Step 2 : Clone the project into your system
git clone https://github.com/lucidexploration/JonBot-NG.git

You are almost done,
Step 3: Import the project into your workspace using IDE.
Everything is ready, enjoy coding.


text:
Q: Undefined reference to static member variable when specializing I have the following code:
    struct All {
    All() {}
    ~All() {}

    template <typename T>
    static struct Item {
        T var;
    } item;
    virtual void setVal() noexcept {}
};

template <typename T>
struct any : public All
{
    public:
        any() : All() {}
        ~any() {}
        T value;
        void setVal() noexcept override {
            All::item<decltype(value)>.var = value; // Error appears here
        }
};

And the following error:

undefined reference to All:item<int>

I don't understand this error, because item is a static member variable template, and i have to specialize it...
Help me !

A: Your bug is that you never defined the static member variable. You only declared it. Add a definition:
template <typename T>
All::Item<T> All::item = {};

However, your syntax for defining the type of the member variable template and declaring the variable itself is not accepted by the compilers that I tested. g++ (5.2.0) is fine with the declaration, but complains that All::Item is not a template when specifying the type for the variable definition. clang++ (3.6.0) does not even accept your declaration. Simply separating the definition of the type and the declaration of the variable solved the issue:
template <typename T>
struct Item {
    T var;
};

template <typename T>
static Item<T> item;


text:
Q: LSCOLORS format I want to configure my .bash_profile and I've seen this post about BSD based ls configuration:
https://www.cyberciti.biz/faq/apple-mac-osx-terminal-color-ls-output-option/
I just don't know what is the difference between first directory and the last two (directory) row, or between the executable (5th) row and the 8th and 9th row.

A: What you are comparing here is basically a "standard" entity (file/folder) with entities that have special permissions attached:

*

*directory (first row), is just that.  A directory (or folder) of other directories and/or files.  These directories all have permissions on who can read/write/execute based on user/group associations.

*

*directory writable by others with sticky bit set (10th row) means it's a directory to which users of other groups (than the owner/group) can write to but only the file owner or the root user can modify the file.

*directory writable to others, without sticky (11th row) is also a directory that can be written to by others, but anyone can modify the file.

*executable means that a file can by run by the owner or users in the group.

*

*executable with setuid bit set (8th row) this is also an executable file, but when the file is run, it will execute with the file owners privileges, not the one running the file.  For example, if a file is owned by root, but run by you, it will execute as if root ran it.

*executable with setgid bit set  (9th row) This is the same as above, except instead of the file's owner, it will be executed with the privileges of the group that owns it (i.e. wheel).
You can find more info on the LSCOLORS including a "color calculator" on the post https://apple.stackexchange.com/a/282189/119271


text:
Q: Degree of a pull back bundle on product manifold For any Kähler manifold $(X^n,\omega)$ and a holomorphic line bundle $L$ on it, let's define the degree of $L$ to be $\int_X c_1(L)\wedge w^{n-1}$. Now let's take $(X,\omega_1)$ and $(Y,\omega_2)$ two compact Riemann surfaces with $\omega_1,\omega_2$ denoting the respective Kähler forms on them. Now say $L$ is a holomorphic line bundle on $X$, I want to see if deg $L$=deg $\pi_1^*(L)?$ We get
\begin{align*}
& \int_{X\times Y} c_1(\pi_1^* L)\wedge (\pi_1^*\omega_1+\pi_2^*\omega_2)\\
&=\int_{X\times Y}\pi_1^*c_1 (L)\wedge \pi_2^*\omega_2+\int_{X\times Y}\pi_1^*c_1 (L)\wedge \pi_1^*\omega_1\\
&=\int_{X\times Y}\pi_1^*c_1 (L)\wedge \pi_2^*\omega_2+\int_{X\times Y}\pi_1^*(c_1(L)\wedge\omega_1)\\
&=\int_{X\times Y}\pi_1^*c_1 (L)\wedge \pi_2^*\omega_2+0
\end{align*}
I want to use some form of Fubini to prove my guess but I am not totally sure how to do it. Any help is appreciated.


text:
Q: How to call a Macro from Apache POI library in Java? I have :

*

*Macro named "process" that does all the processing work for my worksheets.

*I want my Java code that uses Apache POI, to call this macro so that it can process the sheets for me.

*How can I call a Macro in Apache POI in Java ?

:: Note ::

*

*I am using import org.apache.poi.ss.usermodel in Apache POI.

*Please, give sample code. (I am new to Apache POI and Java itself.)

A: You can use other tool like com4j. I created a POC just today and works like a charm. Just follow these steps:

*

*Download the last version here

*Using Apache Ant build the sample: samples\excel

*With the code generated by tlbimp (it is just a part of com4j), create a small app and write a code like:
// Starts excel and open an existing workbook
_Application app = ClassFactory.createApplication();
app.setVisible(0, true);
_Workbook wb = app.getWorkbooks().open("c:\\test.xlsx", null, null, null, null, null, null, null,
        null, null, null, null, null, null, null, 0);

// run a macro
Variant macro = new Variant(Variant.Type.VT_BSTR);
macro.set("my_macro");
wb.getApplication().run(macro, null, null, null, null, null, null, null, null, null, null, null,
        null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
        null, null, null, null);

// Save the excel file and quit
Variant saveBeforeExit = new Variant(Variant.Type.VT_BOOL);
saveBeforeExit.set(1);
wb.close(saveBeforeExit, Variant.getMissing(), Variant.getMissing(), 0);
app.quit();

*Further examples: com4j tutorials

A: I think, you can't.

Macros
Macros can not be created. However, reading and re-writing files
  containing macros will safely preserve the macros.

Apache POI Limitations

A: I don't think this is possible. POI is a library to read/edit Office files, macros are a whole other beast. You would have to implement a Visual Basic for Applications Interpreter into POI to accomplish this. Macros that are already in your Excel workbook are preserved, but you cannot add new ones or call existing ones.

A: One little hacky way to do this is to make your macros run automatically when the workbook is opened. This can be done from vba in ThisWorkbook module.
Then you can open excel with Desktop.getDesktop().open(new File(filePath)); and with apache POI and FileInputStream just get the result of 'process' .


text:
Q: Having issues with creating pivot table with VBA So I have been able to somewhat create a pivot table and I will show you what I mean. Here is my code so far.
Dim WSD As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable
Dim PRange As Range
Dim FinalRow As Long
Dim FinalCol As Long
Dim StartPT As String
Set WSD = Worksheets("aggregateData")
Set WSD2 = Worksheets("Sheet12")

' Select the data for pivot table

FinalRow = WSD.Cells(Rows.Count, 2).End(xlUp).Row
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = WSD.Cells(2, 1).Resize(FinalRow, FinalCol)
Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=PRange)

'Where do I want the pivot table to start

StartPT = WSD2.Range("A1").Address(ReferenceStyle:=xlR1C1)

'Begin to Create the Pivot Table

Set PT = PTCache.CreatePivotTable(TableDestination:=StartPT, TableName:="POS Data")

PT.PivotFields("Fineline").Orientation = xlRowField

End Sub

When I run this code, I get the beginnings of a pivot table. However, the pivot table appears as white instead of the blue that a normal pivot table has. Any help would be appreciated.
Thanks,
G

A: Please replace this row Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=PRange) of your code with this code Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion15) . xlPivotTableVersion15 is standard blue version of PivotTable. Please confirm if this resolves your question.


text:
Q: How to read collections seperately from firestore I wrote some code to read the collections and write to the logcat but I want to read them separately and add to a string to use them after. I have attributes as name, cityLONG, cityLAT, campaignStartDate, campaignEndDate under collections.
Logcat : 8sAtwKcm273R1io1Blre => {name=TEST_LOC, cityLONG=29.3054092, cityLAT=40.9301514, campaignStartDate=2019-04-30, campaignEndDate=2019-10-30}

public void readFirestore() {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("campaigns")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d(TAG, document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
}

A: You can use getString() on a document to get specific string fields, or use get() for other types and cast them yourself.
Your code would be like:
FirebaseFirestore db = FirebaseFirestore.getInstance();
        db.collection("campaigns")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful() && task.getResult() != null) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                                String cityLONG = document.getString("cityLONG");
                                //and so on
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });


text:
Q: crud trigger next button calendar I have a site developed in crud with codeigniter.
I would when I enter into a determinate function in my view to trigger the button dhx_cal_next_button that goes on of a week for example.
I have tried but nothing succeed:
$('.dhx_cal_next_button').trigger('click');

I have seen that into the file dhtmlxscheduler.js there is this code (I have cut more code out this function):
scheduler._click={
    dhx_cal_next_button:function(dummy,step){
        scheduler.setCurrentView(scheduler.date.add( //next line changes scheduler._date , but seems it has not side-effects
            scheduler.date[scheduler._mode+"_start"](scheduler._date),(step||1),scheduler._mode));
    }
};

How can I simulate the click event on this button?
Thanks


text:
Q: Equation $2n^2=m^2+1$ Given the equation
$$2n^2=m^2+1$$
Is there a general solution?

since $m$ is odd for example  $$2\cdot5^2=7^2+1$$ $$2\cdot29^2=41^2+1$$
Any hint would be appreciation.

A: There are infinitely many solutions. You will understand where they come from once I write down this little table for you:
$$
n = \quad 5 \quad 12 \quad 29 \quad 70  \quad ...\\
m = \quad 7 \quad 17 \quad 41 \quad 99 \quad ...\\
$$
If you have not yet understood the pattern : the number in each top row is the sum of the numbers in the previous column (e.g. $70 = 41+29$), and the difference between numbers in the same column is the top number of previous column ($e.g. 99-70 = 29$).
Now, you can see how to continue this table and obtain infinitely many solutions. I would encourage you to find an algebraic proof of this fact.

A: If
$2n^2=m^2+1$
then
$2(3n+2m)^2 = 18n^2 + 14nm +8m^2$
$=9(m^2 + 1) + 14nm + 8m^2$
$=9(m^2+1) + 14nm + 8(2n^2-1)$
$=16n^2 + 14nm + 9m^2 + 1$
$=(4n+3m)^2 + 1$
so we have (1,1) -> (5,7) -> (29,41) etc.


text:
Q: Biblatex: Cannot get new BibliographyOption to work from document preamble I am trying to add a user option in biblatex to choose between two ways of displaying DOIs, but I can't get the option to take effect if it's issued by the user in the preamble.
To illustrate my problem, I prepared the MWE below. The test.bbx style loads authoryear.bbx and adds the option compactdois. If I set the option to true in the bbx file (either via ExecuteBibliographyOptions or via settoggle), DOIs are in fact displayed in a compact way. But issuing the commands in the document preamble in any of three ways (as a package option, via ExecuteBibliographyOptions or via settoggle) does not work.
What am I doing wrong? I would like the option to be able to be set in the document preamble, instead of once and for all in the bbx style.
MWE:
\documentclass{minimal}

\begin{filecontents}{\jobname.bib}
@Article{abbott-1997-NoteNatureWater,
  author       = {Abbott, Barbara},
  title        = {A Note on the Nature of {\emph{Water}}},
  journal      = {Mind},
  year         = 1997,
  volume       = 106,
  number       = 422,
  pages        = {311-319},
  doi          = {10.1093/mind/106.422.311}
}
\end{filecontents}

\begin{filecontents}{test.bbx}
\RequireBibliographyStyle{authoryear}

\newtoggle{test:compactdois}
\DeclareBibliographyOption[boolean]{compactdois}[true]{%
  \settoggle{test:compactdois}{#1}}

% \ExecuteBibliographyOptions{compactdois}                       % works
% \settoggle{test:compactdois}{true}                             % works

\iftoggle{test:compactdois}%
{\DeclareFieldFormat{doi}{%
    \mkbibacro{DOI}\addcolon\space{#1}}}
{\DeclareFieldFormat{doi}{%
    \url{https://doi.org/#1}}}
\end{filecontents}

\usepackage[backend=biber,bibstyle=test]{biblatex}
%\usepackage[backend=biber,bibstyle=test,compactdois]{biblatex}  % no effect

% \ExecuteBibliographyOptions{compactdois}                       % no effect
% \settoggle{test:compactdois}{true}                             % no effect

\addbibresource{\jobname.bib}

\begin{document}

\nocite{*}

\printbibliography[heading=none]

\end{document}


text:
Q: Is it possible to send a signal from an intent and recover it in another intent I have 2 activities.. one is launched via deep links. MainActivity doesn't start DeeplinkActivity. How do I know from MainActivity when DeeplinkActivity finishes.
I have tried setting an intent filter programmatically. then added it to MainActivity then in DeeplinkActivity sendBroadcast.
I was unsuccessful since the broadcast recover method in MainActivity wasn't responding to broadcast sent from Deeplink via sendBroadcast(getIntent())

A: You can use interface, inside onDestroy() of DeepLink activity call the interface method and implement the method in MainActivity.
Check this answer.
https://stackoverflow.com/a/19027202/7248394

A: The function you are looking for is putExtra()
put this in your FirstActivity :
Intent intent  = new Intent (FirstActivity.this , SecondActivity.class);
intent.putExtra("your key" , yourBooleanVariable) ;
FirstActivity.this.startActivity(intent) ;

And this code in Your Second Activity :
Intent intent = getIntent() ;
Bundle bundle = intent.getExtras();
if(intent.hasExtra("your key")){
Boolean boolean = bundle.getBoolean();
}

you can put everything in a bundle with putExtra and get it from the bundle in the second Activity

A: Both the Model and Broadcast method work.
I chose to use the Broadcast method much simpler

MainActivity

public class MainActivity extends Activity {

    private BroadcastReciever receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context p1, Intent p2) {
                // TODO: Implement this method
            }
        };
        registerReceiver(receiver, new IntentFilter(getPackageName() + ".FOO_BAR"));

    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}

DeepLink

public class DeepLink extends Activity {
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        sendBroadcast(new Intent(getPackageName() + ".FOO_BAR"));
    }
}


text:
Q: Red dots in elasticsearch index output What are the red dots that Kibana inserts in index data as seen in this image? This is from me performing a simple query on a description field in my local environment. At first I thought they may be calling out invalid characters, but I don't know why (for example) B or 5 would be invalid. They are not part of the data, i.e. you cannot copy/paste them, which is why I'm led to believe they're some sort of warning. I have tried a variety of Google searches, but haven't come up with anything in the documentation or otherwise.

A: I think I found the answer here: https://discuss.elastic.co/t/what-is-this-red-dot-in-index-data/269612/8 - they were non breaking spaces. I replaced them with regular spaces in my string and the red dots went away.

A: If you are sure about that they are not from your data ingestion pipeline or they are not already exit in you input data before indexing, I guess it happens in analyzer level, It happens when you indexing documents with regard of your analyzing strategy (here in your case, I guess it's Elastic default strategy) and creating tokens from input streams to create inverted index tables for different fields.
If you look at it this happened in your text when the Alphabet word followed by numeric annotations, By red dots he tries to show the case of unplanned tokens which he created by his own for inverted index tables.
For more info:
https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-analyzers.html


text:
Q: How to export a row in a DataGridView to a txt file As I can select a row in a DataGridView and export it to a .txt file that has the name of a column of DataGridView
At the moment I have a button to export all data to a .txt gridview here is the code
private void button2_Click(object sender, EventArgs e)
    {
        if (!Directory.Exists(@"D:\Carpeta"))
        {
            Directory.CreateDirectory(@"D:\Carpeta");
        }

        TextWriter sw = new StreamWriter(@"D:\Carpeta\Archivo.txt");
        int rowcount = TablaDatos.Rows.Count;
        for(int i = 0; i < rowcount -1; i++)
        {
            sw.WriteLine(TablaDatos.Rows[i].Cells[0].Value.ToString()+"\t"
                         +TablaDatos.Rows[i].Cells[1].Value.ToString()+"\t"
                          +TablaDatos.Rows[i].Cells[2].Value.ToString()+"\t"
                           +TablaDatos.Rows[i].Cells[3].Value.ToString()+"\t");
        }
        sw.Close();
        MessageBox.Show("Datos Exportados correctamente");
    }

I need to export row by row creating a txt for each row and not the entire DataGridView

A: There you go.
private void button2_Click(object sender, EventArgs e) {
    if (!Directory.Exists(@"D:\Carpeta"))
        Directory.CreateDirectory(@"D:\Carpeta");

    for (int i = 0; i < TablaDatos.RowCount; ++i) {
        var line = string.Join("\t", TablaDatos.Rows[i].Cells.Cast<DataGridViewCell>());
        File.WriteAllText(@"D:\Carpeta\" + $"Archivo-row-{i}.csv", line);
    }

    MessageBox.Show("Datos Exportados correctamente");
}

A: You can use either of these options:
Option 1
Set the MultiSelect property of grid to false and then select desired row, then you can use DataGridView.GetClipboardContent. This method retrieves the formatted values that represent the contents of the selected cells for copying to the Clipboard. The result is tab-delimited:
grid.MultiSelect = false;
grid.Rows[i].Selected = true;
grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText;
var text = grid.GetClipboardContent().GetText();

Option 2
you can get text representation for the row at index i by joining formatted value of each cells. The result could be delimited by any character that you need:
var text = string.Join("\t", grid.Rows[i].Cells.Cast<DataGridViewCell>()
                                 .Where(x=> x.Visible).Select(x=> x.FormattedValue));

To save text to a file
You can use File.WriteAllText method:
System.IO.File.WriteAllText(filePath, text);


text:
Q: Cannot Find Symbol getHomeTimeline() I'm trying to use the Twitter4J on a JSP test page that I'm beginning to work with, using this code:
<%-- Includes --%>
<%@page import="twitter4j.Status"%>
<%@page import="java.util.List"%>
<%@page import="twitter4j.TwitterFactory"%>
<%@page import="twitter4j.Twitter"%>
<%@page import="twitter4j.api.TimelineMethods"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

Hello World!

        <%
            Twitter twitter = new TwitterFactory().getInstance();
            List<Status> statuses = getHomeTimeline();
        %>

The problem is that Netbeans is telling me that at the line 19(the getHomeTimeline one) he can't find the symbol. What should I do to correct this?

A: Shouldn't it be twitter.getHomeTimeLine();?


text:
Q: Outlook 2013 marking email read I'm using MS Outlook 2013 and have four email accounts with IMAP settings. One of my account's email becomes read without reading them on any device in few seconds, reading pane and all other setting are identical on all accounts.
How can I set Outlook so that it will not mark these emails as read without reading them?

A: In Outlook 2013, you have to go to File > Options > Mail
Then, under the section that says "Outlook Panes" click the button that says "Reading Pane"
There you can change the settings to not mark email as read when seen on the reading pane.
The settings should apply to all email accounts.
If you have already checked these settings and still have problems, then it's likely that you have a specific rule for that email account that marks email as read.
To see what are your current rules for each account go to
File > Info > Rules and Alert
Then select the email account you are having issues with and check if there is any rule that could be causing mail to be marked as read.


text:
Q: JasperReport no funciona una vez compilado el programa Alguien sabe por qué JasperReport me funciona al ejecutar el programa en Netbeans pero después no funciona con el programa compilado?
El programa que he desarrollado y donde aplicó el JasperReport es este:
Problemas con JRLoader de JasperReport en Hibernate

A: es por la ruta.
He creado esto y funciona, pero estoy intentando acceder a la ruta relativa, para no cargar mucho el programa.
File file = new File("src\\Reportes\\ReportePresupuesto.jasper");

    if(file.exists()){
        try{
            JasperReport reporte = (JasperReport) JRLoader.loadObject(file);//(getClass().getResource("Reportes\\ReportePresupuesto.jasper"));;//JasperCompileManager.compileReport("src/Reportes/ReportePresupuesto.jrxml");
            JasperPrint  print = JasperFillManager.fillReport(reporte, null, new JRBeanCollectionDataSource(lista));
            JasperViewer view = new JasperViewer(print, false);
            view.setVisible(true);
            view.setTitle("Guardar Presupuesto:");
        }catch(JRException e){
            e.printStackTrace();
        }
    }else{
        File file2 = new File("ReportePresupuesto.jasper");
        try{
            JasperReport reporte = (JasperReport) JRLoader.loadObject(file2);//(getClass().getResource("Reportes\\ReportePresupuesto.jasper"));;//JasperCompileManager.compileReport("src/Reportes/ReportePresupuesto.jrxml");
            JasperPrint  print = JasperFillManager.fillReport(reporte, null, new JRBeanCollectionDataSource(lista));
            JasperViewer view = new JasperViewer(print, false);
            view.setVisible(true);
            view.setTitle("Guardar Presupuesto:");
        }catch(JRException e){
            e.printStackTrace();
        }
    }

Así funciona pero me obliga a sacar los .jasper a la carpeta dist
y no quiero que quede así, estoy probando rutas dentro del .jar para por lo menos evitar tener que copiar estos archivos
gracias!


text:
Q: How to add multiple path on same port VirtualHost I want to add multiple paths like "localhost:8080/phpmyadmin" and "localhost:8080/index.php" but it doesn't want to work I create a phpmyadmin.conf in conf-availables with
# phpMyAdmin default Apache configuration
<VirtualHost *:8080>
Alias /phpmyadmin /usr/share/phpmyadmin

<Directory /usr/share/phpmyadmin>
    Options SymLinksIfOwnerMatch
    DirectoryIndex index.php

    <IfModule mod_php5.c>
        <IfModule mod_mime.c>
            AddType application/x-httpd-php .php
        </IfModule>
        <FilesMatch ".+\.php$">
            SetHandler application/x-httpd-php
        </FilesMatch>

        php_value include_path .
        php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
        php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
        php_admin_value mbstring.func_overload 0
    </IfModule>
    <IfModule mod_php.c>
        <IfModule mod_mime.c>
            AddType application/x-httpd-php .php
        </IfModule>
        <FilesMatch ".+\.php$">
            SetHandler application/x-httpd-php
        </FilesMatch>

        php_value include_path .
        php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp
        php_admin_value open_basedir /usr/share/phpmyadmin/:/etc/phpmyadmin/:/var/lib/phpmyadmin/:/usr/share/php/php-gettext/:/usr/share/php/php-php-gettext/:/usr/share/javascript/:/usr/share/php/tcpdf/:/usr/share/doc/phpmyadmin/:/usr/share/php/phpseclib/
        php_admin_value mbstring.func_overload 0
    </IfModule>

</Directory>

# Authorize for setup
<Directory /usr/share/phpmyadmin/setup>
    <IfModule mod_authz_core.c>
        <IfModule mod_authn_file.c>
            AuthType Basic
            AuthName "phpMyAdmin Setup"
            AuthUserFile /etc/phpmyadmin/htpasswd.setup
        </IfModule>
        Require valid-user
    </IfModule>
</Directory>

# Disallow web access to directories that don't need it
<Directory /usr/share/phpmyadmin/templates>
    Require all denied
</Directory>
<Directory /usr/share/phpmyadmin/libraries>
    Require all denied
</Directory>
<Directory /usr/share/phpmyadmin/setup/lib>
    Require all denied
</Directory>
</VirtualHost>

and a backend.conf with
<VirtualHost *:8080>
DocumentRoot "/var/www/backend/api/public"
</VirtualHost>

but I have a 404 not found on localhost when I do an a2inconf phpmyadmin and backend and after i reload apache2
What is wrong with my virtualhost ?

A: You need to place both configs in the same VirtualHost block. You can't split it up into multiple configuration files.
<VirtualHost *:8080>
  DocumentRoot "/var/www/backend/api/public"
  Alias /phpmyadmin /usr/share/phpmyadmin
  # rest of config ...
</VirtualHost>


text:
Q: Maximizing inner product Suppose we have two row vectors $a$ and $b$ of nonnegative real numbers such that, for $j<k$ $a_j\leq a_k$ and $b_j\leq b_k$. Let P be a permutation matrix. Can we prove (or disprove) that
$$ aPb^T \leq ab^T ?$$
Also, suppose we have two row vectors $a$ and $b$ of nonnegative real numbers. Let $ P_m$ be the cyclical permutation matrix that shifts by m. Is there any sort of closed form expression for the m that maximizes
$$ a P_m b^T ?$$


text:
Q: Cmake Mechanism for making makefile in windows I am working on Qt and cmake so I want to know how cmake generate makefile. I analysis makefile that generated by cmake but i founded that cmake call cmake command again in the makefile insted  of using gcc or cl command for building projects. In other word how cmake execute gcc compiler for building executable file?

A: CMake creates the make-files or project files but it does not trigger any compiler step. For a description see Wikipedia
As the question is tagged with mingw I assume this is your environment. Thus the steps are:

*

*Write your CMakeList.txt

*Create and switch into your build directory: mkdir build

*Create make-files using cmake: cmake PATH\TO\YOUR\SOURCES

*Build the project: make or nmake


text:
Q: What's the preferred way to return an empty table in SQL? I know I can return an empty table using the following query :
select * from tbFoo where 1=2

but that code doesn't look nice to me.
Is there a 'standard' way of doing this?
If you're wondering why I want to do such a strange thing, it's because I can't name the datatables I return from a stored procedure, so I need empty placeholders.

A: Having just run both:
SELECT TOP 0 * FROM Table
and
SELECT * FROM Table WHERE 1=0

They produce exactly the same execution plan.

A: Most of the time I see 1=0 but yes thats pretty much the standard approach when you really have to.  Although really having to is rare.

A: What you really need is information_schema, using it will allow you to find out the definition of a table.
You don't mention which database you are using, so here is a link about information_schema Support in MySQL, PostgreSQL (and MSSQL, Oracle, Etc)
An example from the site;
SELECT table_name, column_name, is_nullable, data_type, character_maximum_length
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = 'employees'

In your case, all you need are the column names;
SELECT column_name
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = 'employees'


text:
Q: storagegateway.ListGateways() returning "Invalid resource" with status code: 400 I am having trouble using the go sdk to list all of the storage gateways in a region using the following code:
package main

import (
    "fmt"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/storagegateway"
)

func newSess() (sess *session.Session) {
    sess, err := session.NewSession(&aws.Config{
        Region: aws.String("us-east-2"),
    })

    if err != nil {
        fmt.Printf("Error creating session: %s\n", err)
        return
    }

    return sess
}

func main() {
    sgw := storagegateway.New(newSess())

    input := &storagegateway.ListGatewaysInput{
        Limit:  aws.Int64(5),
        Marker: aws.String("1"),
    }

    result, err := sgw.ListGateways(input)
    if err != nil {
        fmt.Printf("Error listing gateways %s\n", err)
        return
    }

    fmt.Println(result)

}

My environment is the following:

*

*Go version: 1.9.2 darwin/amd64

*Operating system: macOS 10.13.2

*aws-sdk-go: v1.12.63

The SDK is using the default profile specified in ~/.aws/config as it should and the credentials are correct as well. Furthermore, I am able to list the gateways using the awscli alone.
This could very well be something simple that I have overlooked as I am no expert. That said, any help would be greatly appreciated.

A: The example code seems to work as expected for me by simply removing the Marker: aws.String("1") line.


text:
Q: Cannot read property 'URI' of undefined, Ionic2 "TypeError: Cannot read property 'URI' of undefined"
I got this error whenever I try to use native screenshot method in Ionic2.
My code:
this.screenshot.URI(80).then((result) => {
  console.log(result);
}, (err) => {
  console.log(err);
});

This is Ionic2 screenshot documentation: https://ionicframework.com/docs/native/screenshot/
"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/compiler-cli": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@ionic-native/camera": "^3.6.0",
"@ionic-native/core": "3.6.1",
"@ionic-native/file": "^3.6.0",
"@ionic-native/file-path": "^3.6.0",
"@ionic-native/screenshot": "^3.6.1",
"@ionic-native/splash-screen": "3.4.2",
"@ionic-native/status-bar": "3.4.2",
"@ionic-native/transfer": "^3.6.0",
"@ionic/storage": "2.0.1",
"crypto-js": "3.1.9-1",
"fast-sha256": "1.0.0",
"ionic-angular": "3.0.1",
"ionic-native": "^3.5.0",
"ionicons": "3.0.0",
"rxjs": "5.1.1",
"sha256": "0.2.0",
"sw-toolbox": "3.4.0",
"ts-md5": "1.2.0",
"zone.js": "^0.8.4"


text:
Q: Header that is not displayed in TCPDF I want to set up a header and a footer on a PDF page with TCPDF.
I try to do so, with the help of @ Simone Rossaini  in comments :
    <?php
require_once('C:\Users\Administrateur\Desktop\testjelix\vendor\tecnickcom\tcpdf\examples\tcpdf_include.php');

// create new PDF document
$pdf = new TCPDF;
class FDR extends TCPDF {

    //Page header
    public function Header() {
        // Set font
        $this->SetFont('helvetica', 'B', 35);
        // Title
        //Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M')
        $this->Cell(0, 0, 'Feuille de route', 0, false, 'C', 0, '', 0, false, 'M', 'M');
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        //date time
        $tDate = date("F j, Y, g:i a");
        $this->Cell(0, 10, 'Document généré par Wee.org le '.$tDate, 0, false, 'R', 0, '', 0, false, 'T', 'M');
    }
}

// create new PDF document
$pdf = new FDR(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDFCREATOR);
$pdf->SetAuthor('Wee');
$pdf->SetTitle('Feuille de route');
$pdf->SetSubject('GBiuac');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set font
$pdf->SetFont('helvetica', '', 11);

// add a page
$pdf->AddPage('L', 'A4');

//Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false)
$pdf->Image('C:\Users\Administrateur\Desktop\testjelix\gp-logo.jpg', '', '', "", 35, '', '', 'T', false, 300, 'L', false, false, 1, false, false, false);
$pdf->Ln(40);
//Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M')
$pdf->Cell(0, 0, 'COVID 19', 1, 1, 'C', 0, '', 1);
//MultiCell(w, h, txt, border = 0, align = 'J', fill = 0, ln = 1, x = '', y = '', reseth = true, stretch = 0, ishtml = false, autopadding = true, maxh = 0) ⇒ Object
$pdf->MultiCell(0, 2, 'En raison des mesures Covid, nous prenons toutes les mesures nécessaires pour la sécurité et la sérénité de nos invités et du public.Le port du masque est obligatoire pour tous vos rendez-vous - Les règles sanitaires à respecter seront indiquées à l\'entrée de chaque lieu du Festival. Un masque spécial vous sera donné à votre arrivée.', 0, '', 0, 1, '', '', true);
$pdf->Cell(0, 0, 'SOIREE', 1, 2, 'C', 0, '', 3);
$pdf->MultiCell(0, 2, 'Chaque soir, après votre séance, nous vous donnons RDV au Garage / Librairie des Bauges à partir de 22:00, 22:30 pour partager un moment autour d\'un verre (ou non). En toute sécurité et quiétude.', 0, '', 0, 1, '', '', true);
$pdf->Cell(0, 0, 'VOUS ET VOTRE CHARGE D\'ACCUEIL', 1, 1, 'C', 0, '', 3);

   $tbl = <<<EOD

        Prénom
        Nom
        Téléphone
        Chargé d'accueil
        JS
        ESNLT
        06 70 80

        Max
        JAZZAVILLE
        59 78

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

$pdf->Cell(0, 0, 'TRANSPORTS', 1, 1, 'C', 0, '', 3);
 $tbl = <<<EOD

        Transport SNCF
        Véhicule Personnel

        Lieu d'arrivée
        Chambéry
        Date et horaire d'arrivée Train
        13:18
        Horaire de RDV pour transfert
        13:20
        Lieu de RDV
        Salle de la Municipalité - Hôtel de Ville

        Lieu de départ
        Chambéry
        Date et horaire départ Train
        10:22
        Horaire de RDV pour transfert
        9:00

        Contact Bureau Transport
        M. Denis BOHAN
        06 08 86  26 22
        Parking : Parking du Palais de Justice - 12 cours de l'Hôtel de Ville

        M. François GIORS
        06 27 15 18 31

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

$pdf->Cell(0, 0, 'HEBERGEMENT', 1, 1, 'C', 0, '', 3);
   $tbl = <<<EOD

        Lieu
        Résidence 3*** Citadelle de Conflans - Place de Conflans 73200 ALBERTVILLE

        Code porte
        07200 - En cas de problèmes d'ouverture : 04 79 37 84 60

        Nuitée
        jeudi 15 octobre
        vendredi 16 octobre
        samedi 17 octobre
        dimanche 18 octobre
        CHAMBRE

        7

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

// add a page
$pdf->AddPage('L', 'A4');
$pdf->Cell(0, 0, 'RESTAURATION CATERING', 1, 1, 'C', 0, '', 3);
 $tbl = <<<EOD

        Lieu
        Salle René Cassin

        Repas Menu
        Cantine bio - Repas bio à dominante végétarienne

        Horaires de service
        Midi de 11:30 à 14:00
        Soir de 18:30 à 21:30
        Signaler un retard ou une demande
        Mme Bernadette
        06 61 20 10

        Régime alimentaire signalé par l'invité

        Repas prévus
        jeudi 15 soir
        vendredi 16 midi
        vendredi 16 soir
        samedi 17 midi
        samedi 17 soir
        dimanche 18 midi
        dimanche 18 soir

        0
        0
        0
        0
        0
        7
        GARAGE 7 + MAX

Vous avez été informé par la présente feuille de route de la commande de vos repas. Nous vous remercions de la respecter afin d'éviter tout gaspillage, qui serait incohérent avec les valeurs que nous défendons. Si vous souhaitez ne pas bénéficier des repas et les prendre en dehors de l'organisation à votre charge, nous vous remercions d'informer M. Jean Sébastien ESNAULT 06 03 70 80

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

$pdf->Cell(0, 0, 'VOTRE PLANNING', 1, 1, 'C', 0, '', 3);

$tbl = <<<EOD

        Date et heure
        Vos rendez vous
        Lieu
        Heure RDV
        Contact Animateur
        Infos complémentaires

        14:00
        Catering + Raccord
        René CASSIN
        14:00
        JS ESNAULT 06 70 80

        15:00
        Dépose Bagages Citadelle + Prise de clés
        Citadelle
        15:00
        JS ESNAULT 06 03 00 70 80

        15:30 > 17:15
        Arrivée Dôme : montage, patch, balances
        Dôme Théâtre
        15:30
        JS ESNAULT 06 03 70 80

        17:45 (+ ou - 10 minutes)
        Concert / Fin 19:00 à 19:20
        Dôme Théâtre

        JS ESNAULT 06 70 80

BILLETS EXONERES >Assister à des séances en dehors de vos interventions

Veuillez prendre contact avec votre chargé d'accueil à l'arrivée pour voir quelles séances peuvent être disponbiles et combinables avec votre planning et votre présence.

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

$pdf->AddPage('L', 'A4');

$pdf->Cell(0, 0, 'VOS CONTACTS UTILES', 1, 1, 'C', 0, '', 3);
 $tbl = <<<EOD

        Votre chargé d'accueil
        Chantal
        BOA
        06 37 87 1

        Chargé d'accueil (au cas où le vôtre n'est pas disponible)
        Jannick
        LADY
        06 11 57 39 90

        Délégué Général  du Festival
        Jean Sébastien
        ESNT
        06 03 80

        Transports et navettes
        Denis
        Bon
        06 26 22

        Hébergement - Citadelle de Conflans

        04 84 60

        Restauration Catering
        Bernadette
        PAVILLIERS
        06 61 10

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');

$pdf->Ln(6);

// example using general stretching and spacing

// ---------------------------------------------------------

//Close and output PDF document
$pdf->Output('FDR.pdf', 'I');

//============================================================+
// END OF FILE
//============================================================

However, nothing is displayed ... I have a white space with a black line at the top of my header ... below, my lines of the rest of the code and at the bottom, nothing for the footer.
how to apply these functions? Should we call them back below?
Thanks for any help or explanation.

A: You extend class but you don't use it.
You need to extend it then use new with the name you choise like:
require_once('C:\Users\Administrateur\testjelix\vendor\tecnickcom\tcpdf\examples\tcpdf_include.php');
class FdrPdf extends TCPDF {

    private $invoice_footer;

    //Page header
    public function Header() {
        // Logo
        $image_file = K_PATH_IMAGES . 'C:\Users\Administrateur\testjelix\gp-logo.jpg';
        $this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
        // Set font
        $this->SetFont('helvetica', 'B', 35);
        // Title
        $this->Cell(0, 15, 'Feuille de route', 0, false, 'C', 0, '', 0, false, 'M', 'M');
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        $this->invoice_footer = 'Document généré le ' . $dtnow->toString(jDateTime::LANG_DFORMAT) . ' à ' . substr($dtnow->toString(jDateTime::LANG_TFORMAT), 0, -3) . ' via me.org - www.me.org';
    }

}

// create new PDF document
$pdf = new FdrPdf;
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Me');
$pdf->SetTitle('Feuille de route');
$pdf->SetSubject('GB');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 35);
// add a page
$pdf->AddPage('L', 'A4');
$pdf->setPrintHeader(true);
$pdf->setPrintFooter(true);
$pdf->Ln(40);
$pdf->SetFont('helvetica', '', 11);
//Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M')
$pdf->Cell(0, 0, 'COVID 19', 1, 1, 'C', 0, '', 1);
$pdf->MultiCell(0, 2, 'En raison des mesures Covid, nous prenons toutes les mesures nécessaires pour la sécurité et la sérénité de nos invités et du public.Le port du masque est obligatoire pour tous vos rendez-vous - Les règles sanitaires à respecter seront indiquées à l\'entrée de chaque lieu du Festival. Un masque spécial vous sera donné à votre arrivée.', 0, '', 0, 1, '', '', true);
$pdf->Cell(0, 0, 'SOIREE', 1, 2, 'C', 0, '', 3);
$pdf->MultiCell(0, 2, 'Chaque soir, après votre séance, nous vous donnons RDV au Garage / Librairie des Bauges à partir de 22:00, 22:30 pour partager un moment autour d\'un verre (ou non). En toute sécurité et quiétude.', 0, '', 0, 1, '', '', true);

$pdf->Cell(0, 0, 'VOUS ET VOTRE CHARGE D\'ACCUEIL', 1, 1, 'C', 0, '', 3);

$tbl = <<<EOD

        Prénom
        Nom
        Téléphone
        Chargé d'accueil
        JS
        ESNAULT
        06 03 00 70 80

        Max
        JAZZALBERTVILLE
        06 98 54 59 78

EOD;

$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->Output('test.pdf', 'I');
exit;

Another problem is $dtnow doesn't exist into function, if you have it outside use global $dtnow and all work.


text:
Q: EF One to One relationship creates new record each on each call to `SaveChanges()` I have an EF model which enforces a user > address one to one relationship which trimmed down looks like this:
public class User
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int AddressId { get; set; }
  [ForeignKey(nameof(AddressId))]
  public Address Address { get; set; } = new Address();
}

public class Address
{
  public int Id { get; set; }
}

I'm using the a generic repository pattern but the same thing happens if I work directly on the EF context.
If I do this:
public void Create()
{
  var user = new User();
  context.Users.Add(user);
  context.SaveChanges();
}

I get a user created in my DB with an attached address and both the AddressId and Address.Id property are set to a correct value.
However if I do this:
public void Update(int userId, String name)
{
  var user = context.Users.Single(x => x.Id == userId);
  user.Name = name;
  context.SaveChanges();
}

When I look at the user after the SaveChanges() the name updates as expected but I have an entirely new Address record created in the DB and EF has incremented the AddressId property for the user to the new Address.Id.
This seems like I've made a basic error either in the schema definition, or in how I'm expecting things to work.
Can anyone shed any light on this? appreciate any thoughts.
EDIT
If I make the AddressId on the User a nullable int and then tweak the create method like this:
public void Create()
{
  var user = new User();
  var address = new Address()
  context.Addresses.Add(address);
  user.Address = address;
  context.Users.Add(user);
  context.SaveChanges();
}

Then things work as I'd expect.

A: I think the problem at this row: public Address Address { get; set; } = new Address() - each time, when EF retrives User from database, it rewrites old Address to completely new one, that is why AddressId is changed and icremented. So, simply remove new Address(), EF will have done all work by itself:
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int AddressId { get; set; }
    //[ForeignKey(nameof(AddressId))] is redundant
    public virtual Address Address { get; set; }// = new Address();
}

public class Address
{
    public int Id { get; set; }

    public virtual ICollection<User> Users {get;set;}
    public virtual ICollection<Organization> Organizations {get;set;}
}

Usage with not nullable AddressId:
public void Create()
{
    var address = new Address()
    context.Addresses.Add(address);
    context.SaveChanges();

    var user = new User{ AddressId = address.Id };
    context.Users.Add(user);
    context.SaveChanges();
}