问:
Inserting a Custom Script in React Helmet/ Gatsby
I have this custom script that from a third party I am trying to embed into React Helmet

Usually the scripts are given only as a src url. If I am given the code below, what is the best practice to embed the embed the script with React Helmet

```<code>    <script>
document.getElementsByTagName('head')[0].appendChild(function(s){
    var d=document,m2g=d.createElement('script'),l=function(){Mobi2Go.load(s.container,s.ready);},jq=window.jQuery&&+window.jQuery.fn.jquery.replace(/^(\d+).*$/,'$1')===1&&+window.jQuery.fn.jquery.replace(/^\d+\.(\d+).*$/,'$1')>=7,qs=window.location.search.substring(1),re='=(.*?)(?:;|$)',c=d.cookie.match('MOBI2GO_SESSIONID'+re),w=window.innerWidth;
    m2g.src='https://www.mobi2go.com/store/embed/1990-v8oL.js?'+qs+(jq?'&no_jquery':'')+(c?'&s='+c[1]:'')+'&device_width='+w;
    if(m2g.onload!==undefined)m2g.onload=l;else m2g.onreadystatechange=function(){if(m2g.readyState!=='loaded'&&m2g.readyState!=='complete')return;m2g.onreadystatechange=null;l();}
    window.Mobi2Go_est = +(new Date);
    return m2g;
}({
    container: 'Mobi2Go-Storefront', // Replace with ID  of the element to inject UI into
    ready: function() {} // Callback to fire when app is ready
}));
</script>
</code>```

There is obviously errors if I include all of that in the React Helmet
Not sure what is the best practice to make it work.

I have also tried placing it in the html.js file in gatsby

```<code> import React from 'react';
import PropTypes from 'prop-types';

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
      <script
        dangerouslySetInnerHTML={{
          __html: `
          document.getElementsByTagName('head')[0].appendChild(function(s){
            var d=document,m2g=d.createElement('script'),l=function(){Mobi2Go.load(s.container,s.ready);},jq=window.jQuery&&+window.jQuery.fn.jquery.replace(/^(\d+).*$/,'$1')===1&&+window.jQuery.fn.jquery.replace(/^\d+\.(\d+).*$/,'$1')>=7,qs=window.location.search.substring(1),re='=(.*?)(?:;|$)',c=d.cookie.match('MOBI2GO_SESSIONID'+re),w=window.innerWidth;
            m2g.src='https://www.mobi2go.com/store/embed/1990-v8oL.js?'+qs+(jq?'&no_jquery':'')+(c?'&s='+c[1]:'')+'&device_width='+w;
            if(m2g.onload!==undefined)m2g.onload=l;else m2g.onreadystatechange=function(){if(m2g.readyState!=='loaded'&&m2g.readyState!=='complete')return;m2g.onreadystatechange=null;l();}
            window.Mobi2Go_est = +(new Date);
            return m2g;
        }({
            container: 'Mobi2Go-Storefront', // Replace with ID  of the element to inject UI into
            ready: function() {} // Callback to fire when app is ready
        })););
        `,
        }}
      />
    </html>
  );
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
};
</code>```

答:
It should work using react-helmet, there are examples of it in the README.

You might be missing type="text/javascript" in your script tag:

```

Al alternative option if this doesn't work for you is to customize Gatsby's html.js.

Body:
I have this custom script that from a third party I am trying to embed into React Helmet

Usually the scripts are given only as a src url. If I am given the code below, what is the best practice to embed the embed the script with React Helmet

There is obviously errors if I include all of that in the React Helmet
Not sure what is the best practice to make it work.

I have also tried placing it in the html.js file in gatsby

 import React from 'react';
import PropTypes from 'prop-types';

export default function HTML(props) {
  return (

        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}

        {props.preBodyComponents}
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}

Body:
It should work using react-helmet, there are examples of it in the README.

You might be missing type="text/javascript" in your script tag:

<script type="text/javascript">
  // your script goes here
</script>

Al alternative option if this doesn't work for you is to customize Gatsby's html.js.


来源: stackexchange

问:
Matching a C++ style regex with sed?
Does anyone know how to match this C++ style regex using sed?  Specifically to break it into multiple parts using (pattern) and \n?

```<code>// ZIP code pattern: XXddddd-dddd and variants
regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");
</code>```

For instance the following string would match AB00000-0000 and \1, \2, \3 would print appropriate substrings from pattern space.

SOLUTION:
Here is the sed answer, which accounts for initial two characters.

```<code>$ echo AB00000-0000 | sed 's/\([[:alpha:]]\{2\}\)[[:space:]]*\([[:digit:]]\{5\}\)\(-\([[:digit:]]\{4\}\)\)\{0,1\}/\1 \2 \4/'
AB 00000 0000
</code>```

Thank you

ContentLicense: CC BY-SA 4.0

Title: Matching a C++ style regex with sed?

Body:
Does anyone know how to match this C++ style regex using sed?  Specifically to break it into multiple parts using (pattern) and \n?

// ZIP code pattern: XXddddd-dddd and variants
regex pat (R"(\w{2}\s*\d{5}(−\d{4})?)");

For instance the following string would match AB00000-0000 and \1, \2, \3 would print appropriate substrings from pattern space.

SOLUTION:
Here is the sed answer, which accounts for initial two characters.

$ echo AB00000-0000 | sed 's/\([[:alpha:]]\{2\}\)[[:space:]]*\([[:digit:]]\{5\}\)\(-\([[:digit:]]\{4\}\)\)\{0,1\}/\1 \2 \4/'
AB 00000 0000

Thank you

Body:
Assuming you have a file which contains:

NJ 08542-0033
PA19103-0200
NY10002

Then the sed command:

sed 's/[[:alpha:]]\{2\}[[:space:]]*\([[:digit:]]\{5\}\)\(-\([[:digit:]]\{4\}\)\)\{0,1\}/\1 \3/' file

will output:

08542 0033
19103 0200
10002


问:
Node js Empty object when executing a function from a required file
so i have this news api js file i can run and execute the api and see a full result when consoling

const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('2a59HIDDEN1bd60');

  newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });```
</div>
</div>
</p>

<p>but when i require the above code in another file its coming as empty object</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const passport = require("passport");
const newsapiapi = require("../services/newsApi");

module.exports = (app) => {

  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: ["profile", "email"],
    })
  );

  app.get("/auth/google/callback", passport.authenticate("google"));
  app.get('/api/current_user',(req,res)=>{
      res.send(req.user);
  })
  app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi
    console.log("-----------",resp)

    res.send("hello")

})
};</code>```

In other words the object is empty when executing under  app.get('/api/newsapi') but i get the data with no issue on the first code where the api lies

答:
Because you are not exporting anything from the above file. add module.exports.</p>

```<code>module.exports = newsapi.v2.sources({
        category: 'technology',
        language: 'en',
        country: 'us'
      }).then( response => {
      console.log(response)
        return response
      });
</code>```

Body:
so i have this news api js file i can run and execute the api and see a full result when consoling

const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('2a59HIDDEN1bd60');

  newsapi.v2.sources({
    category: 'technology',
    language: 'en',
    country: 'us'
  }).then( response => {
  console.log(response)
    return response
  });

but when i require the above code in another file its coming as empty object

const passport = require("passport");
const newsapiapi = require("../services/newsApi");

module.exports = (app) => {

  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: ["profile", "email"],
    })
  );

  app.get("/auth/google/callback", passport.authenticate("google"));
  app.get('/api/current_user',(req,res)=>{
      res.send(req.user);
  })
  app.get('/api/newsapi',(req,res)=>{
    var resp =  newsapiapi
    console.log("-----------",resp)

    res.send("hello")

})
};

In other words the object is empty when executing under  app.get('/api/newsapi') but i get the data with no issue on the first code where the api lies

Body:
Because you are not exporting anything from the above file. add module.exports.

module.exports = newsapi.v2.sources({
        category: 'technology',
        language: 'en',
        country: 'us'
      }).then( response => {
      console.log(response)
        return response
      });


问:
Display Data in List view after SAX Parsing
Can anyone give me a full tutorial series Link or sample eclipse project code Link for displaying data in list view after SAX Parsing of XML in Android.

Thanks in advance.

答: declare scrollview in xml & relativelayout as it's child. Now you can add them create number of table rows that you want to display(dynamically) add data to it & add these table row to relativealayout.So will get the feel of listview. I have used this way & work excellent for me.</p>

ContentLicense: CC BY-SA 3.0


问:
OpenPGP public key import in Java
I trying to import a existint pgp public key :

```<code>-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Keybase OpenPGP v1.0.0
Comment: https://keybase.io/crypto

xm8EXtFujBMFK4EEACIDAwQNLpTSC8Tvvve477Qw8YLe7toYxzYgDQRQbcaIajuF
QwWbnns+gZ9EDKIijcmi80QYPICDzrxKCaUOIIN+4//AUkCULovLC67qoEkcgDBY
Zig7GIoTPPYHVgEwr9baTqrNHGl2YW4gPGl2YWxiZXJ0bzg5QGdtYWlsLmNvbT7C
jwQTEwoAFwUCXtFujAIbLwMLCQcDFQoIAh4BAheAAAoJEO8cm+rVKFm/INMBgLQn
5itjscBcGoK605Wlsmk0lmTFK2qE7GmhFsFVg4Ut3vL2BjFBtlSzj21CH8bneQGA
1Btl14COww3h2u0rZY7HcsgzsWV8gaKBfAN/KpmOfxXqZ7HqrNc7o4XuXJH5QVrC
zlIEXtFujBMIKoZIzj0DAQcCAwS8t6iC+Ik9ZbgOY2JwmC8eILILiu3HUM/mqa4q
zBNe+gWgpHPNBjPHJKDYCTByy6UAb3eJHCjJZOj6ZU4BdmfPwsAnBBgTCgAPBQJe
0W6MBQkPCZwAAhsuAGoJEO8cm+rVKFm/XyAEGRMKAAYFAl7RbowACgkQUa2LyJhX
0c/6qQD/WWZpNX0O/k6kYrzK1i/xk0NBLLb4nNq0OB04x7gWuGoBAOPpxjoqRURV
0Hozha+XV9u1aTq+fOMDZxTNgL5FG0KGo4cBf0vATKVZw9wcq+s4mZIXZxs4rAod
sFe5fLgpzZvT/RIHVIU6uJieUsee4hgs0H2ErwGAihWWRrnmaJcsaKC9rq2na3fr
X6BcXRlGbavVofoX+nPyJKDDayHXZ2m4jmgllZe+zlIEXtFujBMIKoZIzj0DAQcC
AwTFxy3Kjj8Jy/fW5W21oG6+aY/ekTChtUANz28MiUvy1de4DYZkFxukRzudT3ij
c2zzsi8UBN02q2cvqY0luAvEwsAnBBgTCgAPBQJe0W6MBQkPCZwAAhsuAGoJEO8c
m+rVKFm/XyAEGRMKAAYFAl7RbowACgkQ103VlblSzhyRKAD/ac/TbN5EaFNdEMWn
28OW8uiDbKl/39EYVE/yr6DjQigA/0VkcoPWN3eVxj44d/cAWhRbWqoy04A+lRtC
wAEV6VXNOdUBgN4AuhF9urpqXFfJ/1s1G8GbRzY0wTpHuZEAjyrBtC+hBgVN0Us7
OYpM6CC6dXOejwGAurQgQOH/i++M8olxZAEnVj0vrP93hjs90N8DbtuIc/7Beb6o
uJ9OEwREoizWqTdn
=4fnu
-----END PGP PUBLIC KEY BLOCK-----
</code>```

But my public key always is getting null value.
This public key is create with algoritm ecdsa ,you can see the values used in this page : keyPropertes

This is my method to read the publicKey ,it works if the algoritms to creaate the key is Rsa :

```<code>public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
        in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);

        PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);

        //
        // we just loop through the collection till we find a key suitable for encryption, in the real
        // world you would probably want to be a bit smarter about this.
        //
        PGPPublicKey key = null;

        //
        // iterate through the key rings.
        //
        Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();

        while (key == null && rIt.hasNext()) {
            PGPPublicKeyRing kRing = rIt.next();
            Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();
            while (key == null && kIt.hasNext()) {
                PGPPublicKey k = kIt.next();

                if (k.isEncryptionKey()) {
                    key = k;
                }
            }
        }

        if (key == null) {
            throw new IllegalArgumentException("Can't find encryption key in key ring.");
        }

        return key;
    }
