问:
bootstrap-toggle switch is showing up as a checkbox
I have a ToggleSwitch component in react which I have made using bootstrap-toggle. But it is showing up as a checkbox and not as a toggle switch. Any help on this how to make it work?

ToggleSwitch.js

```<code>import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-toggle/css/bootstrap-toggle.css";

class ToggleSwitch extends Component {
  render() {
    return (
      <div className="toggle-switch">
        <input
          type="checkbox"
          data-toggle="toggle"
          data-on="Ready"
          data-off="Not Ready"
          data-onstyle="success"
          data-offstyle="danger"
        />
      </div>
    );
  }
}

export default ToggleSwitch;
</code>```

答:
There is probably something wrong with the order in which JavaScript files are being called.

For CSS call the necessary files:

Bootstrap 4

Bootstrap4-toggle

For JavaScript, call the files in this order:

jQuery Slim

Bootstrap 4

Bootstrap4-toggle

Working snippet:

const element = (

    <input
      type="checkbox"
      data-toggle="toggle"
      data-on="Ready"
      data-off="Not Ready"
      data-onstyle="success"
      data-offstyle="danger"
    />

);

ReactDOM.render(
  element,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet"/>

<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script></code>```

Body:
I have a ToggleSwitch component in react which I have made using bootstrap-toggle. But it is showing up as a checkbox and not as a toggle switch. Any help on this how to make it work?

ToggleSwitch.js

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "bootstrap-toggle/css/bootstrap-toggle.css";

class ToggleSwitch extends Component {
  render() {
    return (

        <input
          type="checkbox"
          data-toggle="toggle"
          data-on="Ready"
          data-off="Not Ready"
          data-onstyle="success"
          data-offstyle="danger"
        />

    );
  }
}

export default ToggleSwitch;

Body:
There is probably something wrong with the order in which JavaScript files are being called.

For CSS call the necessary files:

Bootstrap 4

Bootstrap4-toggle

For JavaScript, call the files in this order:

jQuery Slim

Bootstrap 4

Bootstrap4-toggle

Working snippet:

const element = (
  <div className="toggle-switch">
    <input
      type="checkbox"
      data-toggle="toggle"
      data-on="Ready"
      data-off="Not Ready"
      data-onstyle="success"
      data-offstyle="danger"
    />
  </div>
);

ReactDOM.render(
  element,
  document.getElementById('app')
);

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet"/>

<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>


来源: stackexchange

问:
"Three sums" problem space complexity - Why is it O(n)?
Leetcode - Three sums

https://leetcode.com/problems/3sum/

```<code>def threeNumberSum(array, targetSum):
    array = sorted(array)
    results = []
    for idx, elem in enumerate(array):
        i = idx + 1
        j = len(array) - 1
        target = targetSum - elem
        while i < j:
            currentSum = array[i] + array[j]
            if currentSum == target:
                result = [array[i], array[j], array[idx]]
                results.append(sorted(result))
                i += 1
                j -= 1
            elif currentSum < target:
                i += 1
            else:
                j -= 1

    return results
</code>```

So time is O(n^2), I am fine with that, but space is O(n), according to Algoexpert.io, and I am not sure of why. His explanation was:

"We might end up storing every single number in our array, if every single number is used in some triplet, we will store a lot of numbers and it is going to be bound by O(n) space. Even if some numbers are used multiple times, it will be bounded by O(n)"

But I can't make sense of his explanation yet. If the provided array has (nearly) all unique triplet permutations summing to that target number, isn't space complexity going to be n choose 3 instead? If its n choose k=3 simplifying it would yield O(n^3).

Note, however, that the Algoexpert problem has one additional assumption with the input array that every element will be distinct, whereas the Leetcode version doesn't have that assumption. How would I formally address that information in space complexity analysis?

答:
If your code is correct (and I have no reason to assume it isn't), then the space complexity for the list of matching triplets is in fact O(n2).

It's not O(n3) because the third member of any triplet is uniquely determined by the first two, so there is no freedom of choice for this value.

If all the numbers are unique, then the space requirement is definitely O(n2):

```<code>>>> [len(threeNumberSum(range(-i,i+1),0)) for i in range(1,10)]
[1, 2, 5, 8, 13, 18, 25, 32, 41]
</code>```

You should be able to satisfy yourself that the terms in this series correspond to ceil(n2/2). (See https://oeis.org/A000982).

If there are repeated numbers in the list, then the overall space requirement should decrease (relative to n) due to the requirement for unique triplets in the returned array.

ContentLicense: CC BY-SA 4.0

Body:
Leetcode - Three sums

https://leetcode.com/problems/3sum/

def threeNumberSum(array, targetSum):
    array = sorted(array)
    results = []
    for idx, elem in enumerate(array):
        i = idx + 1
        j = len(array) - 1
        target = targetSum - elem
        while i < j:
            currentSum = array[i] + array[j]
            if currentSum == target:
                result = [array[i], array[j], array[idx]]
                results.append(sorted(result))
                i += 1
                j -= 1
            elif currentSum < target:
                i += 1
            else:
                j -= 1

    return results

So time is O(n^2), I am fine with that, but space is O(n), according to Algoexpert.io, and I am not sure of why. His explanation was:

"We might end up storing every single number in our array, if every single number is used in some triplet, we will store a lot of numbers and it is going to be bound by O(n) space. Even if some numbers are used multiple times, it will be bounded by O(n)"

But I can't make sense of his explanation yet. If the provided array has (nearly) all unique triplet permutations summing to that target number, isn't space complexity going to be n choose 3 instead? If its n choose k=3 simplifying it would yield O(n^3).

Note, however, that the Algoexpert problem has one additional assumption with the input array that every element will be distinct, whereas the Leetcode version doesn't have that assumption. How would I formally address that information in space complexity analysis?

Body:
If your code is correct (and I have no reason to assume it isn't), then the space complexity for the list of matching triplets is in fact O(n2).

It's not O(n3) because the third member of any triplet is uniquely determined by the first two, so there is no freedom of choice for this value.

If all the numbers are unique, then the space requirement is definitely O(n2):

>>> [len(threeNumberSum(range(-i,i+1),0)) for i in range(1,10)]
[1, 2, 5, 8, 13, 18, 25, 32, 41]

You should be able to satisfy yourself that the terms in this series correspond to ceil(n2/2). (See https://oeis.org/A000982).

If there are repeated numbers in the list, then the overall space requirement should decrease (relative to n) due to the requirement for unique triplets in the returned array.


问:
Echart Bar Graph Reverse Yaxis
I am trying to create a bar graph use Echarts. I am trying to reverse the YAxis. The data that I am trying to display considers a lower time as a higher score and a higher time as a lower score. Currently, the graph display as the higher time has a higher score. I am having trouble trying to reverse the YAxis. Any help would be great. </p>

```<code><script type="text/javascript">
  var dom = document.getElementById("chartPace");
  var myChart = echarts.init(dom);
  app.title = 'Test';

option = {
color: ["#000000"],
responsive: true,
maintainAspectRatio: false,

grid : {
      height: '250',
      width: '450'
  },
  title : {
      text: 'test'
  },
  xAxis : [
      {
          type : 'category',
          data : ['Mon','Tue','Wensday','Tue','Wensday'],
          axisTick: {
              alignWithLabel: true
          },
      }
  ],
  yAxis : [
      {
          type : 'time',
          reversed:true,
          axisLabel: {
          formatter: function (value) {
            var value = new Date(value);
            var minutes = value.getMinutes();
            if (value.getSeconds().toString().length < 2){
              var seconds =  "0" + value.getSeconds();
            }
            else{
              var seconds = value.getSeconds();
            }
            return minutes +":" + seconds;
            //return value;
          }
        }
      }
  ],
  tooltip:{
    formatter : function (params) {

      var value = new Date(params['data']);
            var minutes = value.getMinutes();
            if (value.getSeconds().toString().length < 2){
              var seconds =  "0" + value.getSeconds();
            }
            else{
              var seconds = value.getSeconds();
            }
              return minutes +":" + seconds;
    }
  },
  series : [
      {
          name:'Avg Pace',
          type:'bar',
          barWidth: '60%',
          data:[new Date(2014, 9, 1, 0, 2,30),
          new Date(2014, 9, 1, 0, 1,05),
          new Date(2014, 9, 1, 0, 2,30),
          new Date(2014, 9, 1, 0, 3,20),
          new Date(2014, 9, 1, 0, 1,25),
          new Date(2014, 9, 1, 0, 0,00)]
      }
  ]
  };

  if (option && typeof option === "object") {
  myChart.setOption(option, true);
  }
  $(window).on('resize', function(){
      if(chart != null && chart != undefined){
          chart.resize();
      }
  });
  </script>
</code>```

答: You can use inverse:true in Y-axis.

Title: Echart Bar Graph Reverse Yaxis

Body: You can use inverse:true in Y-axis.


问:
No indent for paragraphs after figures?
The default style for my document is that paragraphs are indented. That's fine. But I need no indentation for paragraphs that follow a figure or other objects.

Using \noindent manually does not work well, because you don't know which paragraph will follow the figure in the final output (LaTeX places figures automatically).

So I need paragraphs that follow figures in the output to not be indented (in the tex source you can't see which ones that would be). How can that be achieved?

答: Looks like checking which paragraphs come after figures and putting \noindent in front of everyone manually is the only way to do this.

OwnerDisplayName: webjunkie

ContentLicense: CC BY-SA 2.5

Title: No indent for paragraphs after figures?


问:
COBOL Question - UNICODE
We are currently looking to convert our legacy COBOL code from ANSII to UNICODE however we have come across a problem where just changing the PIC X fields to PIC N and setting NSYMBOL(NATIONAL) will cause problems when data structures contain a REDEFINES or RENAME statement with elementary DATA items using PIC 9 fields.

```<code>01 WS-RECORD PIC N(26).
01 WS-RECORD-1 REDEFINES WS-RECORD.
02 WS-NUM PIC 9(6).
02 WS-DATA PIC N(20).

MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.
</code>```

In the above the string being moved will be in UTF-16 format, therefore the field WS-NUM will be corrupt as it will contain X"310032003300" which is an invalid numeric, WS-DATA will contain X"3400350036004100..etc

The question is, when using NATIONAL (UTF-16) data types how can numerics be handled so as to get the correct data after it has been redefined.

I can sort of get this to work doing the following but will get invalid data in other WS-RECORD.

```<code>MOVE 123456 TO WS-NUM.
MOVE N"ABCDEFGHIJKLM" TO WS_DATA.
</code>```

The above will be correct, however if I examine WS-RECORD I will see ???ABCDEFGHIJKLM where ??? is X"313233343536" in hexi-decimal.

Our problem is that we have multiple data records depending on the record type identifier, we also use redefines on many of our LINKAGE ITEMS.

Has anyone had experience moving from legacy ASCII to UNICODE?

答:
A solution suggested by MicroFocus is below:-

The size of WS-NCHAR-1 and WS-NCHAR-FIELD are different sizes because the size of “pic 9(6)” is half the size of “pic n(6)”.

So the quick but untidy solution is to place a filler and then re-correct the field by using “FUNCTION DISPLAY-OF”, although this works the customer really needs to understand that the size of “pic n” is different to “pic 9”, hence care is needed when you use redefines and during conversion.

A tweaked example that should show you what I mean in code…

```<code>01 ONE-PICN           PIC N.
01 ONE-PIC9           PIC 9.

01 WS-NCHAR-FIELD     PIC N(20).
01 WS-NCHAR-1 REDEFINES WS-NCHAR-FIELD.
   02  WS-NUM            PIC 9(6).
   02  FILLER            PIC X(6).
   02  WS-REST           PIC N(14).

DISPLAY "PIC N SIZE     : " length of ONE-PICN
DISPLAY "PIC 9 SIZE     : " length of ONE-PIC9

DISPLAY "WS-NCHAR-FIELD : " length of WS-NCHAR-FIELD
DISPLAY "WS-NCHAR-1     : " length of WS-NCHAR-1

DISPLAY "WS-REST        : " length of WS-REST
DISPLAY "WS-NUM         : " length of WS-NUM

MOVE N"123456ABCDEFGHIJKLM"  TO WS-NCHAR-FIELD.

MOVE FUNCTION DISPLAY-OF(WS-NCHAR-FIELD(1:6),1252) TO WS-NUM

DISPLAY "WS-NUM     : " WS-NUM    DISPLAY "WS-REST    : " WS-REST
</code>```

The above does not work for S9(n) COMP or S9(n)V9(n) ELEMENTRY ITEMS,  with VISUAL COBOL I found that I could just MOVE numeric values directly into PIC N(n) ELEMENTS and then use FUNCTION NUMVAL() to obtain the actual numeric, I am yet to try with Signed/COMP and decimal fields.

Thanks all for your help.

ContentLicense: CC BY-SA 3.0

Title: COBOL Question - UNICODE

Body:
We are currently looking to convert our legacy COBOL code from ANSII to UNICODE however we have come across a problem where just changing the PIC X fields to PIC N and setting NSYMBOL(NATIONAL) will cause problems when data structures contain a REDEFINES or RENAME statement with elementary DATA items using PIC 9 fields.

01 WS-RECORD PIC N(26).
01 WS-RECORD-1 REDEFINES WS-RECORD.
02 WS-NUM PIC 9(6).
02 WS-DATA PIC N(20).

MOVE N"123456ABCDEFGHIJKLM" TO WS-RECORD.

In the above the string being moved will be in UTF-16 format, therefore the field WS-NUM will be corrupt as it will contain X"310032003300" which is an invalid numeric, WS-DATA will contain X"3400350036004100..etc

The question is, when using NATIONAL (UTF-16) data types how can numerics be handled so as to get the correct data after it has been redefined.

I can sort of get this to work doing the following but will get invalid data in other WS-RECORD.

MOVE 123456 TO WS-NUM.
MOVE N"ABCDEFGHIJKLM" TO WS_DATA.

The above will be correct, however if I examine WS-RECORD I will see ???ABCDEFGHIJKLM where ??? is X"313233343536" in hexi-decimal.

Our problem is that we have multiple data records depending on the record type identifier, we also use redefines on many of our LINKAGE ITEMS.

Has anyone had experience moving from legacy ASCII to UNICODE?

Body:
A solution suggested by MicroFocus is below:-

The size of WS-NCHAR-1 and WS-NCHAR-FIELD are different sizes because the size of “pic 9(6)” is half the size of “pic n(6)”.

So the quick but untidy solution is to place a filler and then re-correct the field by using “FUNCTION DISPLAY-OF”, although this works the customer really needs to understand that the size of “pic n” is different to “pic 9”, hence care is needed when you use redefines and during conversion.

A tweaked example that should show you what I mean in code…

01 ONE-PICN           PIC N.
01 ONE-PIC9           PIC 9.

01 WS-NCHAR-FIELD     PIC N(20).
01 WS-NCHAR-1 REDEFINES WS-NCHAR-FIELD.
   02  WS-NUM            PIC 9(6).
   02  FILLER            PIC X(6).
   02  WS-REST           PIC N(14).

DISPLAY "PIC N SIZE     : " length of ONE-PICN
DISPLAY "PIC 9 SIZE     : " length of ONE-PIC9

DISPLAY "WS-NCHAR-FIELD : " length of WS-NCHAR-FIELD
DISPLAY "WS-NCHAR-1     : " length of WS-NCHAR-1

DISPLAY "WS-REST        : " length of WS-REST
DISPLAY "WS-NUM         : " length of WS-NUM

MOVE N"123456ABCDEFGHIJKLM"  TO WS-NCHAR-FIELD.

MOVE FUNCTION DISPLAY-OF(WS-NCHAR-FIELD(1:6),1252) TO WS-NUM

DISPLAY "WS-NUM     : " WS-NUM    DISPLAY "WS-REST    : " WS-REST

The above does not work for S9(n) COMP or S9(n)V9(n) ELEMENTRY ITEMS,  with VISUAL COBOL I found that I could just MOVE numeric values directly into PIC N(n) ELEMENTS and then use FUNCTION NUMVAL() to obtain the actual numeric, I am yet to try with Signed/COMP and decimal fields.

Thanks all for your help.


问:
autoResizeColumns Takes Too Long to Process
I spent a couple of hours trying to figure out why my script takes so long to process. I ended up realizing the culprit was autoResizeColumns(). The more rows on a sheet the longer it takes. It takes about a minute for about 6K rows. In my case I had to call it twice on two different sheets, both about 6K rows.

Is there really no other option? Doing this action manually on a sheet using the mouse takes significantly less time. So my question to you is what methods are you using to resize columns automatically?

答:
Answer:

Using the Advanced Sheets Service[1] you can build a batch request[2] in Google Apps Script for your Sheet which auto resizes the columns for you.

Building the Batch Request:

After enabling the Advanced Sheets Service from the Resources > Advanced Google services... menu option and clicking the On switch, you can build a batch request as a JSON object.

The structure of your batch request will have to look something like this:

{
  "requests": [
    {
      "autoResizeDimensions": {
        "dimensions": {
          "sheetId": "your-sheet-id",
          "dimension": "COLUMNS",
          "startIndex": X,
          "endIndex": Y
        }
      }
    }
  ]
}
```
<p>Where <code>X</code> and <code>Y</code> are integers representing the first and last columns you wish to have auto-resized. You can find more information about it in the 'Automatically resize a column' section<sup>[3]</sup> of the 'Row and Column Operations' documentation<sup>[4]</sup>.</p>
<p><strong>NB: The <code>startIndex</code> and <code>endIndex</code> values are array-like and so start at 0. If you wish to update the first 1000 columns you must use a <code>startIndex</code> of 0 and and <code>endIndex</code> of 999.</strong></p>
<h3>Example Code:</h3>
<pre class="lang-js prettyprint-override"><code>function resizeColumns() {
  // You can still use the SpreadsheetApp methods to get the Spreadsheet
  // and Sheet IDs which you need for the batch request
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetId = ss.getSheetByName("Name-of-Sheet-to-resize").getSheetId();

  // Define the range of columns
  var X = 0;
  var Y = 999;

  // Build the batch resource
  var resource = {
  "requests": [
    {
      "autoResizeDimensions": {
        "dimensions": {
          "sheetId": sheetId,
          "dimension": "COLUMNS",
          "startIndex": X,
          "endIndex": Y
        }
      }
    }
  ]
}
  // Make the batch request
  Sheets.Spreadsheets.batchUpdate(resource, ss.getId());

}
</code>```

References:

Advanced Sheets Service

Method: spreadsheets.batchUpdate

Google Sheets > API v4 - Row and Column Operations

Automatically resize a column

Body:
Answer:

Using the Advanced Sheets Service[1] you can build a batch request[2] in Google Apps Script for your Sheet which auto resizes the columns for you.

Building the Batch Request:

After enabling the Advanced Sheets Service from the Resources > Advanced Google services... menu option and clicking the On switch, you can build a batch request as a JSON object.

The structure of your batch request will have to look something like this:

{
  "requests": [
    {
      "autoResizeDimensions": {
        "dimensions": {
          "sheetId": "your-sheet-id",
          "dimension": "COLUMNS",
          "startIndex": X,
          "endIndex": Y
        }
      }
    }
  ]
}

Where X and Y are integers representing the first and last columns you wish to have auto-resized. You can find more information about it in the 'Automatically resize a column' section[3] of the 'Row and Column Operations' documentation[4].

NB: The startIndex and endIndex values are array-like and so start at 0. If you wish to update the first 1000 columns you must use a startIndex of 0 and and endIndex of 999.

Example Code:

function resizeColumns() {
  // You can still use the SpreadsheetApp methods to get the Spreadsheet
  // and Sheet IDs which you need for the batch request
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetId = ss.getSheetByName("Name-of-Sheet-to-resize").getSheetId();

  // Define the range of columns
  var X = 0;
  var Y = 999;

  // Build the batch resource
  var resource = {
  "requests": [
    {
      "autoResizeDimensions": {
        "dimensions": {
          "sheetId": sheetId,
          "dimension": "COLUMNS",
          "startIndex": X,
          "endIndex": Y
        }
      }
    }
  ]
}
  // Make the batch request
  Sheets.Spreadsheets.batchUpdate(resource, ss.getId());

}

References:

Advanced Sheets Service

Method: spreadsheets.batchUpdate

Google Sheets > API v4 - Row and Column Operations

Automatically resize a column


问:
Map Values to Keys
I have a data frame with a 'State' column denoting each record's State. I want to map the States to regions and I've created a dict:

```<code>     di = {'Mideast': ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA'], 'West': [ . . , . .], . . . }
</code>```

which is built using variables such as

```<code>    Mideast = ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA']
</code>```

Why a naive method like this does not work?

```<code>    for i in df_test['State']:
        if i in Mideast: i = 'Mideast';
</code>```

a sample value from the df:

```<code>State   Area Code    Phone    Intl Calls  Intl Charge  CustServ Calls   Churn?
KS       415        382-4657       3          2.7           1           False.
</code>```

I've searched online for possible solutions. I am trying them, but it bugs me that the method above seems so out of bounds that nobody even mentioned it. I am apparently not understanding something very fundamental, but I don't know what it is.

答:
Try this :

```<code>di = {'Mideast': ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA'], 'West': [ . . , . .], . . . }

mod_dict = {v:k for k,val in di.iteritems() for v in val}

for k,v in mod_dict.iteritems():

    df_test.loc[df_test['States'] = k, 'States'] = v

</code>```

I have converted initial di to mod_dict of form

```<code> 'DC': 'Mideast',
 'DL': 'Mideast',
 'MD': 'Mideast',
 'NJ': 'Mideast',
 'NY': 'Mideast',
 'PA': 'Mideast'}
 .
 .
 .
</code>```

Now I am looking for each country code in df and if found replacing it with the value of that code with region name.

Hope this helps.

Title: Map Values to Keys

Body:
I have a data frame with a 'State' column denoting each record's State. I want to map the States to regions and I've created a dict:

     di = {'Mideast': ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA'], 'West': [ . . , . .], . . . }

which is built using variables such as

    Mideast = ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA']

Why a naive method like this does not work?

    for i in df_test['State']:
        if i in Mideast: i = 'Mideast';

a sample value from the df:

State   Area Code    Phone    Intl Calls  Intl Charge  CustServ Calls   Churn?
KS       415        382-4657       3          2.7           1           False.

I've searched online for possible solutions. I am trying them, but it bugs me that the method above seems so out of bounds that nobody even mentioned it. I am apparently not understanding something very fundamental, but I don't know what it is.

Body:
Try this :

di = {'Mideast': ['DL', 'DC', 'MD', 'NJ', 'NY', 'PA'], 'West': [ . . , . .], . . . }

mod_dict = {v:k for k,val in di.iteritems() for v in val}

for k,v in mod_dict.iteritems():

    df_test.loc[df_test['States'] = k, 'States'] = v

I have converted initial di to mod_dict of form

 'DC': 'Mideast',
 'DL': 'Mideast',
 'MD': 'Mideast',
 'NJ': 'Mideast',
 'NY': 'Mideast',
 'PA': 'Mideast'}
 .
 .
 .

Now I am looking for each country code in df and if found replacing it with the value of that code with region name.

Hope this helps.


问:
How to parse JSON data and print on terminal in flutter?
This is my Json data :

```<code>     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}
</code>```

I want to print only  this data from jSON data:

```<code>[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]
</code>```

How to get this data from whole jSON data ?

答: The problem is your json is not properly formatted. first format it properly, you can copy and paste your json in any prettify json website and try to format it properly, if problem persists then do let me know.</p>

Body:
This is my Json data :

     {
   "result":"0",
   "school_name":"Global Academy International",
   "school_code":"GAIS",
   "dashboard":"{\"privilege\":[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":159,\"privilege_desc\":\"V4_MYATTENDANCE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1188},{\"activity_id\":159,\"privilege_desc\":\"V4_MYLEAVESTATUS\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1189},{\"activity_id\":159,\"privilege_desc\":\"V4_MEMO\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1193},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1198},{\"activity_id\":161,\"privilege_desc\":\"V4_SUBJECTWISELATE\",\"activity_desc\":\"V4_STUDENT_ATTENDANCE\",\"privilege_id\":1201},{\"activity_id\":162,\"privilege_desc\":\"V4_LEAVE_REQUISITION\",\"activity_desc\":\"V4_TEACHER_LEAVE\",\"privilege_id\":1203},{\"activity_id\":164,\"privilege_desc\":\"V4_ASSIGNMENT\",\"activity_desc\":\"V4_STUDENT_ASSIGNMENT\",\"privilege_id\":1206},{\"activity_id\":166,\"privilege_desc\":\"V4_SCHOOL_CALENDAR\",\"activity_desc\":\"V4_CALENDAR\",\"privilege_id\":1208},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}],\"resultPrivilege\":\"0\",\"resultProfile\":\"0\",\"profile\":{\"empid\":\"EMP183\",\"name\":\"BACHIR Raji Kashkash\",\"designation\":\"TEACHER\",\"photo_path\":\"/container/school_data/GAIS/photo/Staff/EMP183.jpg\",\"department_name\":\"HIGH SCHOOL - T\"}}",
   "employee_id":"EMP183",
   "school_url":"http://ict.gaiqatar.com"
}

I want to print only  this data from jSON data:

[{\"activity_id\":159,\"privilege_desc\":\"V4_MYPROFILE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1185},{\"activity_id\":159,\"privilege_desc\":\"V4_MYTIMETABLE\",\"activity_desc\":\"V4_DASHBOARD\",\"privilege_id\":1186},{\"activity_id\":168,\"privilege_desc\":\"V4_LOGOUT\",\"activity_desc\":\"V4_LOGOUT\",\"privilege_id\":1210}]

How to get this data from whole jSON data ?


问:
Using oauth2 by server in behalf of client
I am trying to build an application which requires to access user's google apis on their behalf once they give consent.

What I am trying to build?

An azure database is scheduled to put some data on user specified spreadsheets on their google drive.

What is the problem?

I am unable to figure out how to upload data to user specified spreadsheets when the user is offline.

What workflow do I want?

User logs in with Google Account

User gives consent to web app to access spreadsheets api (just once)

Thereafter my server should update the sheets as per the schedule without the user's interferance

User can later check back to see the updated data on their sheets.

I want to know how should I implement to get this mechanism?

答:
Request offline access of the user get a refresh token. Store the refresh token and when ever you need to access the users account later use the refresh token to request a new access token.

I recommend looking for a google client library in your chosen language most of them handle this functionality internally.


问:
How to create property to define different schema name with universal prefix?
The problem is that I have a lot of nativeQueries where I use schema name prefix to define table which I want to use.

For example:

SELECT * FROM SCHEMA.USERS u WHERE u.id = 100;
```

<p>The problem is that now I have 2 database with the same tables but different schema names.</p>

```DB1: SCHEMA_1.USERS
DB2: SCHEMA_2.USERS
```

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA? As I checked, Oracle SYNONYM is not working for schemas..

答:
According to the hibernate documentation

When using multiple database catalogs and schemas, Hibernate offers the possibility of setting a global catalog or schema so that you don’t have to declare it explicitly for every entity.

<property name="hibernate.default_catalog" value="crm"/>
<property name="hibernate.default_schema" value="analytics"/>
```
</blockquote>

<p>and further:</p>

<blockquote>
  <p>However, for native queries, the SQL query is passed as is, therefore you need to explicitly set the global catalog and schema whenever you are referencing a database table. Fortunately, Hibernate allows you to resolve the current global catalog and schema using the following placeholders:</p>

  <p>{h-catalog} - resolves the current <code>hibernate.default_catalog</code> configuration property value.</p>

  <p>{h-schema} - resolves the current <code>hibernate.default_schema</code> configuration property value.</p>

  <p>{h-domain} - resolves the current <code>hibernate.default_catalog</code> and <code>hibernate.default_schema</code> configuration property values (e.g. catalog.schema).</p>
</blockquote>

<p>So, you can avoid the explicit mention the schema name in your native sql:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT * FROM {h-schema}USERS u WHERE u.id = 100;
</code>```

But as for your question:

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA?

I guess it's impossible to do with using only standard hibernate  functionality.

Body:
The problem is that I have a lot of nativeQueries where I use schema name prefix to define table which I want to use.

For example:

SELECT * FROM SCHEMA.USERS u WHERE u.id = 100;

The problem is that now I have 2 database with the same tables but different schema names.

DB1: SCHEMA_1.USERS
DB2: SCHEMA_2.USERS

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA? As I checked, Oracle SYNONYM is not working for schemas..

Body:
According to the hibernate documentation

When using multiple database catalogs and schemas, Hibernate offers the possibility of setting a global catalog or schema so that you don’t have to declare it explicitly for every entity.

<property name="hibernate.default_catalog" value="crm"/>
<property name="hibernate.default_schema" value="analytics"/>

and further:

However, for native queries, the SQL query is passed as is, therefore you need to explicitly set the global catalog and schema whenever you are referencing a database table. Fortunately, Hibernate allows you to resolve the current global catalog and schema using the following placeholders:

{h-catalog} - resolves the current hibernate.default_catalog configuration property value.

{h-schema} - resolves the current hibernate.default_schema configuration property value.

{h-domain} - resolves the current hibernate.default_catalog and hibernate.default_schema configuration property values (e.g. catalog.schema).

So, you can avoid the explicit mention the schema name in your native sql:

SELECT * FROM {h-schema}USERS u WHERE u.id = 100;

But as for your question:

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA?

I guess it's impossible to do with using only standard hibernate  functionality.


问:
DownloadManager Error Message when opening the file
hey guys im making this simple app to fetch apk's that are stored on a server for clients.
i get the file downloaded and i want to open it to install.

so the first issue is that it downloads it twice?
second is i get error parsing application when it opens it?but if i open the file from the phone it works..

First downloading from my adapter :

```<code> Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .mkdirs();

                DownloadManager manager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);

                DownloadManager.Request request = new DownloadManager.Request (Uri.parse (appUrlString));
                request.setAllowedNetworkTypes (DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);

                request.setDescription ("Downloading");
                request.setTitle (appName);

                request.allowScanningByMediaScanner ();
                request.setNotificationVisibility (
                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS,  appName+".apk");

                manager.enqueue (request);
                mCallback.onClick (String.valueOf (manager.enqueue (request)),appName);

            }
        });
</code>```

Opening the file from my Main Activity:

```<code>private BroadcastReceiver onDownloadComplete = new BroadcastReceiver () {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Fetching the download id received with the broadcast
            long id = intent.getLongExtra (DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            spinner.setVisibility (View.GONE);
            Toast.makeText (context, "Download Completed", Toast.LENGTH_SHORT).show ();

            Log.d ("INTENT ", String.valueOf (id) + "DID " + downloadID);
            openDownloadedAttachment(context, id);
        }
    };

    @Override
    public void onClick(String value, String fileName) {
        spinner.setVisibility (View.VISIBLE);
        Log.d ("INTENT REC", value + " " + fileName);
        fileNameDownloaded = fileName;
        downloadID = value;
    }

private void openDownloadedAttachment(final Context context, final long downloadId) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query ();
        query.setFilterById (downloadId);
        Cursor cursor = downloadManager.query (query);
        if (cursor.moveToFirst ()) {
            int downloadStatus = cursor.getInt (cursor.getColumnIndex (DownloadManager.COLUMN_STATUS));
            String downloadLocalUri = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_LOCAL_URI));
            String downloadMimeType = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_MEDIA_TYPE));
            if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
                openDownloadedAttachment (context, Uri.parse (downloadLocalUri), downloadMimeType);
            }
        }
        cursor.close ();
    }

    private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
        if (attachmentUri != null) {
            // Get Content Uri.
            if (ContentResolver.SCHEME_FILE.equals (attachmentUri.getScheme ())) {
                // FileUri - Convert it to contentUri.
                File file = new File (attachmentUri.getPath ());
                attachmentUri = FileProvider.getUriForFile (MainActivity.this, "com.handshake.downloadmanager.provider", file);

                System.out.println ("Opening: " + attachmentUri);
            }

            Intent openAttachmentIntent = new Intent (Intent.ACTION_VIEW);
            openAttachmentIntent.setDataAndType (attachmentUri, attachmentMimeType);
            openAttachmentIntent.setFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                context.startActivity (openAttachmentIntent);
                System.out.println ("Opening attachement: " + openAttachmentIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText (context, context.getString (R.string.unable_to_open_file), Toast.LENGTH_LONG).show ();
            }
        }
    }
</code>```

I have an interface that tells my mainActivity what is the id of the download and when it is done.

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>
</code>```

```<code>provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provide_paths" />
        </provider>
</code>```

So why does it download 2 times? and the error message when trying to open it?

EDIT:
i settle one issue with the error message for package error. need to open the app setting to all the app to install

```<code> private void askSettings(){
        Intent intent = new Intent ();
        intent.setAction (Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        Uri uri = Uri.fromParts ("package", this.getPackageName (), null);
        intent.setData (uri);
        this.startActivity (intent);
    }
</code>```

but the downloading 2 times is my headache lol

答:
So stupid mistake..lol

i send the request id to my interface but the way i sent it

```<code>mCallback.onClick (String.valueOf (manager.enqueue (request)),appName);
</code>```

im calling the enqueue again..lol just needed to put request..uhh thx guys

Body:
hey guys im making this simple app to fetch apk's that are stored on a server for clients.
i get the file downloaded and i want to open it to install.

so the first issue is that it downloads it twice?
second is i get error parsing application when it opens it?but if i open the file from the phone it works..

First downloading from my adapter :

 Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        .mkdirs();

                DownloadManager manager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);

                DownloadManager.Request request = new DownloadManager.Request (Uri.parse (appUrlString));
                request.setAllowedNetworkTypes (DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);

                request.setDescription ("Downloading");
                request.setTitle (appName);

                request.allowScanningByMediaScanner ();
                request.setNotificationVisibility (
                        DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                request.setDestinationInExternalPublicDir (Environment.DIRECTORY_DOWNLOADS,  appName+".apk");

                manager.enqueue (request);
                mCallback.onClick (String.valueOf (manager.enqueue (request)),appName);

            }
        });

Opening the file from my Main Activity:

private BroadcastReceiver onDownloadComplete = new BroadcastReceiver () {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Fetching the download id received with the broadcast
            long id = intent.getLongExtra (DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            spinner.setVisibility (View.GONE);
            Toast.makeText (context, "Download Completed", Toast.LENGTH_SHORT).show ();

            Log.d ("INTENT ", String.valueOf (id) + "DID " + downloadID);
            openDownloadedAttachment(context, id);
        }
    };

    @Override
    public void onClick(String value, String fileName) {
        spinner.setVisibility (View.VISIBLE);
        Log.d ("INTENT REC", value + " " + fileName);
        fileNameDownloaded = fileName;
        downloadID = value;
    }

private void openDownloadedAttachment(final Context context, final long downloadId) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService (Context.DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query ();
        query.setFilterById (downloadId);
        Cursor cursor = downloadManager.query (query);
        if (cursor.moveToFirst ()) {
            int downloadStatus = cursor.getInt (cursor.getColumnIndex (DownloadManager.COLUMN_STATUS));
            String downloadLocalUri = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_LOCAL_URI));
            String downloadMimeType = cursor.getString (cursor.getColumnIndex (DownloadManager.COLUMN_MEDIA_TYPE));
            if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
                openDownloadedAttachment (context, Uri.parse (downloadLocalUri), downloadMimeType);
            }
        }
        cursor.close ();
    }

    private void openDownloadedAttachment(final Context context, Uri attachmentUri, final String attachmentMimeType) {
        if (attachmentUri != null) {
            // Get Content Uri.
            if (ContentResolver.SCHEME_FILE.equals (attachmentUri.getScheme ())) {
                // FileUri - Convert it to contentUri.
                File file = new File (attachmentUri.getPath ());
                attachmentUri = FileProvider.getUriForFile (MainActivity.this, "com.handshake.downloadmanager.provider", file);

                System.out.println ("Opening: " + attachmentUri);
            }

            Intent openAttachmentIntent = new Intent (Intent.ACTION_VIEW);
            openAttachmentIntent.setDataAndType (attachmentUri, attachmentMimeType);
            openAttachmentIntent.setFlags (Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                context.startActivity (openAttachmentIntent);
                System.out.println ("Opening attachement: " + openAttachmentIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText (context, context.getString (R.string.unable_to_open_file), Toast.LENGTH_LONG).show ();
            }
        }
    }

I have an interface that tells my mainActivity what is the id of the download and when it is done.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external_files"
        path="." />
</paths>

provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provide_paths" />
        </provider>

So why does it download 2 times? and the error message when trying to open it?

EDIT:
i settle one issue with the error message for package error. need to open the app setting to all the app to install

 private void askSettings(){
        Intent intent = new Intent ();
        intent.setAction (Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        Uri uri = Uri.fromParts ("package", this.getPackageName (), null);
        intent.setData (uri);
        this.startActivity (intent);
    }

but the downloading 2 times is my headache lol

Body:
So stupid mistake..lol

i send the request id to my interface but the way i sent it

mCallback.onClick (String.valueOf (manager.enqueue (request)),appName);

im calling the enqueue again..lol just needed to put request..uhh thx guys


问:
Execute multiple CMD tasks and update asynchronously
I'm implementing a C# application. I need to execute a program on multiple remote machines at the same time. To do so I'm using PSExec over a CMD with multithreading. Basically, for each machine, I start a thread that starts a CMD process. Depending on the result of the program executed remotely I'd like to either take an action or kill it if it takes more than x minutes (hope that makes sense).

The issue I've got is that I don't really know how to control for how long the process has been running other than using WaitForExit and, that doesn't really let me go multi-threading as it waits till the CMD call has finished.

I'm sure there must be a way of doing this but I cannot really figure it out. Could anyone please help me?

Here is my code (I'm new at c# coding so might not be the best code, feel free to correct any part of it you consider it is not right):

```<code>public async void BulkExecution()
{
    //Some code
    foreach (string machine in Machines)
    {
        //more code to work out the CMDline and other duties.
        var result = Task.Factory.StartNew(r => ExecutePsexec((string)r, RunBeforeKillMsec), CMDLine);
        await result;
    }
    //More Code
}

private static void ExecutePsexec(string CMDline, int RunBeforeKillMsec)
{
    Process compiler = new Process();
    compiler.StartInfo.FileName = "psexec.exe";
    compiler.StartInfo.Arguments = CMDline;
    compiler.StartInfo.UseShellExecute = false;
    compiler.StartInfo.RedirectStandardOutput = true;
    compiler.Start();

    if (!compiler.WaitForExit(RunBeforeKillMsec))
    {
        ExecutePSKill(CMDline);
    }
    else
    {
        //Some Actions here
        Common.Log(LogFile, CMDline.Split(' ')[0] + " finished successfully");
    }
}
</code>```

答:
Async void methods should be avoided. You should change the signature of the BulkExecution method to return a Task, so that you can await it and handle any exceptions that may occur. Inside the method create a Task for each machine, and then await all tasks with the Task.WhenAll method:

```<code>public async Task BulkExecution()
{
    //Some code
    Task[] tasks = Machines.Select(machine =>
    {
        //more code to work out the CMDline and other duties.
        return Task.Run(r => ExecutePsexec(CMDLine, ExecutionTimeoutMsec));
    }).ToArray();
    await Task.WhenAll(tasks);
    //More Code
}
</code>```

Body:
I'm implementing a C# application. I need to execute a program on multiple remote machines at the same time. To do so I'm using PSExec over a CMD with multithreading. Basically, for each machine, I start a thread that starts a CMD process. Depending on the result of the program executed remotely I'd like to either take an action or kill it if it takes more than x minutes (hope that makes sense).

The issue I've got is that I don't really know how to control for how long the process has been running other than using WaitForExit and, that doesn't really let me go multi-threading as it waits till the CMD call has finished.

I'm sure there must be a way of doing this but I cannot really figure it out. Could anyone please help me?

Here is my code (I'm new at c# coding so might not be the best code, feel free to correct any part of it you consider it is not right):

public async void BulkExecution()
{
    //Some code
    foreach (string machine in Machines)
    {
        //more code to work out the CMDline and other duties.
        var result = Task.Factory.StartNew(r => ExecutePsexec((string)r, RunBeforeKillMsec), CMDLine);
        await result;
    }
    //More Code
}

private static void ExecutePsexec(string CMDline, int RunBeforeKillMsec)
{
    Process compiler = new Process();
    compiler.StartInfo.FileName = "psexec.exe";
    compiler.StartInfo.Arguments = CMDline;
    compiler.StartInfo.UseShellExecute = false;
    compiler.StartInfo.RedirectStandardOutput = true;
    compiler.Start();

    if (!compiler.WaitForExit(RunBeforeKillMsec))
    {
        ExecutePSKill(CMDline);
    }
    else
    {
        //Some Actions here
        Common.Log(LogFile, CMDline.Split(' ')[0] + " finished successfully");
    }
}

Body:
Async void methods should be avoided. You should change the signature of the BulkExecution method to return a Task, so that you can await it and handle any exceptions that may occur. Inside the method create a Task for each machine, and then await all tasks with the Task.WhenAll method:

public async Task BulkExecution()
{
    //Some code
    Task[] tasks = Machines.Select(machine =>
    {
        //more code to work out the CMDline and other duties.
        return Task.Run(r => ExecutePsexec(CMDLine, ExecutionTimeoutMsec));
    }).ToArray();
    await Task.WhenAll(tasks);
    //More Code
}


问:
Optimize form (containing .png backgrounds) loading in C#
My problem is that I have an application developed in C# and before adding .png backgrounds all the forms are loading smoothly. After adding the backgrounds, the forms are loading much more difficult than before.

What can I possibly do in order to avoid the slow loading of the forms?

Thanks!

答:
Png format is faster than jpg and bmp.but you must load them at application startup.

```<code>Image Backgrund1 = Image.FromFile(@"MyFile1.png");
...
..
.
</code>```

And in the load event set them to background;

```<code>this.BackgroundImage = Background1
</code>```

Did you test it?

Also you can compress your images with some software such as photoshop -> Save for Web.
It

Body:
Png format is faster than jpg and bmp.but you must load them at application startup.

Image Backgrund1 = Image.FromFile(@"MyFile1.png");
...
..
.

And in the load event set them to background;

this.BackgroundImage = Background1

Did you test it?

Also you can compress your images with some software such as photoshop -> Save for Web.
It


问:
How to transform the coordinate axes in matplotlib
I want to plot a hexagonal lattice starting off from the meshgrid function that gives me a square lattice.

```<code>import numpy as np
import matplotlib.pyplot as plt

xx, yy = np.meshgrid(np.arange(10), np.arange(10), indexing='ij')
plt.scatter(xx,yy)
plt.show()
</code>```

If transform all of the points by the matrix A that contains the basis vectors of the hexagonal lattice I get:

```<code>A = np.array([[3./2, 3./2],[np.sqrt(3)/2, -np.sqrt(3)/2]])
pts = np.einsum('ij,jk->ik',A,np.array([xx.flatten(),yy.flatten()]))
plt.scatter(pts[0,:], pts[1,:])
plt.show()
</code>```

I think it would be more elegant if, instead of transforming each point, I could just transform the axes of my coordinate system to get the same result. Is there a function in matplotlib that allows me to change the basis vectors from [1,0] and [0,1] to [3./2, sqrt(3)/2] and [3./2, -sqrt(3)/2]? Or can I give such a matrix to np.meshgrid?

答:
You can provide an affine transform to the scatter to skew rotate the points.</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

xx, yy = np.meshgrid(np.arange(10), np.arange(10))
A = np.array([[3./2, 3./2, 0],[np.sqrt(3)/2, -np.sqrt(3)/2, 0], [0,0,1]])

fig, ax = plt.subplots()
plt.scatter(xx.flat, yy.flat, transform=mtrans.Affine2D(A) + ax.transData)
plt.show()
</code>```

Body:
I want to plot a hexagonal lattice starting off from the meshgrid function that gives me a square lattice.

import numpy as np
import matplotlib.pyplot as plt

xx, yy = np.meshgrid(np.arange(10), np.arange(10), indexing='ij')
plt.scatter(xx,yy)
plt.show()

If transform all of the points by the matrix A that contains the basis vectors of the hexagonal lattice I get:

A = np.array([[3./2, 3./2],[np.sqrt(3)/2, -np.sqrt(3)/2]])
pts = np.einsum('ij,jk->ik',A,np.array([xx.flatten(),yy.flatten()]))
plt.scatter(pts[0,:], pts[1,:])
plt.show()

I think it would be more elegant if, instead of transforming each point, I could just transform the axes of my coordinate system to get the same result. Is there a function in matplotlib that allows me to change the basis vectors from [1,0] and [0,1] to [3./2, sqrt(3)/2] and [3./2, -sqrt(3)/2]? Or can I give such a matrix to np.meshgrid?

Body:
You can provide an affine transform to the scatter to skew rotate the points.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans

xx, yy = np.meshgrid(np.arange(10), np.arange(10))
A = np.array([[3./2, 3./2, 0],[np.sqrt(3)/2, -np.sqrt(3)/2, 0], [0,0,1]])

fig, ax = plt.subplots()
plt.scatter(xx.flat, yy.flat, transform=mtrans.Affine2D(A) + ax.transData)
plt.show()


问:
For loop in pandas dataframe
i have the following dataframe in pandas:

```<code>src_ch_id;src_ch_name;src_ch_desc;src_table_name
aa;q1;11;DataTable_4
bb;q2;22;DataTable_4
cc;q3;33;DataTable_4
</code>```

With this dataframe I will create an insert for every row to a database. For testing I will print the parameters.

```<code>for index in channeldef_data_df:
   src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
   print('--')
   print(src_ch_id)
</code>```

I gives the following error:

".iloc requires numeric indexers, got ['src_ch_id']"

I think the problem is the [index] part in the code. What is my mistake  in the loop?

答:
Use pandas.DataFrame.iterrows to Iterate over DataFrame rows as (index, Series) pairs.

like for index, row in channeldef_data_df.iterrows():

>>> for index,_ in channeldef_data_df.iterrows():
...     src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
...     print(src_ch_id)
...
0    aa
Name: src_ch_id, dtype: object
1    bb
Name: src_ch_id, dtype: object
2    cc
Name: src_ch_id, dtype: object
```

<p>You are using <code>for index in channeldef_data_df:</code> it will only return column names in your code.</p>

<pre class="lang-py prettyprint-override"><code>>>> for index in channeldef_data_df:
...     print(index)
...
src_ch_id
src_ch_name
src_ch_desc
src_table_name
</code>```

Title: For loop in pandas dataframe

Body:
i have the following dataframe in pandas:

src_ch_id;src_ch_name;src_ch_desc;src_table_name
aa;q1;11;DataTable_4
bb;q2;22;DataTable_4
cc;q3;33;DataTable_4

With this dataframe I will create an insert for every row to a database. For testing I will print the parameters.

for index in channeldef_data_df:
   src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
   print('--')
   print(src_ch_id)

I gives the following error:

".iloc requires numeric indexers, got ['src_ch_id']"

I think the problem is the [index] part in the code. What is my mistake  in the loop?

Body:
Use pandas.DataFrame.iterrows to Iterate over DataFrame rows as (index, Series) pairs.

like for index, row in channeldef_data_df.iterrows():

>>> for index,_ in channeldef_data_df.iterrows():
...     src_ch_id = channeldef_data_df.iloc[[index], channeldef_data_df.columns.get_loc('src_ch_id')]
...     print(src_ch_id)
...
0    aa
Name: src_ch_id, dtype: object
1    bb
Name: src_ch_id, dtype: object
2    cc
Name: src_ch_id, dtype: object

You are using for index in channeldef_data_df: it will only return column names in your code.

>>> for index in channeldef_data_df:
...     print(index)
...
src_ch_id
src_ch_name
src_ch_desc
src_table_name


问:
Finding the nth value of the Recaman sequence using a lambda expression
I am studying the stream API and I have some questions. I will be very grateful if you can help.
My code 1:

```<code>public long recaman(long n) {
    HashSet<Long> s = new HashSet<>();
    s.add(0L);
    long prev = 0;
    for (int i = 1; i < n; i++) {
        long curr = prev - i;
        if (curr < 0 || s.contains(curr)) {
            curr = prev + i;
        }
        s.add(curr);
        prev = curr;
    }
    return prev;
}
</code>```

My code 2:

```<code>public int recaman(int n) {
    int[] seq = new int[n];
    boolean[] check = new boolean[10 * n];

    seq[0] = 0;
    check[0] = true;
    for (int k = 1; k < n; k++)
    {
        int minusVal = seq[k - 1] - k;
        int plusVal = seq[k - 1] + k;
        if ((minusVal > 0) && (!check[minusVal]))
        {
            seq[k] = minusVal;
            check[minusVal] = true;
        } else
        {
            seq[k] = plusVal;
            check[plusVal] = true;
        }
    }
    return seq[n - 1];
}
</code>```

How do I rewrite the code using a lambda expression (or use functional programming paradigm)?

答:
In both functions you are iterating over an int variable (i in the first one, k in the second)

Your loops use the iteration variable explicitly (in long curr = prev - i; and in int minusVal = seq[k - 1] - k;). As such it is not a "pure" iteration variable anymore, but it's both an iteration variable and data.

One of the goals of Streams is to abstract iteration, and do away with iteration variables. In a lambda function, the position of an element in the stream is not available. Thus, what you ask for is impossible with the Java Stream API.

If you still want to use functional programming paradigm to solve this problem, you should use recursion (ie. Streams are not the right tool for your job, recursion is).

Body:
I am studying the stream API and I have some questions. I will be very grateful if you can help.
My code 1:

public long recaman(long n) {
    HashSet<Long> s = new HashSet<>();
    s.add(0L);
    long prev = 0;
    for (int i = 1; i < n; i++) {
        long curr = prev - i;
        if (curr < 0 || s.contains(curr)) {
            curr = prev + i;
        }
        s.add(curr);
        prev = curr;
    }
    return prev;
}

My code 2:

public int recaman(int n) {
    int[] seq = new int[n];
    boolean[] check = new boolean[10 * n];

    seq[0] = 0;
    check[0] = true;
    for (int k = 1; k < n; k++)
    {
        int minusVal = seq[k - 1] - k;
        int plusVal = seq[k - 1] + k;
        if ((minusVal > 0) && (!check[minusVal]))
        {
            seq[k] = minusVal;
            check[minusVal] = true;
        } else
        {
            seq[k] = plusVal;
            check[plusVal] = true;
        }
    }
    return seq[n - 1];
}

How do I rewrite the code using a lambda expression (or use functional programming paradigm)?


问:
How to create my own extension that is also available in web-GUI
We'd like to develop a GCP Dataflow extension that we can make available to our data engineers in the Dataflow pipeline builder GUI. I thought I understood that is possible in one of the webinars, but can't find any documentation about it. An example project would also be great.

thanks a lot for your help
Juergen

答: What you are describing is Cloud Dataflow templates, so your memory is correct. From these public docs there are sublinks on how to create and then run your custom templates. </p>


问:
Why does my little Flask app with keras and tensorflow backend crash on subsequent image uploads?
for an assignment, we did image classifcation with Keras and TF that image classifies dogs vs cats. I wrote a simple Flask app that allows for a demo of uploading a pic and display whether the uploaded image scores dog or cat.

I can run a single upload and that displays nicely, but if I upload another image, I get:

```<code>TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 32), dtype=float32) is not an element of this graph.
</code>```

with the line:

```<code>  model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')
</code>```

highlighted in flask debug page

I'm new to this so I'm confused as to how to fix this. Here is my code:

```<code>@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():

    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:
            import keras
            from keras.models import load_model
            from keras import backend as K
            import numpy as np
            model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')
            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)
</code>```

The upload paths are paths on my laptop. I'm hoping to fix this an push to heroku or related.

I've read some posts about clearing the keras session. Is this the issue?

Thanks for any assistance.

答:
I've changed your code a bit according to my comment, it should be working now.</p>

```<code>import keras
from keras.models import load_model
from keras import backend as K
import numpy as np

model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')

@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():
    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:

            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)```
</code>```

Body:
for an assignment, we did image classifcation with Keras and TF that image classifies dogs vs cats. I wrote a simple Flask app that allows for a demo of uploading a pic and display whether the uploaded image scores dog or cat.

I can run a single upload and that displays nicely, but if I upload another image, I get:

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 32), dtype=float32) is not an element of this graph.

with the line:

  model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')

highlighted in flask debug page

I'm new to this so I'm confused as to how to fix this. Here is my code:

@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():

    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:
            import keras
            from keras.models import load_model
            from keras import backend as K
            import numpy as np
            model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')
            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)

The upload paths are paths on my laptop. I'm hoping to fix this an push to heroku or related.

I've read some posts about clearing the keras session. Is this the issue?

Thanks for any assistance.

Body:
I've changed your code a bit according to my comment, it should be working now.

import keras
from keras.models import load_model
from keras import backend as K
import numpy as np

model = load_model('/Volumes/T5_500G/Capstone/v2/flask/models/model_weights.h5')

@app.route('/upload_image', methods=['GET', 'POST'])
def upload_image():
    prediction_results = {}
    animals = ['% Cat Score', '% Dog Score']
    animals_scores = []
    imageUrl = ""

    if request.method == 'POST':

        if request.files:

            print(request.files)
            print(request.files['image'].filename)
            imageUrl = "/static/uploads/"+request.files['image'].filename
            image2 = app.config['IMAGE_UPLOADS']+"/"+request.files['image'].filename
            request.files['image'].save(image2)
            img_path = image2
            img = keras.preprocessing.image.load_img(img_path, target_size=(224,224))
            img_array = keras.preprocessing.image.img_to_array(img)
            expanded_img_array = np.expand_dims(img_array, axis=0)
            preprocessed_img = expanded_img_array / 255. # Preprocess the image
            prediction = model.predict(preprocessed_img)
            pred_list = prediction.tolist()
            animals_scores.append(pred_list[0][0])
            animals_scores.append(pred_list[0][1])
            print(prediction_results)

            imageUrl = "/static/uploads/"+request.files['image'].filename
    return render_template('/upload_image.html',imageUrl=imageUrl, animals=animals, animals_scores=animals_scores)```


问:
How can I run some code in the event that a watched folder does not exist?
I have a Mule 4 flow that uses the [File] On New or Updated File event source. This element is configured to wait for file changes within a specific folder.

When I deploy my flow, and the deployed application does not have access to the specified folder, a log message is generated and the flow terminates. However, I'd like to add some additional processing in this case. (I'd like to log a message to an alternative event log).

I tried adding an On Error Propagate element to the flow, but this is not triggered when the error occurs - I think this is because the error is a system error rather than a messaging error.

If I could add a step before the On New or Updated File element, then I could check for the existence of the folder, and execute that extra code there - but I see no way to do that either.

答:
Well, I was able to do something that "works". I created another flow that runs on a (long) timer, which runs immediately and checks for the existence of the folder by attempting to list its contents. If that fails, then the On Error ... block of that flow is reached, because in this case the error is treated as a messaging error rather than a system error.

Not an ideal solution, but a solution nonetheless.


答:
If you only want to extract src_ch_id and print, may be you can use itertuples()

```<code>for index in channeldef_data_df.itertuples():
    src_ch_id = index.src_ch_id
    print('--')
    print(src_ch_id)
</code>```

This way you get src_ch_id for each row

Title: For loop in pandas dataframe

Body:
If you only want to extract src_ch_id and print, may be you can use itertuples()

for index in channeldef_data_df.itertuples():
    src_ch_id = index.src_ch_id
    print('--')
    print(src_ch_id)

This way you get src_ch_id for each row


问:
RelatedObjectDoesNotExist. User has no profile
I've read some other answers for this (almost) question but they didn't help. I have the following 2 files mixed for user and profile apps(?).
In other answers they said this happens if you don't use >objects.get_or_create or not making signals.py file you'll get this error but I've gone through both of those ways and no results.
This is the traceback I get:

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:3000/profile/

Django Version: 3.0.3
Python Version: 3.7.3
Installed Applications:
['blog',
 'users',
 'crispy_forms',
 'django_cleanup',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/mahoursanat/users/views.py", line 38, in profile
    p_form = ProfileUpdateForm(instance=request.user.profile)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 225, in inner
    return func(self._wrapped, *args)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 423, in __get__
    self.related.get_accessor_name()

Exception Type: RelatedObjectDoesNotExist at /profile/
Exception Value: User has no profile.
</code>```

forms.py:

```<code>from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']
</code>```

signal.py:

```<code>from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()
</code>```

models.py for profile model:

```<code>from django.db import models
from django.contrib.auth.models import User
from PIL import Image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)
</code>```

and this is the views.py file:

```<code>from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, ProfileUpdateForm, UserUpdateForm

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(
                request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()
    context = {
        'form': form
    }
    return render(request, 'users/register.html', context)

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(
            request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:

        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)
</code>```

Thanks for reading this :).

P.S. As I see in admin page, no profiles are made after registration (neither from site nor admin page).

答:
```<code>define all apps in the end of Installed apps.

Installed Applications:
[
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog', #use <your_app>.apps.<YourAppConfig (class name)> instead of app name
 'users',
 'crispy_forms',
 'django_cleanup',
]
</code>```

Body:
I've read some other answers for this (almost) question but they didn't help. I have the following 2 files mixed for user and profile apps(?).
In other answers they said this happens if you don't use >objects.get_or_create or not making signals.py file you'll get this error but I've gone through both of those ways and no results.
This is the traceback I get:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:3000/profile/

Django Version: 3.0.3
Python Version: 3.7.3
Installed Applications:
['blog',
 'users',
 'crispy_forms',
 'django_cleanup',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/mahoursanat/users/views.py", line 38, in profile
    p_form = ProfileUpdateForm(instance=request.user.profile)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/utils/functional.py", line 225, in inner
    return func(self._wrapped, *args)
  File "/home/wss/Desktop/projects/python/django/mahour_sanat/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 423, in __get__
    self.related.get_accessor_name()

Exception Type: RelatedObjectDoesNotExist at /profile/
Exception Value: User has no profile.

forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username', 'email']

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['image']

signal.py:

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

models.py for profile model:

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

        img = Image.open(self.image.path)

        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

and this is the views.py file:

from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, ProfileUpdateForm, UserUpdateForm

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(
                request, f'Your account has been created! You are now able to log in')
            return redirect('login')
    else:
        form = UserRegisterForm()
    context = {
        'form': form
    }
    return render(request, 'users/register.html', context)

@login_required
def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form = ProfileUpdateForm(
            request.POST, request.FILES, instance=request.user.profile)
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated!')
            return redirect('profile')
    else:

        u_form = UserUpdateForm(instance=request.user)
        p_form = ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/profile.html', context)

Thanks for reading this :).

P.S. As I see in admin page, no profiles are made after registration (neither from site nor admin page).


问:
Android Material and appcompat Manifest merger failed
I have next grade

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.material:material:1.0.0-rc01'
}
</code>```

But when I want to build app I get next log:

```<code>Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0-alpha3] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0-alpha3] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-19:19 to override.
</code>```

Okey! Go to manifest and do it:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="ru.chopcode.myapplication">

    <application
        tools:replace="android:appComponentFactory"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    </application>

</manifest>
</code>```

Then I get this error in my Logcat:

```<code>Manifest merger failed with multiple errors, see logs that I have Linked with it
</code>```

答:
in my case i am add in manifest file `

```<code>tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"
</code>```

application tag of course,
It will work

Body:
I have next grade

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.android.material:material:1.0.0-rc01'
}

But when I want to build app I get next log:

Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0-alpha3] AndroidManifest.xml:22:18-91
    is also present at [androidx.core:core:1.0.0-alpha3] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
    Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-19:19 to override.

