问:
How can I use an href link within a "data" attribute - or rewrite it with jQuery?
I'm using the data attribute to show a credit for a photo on a site:

```<code><div id="test" data-credit="name">
</code>```

But how do I do use a link, like this?:

```<code><div id="test" data-credit="<a href="http://mydomain.com">name</a>">
</code>```

Escaping the html, like this, doesn't work:

```<code><a href="http://mydomain.com" >name</a>
</code>```

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

答:
The issue is in the double quotes around the href value. Since you are using double quotes for The data-credit attribute, you would need to change the quotes around the href attribute to single quotes. Otherwise, you are closing the data-credit double quotes with the opening href double quote.

Try:

```<code><div id="test" data-credit="<a href='http://mydomain.com'>name</a>">
</code>```

If the HTML markup is in-tact, you could then easily access the data-credit attribute, for example:

```<code>$('#test').attr('data-credit');
</code>```

Body:
I'm using the data attribute to show a credit for a photo on a site:

But how do I do use a link, like this?:

<div id="test" data-credit="name">

Escaping the html, like this, doesn't work:

name

It that can't be done, how would I use jQuery to rewrite the data-credit "name" into "name" on document ready?

JSfiddle here: http://jsfiddle.net/8muBm/58/

Body:
The issue is in the double quotes around the href value. Since you are using double quotes for The data-credit attribute, you would need to change the quotes around the href attribute to single quotes. Otherwise, you are closing the data-credit double quotes with the opening href double quote.

Try:

<div id="test" data-credit="<a href='http://mydomain.com'>name</a>">

If the HTML markup is in-tact, you could then easily access the data-credit attribute, for example:

$('#test').attr('data-credit');


来源: stackexchange

问:
npm install ->Failed at the node-sass@4.5.0 postinstall script
I'm trying to do npm install and an error appears :

```<code>Failed at the node-sass@4.5.0 postinstall script.
</code>```

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0

答:
Solved this by force installing node-sass locally: npm install -f node-sass

I was pretty sure I knew what I was doing... this

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to do npm install and an error appears :

Failed at the node-sass@4.5.0 postinstall script.

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0


问:
Date-time always giving 1200HRS
I'm working on a chatbot and using Dialogflow's sys.date-time entity. So when I'm presenting some dates to the bot, like "Today", or "Feb 14", I always get

```<code>"parameters": {
  "date-time": "2021-02-14T12:00:00Z"
}
</code>```

whereas I want

```<code>"parameters": {
  "date-time": "2021-02-14T00:00:00Z"
}
</code>```

Right now I'm using my app to replace the datetime with hours=0, however, I also want the bot to give

```<code>"parameters": {
  "date-time": "2021-02-14T08:00:00Z"
}
</code>```

when I say "feb 14 8AM" (hour is explictly mentioned), but the app will replace the hours. So gonna have to fix it from Dialogflow side. Any solutions please?

答:
I was able to solve this semantic bug by properly analysing the value received for @sys.date-time built-in entity of Dialogflow with multiple phrases.

When just a day/date is mentioned (say Feb 14 2020), this is the data I receive:

```<code>"parameters": {
  "date-time": "2020-02-14T12:00:00Z"
}
</code>```

When I mention time along with the date explicitly (say Feb 14 3pm), this is the data received:

```<code>"parameters": {
  "date-time": {
    "date_time": "2021-02-14T15:00:00Z"
  }
}
</code>```

The difference here is that in the second case, a nested dictionary is presented in date-time.

Distinguishing between that, I was able to slice the ISO-8601 format on my app and replace 12:00:00 with 00:00:00, but if I received a dictionary instead, I did not slice/replace it.

Title: Date-time always giving 1200HRS

Body:
I'm working on a chatbot and using Dialogflow's sys.date-time entity. So when I'm presenting some dates to the bot, like "Today", or "Feb 14", I always get

"parameters": {
  "date-time": "2021-02-14T12:00:00Z"
}

whereas I want

"parameters": {
  "date-time": "2021-02-14T00:00:00Z"
}

Right now I'm using my app to replace the datetime with hours=0, however, I also want the bot to give

"parameters": {
  "date-time": "2021-02-14T08:00:00Z"
}

when I say "feb 14 8AM" (hour is explictly mentioned), but the app will replace the hours. So gonna have to fix it from Dialogflow side. Any solutions please?

Body:
I was able to solve this semantic bug by properly analysing the value received for @sys.date-time built-in entity of Dialogflow with multiple phrases.

When just a day/date is mentioned (say Feb 14 2020), this is the data I receive:

"parameters": {
  "date-time": "2020-02-14T12:00:00Z"
}

When I mention time along with the date explicitly (say Feb 14 3pm), this is the data received:

"parameters": {
  "date-time": {
    "date_time": "2021-02-14T15:00:00Z"
  }
}

The difference here is that in the second case, a nested dictionary is presented in date-time.

Distinguishing between that, I was able to slice the ISO-8601 format on my app and replace 12:00:00 with 00:00:00, but if I received a dictionary instead, I did not slice/replace it.


问:
C++ pointer problem : How to fix bugs in these codes?
```<code>#include <vector>
struct node{
    int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;
</code>```

This prints 999999999 as output. I want to have 123456789.

What is the best way to modify this? I mean, what is the best fashion?

答:
You forgot to declare the function main. Outside any function you may use only declarations. So at least this part of the code

```<code>for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;
</code>```

must be placed in a function.

This loop

```<code>for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
</code>```

places the same pointer in the vector. So this statement

```<code>    temp->x = i;
</code>```

changes the data member x of the same object pointed to by the same pointer temp the copy of which is pushed in the vector. That is after this loop all elements of the vector will point to the same one dynamically allocated object.

You need to create a new object of the type node for each value i.

The program can look for example the following way

```<code>#include <iostream>
#include <memory>
#include <vector>

struct node{
    int x;
};

int main()
{
    std::vector<std::unique_ptr<node>> ptrs;

    for ( int i = 0; i < 10; i++ )
    {
        ptrs.emplace_back( new node { i } );
    }

    for ( const auto &p : ptrs )
    {
        std::cout << p->x << ' ';
    }
    std::cout << '\n';

    return 0;
}
</code>```

Its output is

```<code>0 1 2 3 4 5 6 7 8 9
</code>```

Using the smart pointer unique_ptr allows you not to bother about deleting the allocated memory.

Body:
#include <vector>
struct node{
    int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;

This prints 999999999 as output. I want to have 123456789.

What is the best way to modify this? I mean, what is the best fashion?

Body:
You forgot to declare the function main. Outside any function you may use only declarations. So at least this part of the code

for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;

must be placed in a function.

This loop

for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}

places the same pointer in the vector. So this statement

    temp->x = i;

changes the data member x of the same object pointed to by the same pointer temp the copy of which is pushed in the vector. That is after this loop all elements of the vector will point to the same one dynamically allocated object.

You need to create a new object of the type node for each value i.

The program can look for example the following way

#include <iostream>
#include <memory>
#include <vector>

struct node{
    int x;
};

int main()
{
    std::vector<std::unique_ptr<node>> ptrs;

    for ( int i = 0; i < 10; i++ )
    {
        ptrs.emplace_back( new node { i } );
    }

    for ( const auto &p : ptrs )
    {
        std::cout << p->x << ' ';
    }
    std::cout << '\n';

    return 0;
}

Its output is

0 1 2 3 4 5 6 7 8 9

Using the smart pointer unique_ptr allows you not to bother about deleting the allocated memory.


问:
Ruby sort by multiple values?
I have an array of hashes:

```<code>a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]
</code>```

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

```<code>a.sort_by {|h| [ h['foo'],h['bar'] ]}
</code>```

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

答:
consider compacting the array (removing nil entries), and as a bonus, if it's string comparision, downcase the values for case insensitive sorting.</p>

```<code>a.compact.sort_by { |h| [h['foo'].downcase, h['bar'].downcase] }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ruby sort by multiple values?

Body:
I have an array of hashes:

a=[{ 'foo'=>0,'bar'=>1 },
   { 'foo'=>0,'bar'=>2 },
   ... ]

I want to sort the array first by each hash's 'foo', then by 'bar'. Google tells me this is how it's done:

a.sort_by {|h| [ h['foo'],h['bar'] ]}

But this gives me the ArgumentError "comparison of Array with Array failed". What does this mean?

Body:
consider compacting the array (removing nil entries), and as a bonus, if it's string comparision, downcase the values for case insensitive sorting.

a.compact.sort_by { |h| [h['foo'].downcase, h['bar'].downcase] }


问:
node-sass@4.5.1 postinstall: `node scripts/build.js`
I am trying to build angular-cli on jenkins and getting below error. I am using node (v6.10.0) and npm( v3.10.10). I don't have any direct dependency for node-sass in my package.json so it looks like a peer dependency. I have google this error and it looks like there is some issue with node/npm version. I am using latest version of node so really not sure what's the issue here.

node-sass@4.5.1 postinstall: node scripts/build.js

npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the node-sass@4.5.1 postinstall script 'node
    scripts/build.js'.
    npm ERR! Make sure you have the latest version of node.js and npm
    installed. npm ERR! If you do, this is most likely a problem with the node-sass package,npm ERR! not with npm itself.

Tell the author that this fails on your system:
npm ERR!     node scripts/build.js

答:
by force installing node-sass locally: npm install -f node-sass

I was pretty sure I knew what I was doing... this

ContentLicense: CC BY-SA 3.0


问:
How do I use an if statement in a Vue.js function?
What I am trying to do is have the result function offer two different equations:

return this.number1*(this.number2/100) if the {{ basketballbet.odds }} value is positive

return this.number1*(100/this.number2) if the {{ basketballbet.odds }} value is negative.

Does anyone know if this is possible?

code:

```<code><div id="odds_calculator">
<p>Placing <input type="number" name="number1" v-on:input= "update_number1"> on this bet would win you $XXXX if you were to win the bet.</p>

  <p>Bet Amount: [[ number1  ]] </p>
  <p>Odds: {{ basketballbet.odds }}</p>

  <hr>
  <p>Result: [[ result() ]]</p>