</code>```

can you give me a big help with this ?

Thanks in advance, best regards ;)

答:
Your code is looking for an encryption-capable key. All three keys in that keyblock are ECDSA (algorithm 19) which is only usable for signature verification, including 'certification' (key signing) and 'authorization' (SSH) both of which are actually kinds of signatures. If you truly want encryption you need an ECDH (algorithm 18) subkey. See https://www.rfc-editor.org/rfc/rfc6637#section-5 .
If you truly want verification, you need to change your code.

Title: OpenPGP public key import in Java

Body:
I trying to import a existint pgp public key :

-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: Keybase OpenPGP v1.0.0
Comment: https://keybase.io/crypto

xm8EXtFujBMFK4EEACIDAwQNLpTSC8Tvvve477Qw8YLe7toYxzYgDQRQbcaIajuF
QwWbnns+gZ9EDKIijcmi80QYPICDzrxKCaUOIIN+4//AUkCULovLC67qoEkcgDBY
Zig7GIoTPPYHVgEwr9baTqrNHGl2YW4gPGl2YWxiZXJ0bzg5QGdtYWlsLmNvbT7C
jwQTEwoAFwUCXtFujAIbLwMLCQcDFQoIAh4BAheAAAoJEO8cm+rVKFm/INMBgLQn
5itjscBcGoK605Wlsmk0lmTFK2qE7GmhFsFVg4Ut3vL2BjFBtlSzj21CH8bneQGA
1Btl14COww3h2u0rZY7HcsgzsWV8gaKBfAN/KpmOfxXqZ7HqrNc7o4XuXJH5QVrC
zlIEXtFujBMIKoZIzj0DAQcCAwS8t6iC+Ik9ZbgOY2JwmC8eILILiu3HUM/mqa4q
zBNe+gWgpHPNBjPHJKDYCTByy6UAb3eJHCjJZOj6ZU4BdmfPwsAnBBgTCgAPBQJe
0W6MBQkPCZwAAhsuAGoJEO8cm+rVKFm/XyAEGRMKAAYFAl7RbowACgkQUa2LyJhX
0c/6qQD/WWZpNX0O/k6kYrzK1i/xk0NBLLb4nNq0OB04x7gWuGoBAOPpxjoqRURV
0Hozha+XV9u1aTq+fOMDZxTNgL5FG0KGo4cBf0vATKVZw9wcq+s4mZIXZxs4rAod
sFe5fLgpzZvT/RIHVIU6uJieUsee4hgs0H2ErwGAihWWRrnmaJcsaKC9rq2na3fr
X6BcXRlGbavVofoX+nPyJKDDayHXZ2m4jmgllZe+zlIEXtFujBMIKoZIzj0DAQcC
AwTFxy3Kjj8Jy/fW5W21oG6+aY/ekTChtUANz28MiUvy1de4DYZkFxukRzudT3ij
c2zzsi8UBN02q2cvqY0luAvEwsAnBBgTCgAPBQJe0W6MBQkPCZwAAhsuAGoJEO8c
m+rVKFm/XyAEGRMKAAYFAl7RbowACgkQ103VlblSzhyRKAD/ac/TbN5EaFNdEMWn
28OW8uiDbKl/39EYVE/yr6DjQigA/0VkcoPWN3eVxj44d/cAWhRbWqoy04A+lRtC
wAEV6VXNOdUBgN4AuhF9urpqXFfJ/1s1G8GbRzY0wTpHuZEAjyrBtC+hBgVN0Us7
OYpM6CC6dXOejwGAurQgQOH/i++M8olxZAEnVj0vrP93hjs90N8DbtuIc/7Beb6o
uJ9OEwREoizWqTdn
=4fnu
-----END PGP PUBLIC KEY BLOCK-----

But my public key always is getting null value.
This public key is create with algoritm ecdsa ,you can see the values used in this page : keyPropertes

This is my method to read the publicKey ,it works if the algoritms to creaate the key is Rsa :

public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
        in = org.bouncycastle.openpgp.PGPUtil.getDecoderStream(in);

        PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);

        //
        // we just loop through the collection till we find a key suitable for encryption, in the real
        // world you would probably want to be a bit smarter about this.
        //
        PGPPublicKey key = null;

        //
        // iterate through the key rings.
        //
        Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();

        while (key == null && rIt.hasNext()) {
            PGPPublicKeyRing kRing = rIt.next();
            Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();
            while (key == null && kIt.hasNext()) {
                PGPPublicKey k = kIt.next();

                if (k.isEncryptionKey()) {
                    key = k;
                }
            }
        }

        if (key == null) {
            throw new IllegalArgumentException("Can't find encryption key in key ring.");
        }

        return key;
    }

can you give me a big help with this ?

Thanks in advance, best regards ;)


问:
Set specific cells with values to trigger with google script one by one
Before VS After looks after running my current codeI'm trying to trigger an action that will allow me to send my current google script into an app.
I tried to look around google and came out with what I have now.

I have a drop-down list at column "K3:K100". There are two options (Slack & Not Yet).

I want my script to be able to run when I select "Slack" and will change to "slacked" once the script is done running while if any of the columns are selected as "Not Yet" it will not run or do anything. Currently, this code works but it turns the whole column of K3:K100 to "Slacked" including the column that are written "Not yet" selected. Please help! I'm new to this.

TLDR: I want K3 column when "Slack" selected turns to slacked with google script while K4 column will not turn to "Slacked" instead just be "not yet" when the drop list is selected as I have programmed the script to run based on "Slack".As of now, it overwrites everything on column K3:K100 to "Slacked" once the script is run. I want those that are currently selected as "Not Yet" to be as it is not overwritten.

```<code>function SendSlack(){

  // get information from the range of
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var lastrow = sheet.getLastRow();

  var range = sheet.getRange(2,1,lastrow-3,12).getValues();

  // create timestamp to mark when communication was sent
  var timestamp = new Date();

  // loop over range and send communication if "SLACK" option chosen
  for (var i = 0; i < range.length; i++)
  {SpreadsheetApp.getActiveSheet().getRange('K3:K100').setValue('Slacked'); // this makes it to "slacked when you press slacked and run script"
    if (range[i][10] == "Slack")
      sendToSlack(range[i]);

    };
  }
}
</code>```

答:
Try this:</p>

```<code>function SendSlack(){
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var rg=sheet.getRange(2,1,sheet.getLastRow()-1,12);
  var vs=rg.getValues();
  //var timestamp = new Date();
  for (var i=0;i< vs.length;i++) {
    if (vs[i][10]=="Slack"){
      sendToSlack(vs[i]);
      sheet.getRange(i+2,11).setValue("Not Yet");//assume column 11 is validation dropdown
    }
  }
}
</code>```

Body:
Before VS After looks after running my current codeI'm trying to trigger an action that will allow me to send my current google script into an app.
I tried to look around google and came out with what I have now.

I have a drop-down list at column "K3:K100". There are two options (Slack & Not Yet).

I want my script to be able to run when I select "Slack" and will change to "slacked" once the script is done running while if any of the columns are selected as "Not Yet" it will not run or do anything. Currently, this code works but it turns the whole column of K3:K100 to "Slacked" including the column that are written "Not yet" selected. Please help! I'm new to this.

TLDR: I want K3 column when "Slack" selected turns to slacked with google script while K4 column will not turn to "Slacked" instead just be "not yet" when the drop list is selected as I have programmed the script to run based on "Slack".As of now, it overwrites everything on column K3:K100 to "Slacked" once the script is run. I want those that are currently selected as "Not Yet" to be as it is not overwritten.

function SendSlack(){

  // get information from the range of
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var lastrow = sheet.getLastRow();

  var range = sheet.getRange(2,1,lastrow-3,12).getValues();

  // create timestamp to mark when communication was sent
  var timestamp = new Date();

  // loop over range and send communication if "SLACK" option chosen
  for (var i = 0; i < range.length; i++)
  {SpreadsheetApp.getActiveSheet().getRange('K3:K100').setValue('Slacked'); // this makes it to "slacked when you press slacked and run script"
    if (range[i][10] == "Slack")
      sendToSlack(range[i]);

    };
  }
}

Body:
Try this:

function SendSlack(){
  var depositid = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = depositid.getSheetByName("MYSHEETNAME");
  var rg=sheet.getRange(2,1,sheet.getLastRow()-1,12);
  var vs=rg.getValues();
  //var timestamp = new Date();
  for (var i=0;i< vs.length;i++) {
    if (vs[i][10]=="Slack"){
      sendToSlack(vs[i]);
      sheet.getRange(i+2,11).setValue("Not Yet");//assume column 11 is validation dropdown
    }
  }
}


问:
How do I calculate a webm's duration metadata value as hex?
I basically want to take a time value, convert it into a hexadecimal format value that the webm metadata can read.

Here is an example value:
44 89 88 40 D5 51 C0 00 00 00 00 = 00:00:21.831000000

How would I calculate this, can you provide examples?

答:
It's a 64-bit Double, can be calculated with this: binaryconvert
Input example: 48000 would be 48 seconds flat. 100000 would be 1 minute 40 seconds. Etc.
Output as hex is shown when you convert as binary and read the left side on the site's output.</p>


问:
symbol not found error when trying to call a user defined class using objects in another class
code 1:

```<code>package hello;
public class hi
{
    int x=30;
}
</code>```

code 2:

```<code>package hello;
public class hii
{
    public static void main(String args[])
    {
        hi ob=new hi();
        int u= ob.x+33;
        System.out.println(u);
    }
}
</code>```

error when compiling code 2:

```<code>    error:cannot find symbol
hi ob =new hi();
^
error:cannot find symbol
hi ob =new hi();
           ^