Okey! Go to manifest and do it:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="ru.chopcode.myapplication">

    <application
        tools:replace="android:appComponentFactory"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    </application>

</manifest>

Then I get this error in my Logcat:

Manifest merger failed with multiple errors, see logs that I have Linked with it

Body:
in my case i am add in manifest file `

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

application tag of course,
It will work


问:
How to debug nodejs.ECONNRESETError: socket hang up
when I send a form with large amount of data file, socket will be abruptly closed by remote server. That's maybe why I got an error of ECONNRESET. How to solve it?

my nodejs code:

```<code>Promise((resolve, reject) => {
  let sendOption = {
    method: 'post',
    host: host,
    port: port,
    path: path,
    headers: form.getHeaders(),
    timeout: options.maxTimeout ? 1 * 60 * 60 * 1000 : 2 * 60 * 1000,
  }
  if (options.userName && options.passWord) {
    let auth = new Buffer(options.userName + ':' + options.passWord).toString('base64');
    sendOption.Authorization = 'Basic ' + auth;
  }
  let request = http.request(sendOption, (res) => {
    let body = ''
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end', () => {
      resolve(JSON.parse(body))
    })
  });
  request.on('error', (err) => reject(err));
  request.write(form.getBuffer());
  request.end();
})
</code>```

Full error：

```<code>2020-02-17 19:09:25,570 ERROR 18664 [-/::1/-/14867ms POST /thirdPartUpload] nodejs.ECONNRESETError: socket hang up
    at connResetException (internal/errors.js:570:14)
    at Socket.socketOnEnd (_http_client.js:440:23)
    at Socket.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