</div>
<script>
new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {

      return this.number1*(this.number2/100);
    },

  },
});
</script>
</code>```

答:
Yes you can but this is also the perfect opportunity to introduce yourself to the ternary operator</p>

```<code>new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {
      //here is the aforementioned ternary operator
      return this.number2 < 0 ? this.number1*(100/this.number2) : this.number1*(this.number2/100);
    },

  },
});
</code>```

Body:
What I am trying to do is have the result function offer two different equations:

return this.number1*(this.number2/100) if the {{ basketballbet.odds }} value is positive

return this.number1*(100/this.number2) if the {{ basketballbet.odds }} value is negative.

Does anyone know if this is possible?

code:

Placing <input type="number" name="number1" v-on:input= "update_number1"> on this bet would win you $XXXX if you were to win the bet.

Bet Amount: [[ number1  ]]

Odds: {{ basketballbet.odds }}

Result: [[ result() ]]

Body:
Yes you can but this is also the perfect opportunity to introduce yourself to the ternary operator

new Vue({
  delimiters: ['[[',']]'],
  el: '#odds_calculator',
  data: {
    number1: 0,
    number2: {{ basketballbet.odds }},
  },
  methods: {
    update_number1: function (event) {
      this.number1 = event.target.value;
    },
    result: function () {
      //here is the aforementioned ternary operator
      return this.number2 < 0 ? this.number1*(100/this.number2) : this.number1*(this.number2/100);
    },

  },
});


问:
Error 'GoogleDataTransport/GDTClock.h' file not found
The problem is where I add "pod 'Firebase'" to Podfile and try run my app. I added GoogleService-Info.plist and try to add my app to firebase. How to fix it?</p>

```<code>Xcode's output:
↳
    In file included from
/AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTUploader.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTUploader.h:19:9: fatal error: 'GoogleDataTransport/GDTUploader.h' file not found
    #import <GoogleDataTransport/GDTUploader.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTNanopbHelpers.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTNanopbHelpers.h:19:9: fatal error: 'GoogleDataTransport/GDTStoredEvent.h' file not found
    #import <GoogleDataTransport/GDTStoredEvent.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTPrioritizer.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTPrioritizer.h:19:9: fatal error: 'GoogleDataTransport/GDTClock.h' file not found
    #import <GoogleDataTransport/GDTClock.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    //AndroidStudioProjects/wts101/ios/Pods/FirebaseCoreDiagnostics/Firebase/CoreDiagnostics/FIRCDLibrary/FIRCoreDiagnostics.m:20:9: fatal error: 'GoogleDataTransport/GDTConsoleLogger.h' file not found
    #import <GoogleDataTransport/GDTConsoleLogger.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    ld: framework not found FirebaseCoreDiagnostics
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Using new build systemnote: Planning buildnote: Constructing build description

</code>```

答: Try using pod update. The pod file may have been updated and you are just running an older version.</p>

Body:
The problem is where I add "pod 'Firebase'" to Podfile and try run my app. I added GoogleService-Info.plist and try to add my app to firebase. How to fix it?

Xcode's output:
↳
    In file included from
/AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTUploader.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTUploader.h:19:9: fatal error: 'GoogleDataTransport/GDTUploader.h' file not found
    #import <GoogleDataTransport/GDTUploader.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTNanopbHelpers.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTNanopbHelpers.h:19:9: fatal error: 'GoogleDataTransport/GDTStoredEvent.h' file not found
    #import <GoogleDataTransport/GDTStoredEvent.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/GDTCCTPrioritizer.m:17:
    //AndroidStudioProjects/wts101/ios/Pods/GoogleDataTransportCCTSupport/GoogleDataTransportCCTSupport/GDTCCTLibrary/Private/GDTCCTPrioritizer.h:19:9: fatal error: 'GoogleDataTransport/GDTClock.h' file not found
    #import <GoogleDataTransport/GDTClock.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    //AndroidStudioProjects/wts101/ios/Pods/FirebaseCoreDiagnostics/Firebase/CoreDiagnostics/FIRCDLibrary/FIRCoreDiagnostics.m:20:9: fatal error: 'GoogleDataTransport/GDTConsoleLogger.h' file not found
    #import <GoogleDataTransport/GDTConsoleLogger.h>
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    1 error generated.
    ld: framework not found FirebaseCoreDiagnostics
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    note: Using new build systemnote: Planning buildnote: Constructing build description


问:
flutter unnecessary statement on call to stream cancel
I have flutter code that creates a stream and cancels the stream during the dispose:

 @override
  void dispose()  {
    if (_playerSubscription != null) {
      _playerSubscription.cancel;
      _playerSubscription = null;
    }
    super.dispose();
  }
```

<p>The problem is that when I submit the code to pub.dev the static analyzer emmits the following error:</p>

<p><code>Avoid using unnecessary statements.</code></p>

<p>The error is emitted on the line:</p>

<pre class="lang-dart prettyprint-override"><code>_playerSubscription.cancel;
</code>```

I've check the code in async.dart and it uses exactly the same three lines that I do.

答:
cancel() is a method. You need to change it like so:

```<code>  @override
  void dispose()  {
    if (_playerSubscription != null) {
      _playerSubscription.cancel();
      _playerSubscription = null;
    }
    super.dispose();
  }
</code>```

Body:
I have flutter code that creates a stream and cancels the stream during the dispose:

 @override
  void dispose()  {
    if (_playerSubscription != null) {
      _playerSubscription.cancel;
      _playerSubscription = null;
    }
    super.dispose();
  }

The problem is that when I submit the code to pub.dev the static analyzer emmits the following error:

Avoid using unnecessary statements.

The error is emitted on the line:

_playerSubscription.cancel;

I've check the code in async.dart and it uses exactly the same three lines that I do.

Body:
cancel() is a method. You need to change it like so:

  @override
  void dispose()  {
    if (_playerSubscription != null) {
      _playerSubscription.cancel();
      _playerSubscription = null;
    }
    super.dispose();
  }


问:
How to use R package in python with importr package
I'm working on a web application using Dash, and I would like to use arules and aruleViz from R within a python script to get a graph of association rules obtained by using an Aprioi algorithm.

I found the rpy2 package and I installed it using conda conda install rpy2 ,then I try to import some packages like base tools by:

```<code>from rpy2.robjects.packages import importr`
arules = importr("tools",)`
</code>```

That was fine(the package was imported)

And when I use: arules = importr("arules",) or arules = importr("arulesViz",)

I got receive the following error:

```<code>RRuntimeError: Error in loadNamespace(name) : there is no package called ‘arulesViz’
</code>```

I saw an option in the importrpackage (lib_loc=None). I'm not sure how can I change it.

If there is any way to solve this, or if you know of a package in python that will help me plot a graph with vertices (I know how to so that with matplot.lib library using scatter but i'm not happy with it) I would greatly appreciate the help!

Thank you!

答:
R packages must be installed before rpy2 can hope to find them. rpy2's importr() relies on R's own package loading system.

If you are certain to have installed that package earlier, you might have installed it in different directory, in a previous R process, and your current R process does not know about that directory. The optional named argument lib_loc accepts the path to that directory (see the doc).

(Note that there is also a utility function to check if an R package is installed without loading it)

Body:
I'm working on a web application using Dash, and I would like to use arules and aruleViz from R within a python script to get a graph of association rules obtained by using an Aprioi algorithm.

I found the rpy2 package and I installed it using conda conda install rpy2 ,then I try to import some packages like base tools by:

from rpy2.robjects.packages import importr`
arules = importr("tools",)`

That was fine(the package was imported)

And when I use: arules = importr("arules",) or arules = importr("arulesViz",)

I got receive the following error:

RRuntimeError: Error in loadNamespace(name) : there is no package called ‘arulesViz’

I saw an option in the importrpackage (lib_loc=None). I'm not sure how can I change it.

If there is any way to solve this, or if you know of a package in python that will help me plot a graph with vertices (I know how to so that with matplot.lib library using scatter but i'm not happy with it) I would greatly appreciate the help!

Thank you!


问:
Custom frequency in fpp package
Here is my data,

```<code>my_df <- data.frame(some_data = sample(1:100, 21, replace=T))
</code>```

I would like to use this time series with ARIMA from fpp package and state that frequency/period is 3. Previously, with forecast package it was easy, I could you use ts(., frequency = 3), but I am not sure how to do it with fpp.

答: The fpp package simply contains data not functions. It depends on the forecast package for all modelling. So you can use ts(my_df$some_data, frequency=3) as usual.

Title: Custom frequency in fpp package

Body:
Here is my data,

my_df <- data.frame(some_data = sample(1:100, 21, replace=T))

I would like to use this time series with ARIMA from fpp package and state that frequency/period is 3. Previously, with forecast package it was easy, I could you use ts(., frequency = 3), but I am not sure how to do it with fpp.


问:
How to save a specific data from a text file and save that resultant data using python
I am new to python and I am trying to read a text file and collect some information from the text.
For Instance, If the text contains "1. Andrew is a student at XYZ University who graduated in 2020 ."
For the above text, I require my answer to be "Student1: Andrew, Graduation year: 2020, University: XYZ". Likewise, I need to verify for n number of students and store the results of n number of students. I just know the basics here where I can open the file in different formats such as read, write...So, I am confused about how to proceed to the next step.

Any help would be appreciated.
Thank you

答:
It sounds as though you might want to look into json instead, as it's a bit easier to work with.

import json

# writing to a json file

data = {"andrew": {"university": "XYZ", "graduation": 2020}}

with open("students.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification

# reading from a json file

with open("students.json", "r") as fp:
    data = json.load(fp)

print(data)
print(data["andrew"])
print(data["andrew"]["university"])

# output:
# {'andrew': {'university': 'XYZ', 'graduation': 2020}}
# {'university': 'XYZ', 'graduation': 2020}
# XYZ

# what the file will look like:
{
    "andrew": {
        "graduation": 2020,
        "university": "XYZ"
    }
}
```