</code>```

答:
You have to import the class:</p>

```<code>import hello.hi;
</code>```

Body:
code 1:

package hello;
public class hi
{
    int x=30;
}

code 2:

package hello;
public class hii
{
    public static void main(String args[])
    {
        hi ob=new hi();
        int u= ob.x+33;
        System.out.println(u);
    }
}

error when compiling code 2:

    error:cannot find symbol
hi ob =new hi();
^
error:cannot find symbol
hi ob =new hi();
           ^

Body:
You have to import the class:

import hello.hi;


问:
how to make a video from extracted frames?
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

答:
Maybe you could try instead of saving images and load them again, make video captures from your source video and pass it to out object (demo_output.avi in this case) ...something like this:

```<code>import cv2

cap = cv2.VideoCapture('path to video/video.mp4')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
ret, frame = cap.read()
fps_video=cap.get(cv2.CAP_PROP_FPS)
height,width = frame.shape[:2]
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values

while ret:
    frame = cv2.resize(frame, None, fx=1.0, fy=1.0, interpolation=cv2.INTER_AREA)

    out.write(frame)
    ret, frame = cap.read()

cap.release()
out.release()
cv2.destroyAllWindows()
</code>```

UPDATE:

If you want images and then save video file:

```<code>import cv2
import os
import numpy as np

vidcap = cv2.VideoCapture('path to video/video.mp4')
success,image = vidcap.read()
fps_video = vidcap.get(cv2.CAP_PROP_FPS)
height,width = image.shape[:2]
count = 0
while success:

    cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
    success,image = vidcap.read()
    print('Read a new frame: ', success)
    count += 1

vidcap.release()
lista = [[x[5:-4],x] for x in os.listdir() if x.endswith('jpg')]

result=[]
for x in lista:
    t1,t2 = np.int(x[0]),x[1]
    result.append([t1,t2])

result.sort()

#recording video back
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values

for img in result:
    frame = cv2.imread(img[1])
    out.write(frame)
out.release()
</code>```

Body:
I extracted the video frames into a folder called "images". After getting images saved in my folder, I use the following code to create the video again. I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

please advise, how do I fix this? I'd like the videos to be at the same rate as the original video, and frames to be in sequential order.

Body:
Maybe you could try instead of saving images and load them again, make video captures from your source video and pass it to out object (demo_output.avi in this case) ...something like this:

import cv2

cap = cv2.VideoCapture('path to video/video.mp4')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
ret, frame = cap.read()
fps_video=cap.get(cv2.CAP_PROP_FPS)
height,width = frame.shape[:2]
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values

while ret:
    frame = cv2.resize(frame, None, fx=1.0, fy=1.0, interpolation=cv2.INTER_AREA)

    out.write(frame)
    ret, frame = cap.read()

cap.release()
out.release()
cv2.destroyAllWindows()

UPDATE:

If you want images and then save video file:

import cv2
import os
import numpy as np

vidcap = cv2.VideoCapture('path to video/video.mp4')
success,image = vidcap.read()
fps_video = vidcap.get(cv2.CAP_PROP_FPS)
height,width = image.shape[:2]
count = 0
while success:

    cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file
    success,image = vidcap.read()
    print('Read a new frame: ', success)
    count += 1

vidcap.release()
lista = [[x[5:-4],x] for x in os.listdir() if x.endswith('jpg')]

result=[]
for x in lista:
    t1,t2 = np.int(x[0]),x[1]
    result.append([t1,t2])

result.sort()

#recording video back
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values

for img in result:
    frame = cv2.imread(img[1])
    out.write(frame)
out.release()


问:
How to make pthreads work concurrent without pthread_join()
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

```<code>void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}
</code>```

Does anyone know how I can do this without using pthread_join()?

答:
When you use thread in your program, created thread will became child thread and the main program will became main thread. So, we need to block the main thread so that it can not close.

If main thread closed then child threads will be exit as well.
So, You need to find the way how to block main thread to not exit.
thread gives us the facility for that is pthread_join(). This will block the main thread until the child thread is working. Main thread will block on pthread_join() line. It will not execute other lines.

If you want to not use pthread_join() you need to find other ways for that.

```<code>Ex:

while(1);
</code>```

while(1); will not end the main thread until you kill the process.

Body:
I'm making a program where I have multiple threads working at the same time. After messing with the code for a while, I had an issue where I would send a string (char *) to the thread to do further operations with, and somehow the string did not send at all.

Later, I wrote a very simple code where I just send a string to a thread and the function prints it to the console. I found out that without using pthread_join(), it wouldn't work at all. I have no idea why, because I know that whenever pthread_join() is called, it blocks every other thread and waits until that one is finished.

Here's the simple program:

void* prisntstr(void* string);

int main(int argc, char *argv[])
{
    char* string = "Hello!";

    pthread_t thread;

    pthread_create(&thread, NULL, prisntstr, (void*)string);

    pthread_join(thread, NULL);

}

void* prisntstr(void* string)
{
    char* str = (char*)string;

    printf("%s\n", str);
}

Does anyone know how I can do this without using pthread_join()?

Body:
When you use thread in your program, created thread will became child thread and the main program will became main thread. So, we need to block the main thread so that it can not close.

If main thread closed then child threads will be exit as well.
So, You need to find the way how to block main thread to not exit.
thread gives us the facility for that is pthread_join(). This will block the main thread until the child thread is working. Main thread will block on pthread_join() line. It will not execute other lines.

If you want to not use pthread_join() you need to find other ways for that.

Ex:

while(1);

while(1); will not end the main thread until you kill the process.


问:
How to sort a dictionary by relative word frequency in two txt files
I’m trying to write some code to read two separate text files, filter out common words, calculate frequency of words in each file, and finally output in order of relative frequency between the two lists. Therefore ideal output is words relatively more frequent in file 1 should appear at the top of the list, the words relatively more frequent in file 2 should appear at the bottom of the list, and those words that appear in both should be in the middle. For example:

```<code>word, freq file 1, freq file 2
Cat 5,0
Dog 4,0
Mouse 2,2
Carrot 1,4
Lettuce 0,5

</code>```

My code currently outputs the words in order of their frequency in file 1, but I cant figure out how to arrange the list so that it the words more common in file 2 appear at the bottom of the list. I get that I need to subtract the frequency of words in file 1 from the frequency of same words in file 2, but I cant figure out how to operate on the tuple in the dictionary...

Please help!

```<code>import re

f1=open('file1.txt','r', encoding="utf-8") #file 1
f2=open('file2.txt','r', encoding="utf-8") #file 2

file_list = [f1, f2] # This will hold all the files

num_files = len(file_list)

stopwords = ["a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"]

frequencies = {} # One dictionary to hold the frequencies

for i, f in enumerate(file_list):   # Loop over the files, keeping an index i
    for line in f:                                      # Get the lines of that file
        for word in line.split():           # Get the words of that file
            word = re.sub(r'[^\w\s]','',word) # Strip punctuation
            word = word.lower()                     # Make lowercase
            if not word in stopwords:           # Remove stopwords
                    if not word.isdigit():      # Ignore digits
                        if not word in frequencies:
                            frequencies[word] = [0 for _ in range(num_files)] # make a list of 0's for any word not seen yet -- one 0 for each file

                        frequencies[word][i] += 1   # Increment the frequency count for that word and file

frequency_sorted = sorted(frequencies, key=frequencies.get, reverse=True)
for r in frequency_sorted:
    print (r, frequencies[r])

</code>```

答:
May be best if the key argument to sorted points to a function that returns simply an integer which is the difference in frequencies in the two files.  Here is a complete solution which incorporates that.

```<code>import re

class FrequencyComparer:

    stopwords = {"a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"}

    def __init__(self, file1, file2):
        self.freq1 = self.get_freqs_from_file(file1)
        self.freq2 = self.get_freqs_from_file(file2)

    def get_freqs_from_file(self, filename):
        matcher = re.compile("[^\w]*([\w']*)[^\w]*$").match
        freqs = {}
        with open(filename) as f:
            for line in f:
                for word in line.split():
                    m = matcher(word.lower())
                    if m:
                        w = m.group(1)
                        if w not in self.stopwords:
                            freqs[w] = freqs.get(w, 0) + 1
        return freqs

    def get_freqs_for_word(self, word):
        return (self.freq1.get(word, 0), self.freq2.get(word, 0))

    def get_relative_freq(self, word):
        freqs = self.get_freqs_for_word(word)
        return freqs[1] - freqs[0]

    def get_all_words(self):
        return set(set(self.freq1.keys()) | set(self.freq2.keys()))

    def get_all_words_by_relative_freq(self):
        all_words = self.get_all_words()
        return sorted(all_words, key=self.get_relative_freq)

fc = FrequencyComparer("file1.txt", "file2.txt")

for word in fc.get_all_words_by_relative_freq():
    print(word, fc.get_freqs_for_word(word))