code: "ECONNRESET"
name: "ECONNRESETError"
pid: 18664
hostname: PC-HZ20139584
    enter code here
</code>```

答:
POST requests need Content-Length: headers declaring the length of their bodies. In your case you send your POST's body with request.write(form.getBuffer());

An absent or wrong Content-Length: header can look to a server like an attempt to exploit a vulnerability. So servers slam the door (abruptly close the connection) on those requests, which shows up in your client as ECONNRESET.

Try something like this.

```<code>const buff = form.getBuffer();
request.setHeader('Content-Length', buff.length);
request.write(buff);
</code>```

Body:
when I send a form with large amount of data file, socket will be abruptly closed by remote server. That's maybe why I got an error of ECONNRESET. How to solve it?

my nodejs code:

Promise((resolve, reject) => {
  let sendOption = {
    method: 'post',
    host: host,
    port: port,
    path: path,
    headers: form.getHeaders(),
    timeout: options.maxTimeout ? 1 * 60 * 60 * 1000 : 2 * 60 * 1000,
  }
  if (options.userName && options.passWord) {
    let auth = new Buffer(options.userName + ':' + options.passWord).toString('base64');
    sendOption.Authorization = 'Basic ' + auth;
  }
  let request = http.request(sendOption, (res) => {
    let body = ''
    res.on('data', function (chunk) {
      body += chunk;
    });
    res.on('end', () => {
      resolve(JSON.parse(body))
    })
  });
  request.on('error', (err) => reject(err));
  request.write(form.getBuffer());
  request.end();
})

Full error：

2020-02-17 19:09:25,570 ERROR 18664 [-/::1/-/14867ms POST /thirdPartUpload] nodejs.ECONNRESETError: socket hang up
    at connResetException (internal/errors.js:570:14)
    at Socket.socketOnEnd (_http_client.js:440:23)
    at Socket.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
code: "ECONNRESET"
name: "ECONNRESETError"
pid: 18664
hostname: PC-HZ20139584
    enter code here

Body:
POST requests need Content-Length: headers declaring the length of their bodies. In your case you send your POST's body with request.write(form.getBuffer());

An absent or wrong Content-Length: header can look to a server like an attempt to exploit a vulnerability. So servers slam the door (abruptly close the connection) on those requests, which shows up in your client as ECONNRESET.

Try something like this.

const buff = form.getBuffer();
request.setHeader('Content-Length', buff.length);
request.write(buff);


问:
Laravel add variable for nested collections
I want to add variable to each object of collection inside collection. Here JSON response like this:

```<code>         {
         "id": 16,
          "survey_id": "8",
          "title": "How are you?",
          "created_at": "2020-02-06 04:21:44",
          "updated_at": "2020-02-06 04:21:44",
              "answers": [
</code>```

Here I want to add variable to each answer

```<code>{
            "id": 52,
            "question_id": "16",
            "text": "VERY GOOD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 53,
            "question_id": "16",
            "text": "OK",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 54,
            "question_id": "16",
            "text": "BAD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "2",
            "responded": 2
        }
    ]
},
</code>```

Overall, I want to add for every answers variable like $respond = $answer->reports()->count(); Help PLease!!

答:
I would fetch the answers from the database before assigning that array to a new question-object-property.</p>

```<code>public function get() {
  // fetch parent question
  $question = Question::where('title', $title)->get();

  // fetch answers
  $answers = Answers::where('parent_id', $question->id)->get();

  // create property called "answers"
  $question->answers = $answers;

  return response()->json($question);
}
</code>```

Body:
I want to add variable to each object of collection inside collection. Here JSON response like this:

         {
         "id": 16,
          "survey_id": "8",
          "title": "How are you?",
          "created_at": "2020-02-06 04:21:44",
          "updated_at": "2020-02-06 04:21:44",
              "answers": [

Here I want to add variable to each answer

{
            "id": 52,
            "question_id": "16",
            "text": "VERY GOOD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 53,
            "question_id": "16",
            "text": "OK",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "4",
            "responded": 2
        },
        {
            "id": 54,
            "question_id": "16",
            "text": "BAD",
            "created_at": "2020-02-06 04:21:44",
            "updated_at": "2020-02-06 04:21:44",
            "reports_count": "2",
            "responded": 2
        }
    ]
},

Overall, I want to add for every answers variable like $respond = $answer->reports()->count(); Help PLease!!

Body:
I would fetch the answers from the database before assigning that array to a new question-object-property.

public function get() {
  // fetch parent question
  $question = Question::where('title', $title)->get();

  // fetch answers
  $answers = Answers::where('parent_id', $question->id)->get();

  // create property called "answers"
  $question->answers = $answers;

  return response()->json($question);
}


问:
Yii2 Customize yii\bootstrap4\ActiveField::radioList option
I'm using yii\bootstrap4\ActiveField::radioList and I'm trying to insert html tag inside the options of my radioList.

```<code>$list = [
    0 => '<strong>Option1</strong><br>
        lorem ipsum lorem ipsum',
    1 => '<strong>Option2</strong><br>
        lorem ipsum lorem ipsum',
    2 => '<strong>Option3</strong><br>
        lorem ipsum lorem ipsum,',
];