A json object behaves exactly like a dictionary - key, value pairs. This will help to navigate and search for/save specific data.

If you'd like to get the number of students, you can do len(data.keys()) if you have the file structure as is in the example.

References:

File context managers

Working with dicts

json.dump() - For saving dictionary objects

json.load() - For loading in dictionary objects

Body:
It sounds as though you might want to look into json instead, as it's a bit easier to work with.

import json

# writing to a json file

data = {"andrew": {"university": "XYZ", "graduation": 2020}}

with open("students.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification

# reading from a json file

with open("students.json", "r") as fp:
    data = json.load(fp)

print(data)
print(data["andrew"])
print(data["andrew"]["university"])

# output:
# {'andrew': {'university': 'XYZ', 'graduation': 2020}}
# {'university': 'XYZ', 'graduation': 2020}
# XYZ

# what the file will look like:
{
    "andrew": {
        "graduation": 2020,
        "university": "XYZ"
    }
}

A json object behaves exactly like a dictionary - key, value pairs. This will help to navigate and search for/save specific data.

If you'd like to get the number of students, you can do len(data.keys()) if you have the file structure as is in the example.

References:

File context managers

Working with dicts

json.dump() - For saving dictionary objects

json.load() - For loading in dictionary objects


问:
SignerSign() failed. (-2146869243/0x80096005)
I've been signing compiled apps for several months and have a script that calls the Windows 10 SDK signtool.  It's been working fine on two different computers and my certificate is valid.  Today, I just started getting an "Unexpected internal error" with the error number listed above. I tried disabling antivirus which helped in this case but not mine.

My app is written in Delphi but I don't think that matters as this same problem was reported on Microsoft's Developer Community under Visual Studio.  I had been using version 10.0.18362.0 of the SDK but after getting this error, found there's an update and tried version 10.0.19041.0 but got the same error.

Anyone else with this problem?  Any suggestions?

答:
Same here. The issue was the demise of the comodoca.com timestamp server.

I switched to using DigiCert:

```<code>"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /tr http://timestamp.digicert.com ...
</code>```

UPDATE 2 (perplexed nailed it) comodoca.com actually still works fine, you just need to add a /td sha256 switch to your signtool.exe command, like this:

```<code>"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /tr http://timestamp.comodoca.com /td sha256 ...
</code>```

It seems DigiCert is throttling the number of timestamps they give out anyway, so I had to switch back. BTW note that you can still use any digital cert from any cert authority, it doesn't have to be from DigiCert to use their timestamp server.

Body:
Same here. The issue was the demise of the comodoca.com timestamp server.

I switched to using DigiCert:

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /tr http://timestamp.digicert.com ...

UPDATE 2 (perplexed nailed it) comodoca.com actually still works fine, you just need to add a /td sha256 switch to your signtool.exe command, like this:

"C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\signtool.exe" sign /tr http://timestamp.comodoca.com /td sha256 ...

It seems DigiCert is throttling the number of timestamps they give out anyway, so I had to switch back. BTW note that you can still use any digital cert from any cert authority, it doesn't have to be from DigiCert to use their timestamp server.


问:
PHP strip unknown file extension
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

```<code>basename('path/to/file.php','.php')
</code>```

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Title: PHP strip unknown file extension

Body:
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Body: $filename = preg_replace('@\.([^\.]+)$@', '', $filename);


问:
Disabling Java Integer Cache
Recently stumbled on a problem related to the Java Integer Cache and I'm looking for a way to disable it.

Right now testing is impossible because we can't say it works unless we test with an integer value outside of the cache.

Our case : We had 8 buggy != comparisons and everything worked fine during 2 months of testing because we never had an underlying database entity with a PK higher than 128.

答:
Since Java 6 introduced Escape Analysis I see no benefit in pooling temporary objects such as Integer. Moreover, Integer cache being "unpredictable" sometimes can prevent Escape Analysis from functioning properly.

Java 8 Escape Analysis can't do scalar replacement of Integer objects if Integer cache is enabled. (Java 13 seems to be doing well either way)

Disabling Integer cache is not supported officially, but it can be done with this code snippet:

```<code>public static Unsafe getUnsafe() {
    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        return (Unsafe) theUnsafe.get(null);
    } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
        return null;
    }
}

public static void disableIntegerCache() {
    try {
        Class<?> clazz = Class.forName("java.lang.Integer$IntegerCache");
        Field cache = clazz.getDeclaredField("cache");
        Field low = clazz.getDeclaredField("low");
        Field high = clazz.getDeclaredField("high");

        Unsafe unsafe = getUnsafe();

        Object base = unsafe.staticFieldBase(low);
        long lowOffset = unsafe.staticFieldOffset(low);
        long highOffset = unsafe.staticFieldOffset(high);
        long cacheOffset = unsafe.staticFieldOffset(cache);

        unsafe.putObjectVolatile(base, cacheOffset, new Integer[0]);
        unsafe.putIntVolatile(base, lowOffset, Integer.MAX_VALUE);
        unsafe.putIntVolatile(base, highOffset, Integer.MIN_VALUE);
    } catch (ClassNotFoundException | NoSuchFieldException | IllegalArgumentException e) {
        e.printStackTrace();
    }
}
</code>```

I use MAX_VALUE and MIN_VALUE because of weird behavior related to JVM intrinsics in valueOf method.

Title: Disabling Java Integer Cache

Body:
Since Java 6 introduced Escape Analysis I see no benefit in pooling temporary objects such as Integer. Moreover, Integer cache being "unpredictable" sometimes can prevent Escape Analysis from functioning properly.

Java 8 Escape Analysis can't do scalar replacement of Integer objects if Integer cache is enabled. (Java 13 seems to be doing well either way)

Disabling Integer cache is not supported officially, but it can be done with this code snippet:

public static Unsafe getUnsafe() {
    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        return (Unsafe) theUnsafe.get(null);
    } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
        e.printStackTrace();
        return null;
    }
}

public static void disableIntegerCache() {
    try {
        Class<?> clazz = Class.forName("java.lang.Integer$IntegerCache");
        Field cache = clazz.getDeclaredField("cache");
        Field low = clazz.getDeclaredField("low");
        Field high = clazz.getDeclaredField("high");

        Unsafe unsafe = getUnsafe();

        Object base = unsafe.staticFieldBase(low);
        long lowOffset = unsafe.staticFieldOffset(low);
        long highOffset = unsafe.staticFieldOffset(high);
        long cacheOffset = unsafe.staticFieldOffset(cache);

        unsafe.putObjectVolatile(base, cacheOffset, new Integer[0]);
        unsafe.putIntVolatile(base, lowOffset, Integer.MAX_VALUE);
        unsafe.putIntVolatile(base, highOffset, Integer.MIN_VALUE);
    } catch (ClassNotFoundException | NoSuchFieldException | IllegalArgumentException e) {
        e.printStackTrace();
    }
}

I use MAX_VALUE and MIN_VALUE because of weird behavior related to JVM intrinsics in valueOf method.


问:
Return new Array that adds up every 2 values?
I am trying to create a method that will take in an array and return a new array that adds every 2 values to create one new value and move on to the next 2 values. If I have an array of {5,8,4,2} I want that array to become {13,6}. So far in my code I have it set up to where it creates an array of {5,8,4,2} and makes it into {13, 12, 6, 0} However, I don't want it to add that way. So I was wondering how do I get my program to skip over the 2nd value after doing the first addition? Also, how do I get rid of that useless zero at the end?</p>

```<code>import java.util.*;
import java.io.*;
public class reduceArray{
   public static int[] reduce(int[] currentArray){
   int[] newArray = new int[currentArray.length];

   for(int i = 0; i < currentArray.length -1; i++){

     newArray[i] = currentArray[i] + currentArray[i+1];

      }

     return newArray;

   }

   public static void main(String[] args){
       int[] arrayANew;
       int[] arrayA = {5,8,4,2};

       arrayANew= reduce(arrayA);

       System.out.println(Arrays.toString(arrayANew) );

    }
}
</code>```