</code>```

Body:
I’m trying to write some code to read two separate text files, filter out common words, calculate frequency of words in each file, and finally output in order of relative frequency between the two lists. Therefore ideal output is words relatively more frequent in file 1 should appear at the top of the list, the words relatively more frequent in file 2 should appear at the bottom of the list, and those words that appear in both should be in the middle. For example:

word, freq file 1, freq file 2
Cat 5,0
Dog 4,0
Mouse 2,2
Carrot 1,4
Lettuce 0,5

My code currently outputs the words in order of their frequency in file 1, but I cant figure out how to arrange the list so that it the words more common in file 2 appear at the bottom of the list. I get that I need to subtract the frequency of words in file 1 from the frequency of same words in file 2, but I cant figure out how to operate on the tuple in the dictionary...

Please help!

import re

f1=open('file1.txt','r', encoding="utf-8") #file 1
f2=open('file2.txt','r', encoding="utf-8") #file 2

file_list = [f1, f2] # This will hold all the files

num_files = len(file_list)

stopwords = ["a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"]

frequencies = {} # One dictionary to hold the frequencies

for i, f in enumerate(file_list):   # Loop over the files, keeping an index i
    for line in f:                                      # Get the lines of that file
        for word in line.split():           # Get the words of that file
            word = re.sub(r'[^\w\s]','',word) # Strip punctuation
            word = word.lower()                     # Make lowercase
            if not word in stopwords:           # Remove stopwords
                    if not word.isdigit():      # Ignore digits
                        if not word in frequencies:
                            frequencies[word] = [0 for _ in range(num_files)] # make a list of 0's for any word not seen yet -- one 0 for each file

                        frequencies[word][i] += 1   # Increment the frequency count for that word and file

frequency_sorted = sorted(frequencies, key=frequencies.get, reverse=True)
for r in frequency_sorted:
    print (r, frequencies[r])

Body:
May be best if the key argument to sorted points to a function that returns simply an integer which is the difference in frequencies in the two files.  Here is a complete solution which incorporates that.

import re

class FrequencyComparer:

    stopwords = {"a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"}

    def __init__(self, file1, file2):
        self.freq1 = self.get_freqs_from_file(file1)
        self.freq2 = self.get_freqs_from_file(file2)

    def get_freqs_from_file(self, filename):
        matcher = re.compile("[^\w]*([\w']*)[^\w]*$").match
        freqs = {}
        with open(filename) as f:
            for line in f:
                for word in line.split():
                    m = matcher(word.lower())
                    if m:
                        w = m.group(1)
                        if w not in self.stopwords:
                            freqs[w] = freqs.get(w, 0) + 1
        return freqs

    def get_freqs_for_word(self, word):
        return (self.freq1.get(word, 0), self.freq2.get(word, 0))

    def get_relative_freq(self, word):
        freqs = self.get_freqs_for_word(word)
        return freqs[1] - freqs[0]

    def get_all_words(self):
        return set(set(self.freq1.keys()) | set(self.freq2.keys()))

    def get_all_words_by_relative_freq(self):
        all_words = self.get_all_words()
        return sorted(all_words, key=self.get_relative_freq)

fc = FrequencyComparer("file1.txt", "file2.txt")

for word in fc.get_all_words_by_relative_freq():
    print(word, fc.get_freqs_for_word(word))


问:
Installation did not succeed. The application could not be installed. Installation failed due to: 'device offline'
In android studio 3.6.3

This error indicates when I click on the Run button to install the program on the emulator.

Installation did not succeed. The application could not be installed.
  Installation failed due to: 'device offline'

答: Disconnect your phone and connect again. This was worked for me. </p>


问:
my font haven't be shown in print preview stimulsoft
I am using StimulSoft software for showing reports in my asp.net mvc project.

In my report all of things is OK, but In print preview my font haven't be applied.

I attached my font in report.cshtml file by using font-face.

How can I solve this problem?

答:
Add font in project for example(fonts folder) then add this code into your service

```<code>Stimulsoft.Base.StiFontCollection.AddFontFile(Server.MapPath("~/fonts/my-font/font-name.ttf"));
</code>```

Then add your fonts to server font folder too!

Body:
Add font in project for example(fonts folder) then add this code into your service

Stimulsoft.Base.StiFontCollection.AddFontFile(Server.MapPath("~/fonts/my-font/font-name.ttf"));

Then add your fonts to server font folder too!


问:
How to store results of a for loop in a vector or a list in R
I want to run a simple for loop and store values in a list or a vector. For example:

```<code>ex = c(10,11,17)

for (i in (0:length(ex))){
  if ex[i] < 12 {
    # store the value in a vector
  }
}
</code>```

How can I do this, when I do not know the length of the vector and therefore cannot define it first?

答:
Another base R option is using na.omit + ifelse

```<code>na.omit(ifelse(ex<12,ex,NA))
</code>```

Body:
I want to run a simple for loop and store values in a list or a vector. For example:

ex = c(10,11,17)

for (i in (0:length(ex))){
  if ex[i] < 12 {
    # store the value in a vector
  }
}

How can I do this, when I do not know the length of the vector and therefore cannot define it first?

Body:
Another base R option is using na.omit + ifelse

na.omit(ifelse(ex<12,ex,NA))


问:
Validating expiration date in php
I am trying to validate credit card expiry date as entered by the user in PHP. This is what I have so far:

```<code>if (!isset($_POST["cardDate"])) {
        header("location:payment.php");
        exit();
    }
    else {
        $cardDate=$_POST["cardDate"];

        if ($cardDate=="") {
        $err_msg .="<p>Please enter the credit card expiration date.</p>";

    }
    else {
        if (!preg_match("/^(0[1-9]|1[0-2])[-][0-9]{2}$/", $cardDate)) {
           $err_msg .= "<p>The expire date format is not correct!</p>";

        }
        else {
            $currentDate = date('m/y');
            $exp = strtotime($cardDate);
            $current = strtotime($currentDate);
            if ($current>$exp) {
                $err_msg .= "<p>Credit card has expired";
            }
        }
    }
    }
</code>```

The code currently is not working and I think it is because the user will be entering the expiry date in the "mm-yy" format and I am not sure whether the $currentDate part of the code conveys that message. Does anyone have any suggestions as to what needs to be changed in order for PHP to validate the expiry date? An example of the input date would be 05/19 or 11/20. The code will then match whether 05/19 or 11/20 has already passed by comparing it to today's date which is 05/20. The card expiry date must be after the current date.
HTML code

```<code><p><label for="cardDate">Credit card expiration date</label>
<input type="text" name="cardDate" id="cardDate" maxlength="5" size="5" required="required" placeholder="mm-yy" /></p>
</code>```

答:
Try this, using PHP DateTime class.
Please note you should strictly ensure the user input is in a valid format.

From PHP Docs:

invert is 1 if the interval represents a negative time period and 0
  otherwise.

$userInput = '05-20'; // Example User input
$cardDate = DateTime::createFromFormat('m-y', $userInput);

$currentDate = new DateTime('now');
$interval = $currentDate->diff($cardDate);

if ( $interval->invert == 1 ) {

    // Expired
    echo "Expired\n";
}
else {
    // Valid
    echo "Valid\n";
}
```

Use the following documentation for more:

PHP DateTime

Title: Validating expiration date in php

Body:
I am trying to validate credit card expiry date as entered by the user in PHP. This is what I have so far:

if (!isset($_POST["cardDate"])) {
        header("location:payment.php");
        exit();
    }
    else {
        $cardDate=$_POST["cardDate"];

        if ($cardDate=="") {
        $err_msg .="
Please enter the credit card expiration date.
";

    }
    else {
        if (!preg_match("/^(0[1-9]|1[0-2])[-][0-9]{2}$/", $cardDate)) {
           $err_msg .= "
The expire date format is not correct!
";

        }
        else {
            $currentDate = date('m/y');
            $exp = strtotime($cardDate);
            $current = strtotime($currentDate);
            if ($current>$exp) {
                $err_msg .= "
Credit card has expired";
            }
        }
    }
    }

The code currently is not working and I think it is because the user will be entering the expiry date in the "mm-yy" format and I am not sure whether the $currentDate part of the code conveys that message. Does anyone have any suggestions as to what needs to be changed in order for PHP to validate the expiry date? An example of the input date would be 05/19 or 11/20. The code will then match whether 05/19 or 11/20 has already passed by comparing it to today's date which is 05/20. The card expiry date must be after the current date.
HTML code

Credit card expiration date
<input type="text" name="cardDate" id="cardDate" maxlength="5" size="5" required="required" placeholder="mm-yy" />

Body:
Try this, using PHP DateTime class.
Please note you should strictly ensure the user input is in a valid format.

From PHP Docs:

invert is 1 if the interval represents a negative time period and 0
  otherwise.

$userInput = '05-20'; // Example User input
$cardDate = DateTime::createFromFormat('m-y', $userInput);

$currentDate = new DateTime('now');
$interval = $currentDate->diff($cardDate);

if ( $interval->invert == 1 ) {

    // Expired
    echo "Expired\n";
}
else {
    // Valid
    echo "Valid\n";
}

Use the following documentation for more:

PHP DateTime


问:
When i install any flutter package, example projects are also including?
When i install any flutter package for eg: shared_preference, "example project" is also including along with that package for iOS, Android and Web. That increases my flutter project size. Initially my project size is in 1 mb or 2mb only. Including example projects also in package installation, my project size also increasing. Now my project size is 136mb.

How can i solve to reduce my project size?

Update :

I created new project.

1
Initial project size.

2 After install shared_preference package.

3 After install pod for iOS.

答: If you are talking about the size of the final application it depends on the assets you have used in your application. If you want to reduce the size of the final application try to reduce the usage of local assets.</p>


问:
Selenium-Debugging: Element is not clickable at point (X,Y)
I try to scrape this site by Selenium.

I want to click in "Next Page" buttom, for this I do:

```<code> driver.find_element_by_class_name('pagination-r').click()
</code>```

it works for many pages but not for all, I got this error

```<code>WebDriverException: Message: Element is not clickable at point (918, 13). Other element would receive the click: <div class="linkAuchan"></div>
</code>```

always for this page

I read this question

and I tried this

```<code>driver.implicitly_wait(10)
el = driver.find_element_by_class_name('pagination-r')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(el, 918, 13)
action.click()
action.perform()
</code>```

but I got the same error

答:
I have written logic to handle these type of exception . </p>

```<code>   def find_element_click(self, by, expression, search_window=None, timeout=32, ignore_exception=None,
                       poll_frequency=4):
    """It find the element and click then  handle all type of exception during click

    :param poll_frequency:
    :param by:
    :param expression:
    :param timeout:
    :param ignore_exception:list It is a list of exception which is need to ignore.
    :return:
    """
    if ignore_exception is None:
        ignore_exception = []

    ignore_exception.append(NoSuchElementException)
    if search_window is None:
        search_window = self.driver

    end_time = time.time() + timeout
    while True:
        try:
            web_element = search_window.find_element(by=by, value=expression)
            web_element.click()
            return True
        except tuple(ignore_exception) as e:
            self.logger.debug(str(e))
            if time.time() > end_time:
                self.logger.exception(e)
                time.sleep(poll_frequency)
                break
        except Exception as e:
            raise
    return False
</code>```

Body:
I try to scrape this site by Selenium.

I want to click in "Next Page" buttom, for this I do:

 driver.find_element_by_class_name('pagination-r').click()

it works for many pages but not for all, I got this error

WebDriverException: Message: Element is not clickable at point (918, 13). Other element would receive the click:

always for this page

I read this question

and I tried this

driver.implicitly_wait(10)
el = driver.find_element_by_class_name('pagination-r')
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(el, 918, 13)
action.click()
action.perform()

but I got the same error