echo $form->field($model, 'field')->radioList($list)->label('Your choose?');
</code>```

Is there a direct way to do it without create a template ?

答:
What you are looking for is the items option which gives you the ease to customize the radio or checkbox inputs and labels.

Although it is not clear what layout you are trying to follow for the radioList but you can change it in the code below, i will focus on what you have mentioned i.e formatting the text labels for the radio-list inputs.

```<code>$list = [
    0 => '<strong>Option1</strong><br>lorem ipsum lorem ipsum',
    1 => '<strong>Option2</strong><br>lorem ipsum lorem ipsum',
    2 => '<strong>Option3</strong><br>lorem ipsum lorem ipsum,',
];

echo $form->field($model, 'field')
    ->radioList(
        $list,
        [
            'item' => function ($index, $label, $name, $checked, $value) {

                $html = '<label >';
                $html .= '<input type="radio" name="' . $name . '" value="' . $value . '" ' . $checked . '>';
                $html .= '<span>' . ucwords($label) . '</span>';
                $html .= '</label>';

                return $html;
            },
        ]
    )
    ->label('Your choose?');
</code>```

Body:
I'm using yii\bootstrap4\ActiveField::radioList and I'm trying to insert html tag inside the options of my radioList.

$list = [
    0 => 'Option1

        lorem ipsum lorem ipsum',
    1 => 'Option2

        lorem ipsum lorem ipsum',
    2 => 'Option3

        lorem ipsum lorem ipsum,',
];

echo $form->field($model, 'field')->radioList($list)->label('Your choose?');

Is there a direct way to do it without create a template ?

Body:
What you are looking for is the items option which gives you the ease to customize the radio or checkbox inputs and labels.

Although it is not clear what layout you are trying to follow for the radioList but you can change it in the code below, i will focus on what you have mentioned i.e formatting the text labels for the radio-list inputs.

$list = [
    0 => '<strong>Option1</strong><br>lorem ipsum lorem ipsum',
    1 => '<strong>Option2</strong><br>lorem ipsum lorem ipsum',
    2 => '<strong>Option3</strong><br>lorem ipsum lorem ipsum,',
];

echo $form->field($model, 'field')
    ->radioList(
        $list,
        [
            'item' => function ($index, $label, $name, $checked, $value) {

                $html = '<label >';
                $html .= '<input type="radio" name="' . $name . '" value="' . $value . '" ' . $checked . '>';
                $html .= '<span>' . ucwords($label) . '</span>';
                $html .= '</label>';

                return $html;
            },
        ]
    )
    ->label('Your choose?');