答:
This will handle arrays of even or odd length.  If odd, the last element in the result array will be the last element in the vals array.

```<code>int[] vals = { 10, 2, 3, 10, 1, 2, 3, 6};
int[] result = new int[(vals.length +1) / 2];
for (int i = 0; i < vals.length; i += 2) {
    result[i / 2] = vals[i] + (i <vals.length-1 ? vals[i + 1] : 0);
}

System.out.println(Arrays.toString(result));
</code>```

prints

```<code>[12, 13, 3, 9]
</code>```

Points to consider.

The results array is sized to round up if need be.

Whether to try and add the last value is controlled by a ternary operator

Body:
I am trying to create a method that will take in an array and return a new array that adds every 2 values to create one new value and move on to the next 2 values. If I have an array of {5,8,4,2} I want that array to become {13,6}. So far in my code I have it set up to where it creates an array of {5,8,4,2} and makes it into {13, 12, 6, 0} However, I don't want it to add that way. So I was wondering how do I get my program to skip over the 2nd value after doing the first addition? Also, how do I get rid of that useless zero at the end?

import java.util.*;
import java.io.*;
public class reduceArray{
   public static int[] reduce(int[] currentArray){
   int[] newArray = new int[currentArray.length];

   for(int i = 0; i < currentArray.length -1; i++){

     newArray[i] = currentArray[i] + currentArray[i+1];

      }

     return newArray;

   }

   public static void main(String[] args){
       int[] arrayANew;
       int[] arrayA = {5,8,4,2};

       arrayANew= reduce(arrayA);

       System.out.println(Arrays.toString(arrayANew) );

    }
}

Body:
This will handle arrays of even or odd length.  If odd, the last element in the result array will be the last element in the vals array.

int[] vals = { 10, 2, 3, 10, 1, 2, 3, 6};
int[] result = new int[(vals.length +1) / 2];
for (int i = 0; i < vals.length; i += 2) {
    result[i / 2] = vals[i] + (i <vals.length-1 ? vals[i + 1] : 0);
}

System.out.println(Arrays.toString(result));

prints

[12, 13, 3, 9]

Points to consider.

The results array is sized to round up if need be.

Whether to try and add the last value is controlled by a ternary operator


问:
2 Datepicker in FlaskForm
I found this on DatePickerWidget with Flask, Flask-Admin and WTforms and this is perfect but I need two datepickers because I want to pickup 2 date (start and end date) for SQL query

py file:

```<code>class ExampleForm(Form):
    dt = DateField('DatePicker', format='%Y-%m-%d')
</code>```

and here I assign to variable:

```<code>date = form.dt.data.strftime('%Y-%m-%d')
</code>```

html file:

```<code><form action="#" method="post">
    {{ form.dt(class='datepickerA') }}
    {{ form.hidden_tag() }}
    <input type="submit"/>
</code>```

I'm not sure how to add one more picker and assign to 2 variable in py file?

Thanks in advance

答:
Your ExampleForm class needs to have two members:

```<code>class ExampleForm(Form):
    dStart = DateField(...)
    dEnd = DateField(...)
</code>```

Then in your form, you would use something like this:

```<code><form action="/process" method="POST">
    {{ form.dStart.label }} {{ form.dStart() }}
    {{ form.dEnd.label }} {{ form.dEnd() }}
    <input type="submit">Do it!</input>
</form>
</code>```

Title: 2 Datepicker in FlaskForm

Body:
I found this on DatePickerWidget with Flask, Flask-Admin and WTforms and this is perfect but I need two datepickers because I want to pickup 2 date (start and end date) for SQL query

py file:

class ExampleForm(Form):
    dt = DateField('DatePicker', format='%Y-%m-%d')

and here I assign to variable:

date = form.dt.data.strftime('%Y-%m-%d')

html file:

<form action="#" method="post">
    {{ form.dt(class='datepickerA') }}
    {{ form.hidden_tag() }}
    <input type="submit"/>

I'm not sure how to add one more picker and assign to 2 variable in py file?

Thanks in advance

Body:
Your ExampleForm class needs to have two members:

class ExampleForm(Form):
    dStart = DateField(...)
    dEnd = DateField(...)

Then in your form, you would use something like this:

<form action="/process" method="POST">
    {{ form.dStart.label }} {{ form.dStart() }}
    {{ form.dEnd.label }} {{ form.dEnd() }}
    <input type="submit">Do it!</input>
</form>


问:
When calculating a CRC, should the remainder be set to something if it becomes 0?
Are there CRC algorithms in which the remainder is checked for zero during the generation, and changed when that happens?

When calculating a CRC, if you start with an initial value (the CRC value, aka the remainder value) of 0, leading zeroes in the data being CRCd will not have an effect. So the CRC for "\0\0\0Hello" will be the same as "Hello".

https://xcore.github.io/doc_tips_and_tricks/crc.html#the-initial-value

This means that if, as the CRC is being calculated, the value becomes zero at some point, any zeroes immediately following that point will have no effect on the CRC. If one or more of the zeroes is lost, the CRC will not be changed.

I want to generate a CRC for some data, so that I can determine when a byte is lost. Is this an esoteric application of the CRC? Because when looking for examples of calculating a CRC, I have not found any examples where the CRC value is checked for 0 during the computation, and some non-zero bits fed in a that point. I would think that this would be the only way to be sure to detect a loss of one or more bits at a point in the data, if the CRC up to that point happened to be 0.

答: If you did that, then it wouldn't be a CRC anymore. So, no. By definition there are no such CRC algorithms.</p>


问:
handling back button android
I have a problem while hitting the back button on an activity, in particular, the back button on the activity closes the application and destroys all the activities, I want to go back in the stack, and in the previously called activity when hitting the back button.

Here is my code:

ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
setSupportActionBar(ChatToolBar);
ActionBar actionBar =  getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);
```

<p>My <strong>AndroidManifest.xml</strong>:</p>

<pre class="lang-xml prettyprint-override"><code><activity
    android:name=".ChatActivity"
    android:parentActivityName=".ProfileActivity" />
</code>```

I also tried:

```<code>        <activity
            android:name=".ChatActivity"
            android:parentActivityName=".ProfileActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ProfileActivity" />
        </activity>
</code>```

Where should be the problem?

答:
you can add button back in action bar

in mainfest.xml

```<code><activity .ActivityB" >
<meta-data
 android:name="android.support.PARENT_ACTIVITY"
 android:value=".ActivityA" />
</code>```

Title: handling back button android

Body:
I have a problem while hitting the back button on an activity, in particular, the back button on the activity closes the application and destroys all the activities, I want to go back in the stack, and in the previously called activity when hitting the back button.

Here is my code:

ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
setSupportActionBar(ChatToolBar);
ActionBar actionBar =  getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);
actionBar.setCustomView(action_bar_view);

My AndroidManifest.xml:

<activity
    android:name=".ChatActivity"
    android:parentActivityName=".ProfileActivity" />

I also tried:

        <activity
            android:name=".ChatActivity"
            android:parentActivityName=".ProfileActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".ProfileActivity" />
        </activity>

Where should be the problem?

Body:
you can add button back in action bar

in mainfest.xml

<activity .ActivityB" >
<meta-data
 android:name="android.support.PARENT_ACTIVITY"
 android:value=".ActivityA" />