Body:
I have written logic to handle these type of exception .

   def find_element_click(self, by, expression, search_window=None, timeout=32, ignore_exception=None,
                       poll_frequency=4):
    """It find the element and click then  handle all type of exception during click

    :param poll_frequency:
    :param by:
    :param expression:
    :param timeout:
    :param ignore_exception:list It is a list of exception which is need to ignore.
    :return:
    """
    if ignore_exception is None:
        ignore_exception = []

    ignore_exception.append(NoSuchElementException)
    if search_window is None:
        search_window = self.driver

    end_time = time.time() + timeout
    while True:
        try:
            web_element = search_window.find_element(by=by, value=expression)
            web_element.click()
            return True
        except tuple(ignore_exception) as e:
            self.logger.debug(str(e))
            if time.time() > end_time:
                self.logger.exception(e)
                time.sleep(poll_frequency)
                break
        except Exception as e:
            raise
    return False


问:
read and write to different textures within same framebuffer
Is it possible to read from texture A and write to texture B that both use the same FBO? I don't believe this has been covered here already. Someone asked the question about OpenGL, but not about WebGL. It seems like the answer is no, based on the answer to this post, but if someone could tell me definitively whether reading/writing to textures in the same fbo is possible it'd really help me. In my code I get the following error:

WebGL warning: drawElementsInstanced: Texture level 0 would be read by TEXTURE_2D unit 0, but written by framebuffer attachment COLOR_ATTACHMENT1, which would be illegal feedback.

the following snippet generates an 'illegal feedback' warning. I know the code may not look/be useful but the point is accomplishing the read/write. To sumarize what I expect to happen is textureA (or call it texture 1) should be used to render to texture B ( aka texture 2 ). I should then see something on the screen; mostly likely 4 greed squares:

/* YOU CAN PROBABLY IGNORE THIS AS IT'S INITIALIZATION CODE */

const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl2');
var fb;
var textures = [];

var tex_datei1 = new Array( 4*64*64 ).fill(9);

var vbo = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER , vbo );

var vertices = new Array( 4*64*64 ).fill( 0 );

gl.bindBuffer( gl.ARRAY_BUFFER , vbo );
gl.bufferData( gl.ARRAY_BUFFER , new Float32Array( vertices ) , gl.STATIC_DRAW );

var ibo = gl.createBuffer();
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER , ibo );

var indices = [ ...Array( vertices.length/4 ).keys() ];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 2;
indices[4] = 3;
indices[5] = 1;
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW);

var vc = `#version 300 es
 precision mediump float;

 uniform sampler2D u_image0;
 uniform sampler2D u_image1;

 in vec3 coordinates;

void main(void) {

  float x = coordinates.x;
  float y = coordinates.y;

  vec4 sample_A = texture( u_image0 , vec2( x , y ) );
  sample_A.x *= 64.0 * 4.0;
  sample_A.y *= 64.0 * 4.0;

  gl_Position = vec4( sample_A.x/10.0 , sample_A.y/10.0 , 0.0 , 1.0 );

  gl_PointSize = 30.0;

}
`;

var vs = gl.createShader( gl.VERTEX_SHADER );
gl.shaderSource( vs , vc );
gl.compileShader(vs);
if( !gl.getShaderParameter( vs , gl.COMPILE_STATUS ) ){
  console.log( gl.COMPILE_STATUS );
  console.log( gl.getShaderInfoLog(vs) );
}

var fc = `#version 300 es
precision highp float;
out vec4 color;
void main(void) {
  color = vec4( 0.5 , 0.5 , 0.0 , 1.0 );
}
`;

var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, fc);
gl.compileShader(fs);
if( !gl.getShaderParameter( fs , gl.COMPILE_STATUS ) ){
  console.log( gl.COMPILE_STATUS );
  console.log( gl.getShaderInfoLog(fs) );
}

var program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
gl.useProgram( program);

var coordinates_u_loc = gl.getAttribLocation(program, "coordinates");
var u_image0_loc = gl.getUniformLocation( program , "u_image0");
var die_berechnung_u_image1Location = gl.getUniformLocation( program , "u_image1");

gl.bindBuffer( gl.ARRAY_BUFFER , vbo );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER , ibo );
gl.enableVertexAttribArray( coordinates_u_loc );
gl.vertexAttribPointer( coordinates_u_loc , 4 , gl.FLOAT , false , 0 , 0 );

/* HERE IS WHERE I GET INTO FRAMEBUFFER SETUP */

fb = gl.createFramebuffer();
gl.bindFramebuffer( gl.FRAMEBUFFER , fb );

gl.uniform1i( u_image0_loc , 0);
//gl.uniform1i( u_image1_loc , 1);

var internal_formats = [ gl.RGBA , gl.RGBA ];
var formats = [ gl.RGBA , gl.RGBA ];
var types = [ gl.UNSIGNED_BYTE , gl.UNSIGNED_BYTE ];

var datas = [ new Uint8Array( tex_datei1.slice() ) , new Uint8Array( tex_datei1.slice() ) ];

for( var i = 0 ; i < datas.length ; i++ ){

  var texture = gl.createTexture();
  gl.bindTexture( gl.TEXTURE_2D , texture );

  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  gl.texImage2D( gl.TEXTURE_2D ,
    0 ,
    internal_formats[i] ,
    64 ,
    64 ,
    0 ,
    formats[ i ] ,
    types[ i ] ,
    datas[ i ]
  );

  textures.push( texture );

 }

/* HERE MAY LIE MY ISSUE AS I HAVE NO IDEA HOW TO SPECIFY THAT THE SECOND TEXTURE SHOULD BE WRITTEN TO. I'VE TRIED MESSING AROUND WITH THE LAYERS PARAMETER BUT THAT JUST CREATES MIPS ISSUES. */

gl.bindTexture( gl.TEXTURE_2D , textures[ 0 ] );
var attachmentPoint = gl.COLOR_ATTACHMENT0;
gl.framebufferTexture2D( gl.FRAMEBUFFER , attachmentPoint , gl.TEXTURE_2D , textures[ 0 ] , 0 );

gl.bindTexture( gl.TEXTURE_2D , textures[ 1 ] );
var attachmentPoint = gl.COLOR_ATTACHMENT1;
gl.framebufferTexture2D( gl.FRAMEBUFFER , attachmentPoint , gl.TEXTURE_2D , textures[ 1 ] , 0 );

var er = gl.checkFramebufferStatus( gl.FRAMEBUFFER );
if( er !== 36053 ){
  console.log( er );
}

 /* DRAW */

 gl.clearColor( 0.0 , 0.0 , 0.0 , 0.0 );
 gl.enable( gl.DEPTH_TEST );
 gl.clear( gl.COLOR_BUFFER_BIT );

 gl.viewport( 0,0, 64 , 64 );

 gl.activeTexture(gl.TEXTURE1);
 gl.bindTexture(gl.TEXTURE_2D, textures[1] );

 gl.drawElements( gl.POINTS , indices.length , gl.UNSIGNED_SHORT , 0 );
          ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <body>
      <canvas width="64" heigh="64" style="width:64px; height:64px; border:thick solid #0000FF; "></canvas>

    </body>

</html></code>```

答:
Is it possible to read from texture A and write to texture B that both use the same FBO

No, it is not possible. Why would you ever want to do that?

What are you trying to accomplish? Sometimes writing to A and sometimes writing to B? If so make 2 fbos. fboA and fboB, attach texture A to fboA and B to fboB. When you want to write to A bind fboA. When you want to write to B bind fboB. If you sometimes want to write to both make fboAB and attach both A and B.

As it is though the code is not setup to ever write to B when you have both textures attached. See: WebGL 2.0: Multiple output textures from the same program

update

The code is attaching both texture[0] and texture[1] to a framebuffer. So at this point both texture[0] and texture[1] are setup for being written to. Also at that point texture[1] is bound to texture unit 0 for reading.

The shader only references one texture, even though it declares both u_image0 and u_image1 you never use u_image1.

The code then assigns texture[1] to texture unit 1 but it never sets u_image0 so u_image0 is using texture unit 0 since uniforms default to 0.

So then the code calls gl.drawArrays.  Because the framebuffer is using both texture[0] and texture[1] for writing and because the shader it using texture[1] on texture unit 0 for reading that's a feedback loop and so the code gets an error.

Here's a script you can paste at the top of the snippet HTML

```<code><script src="https://greggman.github.io/webgl-helpers/webgl-check-framebuffer-feedback.js"></script>
</code>```

from https://greggman.github.io/webgl-helpers/

When I do that and check the JavaScript console I see this error

Uncaught Error: WebGL feedback loop: texture on uniform: u_image0 bound to texture unit 0 is also attached to current framebuffer on attachment: COLOR_ATTACHMENT1

If you want use texture A to generate texture B then at init time you attach B and only B to a framebuffer object

```<code>// at init time
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
                        gl.TEXTURE_2D, textureB, 0);
</code>```

Then at render time you bind that framebuffer

```<code>// make gl.drawXXX write to textureB
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
</code>```

Bind texture A to some texture unit.

```<code>const unit = 7;
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE, textureA);
</code>```

Tell the shader sampler what unit you put the texture on

```<code>gl.uniform1i(u_image0Location, unit);
</code>```

More info here

Body:
Is it possible to read from texture A and write to texture B that both use the same FBO? I don't believe this has been covered here already. Someone asked the question about OpenGL, but not about WebGL. It seems like the answer is no, based on the answer to this post, but if someone could tell me definitively whether reading/writing to textures in the same fbo is possible it'd really help me. In my code I get the following error:

WebGL warning: drawElementsInstanced: Texture level 0 would be read by TEXTURE_2D unit 0, but written by framebuffer attachment COLOR_ATTACHMENT1, which would be illegal feedback.

the following snippet generates an 'illegal feedback' warning. I know the code may not look/be useful but the point is accomplishing the read/write. To sumarize what I expect to happen is textureA (or call it texture 1) should be used to render to texture B ( aka texture 2 ). I should then see something on the screen; mostly likely 4 greed squares:

/* YOU CAN PROBABLY IGNORE THIS AS IT'S INITIALIZATION CODE */

const canvas = document.querySelector('canvas');
const gl = canvas.getContext('webgl2');
var fb;
var textures = [];

var tex_datei1 = new Array( 4*64*64 ).fill(9);

var vbo = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER , vbo );

var vertices = new Array( 4*64*64 ).fill( 0 );

gl.bindBuffer( gl.ARRAY_BUFFER , vbo );
gl.bufferData( gl.ARRAY_BUFFER , new Float32Array( vertices ) , gl.STATIC_DRAW );

var ibo = gl.createBuffer();
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER , ibo );

var indices = [ ...Array( vertices.length/4 ).keys() ];
indices[0] = 0;
indices[1] = 1;
indices[2] = 2;
indices[3] = 2;
indices[4] = 3;
indices[5] = 1;
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( indices ), gl.STATIC_DRAW);

var vc = `#version 300 es
 precision mediump float;

 uniform sampler2D u_image0;
 uniform sampler2D u_image1;

 in vec3 coordinates;