问:
Invariant failed: You should not use <withRouter(App) /> outside a <Router>
I'm trying to rimplement server-side rendering in my React App. In the server.js I'm just listening for any route (/*) and generate a string with the react server and send it back.

But the "withRouter" is complaining because it thinks it is not inside a router. But it clearly is. This is very strange.

client/src/App.js

class App extends Component {
    render() {
        return (
Hello
)
    }
}
export default withRouter(App)
```

<p><strong>server/index.js</strong></p>

<pre class="lang-js prettyprint-override"><code>const content = ReactDOMServer.renderToString(
    <Provider store={store}>
        <StaticRouter location={location} context={context}>
            <App/>
        </StaticRouter>
    </Provider>
);
</code>```

```<code>Error: Invariant failed: You should not use <withRouter(App) /> outside a <Router>
    at invariant (webpack-internal:///./client/node_modules/tiny-invariant/dist/tiny-invariant.esm.js:11:11)
    at Object.eval [as children] (webpack-internal:///./client/node_modules/react-router/esm/react-router.js:729:88)
    at ReactDOMServerRenderer.render (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3635:55)
    at ReactDOMServerRenderer.read (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
    at Object.renderToString (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)
    at _callee2$ (webpack-internal:///./server/index.js:137:38)
    at tryCatch (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:274:22)
    at Generator.prototype.<computed> [as next] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (webpack-internal:///./server/index.js:7:103)

</code>```

答:
The problem was that the reference to the StaticRouter must be EXACTLY the same.

So the solution was to use the SAME StaticRouter export for both (client and server). Essentially, doing in the server code:

```<code>const { StaticRouter } = require('../client/node_modules/react-router-dom');
</code>```

Hope this helps someone.

Body:
I'm trying to rimplement server-side rendering in my React App. In the server.js I'm just listening for any route (/*) and generate a string with the react server and send it back.

But the "withRouter" is complaining because it thinks it is not inside a router. But it clearly is. This is very strange.

client/src/App.js

class App extends Component {
    render() {
        return (
Hello
)
    }
}
export default withRouter(App)

server/index.js

const content = ReactDOMServer.renderToString(
    <Provider store={store}>
        <StaticRouter location={location} context={context}>
            <App/>
        </StaticRouter>
    </Provider>
);

Error: Invariant failed: You should not use <withRouter(App) /> outside a <Router>
    at invariant (webpack-internal:///./client/node_modules/tiny-invariant/dist/tiny-invariant.esm.js:11:11)
    at Object.eval [as children] (webpack-internal:///./client/node_modules/react-router/esm/react-router.js:729:88)
    at ReactDOMServerRenderer.render (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3635:55)
    at ReactDOMServerRenderer.read (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3373:29)
    at Object.renderToString (webpack-internal:///./node_modules/react-dom/cjs/react-dom-server.node.development.js:3988:27)
    at _callee2$ (webpack-internal:///./server/index.js:137:38)
    at tryCatch (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:274:22)
    at Generator.prototype.<computed> [as next] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (webpack-internal:///./server/index.js:7:103)

Body:
The problem was that the reference to the StaticRouter must be EXACTLY the same.

So the solution was to use the SAME StaticRouter export for both (client and server). Essentially, doing in the server code:

const { StaticRouter } = require('../client/node_modules/react-router-dom');

Hope this helps someone.


问:
Is there a way to access the attribute of another object in python
I'm trying to create three classes one mainly storing attribute of a person, the other two will access to the instance of a person and do a bunch of things to adjust the its attribute values.

I want to keep them in separate way so its easy to manage the content in each class and expand. I think this is not a inheritance problem so my code is obviously wrong for the goal but I have no clue what shall be done.

```<code>
class CreatePerson():
    def __init__(self):
        self.to_do_list=[]

class Shop(CreatePerson):
    def __init__(self,CreatePerson):
        super().__init__()
    def add_element(self,a):
        self.to_do_list+=[a]

class Recreation(CreatePerson):

    def __init__(self,CreatePerson):
        super().__init__()

    def add_element(self,a):
        self.to_do_list+=[a]

if __name__ == '__main__':

    joe=CreatePerson()
    p1=Shop(joe)
    p2=Recreation(joe)
    p1.add_element('whole milk')
    p2.add_element('reading book')
    print(joe.to_do_list)
</code>```

I was hoping it could return following, but obviously it didn't link

```<code>['whole milk','reading book']
</code>```

答:
If I understand correctly, you want your Shop and Recreation objects to share their underlying CreatePerson object. But your code doesn't do that. As @mike scotty commented, you pass in Joe, but don't use Joe for anything. So these new objects just create their own to_do_lists, which are not shared. Here is something like what i imagine you want:

```<code>class CreatePerson():
    def __init__(self):
        self.to_do_list = []
    def add_element(self, a):
        self.to_do_list += [a]

class Shop():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)

class Recreation():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)

>>> joe=CreatePerson()
>>> p1=Shop(joe)
>>> p2=Recreation(joe)
>>> p1.add_element('whole milk')
>>> p2.add_element('reading book')
>>> print(joe.to_do_list)
['whole milk', 'reading book']
</code>```

So now Shop and Recreation aren't instances of a CreatePerson, but they do take a CreatePerson in their constructor, and store a reference to that person. And when you call add_element on those objects, they call the new add_element method that their CreatePerson has.

I'd just like to note that I don't think this is exactly the right abstraction - your Shop has one-and-only-one person, as does your Recreation. But I took it at face value for the purposes of answering this question.

Hope that helps, Happy Coding!

Body:
I'm trying to create three classes one mainly storing attribute of a person, the other two will access to the instance of a person and do a bunch of things to adjust the its attribute values.

I want to keep them in separate way so its easy to manage the content in each class and expand. I think this is not a inheritance problem so my code is obviously wrong for the goal but I have no clue what shall be done.

class CreatePerson():
    def __init__(self):
        self.to_do_list=[]

class Shop(CreatePerson):
    def __init__(self,CreatePerson):
        super().__init__()
    def add_element(self,a):
        self.to_do_list+=[a]

class Recreation(CreatePerson):

    def __init__(self,CreatePerson):
        super().__init__()

    def add_element(self,a):
        self.to_do_list+=[a]

if __name__ == '__main__':

    joe=CreatePerson()
    p1=Shop(joe)
    p2=Recreation(joe)
    p1.add_element('whole milk')
    p2.add_element('reading book')
    print(joe.to_do_list)

I was hoping it could return following, but obviously it didn't link

['whole milk','reading book']

Body:
If I understand correctly, you want your Shop and Recreation objects to share their underlying CreatePerson object. But your code doesn't do that. As @mike scotty commented, you pass in Joe, but don't use Joe for anything. So these new objects just create their own to_do_lists, which are not shared. Here is something like what i imagine you want:

class CreatePerson():
    def __init__(self):
        self.to_do_list = []
    def add_element(self, a):
        self.to_do_list += [a]

class Shop():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)

class Recreation():
    def __init__(self, CreatePerson):
        self.my_person = CreatePerson
    def add_element(self, a):
        self.my_person.add_element(a)

>>> joe=CreatePerson()
>>> p1=Shop(joe)
>>> p2=Recreation(joe)
>>> p1.add_element('whole milk')
>>> p2.add_element('reading book')
>>> print(joe.to_do_list)
['whole milk', 'reading book']

So now Shop and Recreation aren't instances of a CreatePerson, but they do take a CreatePerson in their constructor, and store a reference to that person. And when you call add_element on those objects, they call the new add_element method that their CreatePerson has.

I'd just like to note that I don't think this is exactly the right abstraction - your Shop has one-and-only-one person, as does your Recreation. But I took it at face value for the purposes of answering this question.

Hope that helps, Happy Coding!


问:
Kafka-Ksql Rekeying on stream results in data disappearing after few min
The rekeying works fine in the following scenarios
1. Base topic to stream then rekey - Good
2. Table to stream then rekey - Good

But when trying with
Table - Table join results in new table, create stream on that resulting table, then rekey stream - It appears to work fine for few minutes(select query gets the expected result), and then the data disappears from the newly created stream.

```<code>-- Table on Table join - works as expected
CREATE TABLE JOINRESULT_T AS
SELECT d.DEVICE_ID, d.LOCATION_ALIAS,d.UPDATED_BY,
d.UPDATED_TIMESTAMP AS UPDATED_TIMESTAMP, d.__DELETED AS __DELETED
FROM TABLE1 d LEFT JOIN TABLE2 l ON d.LOCATION_ALIAS=l.ALIAS;

-- Stream from table - works as expected
CREATE STREAM FROMJOIN_S WITH(KAFKA_TOPIC='JOINRESULT_T', VALUE_FORMAT='AVRO');

-- Rekey the above stream - Data disappears after few minutes
CREATE STREAM REKEY_S AS SELECT * FROM FROMJOIN_S PARTITION BY DEVICE_ID;
</code>```

Describe extended command on the stream displays the count of messages the stream is currently holding. But a select command does not give out any results.
The print topic command on the associated topic also does not print anything.

enter image description here

Ksql version : 5.3.1 , also tried latest version
Partitions = 1, replicas =1.

tried to investigate if the topic storage space on kafka server is holding any data and found the log file, snapshot files both to be empty.

what could cause the data to disappear once it is written to the topic?

答:
The most likely cause of this is that the retention on the REKEY_S topic in the Kafka cluster is set low and so is aggressively deleting 'old' messages.

Try investigating that the retention policy / settings is for REKEY_S topic. The policy should NOT be compact, and should have the default topic retention policy set by the Kafka cluster.

If strange retention settings is the cause, then it would be good to know why the retention is being set that way and by what.  If the what is ksql, then its likely a bug and should be raised as a Github issue so it an be investigated.

Body:
The rekeying works fine in the following scenarios
1. Base topic to stream then rekey - Good
2. Table to stream then rekey - Good

But when trying with
Table - Table join results in new table, create stream on that resulting table, then rekey stream - It appears to work fine for few minutes(select query gets the expected result), and then the data disappears from the newly created stream.

-- Table on Table join - works as expected
CREATE TABLE JOINRESULT_T AS
SELECT d.DEVICE_ID, d.LOCATION_ALIAS,d.UPDATED_BY,
d.UPDATED_TIMESTAMP AS UPDATED_TIMESTAMP, d.__DELETED AS __DELETED
FROM TABLE1 d LEFT JOIN TABLE2 l ON d.LOCATION_ALIAS=l.ALIAS;

-- Stream from table - works as expected
CREATE STREAM FROMJOIN_S WITH(KAFKA_TOPIC='JOINRESULT_T', VALUE_FORMAT='AVRO');

-- Rekey the above stream - Data disappears after few minutes
CREATE STREAM REKEY_S AS SELECT * FROM FROMJOIN_S PARTITION BY DEVICE_ID;

Describe extended command on the stream displays the count of messages the stream is currently holding. But a select command does not give out any results.
The print topic command on the associated topic also does not print anything.

enter image description here

Ksql version : 5.3.1 , also tried latest version
Partitions = 1, replicas =1.

tried to investigate if the topic storage space on kafka server is holding any data and found the log file, snapshot files both to be empty.

what could cause the data to disappear once it is written to the topic?


问:
Delete the subwidgets/entries from a tk::menu widget
I want to implement a history/recent-files functionality for my Perl/Tk program.

Here is a working code excerpt from my program to demonstrate my problem.

```<code>#!/usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );

use Tk;

my @history_entries = qw(Back To The History);

my $mw      = MainWindow->new();
my $menubar = $mw->Menu();
$mw->configure( -menu => $menubar );
my $file    = $menubar->cascade( -label => '~File' );
my $history = $file->cascade( -label => '~History', );

build_history();

MainLoop();

#===  FUNCTION  ================================================================
#         NAME:  build_history
#      PURPOSE:  Polulate the history
#===============================================================================
sub build_history {
    foreach (@history_entries) {
        $history->command(
            -label    => $ARG,
            -command  => \&some_function,
            -compound => 'left',
        );
    }
    return;
}    # ----------  end of subroutine build_history  ----------
</code>```

As you can see, the entries are created with $history->command but how can I delete them every time I call build_history?

The reason I want them deleted is that everytime a user opens a file, the last item (in this case 'History') should be deleted and a new item should be put on top of the list. So that I have a maximum of (in this example) four entries.

Any other ways of implementing this functionality with Tk are welcome.

Thanks for your time.

UPDATE:
I followed the advice of "mu" and tried to get the subwidgets with the children() function just after the function is called, like this:

```<code>my @child = $history->children();
foreach my $c ( @child ) {
    if ($c->Exists()){
        $c->destroy;
    }
}
</code>```

The program exits with the error:

```<code>Can't locate object method "children" via package "Tk::Menu::Cascade" at /home/alex/Desktop/stack_history.pl line 28.
</code>```

答:
I ended up rebuilding the whole menu. That's how my code looks like atm. I am not proud of it but it works ... I am open to any form of advice.</p>

```<code>#!/usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );

use Tk;

# History entries are stored in array
my @history_entries = qw(Back To The History);

my $mw = MainWindow->new();
$mw->geometry('200x200');

my $menubar = $mw->Menu();

#Build menus
$mw->configure( -menu => $menubar );
build_menu();

$mw->Button(
    -text    => 'Update History',
    -command => \sub {

        #when a user opens a file insert_history is called.
        insert_history();
    }
)->pack( -side => 'bottom', -anchor => 'sw' );

MainLoop();

#===  FUNCTION  ================================================================
#         NAME:  build_menu
#      PURPOSE:  Update/Build the menu
#===============================================================================
sub build_menu {

    #delete the whole menu
    $menubar->delete(1);

    #built it again
    my $file = $menubar->cascade( -label => '~File' );
    my $history = $file->cascade( -label => '~History', );
    foreach (@history_entries) {
        $history->command(
            -label    => $ARG,
            -compound => 'left',
        );
    }

    return;
}    # ----------  end of subroutine build_menu  ----------

#===  FUNCTION  ================================================================
#         NAME:  insert_history
#      PURPOSE:  Do something with the array containing the history entries.
#                Then rebuild the menu.
#===============================================================================
sub insert_history {

    #make something with the array
    my $last_element = pop @history_entries;
    unshift @history_entries, $last_element;

    #update menu
    build_menu();
    return;
}    # ----------  end of subroutine insert_history  ----------
</code>```

Body:
I want to implement a history/recent-files functionality for my Perl/Tk program.

Here is a working code excerpt from my program to demonstrate my problem.

#!/usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );

use Tk;

my @history_entries = qw(Back To The History);

my $mw      = MainWindow->new();
my $menubar = $mw->Menu();
$mw->configure( -menu => $menubar );
my $file    = $menubar->cascade( -label => '~File' );
my $history = $file->cascade( -label => '~History', );

build_history();

MainLoop();

#===  FUNCTION  ================================================================
#         NAME:  build_history
#      PURPOSE:  Polulate the history
#===============================================================================
sub build_history {
    foreach (@history_entries) {
        $history->command(
            -label    => $ARG,
            -command  => \&some_function,
            -compound => 'left',
        );
    }
    return;
}    # ----------  end of subroutine build_history  ----------

As you can see, the entries are created with $history->command but how can I delete them every time I call build_history?

The reason I want them deleted is that everytime a user opens a file, the last item (in this case 'History') should be deleted and a new item should be put on top of the list. So that I have a maximum of (in this example) four entries.

Any other ways of implementing this functionality with Tk are welcome.

Thanks for your time.

UPDATE:
I followed the advice of "mu" and tried to get the subwidgets with the children() function just after the function is called, like this:

my @child = $history->children();
foreach my $c ( @child ) {
    if ($c->Exists()){
        $c->destroy;
    }
}

The program exits with the error:

Can't locate object method "children" via package "Tk::Menu::Cascade" at /home/alex/Desktop/stack_history.pl line 28.

Body:
I ended up rebuilding the whole menu. That's how my code looks like atm. I am not proud of it but it works ... I am open to any form of advice.

#!/usr/bin/perl

use strict;
use warnings;
use English qw( -no_match_vars );

use Tk;

# History entries are stored in array
my @history_entries = qw(Back To The History);

my $mw = MainWindow->new();
$mw->geometry('200x200');

my $menubar = $mw->Menu();

#Build menus
$mw->configure( -menu => $menubar );
build_menu();

$mw->Button(
    -text    => 'Update History',
    -command => \sub {

        #when a user opens a file insert_history is called.
        insert_history();
    }
)->pack( -side => 'bottom', -anchor => 'sw' );

MainLoop();

#===  FUNCTION  ================================================================
#         NAME:  build_menu
#      PURPOSE:  Update/Build the menu
#===============================================================================
sub build_menu {

    #delete the whole menu
    $menubar->delete(1);

    #built it again
    my $file = $menubar->cascade( -label => '~File' );
    my $history = $file->cascade( -label => '~History', );
    foreach (@history_entries) {
        $history->command(
            -label    => $ARG,
            -compound => 'left',
        );
    }

    return;
}    # ----------  end of subroutine build_menu  ----------

#===  FUNCTION  ================================================================
#         NAME:  insert_history
#      PURPOSE:  Do something with the array containing the history entries.
#                Then rebuild the menu.
#===============================================================================
sub insert_history {

    #make something with the array
    my $last_element = pop @history_entries;
    unshift @history_entries, $last_element;

    #update menu
    build_menu();
    return;
}    # ----------  end of subroutine insert_history  ----------


问:
loop input and listbox
im studying vba and i need to write a code that the users enters the sales of the week "Each day individualy" and show it in an listbox im using this as an last resource i dont need the entire code i just need to known how i can make it happen </p>

答: You need to use an inputbox to get the value from the user. Then you can populate and display the listbox. These links should help you achieve what you want. If you have any specific issues after that then post up the code you have tried with the exact error you are receiving</p>

Title: loop input and listbox


问:
How to keep icons in bootstrap 4 navbar on the top right for mobile view
I have the following code, but I can't find a way to keep the icons on the top right when going into mobile view without duplicating them. I want the order to be:

on desktop:
brand (far left) - nav links (middle) - account & cart icons (right hand side)

on small devices:
brand (left corner) - account & cart icons (right hand side) - (right corner)

```<code><nav class="navbar navbar-light bg-light navbar-expand-md justify-content-center-md">
        <a class="navbar-brand col-2" href="#">Navbar</a>
        <div class="navbar-collapse text-right col col-auto collapse show" id="navbarSupportedContent" style="">
            <ul class="navbar-nav mx-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        Dropdown
                    </a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Something else here</a>
                    </div>
                </li>
                <li class="nav-item">
                    <a class="nav-link disabled" href="#">Disabled</a>
                </li>
            </ul>
        </div>
        <div class="col-auto col-md-3">
            <div class="row">
                <div class="col-sm-12 justify-content-end d-flex">
                        <a class="">
                          Icon
                        </a>
                    <a>
                        Icon
                    </a>
                    <a class="">Icon</a>
                    <div class="">
                        <button class="navbar-toggler" type="button" data-toggle="collapse" >
                            <span class="navbar-toggler-icon"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </nav>
</code>```

EDIT: I have made an easier repro here: https://jsfiddle.net/2dyLzvno/
It renders perfectly UNTIL the screen is mobile view and collapses. Then the links are above instead of below. I cant work out how to get around this.

EDIT 2:

答:
I mentioned the changes I made in the comment lines. I must point out that you have made a very simple and useful structure such as bootstrap very complicated. Documentation I recommend you to review more carefully, especially the grid system. By the way, since you don't share your external css codes, the look may be a little different.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="true" aria-label="Toggle navigation">

    </button>

        Home (current)

        Link

            Dropdown

          Action
          Another action

          Something else here

        Disabled

    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0 ml-auto" type="submit">Search</button>

    </form>

          Cancel

                0

                      0

```
</div>
</div>
</p>

<p>Updated Answer for your snippet: </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<nav class="navbar navbar-light bg-light navbar-expand-md">
  <!--  I removed unnecessary d-flex features.-->
  <!-- Site Logo -->
  Navbar
  <!-- Site Logo End -->

  <!-- Toggle button should be here -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
      <span class="navbar-toggler-icon"></span>
    </button>
  <!-- Toggle button end -->

  <div class="navbar-collapse text-right collapse show w-100 " id="navbarSupportedContent">
    <!-- Links -->
    <ul class="navbar-nav mx-auto">
      <li class="nav-item active">
        Home <span class="sr-only">(current)</span>
      </li>
      <li class="nav-item">
        Link
      </li>
      <li class="nav-item dropdown">

            Dropdown

        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          Action
          Another action
          <div class="dropdown-divider"></div>
          Something else here
        </div>
      </li>
      <li class="nav-item">
        Disabled
      </li>

    </ul>
    <!-- Links End -->

    <!-- There was an unnecessary column and row here.I removed it. Using rows in columns is not recommended.-->

    <!-- Icons -->
    <div class="col-md-3 pr-0">

          Icon

      <a>
          Icon
        </a>
      Icon
      <div class="">
        <!-- What is This ? -->
      </div>
    </div>
    <!-- Icons end -->
  </div>
  <!-- the problem with mobile view is that the collapse class doesn't actually cover the icons class. Mobile view determines collapse class, remember! I took the icons class into the collapse class. -->
</nav>

<!-- JAVASCRIPT for bootstrap -->

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script></code>```

Body:
I have the following code, but I can't find a way to keep the icons on the top right when going into mobile view without duplicating them. I want the order to be:

on desktop:
brand (far left) - nav links (middle) - account & cart icons (right hand side)

on small devices:
brand (left corner) - account & cart icons (right hand side) - (right corner)

        Navbar

                    Home (current)

                    Link

                        Dropdown

                        Action
                        Another action

                        Something else here

                    Disabled

                          Icon

                        Icon

                    Icon

                        <button class="navbar-toggler" type="button" data-toggle="collapse" >

                        </button>

EDIT: I have made an easier repro here: https://jsfiddle.net/2dyLzvno/
It renders perfectly UNTIL the screen is mobile view and collapses. Then the links are above instead of below. I cant work out how to get around this.

EDIT 2:

Body:
I mentioned the changes I made in the comment lines. I must point out that you have made a very simple and useful structure such as bootstrap very complicated. Documentation I recommend you to review more carefully, especially the grid system. By the way, since you don't share your external css codes, the look may be a little different.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="true" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

  <div class="navbar-collapse collapse show text-right" id="navbarSupportedContent">
    <!-- text-right added-->
    <ul class="navbar-nav mx-auto">
      <!--  change with mx-auto -->
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown
          </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0 ml-auto" type="submit">Search</button>
      <!-- ml-auto added-->
    </form>
    <div class="d-inline my-2 my-lg-0">
      <div class="formSearch ml-lg-auto ml-2 pl-lg-3 pl-0 d-inline-flex align-items-end">

        <a class="mobile-search-trigger d-lg-none d-flex" data-toggle="modal" data-target="#searchModal">
          <span class="mdi mdi-magnify"></span>
        </a>

        <a class="search__cancel">
          <span>Cancel</span>
        </a>
      </div>
      <a class="js-offcanvas-trigger user-panel-trigger d-flex justify-content-center align-content-center ml-lg-3 ml-2 c-button" data-offcanvas-trigger="user_panel" href="#user_panel" role="button" aria-controls="user_panel" aria-expanded="false"><span class="c-button__text">
            <span class="nav-icon">
              <span class="mdi mdi-account-outline"></span>
            </span>
          </span></a>
      <div class="cart__container">
        <div class="d-inline-flex align-items-center">
          <ul class="shopping-links">
            <li class="nav-item wishlist-container d-lg-block d-none">
              <a class="nav-link" href="/wishlist">
                <span class="wishlist-label hl-label">
                    <span class="mdi mdi-heart-outline"></span>
                </span>
                <span class="wishlist-qty d-none d-lg-flex">0</span>
              </a>
            </li>
            <li class="nav-item cart-container" id="topcartlink">
              <div class="btn-group dropdown">
                <a class="nav-link js-offcanvas-trigger c-button" data-offcanvas-trigger="right" href="#right" role="button" aria-controls="right" aria-expanded="false"><span class="c-button__text">
                      <span class="cart-label hl-label">
                        <span class="mdi mdi-cart-outline"></span>
                      </span>
                      <span class="cart-qty">0</span>
                    </span></a>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</nav>

Updated Answer for your snippet:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<nav class="navbar navbar-light bg-light navbar-expand-md">
  <!--  I removed unnecessary d-flex features.-->
  <!-- Site Logo -->
  <a class="navbar-brand col-2" href="#">Navbar</a>
  <!-- Site Logo End -->

  <!-- Toggle button should be here -->
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent">
      <span class="navbar-toggler-icon"></span>
    </button>
  <!-- Toggle button end -->

  <div class="navbar-collapse text-right collapse show w-100 " id="navbarSupportedContent">
    <!-- Links -->
    <ul class="navbar-nav mx-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown
          </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>

    </ul>
    <!-- Links End -->

    <!-- There was an unnecessary column and row here.I removed it. Using rows in columns is not recommended.-->

    <!-- Icons -->
    <div class="col-md-3 pr-0">
      <a class="">
          Icon
        </a>
      <a>
          Icon
        </a>
      <a class="">Icon</a>
      <div class="">
        <!-- What is This ? -->
      </div>
    </div>
    <!-- Icons end -->
  </div>
  <!-- the problem with mobile view is that the collapse class doesn't actually cover the icons class. Mobile view determines collapse class, remember! I took the icons class into the collapse class. -->
</nav>

<!-- JAVASCRIPT for bootstrap -->

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>


问:
recursive binarySearch with array of strings
My function works for the first 4 elements, but returns -1 for 12 and 14..even though there in the array.
I've tried changing some of the if statements and using .compare but haven't had any luck.
Any ideas?
Thanks</p>

```<code>/** Searches the array anArray[first] through anArray[last]
 for a given value by using a binary search.
 @pre 0 <= first, last <= SIZE - 1, where SIZE is the
 maximum size of the array, and anArray[first] <=
 anArray[first + 1] <= ... <= anArray[last].
 @post anArray is unchanged and either anArray[index] contains
 the given value or index == -1.
 @param anArray The array to search.
 @param first The low index to start searching from.
 @param last The high index to stop searching at.
 @param target The search key.
 @return Either index, such that anArray[index] == target, or -1.
 */
int binarySearch(const string anArray[], int first, int last, string target)
{
  int index;
  if (first > last)
    index = -1; // target not in original array
  else {
    // If target is in anArray,
    // anArray[first] <= target <= anArray[last]
    int mid = first + (last - first) / 2;
    if (anArray[mid] == target)
      index = mid; // target found at anArray[mid]
    else if (anArray[mid] > target)
      // Point X
      index = binarySearch(anArray, first, mid - 1, target);
    else
      // Point Y
      index = binarySearch(anArray, mid + 1, last, target);
  } // end if
  return index;
}

int main()
{
  const string v[6] = {"1","5","6","9","12","14"};

  int index;
  string searchItem = "12";

  cout << "Searching For: " << searchItem << endl;

  index = binarySearch(v, 0, 6, searchItem);

  cout << "Element found at index " << index << endl;

  system("pause");

  return 0;
}
</code>```

答:
Problem is that you can't compare full strings like you compare numbers (although you can do that with chars according to ascii value). You  have two options, the first and simpler one is defining a function to compare strings, something like:

```<code>int compareStrings (string a, string b) { // -1: a>b, 0: a=b, 1: a<b
    if (a.length() == b.length()) {
        if (a == b) return 0;

        else for (int i = 0; i < a.length(); i++)
            if (a[i] < b[i]) return 1;
            else if (a[i] > b[i]) return -1;
    }

    else return (a.length() < b.length()? 1 : -1);
}
</code>```

and then when you need to retrieve what string is bigger you could do:

```<code>int compResult = compareStrings (anArray[mid], target);
switch (compResult) {
    case -1:
        index = binarySearch(anArray, first, mid - 1, target); break;
    case 1:
        index = binarySearch(anArray, mid + 1, last, target); break;
}
</code>```

The other one is creating a custom "wrapper" class for the strings such that you can override a comparing operator within it, but is a little bit more complicated, and the body of the functions would be pretty much the same, so I would suggest the former solution. But if you want to see how you could accomplish the latter of the solutions, here's a source:
https://www.geeksforgeeks.org/c-program-to-compare-two-strings-using-operator-overloading/

Hope it helps man

Body:
My function works for the first 4 elements, but returns -1 for 12 and 14..even though there in the array.
I've tried changing some of the if statements and using .compare but haven't had any luck.
Any ideas?
Thanks

/** Searches the array anArray[first] through anArray[last]
 for a given value by using a binary search.
 @pre 0 <= first, last <= SIZE - 1, where SIZE is the
 maximum size of the array, and anArray[first] <=
 anArray[first + 1] <= ... <= anArray[last].
 @post anArray is unchanged and either anArray[index] contains
 the given value or index == -1.
 @param anArray The array to search.
 @param first The low index to start searching from.
 @param last The high index to stop searching at.
 @param target The search key.
 @return Either index, such that anArray[index] == target, or -1.
 */
int binarySearch(const string anArray[], int first, int last, string target)
{
  int index;
  if (first > last)
    index = -1; // target not in original array
  else {
    // If target is in anArray,
    // anArray[first] <= target <= anArray[last]
    int mid = first + (last - first) / 2;
    if (anArray[mid] == target)
      index = mid; // target found at anArray[mid]
    else if (anArray[mid] > target)
      // Point X
      index = binarySearch(anArray, first, mid - 1, target);
    else
      // Point Y
      index = binarySearch(anArray, mid + 1, last, target);
  } // end if
  return index;
}

int main()
{
  const string v[6] = {"1","5","6","9","12","14"};

  int index;
  string searchItem = "12";

  cout << "Searching For: " << searchItem << endl;

  index = binarySearch(v, 0, 6, searchItem);

  cout << "Element found at index " << index << endl;

  system("pause");

  return 0;
}

Body:
Problem is that you can't compare full strings like you compare numbers (although you can do that with chars according to ascii value). You  have two options, the first and simpler one is defining a function to compare strings, something like:

int compareStrings (string a, string b) { // -1: a>b, 0: a=b, 1: a<b
    if (a.length() == b.length()) {
        if (a == b) return 0;

        else for (int i = 0; i < a.length(); i++)
            if (a[i] < b[i]) return 1;
            else if (a[i] > b[i]) return -1;
    }

    else return (a.length() < b.length()? 1 : -1);
}

and then when you need to retrieve what string is bigger you could do:

int compResult = compareStrings (anArray[mid], target);
switch (compResult) {
    case -1:
        index = binarySearch(anArray, first, mid - 1, target); break;
    case 1:
        index = binarySearch(anArray, mid + 1, last, target); break;
}

The other one is creating a custom "wrapper" class for the strings such that you can override a comparing operator within it, but is a little bit more complicated, and the body of the functions would be pretty much the same, so I would suggest the former solution. But if you want to see how you could accomplish the latter of the solutions, here's a source:
https://www.geeksforgeeks.org/c-program-to-compare-two-strings-using-operator-overloading/

Hope it helps man


问:
Serialize GWT value object and deserialize it at server side
I have a GWT application that needs to support the downloading of large .csv files. This is done with a ReportServlet which sets the proper content-type and other headers needed for the browser to open the download dialog and start the spreadsheet application.

Since the reports have several filter parameters, I need to pass them to the server somehow. I can not use AJAX callbacks because in that case the browser does not pop up the download dialog.
Currently I am doing this by creating a form with hidden fields for each parameter and parse them each at the server side by hand.

It would be a much more elegant solution to have a serializer for the value object, put the serialized value in one form parameter, deserialize on the server and use it as we were in a regular RPC call.

At first I tried to search the GWT codebase for some serializer/deserializer api but I could not find any. After that I searched for JSON serializers but non of them had either a simple API or support for GWT. These two JSON serializers:
http://code.google.com/p/gwtprojsonserializer/ and http://sites.google.com/site/gson/
could be great, but gwtprojson serializes Dates as timestamps and put the classname in the serialized string while gson as a dateformat string and no classname in the serialized string.

So to finally get to the point

Could anyone suggest an object serializer/deserializer that works both in GWT and java?  Not neccessarily JSON, any other format will do.

or

Has anyone experience with using the serializer libraries mentioned above together, or with other libs that can serialize in GWT and deserialize in Java?

Thanks in advance!
pentike

答:
I have written a custom deserializer for GSon. It is quite simple, so it works well with gwtprojsonserializer.

```
    public class MyDateAdapter implements JsonDeserializer {

  /*
   * (non-Javadoc)
   *
   * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement,
   * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
   */
  @Override
  public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext ctx)
                                                                                throws JsonParseException {
    return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
  }

}
```

We need to register our custom deserializer:

```
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new MyDateAdapter());
    Gson gson = gsonBuilder.create();
```

Body:
I have written a custom deserializer for GSon. It is quite simple, so it works well with gwtprojsonserializer.

    public class MyDateAdapter implements JsonDeserializer {

  /*
   * (non-Javadoc)
   *
   * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement,
   * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext)
   */
  @Override
  public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext ctx)
                                                                                throws JsonParseException {
    return new Date(jsonElement.getAsJsonPrimitive().getAsLong());
  }

}

We need to register our custom deserializer:

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new MyDateAdapter());
    Gson gson = gsonBuilder.create();


问:
Invalid command \"/bin/sh\": file not found
I have a Dockerfile with

```<code>CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

which fails with error: Invalid command \"/bin/sh\": file not found

but the same command runs like this:

```<code>RUN gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

What could be wrong?

Update: The problem starts when I have these two lines added:
ENV APP_HOME /app and WORKDIR $APP_HOME

Dockerfile:

```<code># Dockerfile
FROM penguicky/docker-python3-opencv

ENV APP_HOME /app
WORKDIR $APP_HOME

RUN apt-get update
RUN apt-get install -y libsm6 libxext6 libxrender-dev
RUN pip3 install Flask gunicorn
RUN pip3 install opencv-contrib-python

EXPOSE 8080

#RUN echo $CV_VERSION

COPY . ./

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