void main(void) {

  float x = coordinates.x;
  float y = coordinates.y;

  vec4 sample_A = texture( u_image0 , vec2( x , y ) );
  sample_A.x *= 64.0 * 4.0;
  sample_A.y *= 64.0 * 4.0;

  gl_Position = vec4( sample_A.x/10.0 , sample_A.y/10.0 , 0.0 , 1.0 );

  gl_PointSize = 30.0;

}
`;

var vs = gl.createShader( gl.VERTEX_SHADER );
gl.shaderSource( vs , vc );
gl.compileShader(vs);
if( !gl.getShaderParameter( vs , gl.COMPILE_STATUS ) ){
  console.log( gl.COMPILE_STATUS );
  console.log( gl.getShaderInfoLog(vs) );
}

var fc = `#version 300 es
precision highp float;
out vec4 color;
void main(void) {
  color = vec4( 0.5 , 0.5 , 0.0 , 1.0 );
}
`;

var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, fc);
gl.compileShader(fs);
if( !gl.getShaderParameter( fs , gl.COMPILE_STATUS ) ){
  console.log( gl.COMPILE_STATUS );
  console.log( gl.getShaderInfoLog(fs) );
}

var program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
gl.useProgram( program);

var coordinates_u_loc = gl.getAttribLocation(program, "coordinates");
var u_image0_loc = gl.getUniformLocation( program , "u_image0");
var die_berechnung_u_image1Location = gl.getUniformLocation( program , "u_image1");

gl.bindBuffer( gl.ARRAY_BUFFER , vbo );
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER , ibo );
gl.enableVertexAttribArray( coordinates_u_loc );
gl.vertexAttribPointer( coordinates_u_loc , 4 , gl.FLOAT , false , 0 , 0 );

/* HERE IS WHERE I GET INTO FRAMEBUFFER SETUP */

fb = gl.createFramebuffer();
gl.bindFramebuffer( gl.FRAMEBUFFER , fb );

gl.uniform1i( u_image0_loc , 0);
//gl.uniform1i( u_image1_loc , 1);

var internal_formats = [ gl.RGBA , gl.RGBA ];
var formats = [ gl.RGBA , gl.RGBA ];
var types = [ gl.UNSIGNED_BYTE , gl.UNSIGNED_BYTE ];

var datas = [ new Uint8Array( tex_datei1.slice() ) , new Uint8Array( tex_datei1.slice() ) ];

for( var i = 0 ; i < datas.length ; i++ ){

  var texture = gl.createTexture();
  gl.bindTexture( gl.TEXTURE_2D , texture );

  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  gl.texImage2D( gl.TEXTURE_2D ,
    0 ,
    internal_formats[i] ,
    64 ,
    64 ,
    0 ,
    formats[ i ] ,
    types[ i ] ,
    datas[ i ]
  );

  textures.push( texture );

 }

/* HERE MAY LIE MY ISSUE AS I HAVE NO IDEA HOW TO SPECIFY THAT THE SECOND TEXTURE SHOULD BE WRITTEN TO. I'VE TRIED MESSING AROUND WITH THE LAYERS PARAMETER BUT THAT JUST CREATES MIPS ISSUES. */

gl.bindTexture( gl.TEXTURE_2D , textures[ 0 ] );
var attachmentPoint = gl.COLOR_ATTACHMENT0;
gl.framebufferTexture2D( gl.FRAMEBUFFER , attachmentPoint , gl.TEXTURE_2D , textures[ 0 ] , 0 );

gl.bindTexture( gl.TEXTURE_2D , textures[ 1 ] );
var attachmentPoint = gl.COLOR_ATTACHMENT1;
gl.framebufferTexture2D( gl.FRAMEBUFFER , attachmentPoint , gl.TEXTURE_2D , textures[ 1 ] , 0 );

var er = gl.checkFramebufferStatus( gl.FRAMEBUFFER );
if( er !== 36053 ){
  console.log( er );
}

 /* DRAW */

 gl.clearColor( 0.0 , 0.0 , 0.0 , 0.0 );
 gl.enable( gl.DEPTH_TEST );
 gl.clear( gl.COLOR_BUFFER_BIT );

 gl.viewport( 0,0, 64 , 64 );

 gl.activeTexture(gl.TEXTURE1);
 gl.bindTexture(gl.TEXTURE_2D, textures[1] );

 gl.drawElements( gl.POINTS , indices.length , gl.UNSIGNED_SHORT , 0 );

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">

      <canvas width="64" heigh="64" style="width:64px; height:64px; border:thick solid #0000FF; "></canvas>

Body:
Is it possible to read from texture A and write to texture B that both use the same FBO

No, it is not possible. Why would you ever want to do that?

What are you trying to accomplish? Sometimes writing to A and sometimes writing to B? If so make 2 fbos. fboA and fboB, attach texture A to fboA and B to fboB. When you want to write to A bind fboA. When you want to write to B bind fboB. If you sometimes want to write to both make fboAB and attach both A and B.

As it is though the code is not setup to ever write to B when you have both textures attached. See: WebGL 2.0: Multiple output textures from the same program

update

The code is attaching both texture[0] and texture[1] to a framebuffer. So at this point both texture[0] and texture[1] are setup for being written to. Also at that point texture[1] is bound to texture unit 0 for reading.

The shader only references one texture, even though it declares both u_image0 and u_image1 you never use u_image1.

The code then assigns texture[1] to texture unit 1 but it never sets u_image0 so u_image0 is using texture unit 0 since uniforms default to 0.

So then the code calls gl.drawArrays.  Because the framebuffer is using both texture[0] and texture[1] for writing and because the shader it using texture[1] on texture unit 0 for reading that's a feedback loop and so the code gets an error.

Here's a script you can paste at the top of the snippet HTML

<script src="https://greggman.github.io/webgl-helpers/webgl-check-framebuffer-feedback.js"></script>

from https://greggman.github.io/webgl-helpers/

When I do that and check the JavaScript console I see this error

Uncaught Error: WebGL feedback loop: texture on uniform: u_image0 bound to texture unit 0 is also attached to current framebuffer on attachment: COLOR_ATTACHMENT1

If you want use texture A to generate texture B then at init time you attach B and only B to a framebuffer object

// at init time
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
                        gl.TEXTURE_2D, textureB, 0);

Then at render time you bind that framebuffer

// make gl.drawXXX write to textureB
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

Bind texture A to some texture unit.

const unit = 7;
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE, textureA);

Tell the shader sampler what unit you put the texture on

gl.uniform1i(u_image0Location, unit);

More info here


问:
'Back' browser action in Ruby on Rails
Can the 'Back' browser functionality be invoked from a Rails 'Back' link? </p>

答: You can use link_to("Hello", :back) to generate Hello.

OwnerDisplayName: alamodey

ContentLicense: CC BY-SA 2.5

Title: 'Back' browser action in Ruby on Rails

Body: You can use link_to("Hello", :back) to generate <a href="javascript:history.back()">Hello</a>.

OwnerDisplayName: cpm


问:
what's wrong with my VHDL sine function gen?
```<code>library IEEE;
use IEEE.MATH_REAL.ALL;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.NUMERIC_STD.ALL;

entity SineGen is
    Port (clock             : in  std_logic;
          dac_ab_vpp        : in  integer range 0 to 4095;
          dac_cd_vpp        : in  integer range 0 to 4095;
          sine_dac_ab       : out std_logic_vector(11 downto 0);
          sine_dac_cd       : out std_logic_vector(11 downto 0));
end SineGen;

architecture Behavioral of SineGen is

subtype slv is std_logic_vector(11 downto 0);

begin

        process(clock)
            variable count       : integer range 0 to 255  := 0;
            variable temp_dac_ab : integer range 0 to 4095 := 0;
            variable temp_dac_cd : integer range 0 to 4095 := 0;

        begin
            if rising_edge(clock) then