Update

I tried using this way:

```<code>CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

now I get this:

```<code>2020-06-02 22:03:27.511 EEST[2020-06-02 19:03:27 +0000] [1] [INFO] Starting gunicorn 20.0.4
2020-06-02 22:03:27.513 EEST[2020-06-02 19:03:27 +0000] [1] [ERROR] Invalid address: ('8080', 8000)
</code>```

Update2:

So it works by this:

```<code>CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

But I don't know the explanation why it works like this.

答:
According to the CMD instruction documentation it has three forms:

CMD ["executable","param1","param2"] (exec form, this is the preferred form)

CMD ["param1","param2"] (as default parameters to ENTRYPOINT)

CMD command param1 param2 (shell form)

So regarding your line of code:

```<code>CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

It would be the "third form" of the CMD instruction, that tries to run the "exec" executable and sends gunicorn as a parameter which is not what you would try to achieve. You can try to run it as the shell form:

```<code>CMD gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 app:app
</code>```

Please note that I changed --bind 8080 to --bind :8080 which I'm going to explain next.

In the second part of your post you're talking about the "exec" form of the CMD instruction (first on the list):

```<code>CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

Which executes correctly but has some issues with the port, as nischay already pointed, can be achieved in two ways:

1- By adding the IP address for example the loopback "127.0.0.1:8080"