</code>```

I tried everything and it comes down to that the next two lines makes the output always zero, and I don't understand why. It should've been an output with a sine function. (count is the 256 samples per period. n is the number of bits.) Are the following in valid format?

```<code>                -- A*sin (2PI/2^n * count)
                temp_dac_ab := dac_ab_vpp * integer(round(sin(real(count * integer(math_2_pi/real(256))))));
                temp_dac_cd := dac_cd_vpp * integer(round(sin(real(count * integer(math_2_pi/real(256))))));

                if count < 256 then
                    count := count + 1;
                else
                    count := 0;
                end if;

                sine_dac_ab <= conv_std_logic_vector(temp_dac_ab, slv'length);
                sine_dac_cd <= conv_std_logic_vector(temp_dac_cd, slv'length);

            end if;

        end process;
end Behavioral;
</code>```

答:
I'm realllyyy rusty with my VHDL, but I think you're wanting this:

```<code>temp_dac_ab := integer(round(dac_ab_vpp * sin(real(count * integer(math_2_pi/real(256))))));
temp_dac_cd := integer(round(dac_cd_vpp * sin(real(count * integer(math_2_pi/real(256))))));
</code>```

(You don't want to round / cast the float coming from sin until after you multiply it with dac_ab_vpp / dac_cd_vpp)

Body:
library IEEE;
use IEEE.MATH_REAL.ALL;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.NUMERIC_STD.ALL;

entity SineGen is
    Port (clock             : in  std_logic;
          dac_ab_vpp        : in  integer range 0 to 4095;
          dac_cd_vpp        : in  integer range 0 to 4095;
          sine_dac_ab       : out std_logic_vector(11 downto 0);
          sine_dac_cd       : out std_logic_vector(11 downto 0));
end SineGen;

architecture Behavioral of SineGen is

subtype slv is std_logic_vector(11 downto 0);

begin

        process(clock)
            variable count       : integer range 0 to 255  := 0;
            variable temp_dac_ab : integer range 0 to 4095 := 0;
            variable temp_dac_cd : integer range 0 to 4095 := 0;

        begin
            if rising_edge(clock) then

I tried everything and it comes down to that the next two lines makes the output always zero, and I don't understand why. It should've been an output with a sine function. (count is the 256 samples per period. n is the number of bits.) Are the following in valid format?

                -- A*sin (2PI/2^n * count)
                temp_dac_ab := dac_ab_vpp * integer(round(sin(real(count * integer(math_2_pi/real(256))))));
                temp_dac_cd := dac_cd_vpp * integer(round(sin(real(count * integer(math_2_pi/real(256))))));

                if count < 256 then
                    count := count + 1;
                else
                    count := 0;
                end if;

                sine_dac_ab <= conv_std_logic_vector(temp_dac_ab, slv'length);
                sine_dac_cd <= conv_std_logic_vector(temp_dac_cd, slv'length);

            end if;

        end process;
end Behavioral;

Body:
I'm realllyyy rusty with my VHDL, but I think you're wanting this:

temp_dac_ab := integer(round(dac_ab_vpp * sin(real(count * integer(math_2_pi/real(256))))));
temp_dac_cd := integer(round(dac_cd_vpp * sin(real(count * integer(math_2_pi/real(256))))));

(You don't want to round / cast the float coming from sin until after you multiply it with dac_ab_vpp / dac_cd_vpp)


问:
UIButton in Swift to Toggle Boolean Variables
So I've been trying to make a button that toggles a boolean variable when clicked, and here is what I have so far. How might I move/resize the button and add a statement that toggles the boolean variable named "yes"? Also, I have the line about Image("check") but I don't think it does anything and I don't know why. Any help would be appreciated!</p>

```<code>import SwiftUI
import SDWebImage
import WebKit

struct ContentView: View {
var body: some View {
    Button(action: {

            }) {

            Image("check").resizable().frame(width: 35, height: 35)
            }.foregroundColor(.green)
  }
 }
</code>```

答:
You can use the below code to display the toggle switch in SwiftUI

```<code>struct ContentView: View {
    @State private var showStatus = true

    var body: some View {
        VStack {
            Toggle(isOn: $showStatus) {
                Text("Show Button Status")
            }.padding()

            if showStatus {
                Text("Button is ON")
            }else{
                Text("Button is OFF")
            }
        }
    }
}
</code>```

Body:
So I've been trying to make a button that toggles a boolean variable when clicked, and here is what I have so far. How might I move/resize the button and add a statement that toggles the boolean variable named "yes"? Also, I have the line about Image("check") but I don't think it does anything and I don't know why. Any help would be appreciated!

import SwiftUI
import SDWebImage
import WebKit

struct ContentView: View {
var body: some View {
    Button(action: {

            }) {

            Image("check").resizable().frame(width: 35, height: 35)
            }.foregroundColor(.green)
  }
 }

Body:
You can use the below code to display the toggle switch in SwiftUI

struct ContentView: View {
    @State private var showStatus = true

    var body: some View {
        VStack {
            Toggle(isOn: $showStatus) {
                Text("Show Button Status")
            }.padding()

            if showStatus {
                Text("Button is ON")
            }else{
                Text("Button is OFF")
            }
        }
    }
}


问:
How to write logs to a file in a lagom application
As part of deploying my lagom application to the kubernetes production environment, I am trying to publish all my logs to a file besides writing to the standard output. For this I created a logback.xml under resources directory adding file appender as per suggestion here.

```<code><appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home:-.}/logs/application.log</file>
    <encoder>
        <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
    </encoder>
</appender>
</code>```

But it is failing to create a log file in the container working directory. I get following error instead:

```<code>09:23:33,209 |-INFO in ch.qos.logback.classic.AsyncAppender[ASYNCSTDOUT] - Setting discardingThreshold to 51
09:23:33,209 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.FileAppender]
09:23:33,213 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
09:23:33,217 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:23:33,220 |-INFO in ch.qos.logback.core.FileAppender[FILE] - File property is set to [./logs/application.log]
09:23:33,222 |-ERROR in ch.qos.logback.core.FileAppender[FILE] - Failed to create parent directories for [/opt/docker/./logs/application.log]
09:23:33,222 |-ERROR in ch.qos.logback.core.FileAppender[FILE] - openFile(./logs/application.log,true) call failed. java.io.FileNotFoundException: ./logs/application.log (No such file or directory)
    at java.io.FileNotFoundException: ./logs/application.log (No such file or directory)
    at  at java.io.FileOutputStream.open0(Native Method)
</code>```

I am not really sure why is it failing to create the log directory and the log file under container working directory.

```<code>demiourgos728@ca5fc4a4c1db:/opt/docker$ ls
bin  lib  share
</code>```

I tried providing the read, write, execute permission on the container working directory as shown below but that didn't work either:

```<code>DockerChmodType.UserGroupWriteExecute
</code>```

Please suggest.

Docker base images conf: dockerBaseImage := "adoptopenjdk/openjdk8".

Whole log file here.

K8S definitions

答:
Writing to a file in a container is bad for two reasons:
1. Logs are available only within the container i.e.,would require to get into the container to see the logs
2. They are not available via kubectl log command
3. They are ephemeral in nature i.e., if container crashes, logs will disappear

Instead writing to STDOUT and STDERR is considered as best practise in a container environment. The logs written to STDOUT and STDERR are redirected by docker engine to a location in the node (/var/log/containers/). Moreover, these logs are also available via kubectl logs command.

Practically logs are not even preserved at even a node but are instead moved to a central logging system. You can read more about it here.

Body:
As part of deploying my lagom application to the kubernetes production environment, I am trying to publish all my logs to a file besides writing to the standard output. For this I created a logback.xml under resources directory adding file appender as per suggestion here.

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home:-.}/logs/application.log</file>
    <encoder>
        <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
    </encoder>
</appender>

But it is failing to create a log file in the container working directory. I get following error instead:

09:23:33,209 |-INFO in ch.qos.logback.classic.AsyncAppender[ASYNCSTDOUT] - Setting discardingThreshold to 51
09:23:33,209 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.FileAppender]
09:23:33,213 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE]
09:23:33,217 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property
09:23:33,220 |-INFO in ch.qos.logback.core.FileAppender[FILE] - File property is set to [./logs/application.log]
09:23:33,222 |-ERROR in ch.qos.logback.core.FileAppender[FILE] - Failed to create parent directories for [/opt/docker/./logs/application.log]
09:23:33,222 |-ERROR in ch.qos.logback.core.FileAppender[FILE] - openFile(./logs/application.log,true) call failed. java.io.FileNotFoundException: ./logs/application.log (No such file or directory)
    at java.io.FileNotFoundException: ./logs/application.log (No such file or directory)
    at  at java.io.FileOutputStream.open0(Native Method)

I am not really sure why is it failing to create the log directory and the log file under container working directory.

demiourgos728@ca5fc4a4c1db:/opt/docker$ ls
bin  lib  share

I tried providing the read, write, execute permission on the container working directory as shown below but that didn't work either:

DockerChmodType.UserGroupWriteExecute

Please suggest.

Docker base images conf: dockerBaseImage := "adoptopenjdk/openjdk8".

Whole log file here.

K8S definitions


问:
Why is `ls -lF` listing files with the prefix "~$" not present in the directory?
I'm currently practicing basic Shell Commands in WSL, Windows Subsystem for Linux (I do not have a linux system but I want to get familiar with commands).

I start a bash session on the command prompt window and navigate to my desktop using cd . In desktop I noticed that after using ls -lF some files with the prefix ~$ appear, such as: '~$executable.x'* or '~$file.txt'
These files are not currently present under the desktop directory, but I was able to remember that they were at one point (varying from a week to months ago).
When I do the same process in powershell windows (not using linux commands) I noticed that files displayed match the desktop and no extra files are listed.

I was wondering if anyone could explain what ~$ means in this context? my intuition is telling me they are backed up files that are somehow hidden in the desktop. After googling, all I could find is that ~ reefers to the home. I also understand that $ is the default prompt symbol for the bash shell when it is waiting for me to type something, but I'm still confused on why it would show up as a prefix for the name of a file.

Hope I made my question clear.
I'm currently reading "Linux® Command Line and Shell Scripting BIBLE" by Blum and Bresnahan but I could not find an answer there, this is my last resource after many googling attempts. Any other source for more information on the topic would be helpful.

答:
On Windows, files that start with ~ are used for hidden files. More specifically,, the prefix ~$ are often used as backups for programs, should they crash before writing updates to a file (e.g. Microsoft Word, etc.)

From Wikipedia:

The tilde symbol is used to prefix hidden temporary files that are created when a document is opened in Windows. For example, when you open a Word document called “Document1.doc,” a file called “~$cument1.doc” is created in the same directory. This file contains information about which user has the file open, to prevent multiple users from attempting to change a document at the same time.

See: Why does Word make temporary files?

Relevant superuser question: https://superuser.com/questions/405257/what-type-of-file-is-file


Title: Group items in a list and calculate sums

Body:
I have a list with weekly figures and need to obtain the grouped totals by month.

The following code does the job, but there should be a more pythonic way of doing it with using the  standard libraries.
The drawback of the code below is that the list needs to be in sorted order.

#Test data (not sorted)
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89),
 ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85),
  ('2020/04/19', 6), ('2020/04/26', 5), ('2020/05/03', 14),
 ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28),('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2),]

month = sum_weekly[0][0].split('/')[1]
count=0
out=[]
for item in sum_weekly:
    m_sel = item[0].split('/')[1]
    if m_sel!=month:
        out.append((month, count))
        count=item[1]
    else:
        count+=item[1]
    month = m_sel
out.append((month, count))

# monthly sums output as ('01', 242), ('02', 360), ('03', 220), ('04', 13), ('05', 67)
print (out)

Body:
You can accomplish this with a Pandas dataframe. First, you isolate the month, and then use groupby.sum().

import pandas as pd

sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89), ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85), ('2020/04/19', 6), ('2020/04/26', 5), ('2020/05/03', 14), ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28),('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2)]

df= pd.DataFrame(sum_weekly)
df.columns=['Date','Sum']
df['Month'] = df['Date'].str.split('/').str[1]
print(df.groupby('Month').sum())


问:
Compare clusters with ground truth
I am facing a problem while comparing the results of my HAC clustering with a ground-truth of manually labeled documents.

The entire dataset is composed of 9k docs, while the ground-truth of 100; the last one allows for multi-label, while the clustering process assigns a document only to one cluster.
Both of them are loaded into a pandas dataframe.

Clusters

```<code>id      label
 0          1
 1          4
 2          9
     ....
9k          3
</code>```

Ground Truth

```<code>id    label1    label2    label3    ...    labeln
 0         0         1         0                1
 1         1         0         1    ...         0
           .....