```<code>CMD ["gunicorn", "--bind", "127.0.0.1:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

2- By adding the ":" before the port as pointed in these examples

```<code>CMD ["gunicorn", "--bind", ":8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]
</code>```

Reference to the bind option:

```<code>-b BIND, --bind=BIND - Specify a server socket to bind. Server sockets can be any of $(HOST), $(HOST):$(PORT), fd://$(FD), or unix:$(PATH). An IP is a valid $(HOST).
</code>```

Body:
I have a Dockerfile with

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

which fails with error: Invalid command \"/bin/sh\": file not found

but the same command runs like this:

RUN gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

What could be wrong?

Update: The problem starts when I have these two lines added:
ENV APP_HOME /app and WORKDIR $APP_HOME

Dockerfile:

# Dockerfile
FROM penguicky/docker-python3-opencv

ENV APP_HOME /app
WORKDIR $APP_HOME

RUN apt-get update
RUN apt-get install -y libsm6 libxext6 libxrender-dev
RUN pip3 install Flask gunicorn
RUN pip3 install opencv-contrib-python

EXPOSE 8080

#RUN echo $CV_VERSION

COPY . ./

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

Update

I tried using this way:

CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

now I get this:

2020-06-02 22:03:27.511 EEST[2020-06-02 19:03:27 +0000] [1] [INFO] Starting gunicorn 20.0.4
2020-06-02 22:03:27.513 EEST[2020-06-02 19:03:27 +0000] [1] [ERROR] Invalid address: ('8080', 8000)

Update2:

So it works by this:

CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

But I don't know the explanation why it works like this.

Body:
According to the CMD instruction documentation it has three forms:

CMD ["executable","param1","param2"] (exec form, this is the preferred form)

CMD ["param1","param2"] (as default parameters to ENTRYPOINT)

CMD command param1 param2 (shell form)

So regarding your line of code:

CMD exec gunicorn --bind 8080 --workers 1 --threads 8 --timeout 0 app:app

It would be the "third form" of the CMD instruction, that tries to run the "exec" executable and sends gunicorn as a parameter which is not what you would try to achieve. You can try to run it as the shell form:

CMD gunicorn --bind :8080 --workers 1 --threads 8 --timeout 0 app:app

Please note that I changed --bind 8080 to --bind :8080 which I'm going to explain next.

In the second part of your post you're talking about the "exec" form of the CMD instruction (first on the list):

CMD ["gunicorn", "--bind", "8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

Which executes correctly but has some issues with the port, as nischay already pointed, can be achieved in two ways:

1- By adding the IP address for example the loopback "127.0.0.1:8080"

CMD ["gunicorn", "--bind", "127.0.0.1:8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

2- By adding the ":" before the port as pointed in these examples

CMD ["gunicorn", "--bind", ":8080", "--workers", "1" ,"--threads", "8", "--timeout", "0" ,"app:app"]

Reference to the bind option:

-b BIND, --bind=BIND - Specify a server socket to bind. Server sockets can be any of $(HOST), $(HOST):$(PORT), fd://$(FD), or unix:$(PATH). An IP is a valid $(HOST).