100        0         0         0    ......      0
</code>```

A '1' in a column means that the document with that ID is assigned to that (or those) label (or labels).

The number of clusters is equal to the number of labels (assigned by the user), let's say --> 14

Now I am doing this:

```<code>    # computes all possible pairs
    def all_pairs(partition):
        return list(itertools.combinations(partition, 2))

    # main

    indexes = list(map(int, ground_truth['id'].values.tolist()))
    # reduce clusters_file matching only manually analyzed documents:
    reduced_df = clusters.loc[clusters['id'].isin(indexes), :]

    clusters_groups = reduced_df.groupby('label')
    clusters_k = len(clusters_groups)

    for label, df_group in clusters_groups:

        docs_in_cluster = df_group['id'].values.tolist()
        pairs_docs_in_cluster = all_pairs(docs_in_cluster)

        intersection_list = []

        for col in self.ground_truth.columns[1:]:

            # get pairs for this columns/label
            constraints = list(
                map(int, ground_truth.loc[ground_truth[col] == 1, 'id'].values.tolist())
            )
            pairs_constraints = all_pairs(constraints)

            # find sets intersection (of pairs) between current cluster and ground_truth
            intersection = list(set(pairs_constraints) & set(pairs_docs_in_cluster))

            if len(intersection) > 0:
                # concatenate with other labels from ground_truth
                intersection_list += intersection

        ratio = len(intersection_list) / len(pairs_docs_in_cluster) * 100
        print("Cluster: ", label, "[{}] elements".format(df_group.shape[0]),
              'matched {} unique pairs'.format(len(intersection_list)), "--> {:.2f} %".format(ratio))
</code>```

And I am getting something like:

```<code>Automatic clustering: 8469 elements and k=14 clusters
Ground Truth: 107 elements and m=14 labels
    Cluster:  0 [29] elements matched 111 unique pairs --> 27.34 %
    Cluster:  1 [5] elements matched 1 unique pairs --> 10.00 %
    Cluster:  2 [1] elements matched 0 unique pairs --> 0.00 %
    Cluster:  3 [1] elements matched 0 unique pairs --> 0.00 %
    Cluster:  4 [9] elements matched 5 unique pairs --> 13.89 %
    Cluster:  5 [6] elements matched 2 unique pairs --> 13.33 %
    Cluster:  6 [13] elements matched 27 unique pairs --> 34.62 %
    Cluster:  7 [2] elements matched 0 unique pairs --> 0.00 %
    Cluster:  8 [4] elements matched 3 unique pairs --> 50.00 %
    Cluster:  9 [3] elements matched 0 unique pairs --> 0.00 %
    Cluster:  10 [2] elements matched 0 unique pairs --> 0.00 %
    Cluster:  11 [8] elements matched 2 unique pairs --> 7.14 %
    Cluster:  12 [6] elements matched 10 unique pairs --> 66.67 %
    Cluster:  13 [17] elements matched 29 unique pairs --> 21.32 %
</code>```

That is quite bad, but if I made an inspection of clustering results, they don't look as bad.
Thus I'm thinking that my metric for evaluation (ratio computing) is wrong, but I really can't see where is my mistake (if any).

答:
I would recommend using the NMI- or the AMI-score.

The AMI or (Adjusted Mutual Information) score is rescaled such that random clustering has a score of 0. The NMI (Normalized Mutual Information) is used for cases where you have a different number of clusters and therefore often a golden standard in the clustering community.

Both measures range between 0 and 1, where 0 is considered as random clustering and 1 matches the ground truth perfectly.

There exist also other measures such as F-measure or Purity.

I am not sure, why there exist many different labels in your "ground truth", but probably you can do a majority-voting on these labels to observe one ground truth.

Title: Compare clusters with ground truth

Body:
I am facing a problem while comparing the results of my HAC clustering with a ground-truth of manually labeled documents.

The entire dataset is composed of 9k docs, while the ground-truth of 100; the last one allows for multi-label, while the clustering process assigns a document only to one cluster.
Both of them are loaded into a pandas dataframe.

Clusters

id      label
 0          1
 1          4
 2          9
     ....
9k          3

Ground Truth

id    label1    label2    label3    ...    labeln
 0         0         1         0                1
 1         1         0         1    ...         0
           .....
100        0         0         0    ......      0

A '1' in a column means that the document with that ID is assigned to that (or those) label (or labels).

The number of clusters is equal to the number of labels (assigned by the user), let's say --> 14

Now I am doing this:

    # computes all possible pairs
    def all_pairs(partition):
        return list(itertools.combinations(partition, 2))

    # main

    indexes = list(map(int, ground_truth['id'].values.tolist()))
    # reduce clusters_file matching only manually analyzed documents:
    reduced_df = clusters.loc[clusters['id'].isin(indexes), :]

    clusters_groups = reduced_df.groupby('label')
    clusters_k = len(clusters_groups)

    for label, df_group in clusters_groups:

        docs_in_cluster = df_group['id'].values.tolist()
        pairs_docs_in_cluster = all_pairs(docs_in_cluster)

        intersection_list = []

        for col in self.ground_truth.columns[1:]:

            # get pairs for this columns/label
            constraints = list(
                map(int, ground_truth.loc[ground_truth[col] == 1, 'id'].values.tolist())
            )
            pairs_constraints = all_pairs(constraints)

            # find sets intersection (of pairs) between current cluster and ground_truth
            intersection = list(set(pairs_constraints) & set(pairs_docs_in_cluster))

            if len(intersection) > 0:
                # concatenate with other labels from ground_truth
                intersection_list += intersection

        ratio = len(intersection_list) / len(pairs_docs_in_cluster) * 100
        print("Cluster: ", label, "[{}] elements".format(df_group.shape[0]),
              'matched {} unique pairs'.format(len(intersection_list)), "--> {:.2f} %".format(ratio))

And I am getting something like:

Automatic clustering: 8469 elements and k=14 clusters
Ground Truth: 107 elements and m=14 labels
    Cluster:  0 [29] elements matched 111 unique pairs --> 27.34 %
    Cluster:  1 [5] elements matched 1 unique pairs --> 10.00 %
    Cluster:  2 [1] elements matched 0 unique pairs --> 0.00 %
    Cluster:  3 [1] elements matched 0 unique pairs --> 0.00 %
    Cluster:  4 [9] elements matched 5 unique pairs --> 13.89 %
    Cluster:  5 [6] elements matched 2 unique pairs --> 13.33 %
    Cluster:  6 [13] elements matched 27 unique pairs --> 34.62 %
    Cluster:  7 [2] elements matched 0 unique pairs --> 0.00 %
    Cluster:  8 [4] elements matched 3 unique pairs --> 50.00 %
    Cluster:  9 [3] elements matched 0 unique pairs --> 0.00 %
    Cluster:  10 [2] elements matched 0 unique pairs --> 0.00 %
    Cluster:  11 [8] elements matched 2 unique pairs --> 7.14 %
    Cluster:  12 [6] elements matched 10 unique pairs --> 66.67 %
    Cluster:  13 [17] elements matched 29 unique pairs --> 21.32 %

That is quite bad, but if I made an inspection of clustering results, they don't look as bad.
Thus I'm thinking that my metric for evaluation (ratio computing) is wrong, but I really can't see where is my mistake (if any).


问:
Is it okay to create constant variables just for the sake of readability?
Imagine if I have this piece of code:

```<code>System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)
</code>```

So is it okay to do the following?

```<code>final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)
</code>```

I don't know, I just bought the Clean Code book by Uncle Bob and I started to question myself.

答:
I believe constant is better than the magic number.

With constant, you control the definition in one place and better naming. It'll affect your further maintainability of the code.

And try using enum instead of constant in some situations. Enum has more pros than constant.

In this case enum example is similar to the below code:

enum UserInput {
    NATIONAL(1), INTERNATIONAL(2), UNKNOWN(-1);

    private int input;

    public int getInput() {
        return input;
    }

    UserInput(int i) {
        this.input = i;
    }

    public static UserInput getUserInput(int input) {
        for (UserInput userInput: UserInput.values()) {
            if (userInput.getInput() == input) {
                return userInput;
            }
        }
        return UNKNOWN;
    }
}

//main
public static void main(String[] args) {
        System.out.println("Is the product:\n"+
                "1. National.\n"+
                "2. International.");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        switch (UserInput.getUserInput(choice)) {
            case NATIONAL: break;
            case INTERNATIONAL: break;
            default:
        }
    }

```

check is for more: Why use Enums instead of Constants? Which is better in terms of software design and readability

Body:
Imagine if I have this piece of code:

System.out.println("Is the product:\n"+
                    "1. National.\n"+
                    "2. International.");
int choice = input.nextInt(System.in);
if (choice == 1)
    (...)
else if (choice == 2)
    (...)

So is it okay to do the following?

final int NATIONAL = 1;
final int INTERNATIONAL = 2;
System.out.println("Is the product:\n"+
                        "1. National.\n"+
                        "2. International.");
int choice = input.nextInt(System.in);
if (choice == NATIONAL)
    (...)
else if (choice == INTERNATIONAL)
    (...)

I don't know, I just bought the Clean Code book by Uncle Bob and I started to question myself.

Body:
I believe constant is better than the magic number.

With constant, you control the definition in one place and better naming. It'll affect your further maintainability of the code.

And try using enum instead of constant in some situations. Enum has more pros than constant.

In this case enum example is similar to the below code:

enum UserInput {
    NATIONAL(1), INTERNATIONAL(2), UNKNOWN(-1);

    private int input;

    public int getInput() {
        return input;
    }

    UserInput(int i) {
        this.input = i;
    }

    public static UserInput getUserInput(int input) {
        for (UserInput userInput: UserInput.values()) {
            if (userInput.getInput() == input) {
                return userInput;
            }
        }
        return UNKNOWN;
    }
}

//main
public static void main(String[] args) {
        System.out.println("Is the product:\n"+
                "1. National.\n"+
                "2. International.");
        Scanner sc = new Scanner(System.in);
        int choice = sc.nextInt();
        switch (UserInput.getUserInput(choice)) {
            case NATIONAL: break;
            case INTERNATIONAL: break;
            default:
        }
    }

check is for more: Why use Enums instead of Constants? Which is better in terms of software design and readability


问:
How to prevent form submitting on other button is clicked rather than submit button in JavaScript
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.</p>

```<code><form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />
  <div class="mt-2">
    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>
  </div>
</form>
<script>
  const add_list_form = document.querySelector('#add_list_form');
  add_list_form.addEventListener('submit',(e)=>{ e.preventDefault();
  console.log('form is submitted..') })
<script>
</code>```

答:
See to it that you've added the right type attribute for the 2 buttons

```<code><button type="submit">Submit</button>
<button type="button">Close</button>
</code>```

Body:
There is two buttons with in form, one is for submit the form and other one is close button for hide the form. But the problem is that form is also submitted on close button click, i don't want this behavior and i also don't want to place the close button outside the form.

<form class="add_form" id="add_list_form">
  <input type="text" class="form-control" placeholder="Enter list title..." id="list_value" />

    <button type="submit" class="btn btn-sm btn-success mr-1" id="add_list_btn">Add List</button>
    <button class="btn btn-sm btn-danger" id="close_btn">close</button>

</form>

Body:
See to it that you've added the right type attribute for the 2 buttons

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