问:
jstree isnt creating the tree from json provided
I am using jstree to create a treeview of the locations, rooms, and then assets for a company in a PHP app I am writing.

the purpose of this tree is to allow the user to select an asset during a booking wizard which creates a callout job for the particular asset.

I have the following setup on the page:-

HTML:

```<code><div class="panel panel-primary" style="overflow:auto;" id="assetSelectContainer">
  <div class="panel-body">
    <div id="assetInfo" style="float:right;height:400px;width:45%;">
      <div class="panel panel-default" style="margin:10px;overflow:visible;">
        <div class="panel-heading" style="padding-top:20px;">
          <h4 id="assetname"></h4>
        </div>
        <div class="panel-body">
          <ul class="list-group list-group-flush">
            <li class="list-group-item">Asset Location: <span id="locationname"></span></li>
            <li class="list-group-item">Asset Room: <span id="locationroom"></span></li>
            <li class="list-group-item">Asset Make: <span id="assetmake"></span></li>
            <li class="list-group-item">Asset Model: <span id="assetmodel"></span></li>
            <li class="list-group-item">Asset Type: <span id="assettype"></span></li>
            <li class="list-group-item">Asset Serial No.: <span id="assetserial"></span></li>
            <li class="list-group-item">Asset Tag: <span id="assettag"></span>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="companyAssetTree" style="float:left;height:400px;width:45%;border:1px solid #ccc;">

    </div>
  </div>
</div>
</code>```

Jquery from bookingwizard.js:

```<code>switch (curStep) {
  case 1:

    $("#roomContainer").hide();
    $('#step3Container').hide();
    var jsondata = $.get("../php/treeviewJSON.php");
    var xdata = ''
    //Load First Dropdown Data
    $('#companyAssetTree').jstree({
      "plugins": ["themes", "html_data", "ui", "cookie"],
      'core': {
        'check_callback': true,
        'data': {
          url: "../php/treeviewJSON.php"
        }
      }
    });

    break;
</code>```

JSON Returned from server:

```<code>[{
    "id": "string",
    "parent": "#",
    "text": "Head Office",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office"
    }
  },
  {
    "id": "string",
    "parent": "#",
    "text": "Manchester",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester"
    }
  },
  {
    "id": "string",
    "parent": "#",
    "text": "Birmingham",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Server Room"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Office Block 2",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Office Block 2"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Marketing",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Marketing"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Sales"
    }
  },
  {
    "id": "string",
    "parent": "Head Office",
    "text": "Customer Service",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Customer Service"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Accounts",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Accounts"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Human Resources",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Human Resources"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Sales"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Server Room"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Reception",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Reception"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Sales"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Reception",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Reception"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Server Room"
    }
  }
</code>```

I have followed the documentation from the jstree website and I'm not sure what I am doing wrong here, I followed their structure for the alternate JSON Format:

```<code>// Alternative format of the node (id & parent are required)
{
  id: "string" // required
  parent: "string" // required
  text: "string" // node text
  icon: "string" // string for custom
  state: {
    opened: boolean // is the node open
    disabled: boolean // is the node disabled
    selected: boolean // is the node selected
  },
  li_attr: {} // attributes for the generated LI node
  a_attr: {} // attributes for the generated A node
}
</code>```

and the tree isn't even building from the JSON returned from the server.

I really hope someone can point out where I may be going wrong, thank you in advance :)

答:
The way I re-approached this issue was to create the HTML for the treeView from serverside and then load that into the element's HTML, after doing that I then called on the treeView

```<code>$('#companyAssetTree').jstree();
</code>```

As the html structure was all there already the tree created from that, saving me the headache of trying to rectify a massive amount of JSON Data.

Body:
I am using jstree to create a treeview of the locations, rooms, and then assets for a company in a PHP app I am writing.

the purpose of this tree is to allow the user to select an asset during a booking wizard which creates a callout job for the particular asset.

I have the following setup on the page:-

HTML:

Asset Location:

Asset Room:

Asset Make:

Asset Model:

Asset Type:

Asset Serial No.:

Asset Tag:

Jquery from bookingwizard.js:

switch (curStep) {
  case 1:

    $("#roomContainer").hide();
    $('#step3Container').hide();
    var jsondata = $.get("../php/treeviewJSON.php");
    var xdata = ''
    //Load First Dropdown Data
    $('#companyAssetTree').jstree({
      "plugins": ["themes", "html_data", "ui", "cookie"],
      'core': {
        'check_callback': true,
        'data': {
          url: "../php/treeviewJSON.php"
        }
      }
    });

    break;

JSON Returned from server:

[{
    "id": "string",
    "parent": "#",
    "text": "Head Office",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office"
    }
  },
  {
    "id": "string",
    "parent": "#",
    "text": "Manchester",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester"
    }
  },
  {
    "id": "string",
    "parent": "#",
    "text": "Birmingham",
    "icon": "fas fa-compass",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Server Room"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Office Block 2",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Office Block 2"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Marketing",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Marketing"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Sales"
    }
  },
  {
    "id": "string",
    "parent": "Head Office",
    "text": "Customer Service",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Customer Service"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Accounts",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Accounts"
    }
  }, {
    "id": "string",
    "parent": "Head Office",
    "text": "Human Resources",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Head Office",
      "room": "Human Resources"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Sales"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Server Room"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Reception",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Reception"
    }
  }, {
    "id": "string",
    "parent": "Manchester",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Manchester",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Sales",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Sales"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Office Block 1",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Office Block 1"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Reception",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Reception"
    }
  }, {
    "id": "string",
    "parent": "Birmingham",
    "text": "Server Room",
    "icon": "fas fa-city",
    "li_attr": {
      "locationname": "",
      "room": "",
      "assetid": 0,
      "assetSerialNo": "",
      "assetTag": ""
    },
    "li_atrr": {
      "locationname": "Birmingham",
      "room": "Server Room"
    }
  }

I have followed the documentation from the jstree website and I'm not sure what I am doing wrong here, I followed their structure for the alternate JSON Format:

// Alternative format of the node (id & parent are required)
{
  id: "string" // required
  parent: "string" // required
  text: "string" // node text
  icon: "string" // string for custom
  state: {
    opened: boolean // is the node open
    disabled: boolean // is the node disabled
    selected: boolean // is the node selected
  },
  li_attr: {} // attributes for the generated LI node
  a_attr: {} // attributes for the generated A node
}

and the tree isn't even building from the JSON returned from the server.

I really hope someone can point out where I may be going wrong, thank you in advance :)

Body:
The way I re-approached this issue was to create the HTML for the treeView from serverside and then load that into the element's HTML, after doing that I then called on the treeView

$('#companyAssetTree').jstree();

As the html structure was all there already the tree created from that, saving me the headache of trying to rectify a massive amount of JSON Data.


来源: stackexchange

问:
Execute SAS Stored Process with Python
I know there is a method where you can call a stored process via the SAS Stored Process Web Application, but I was wondering if there is a method where i can call the stored process server directly.

The goal is to call a stored process which delivers data (via the _webout file?) to python, as efficiently as possible. So maybe it could reduce processing time by skipping the SAS Web Application.

I don't think it is possible with SASPy (seems to be using Workspace servers).

Regards.

答:
Your best bet will be to install saspy, configure your sascfg_personal.py file, open a session, and run the stored process.  Something like this:</p>

```<code>import saspy
sas = saspy.SASsession(cfgname='winiomwin')
stp = 'proc stp program="/Shared Data/Stored_Processes/your_SP"; run;'
sas_output = sas.submit(stp)
sas_log = sas_output['LOG']
</code>```

ContentLicense: CC BY-SA 4.0

Title: Execute SAS Stored Process with Python

Body:
Your best bet will be to install saspy, configure your sascfg_personal.py file, open a session, and run the stored process.  Something like this:

import saspy
sas = saspy.SASsession(cfgname='winiomwin')
stp = 'proc stp program="/Shared Data/Stored_Processes/your_SP"; run;'
sas_output = sas.submit(stp)
sas_log = sas_output['LOG']


问:
How to take a portion of one column to match with a portion of another column in pandas?
I am trying to clean up a large dataset. A sample of the dataset shows:

```<code>         Player Name        Headline
0        LeBron James       Woj: NBA. ESPN planning for a H-O-R-S-E tourna...
1        LeBron James       LeBron James suggests 5-10 games before playoffs
2        LeBron James       LeBron James overcomes Pelicans with 34/13/12
3        LeBron James       Anthony Davis (knee) won't play on Sunday
...      ...                ...
105180   Ryan Anderson      Ryan Anderson has first career double-double
105181   Ryan Anderson      Yi says he'll be back after All-Star break
105182   Ryan Anderson      Anderson stays hot in Nets win
</code>```

The problem I am having is that some headlines do not have anything to do with the player name (as you can see in row 0, 3, and 105181).

Question:

Is there a way to clean up the data so a portion of the "Player Name" column is featured in the "Headline" column? The rest that don't match would be removed from the new dataset made.

For example:

Row 0 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 1 and 2 would stay the same.

Row 3 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 105180 would stay the same.

Row 105181 would be removed since "Ryan" or "Anderson" isn't in the "Headline" column.

Row 105182 would stay the same since "Anderson" is in the "Player Name" and "Headline" column.

The new dataset will feature only the filtered data that has a portion of the "Player Name" column in the "Headline" column. I didn't know if there was a way to do this or if str.split should be used on the "Headline" column to split up the name from the rest of the headline then clean up from there.

答:
You can try this:

```<code>df['exists'] = df.apply(lambda x: any([k in x['Headline'] for k in x['Player Name'].split()]), axis=1)
df = df[~df['exists']==False].drop(columns=['exists'])
print(df)
</code>```

Output:

```<code>     Player Name                                          Headline
1   LeBron James  LeBron James suggests 5-10 games before playoffs
2   LeBron James     LeBron James overcomes Pelicans with 34/13/12
4  Ryan Anderson      Ryan Anderson has first career double-double
6  Ryan Anderson                    Anderson stays hot in Nets win
</code>```

Body:
I am trying to clean up a large dataset. A sample of the dataset shows:

         Player Name        Headline
0        LeBron James       Woj: NBA. ESPN planning for a H-O-R-S-E tourna...
1        LeBron James       LeBron James suggests 5-10 games before playoffs
2        LeBron James       LeBron James overcomes Pelicans with 34/13/12
3        LeBron James       Anthony Davis (knee) won't play on Sunday
...      ...                ...
105180   Ryan Anderson      Ryan Anderson has first career double-double
105181   Ryan Anderson      Yi says he'll be back after All-Star break
105182   Ryan Anderson      Anderson stays hot in Nets win

The problem I am having is that some headlines do not have anything to do with the player name (as you can see in row 0, 3, and 105181).

Question:

Is there a way to clean up the data so a portion of the "Player Name" column is featured in the "Headline" column? The rest that don't match would be removed from the new dataset made.

For example:

Row 0 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 1 and 2 would stay the same.

Row 3 would be removed since "LeBron" or "James" isn't in the "Headline" column.

Row 105180 would stay the same.

Row 105181 would be removed since "Ryan" or "Anderson" isn't in the "Headline" column.

Row 105182 would stay the same since "Anderson" is in the "Player Name" and "Headline" column.

The new dataset will feature only the filtered data that has a portion of the "Player Name" column in the "Headline" column. I didn't know if there was a way to do this or if str.split should be used on the "Headline" column to split up the name from the rest of the headline then clean up from there.

Body:
You can try this:

df['exists'] = df.apply(lambda x: any([k in x['Headline'] for k in x['Player Name'].split()]), axis=1)
df = df[~df['exists']==False].drop(columns=['exists'])
print(df)

Output:

     Player Name                                          Headline
1   LeBron James  LeBron James suggests 5-10 games before playoffs
2   LeBron James     LeBron James overcomes Pelicans with 34/13/12
4  Ryan Anderson      Ryan Anderson has first career double-double
6  Ryan Anderson                    Anderson stays hot in Nets win


问:
How to copy Tableau Data Extract logic?
Someone in my org created a Data Extract.  There is an issue in one of the worksheets that uses it, and we suspect it's due to a mistake in how the Union was built.  </p>

<p>But since it's a Data Extract, I can't see the UI for the data merge.  Is there anyway to take a current Data Extract and view the logic that creates it?  </p>

答:
Before going too deep into extract details, note that extracts are not intended to be permanent systems of record for data - just an efficient way to work with query results for optimized reporting. So in general, you should always be able to throw away the extract and look at the original source - or recreate the extract on command. But life isn't always perfect so ...

If you use Tableau Desktop to look at your worksheet, and look at the data source icon at the top of the data pane in the left sidebar, do you see an icon for your data source that looks like two databases with one on top of (shadowing) the other? If so, you can at right click on the data source icon and view its properties to see the source database table or file path. You can then even try disabling the extract to view the original source data.

If instead you see a single database icon, you have a "naked" extract where you've discarded the reference to the original source, (unless it is stored in the catalog mentioned below.)

If your organization purchased the Data Management Add-on for Tableau Server (strongly recommended), then if your data source is published to Tableau Server you can trace its history and origin by exploring the Tableau Catalog. That is especially valuable if the extract was built by a Tableau Prep Flow.

If instead, someone built the extract another way, say by writing a custom app using the Tableau Data Extract API, then the answer is to find that program.

One last point, in recent versions of Tableau, extracts are stored in an efficient relational type database file called Hyper. Hyper extracts can either be a single table (say serializing the results of a query joining multiple tables) or a Hyper extract can contain multiple tables (say serializing caching individual tables and deferring the join for later).

That may not be relevant to your question, but could turn out to matter as you reverse engineer how the extract was created.

Title: How to copy Tableau Data Extract logic?

Body:
Someone in my org created a Data Extract.  There is an issue in one of the worksheets that uses it, and we suspect it's due to a mistake in how the Union was built.

But since it's a Data Extract, I can't see the UI for the data merge.  Is there anyway to take a current Data Extract and view the logic that creates it?


问:
Gunicorn with Django giving a problem with static files
Got a Django project named django_server. When I run

```<code>python manage.py runserver
</code>```

the page shows up as expected

Then, if I run

```<code>gunicorn django_server.wsgi:application --bind 0.0.0.0:8000
</code>```

The page shows without styling

Checking the console, can see the following errors for both .css and .js files

The resource from
  “http://0.0.0.0:8000/static/....css” was blocked
  due to MIME type (“text/html”) mismatch (X-Content-Type-Options:
  nosniff).

In the terminal where the gunicorn command was executed, can read

```<code>NOT FOUND: /static/rest_framework/css/bootstrap.min.css
NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css
...
</code>```

In settings.py I mention

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
</code>```

This is the folder structure

Checked the permissions in static folder (ls -l)and they show as

```<code>drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static
</code>```

Checking the permissions in the files where the problem happens and

Added also to settings.py

```<code>import mimetypes

mimetypes.add_type("text/css",".css",True)
mimetypes.add_type("text/javascript",".js",True)
</code>```

But the error remains.

答:
You need to run python manage.py collectstatic.

On your settings.py I recommend you to use whitenoise to serve your files.

1) pip install whitenoise

2) Add STATICFILES_STORAGE on settings.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

3) Add to your MIDDLEWARE on settings.py

```<code>`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

  'django.middleware.security.SecurityMiddleware',
  ...

]
</code>```

Body:
Got a Django project named django_server. When I run

python manage.py runserver

the page shows up as expected

Then, if I run

gunicorn django_server.wsgi:application --bind 0.0.0.0:8000

The page shows without styling

Checking the console, can see the following errors for both .css and .js files

The resource from
  “http://0.0.0.0:8000/static/....css” was blocked
  due to MIME type (“text/html”) mismatch (X-Content-Type-Options:
  nosniff).

In the terminal where the gunicorn command was executed, can read

NOT FOUND: /static/rest_framework/css/bootstrap.min.css
NOT FOUND: /static/rest_framework/css/bootstrap-tweaks.min.css
...

In settings.py I mention

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static')

This is the folder structure

Checked the permissions in static folder (ls -l)and they show as

drwxrwxr-x 4 tiago tiago 4096 jun 2 15:49 static

Checking the permissions in the files where the problem happens and

Added also to settings.py

import mimetypes

mimetypes.add_type("text/css",".css",True)
mimetypes.add_type("text/javascript",".js",True)

But the error remains.

Body:
You need to run python manage.py collectstatic.

On your settings.py I recommend you to use whitenoise to serve your files.

1) pip install whitenoise

2) Add STATICFILES_STORAGE on settings.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

3) Add to your MIDDLEWARE on settings.py

`MIDDLEWARE = [

  'whitenoise.middleware.WhiteNoiseMiddleware',

  'django.middleware.security.SecurityMiddleware',
  ...

]


问:
Putting an image next to a div block
I've been working on my site for about a week or so, and today I've had some trouble putting an image next to a div block. I've tried messing with the display: several times, but it doesn't give me any results. </p>

```<code>    #indexPic {
  margin-left: 51%;
  }

#whiteBox2 {
  background-color: white;
  color: black;
  margin-left: 25%;
  width: 24%;
  }

  #rainbowdiv1 {
    margin-left: 30px;
    margin-top: 20px;
    }

    #rainbowdiv2 {
      margin-left: 30px;
      padding-bottom: 15px;
      }

 #introtext {
   margin-left: 115px;
   margin-bottom: 1px;
   }

   #extintro {
     margin-left: 70px;
     margin-top: 1px;
     }
</code>```

```<code><div id="whiteBox2">

<img id="rainbowdiv1" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">

<p id="introtext">jeremy . 16 . she/her</p>
<p id="extintro">TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT </p>
<img id="rainbowdiv2" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">
</div>
<img id="indexPic" src="https://66.media.tumblr.com/7cba5035b14f88c9b76b6b7263fc9268/tumblr_plx1skKq6D1uo5v6f_1280.png" alt="An edited, rainbowcored version of Rimi Ushigome's Dreamfest card from BanG DREAM!! Girls Band Party." width="200" height="200">

<img src="https://66.media.tumblr.com/20dc40b763cbcab5b3f9eeb9cdcd4527/tumblr_pylupn2B431yqo9zko1_400.gifv" class="center">
</code>```

<p>ignore the text spam, it's only a placeholder. any extra tips on ways to improve/fix my code are appreciated!! </p>

答:
Hopefully this helps.  I wrapped your image into a div and assigned it the class pic1.  I then set it to float: left; (I also gave it a margin on top to make it a little more center vertically but this is optional. I also set your #whiteBox2 to display: inline-block; Take a look. Hopefully this works for you.

   #indexPic {
  margin-left: 51%;
  }

#whiteBox2 {
  background-color: white;
  color: black;
  margin-left: 25%;
  width: 24%;
  display: inline-block;
  }

  #rainbowdiv1 {
    margin-left: 30px;
    margin-top: 20px;
    }

    #rainbowdiv2 {
      margin-left: 30px;
      padding-bottom: 15px;
      }

 #introtext {
   margin-left: 115px;
   margin-bottom: 1px;
   }

   #extintro {
     margin-left: 70px;
     margin-top: 1px;
     }

     .pic1 {
       float: left;
       margin-top: 50px;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="whiteBox2">

<img id="rainbowdiv1" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">

<p id="introtext">jeremy . 16 . she/her</p>
<p id="extintro">TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT </p>
<img id="rainbowdiv2" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">
</div>
<div class="pic1">
<img id="indexPic" src="https://66.media.tumblr.com/7cba5035b14f88c9b76b6b7263fc9268/tumblr_plx1skKq6D1uo5v6f_1280.png" alt="An edited, rainbowcored version of Rimi Ushigome's Dreamfest card from BanG DREAM!! Girls Band Party." width="200" height="200">
</div>

<img src="https://66.media.tumblr.com/20dc40b763cbcab5b3f9eeb9cdcd4527/tumblr_pylupn2B431yqo9zko1_400.gifv" class="center"></code>```

Title: Putting an image next to a div block

Body:
I've been working on my site for about a week or so, and today I've had some trouble putting an image next to a div block. I've tried messing with the display: several times, but it doesn't give me any results.

    #indexPic {
  margin-left: 51%;
  }

#whiteBox2 {
  background-color: white;
  color: black;
  margin-left: 25%;
  width: 24%;
  }

  #rainbowdiv1 {
    margin-left: 30px;
    margin-top: 20px;
    }

    #rainbowdiv2 {
      margin-left: 30px;
      padding-bottom: 15px;
      }

 #introtext {
   margin-left: 115px;
   margin-bottom: 1px;
   }

   #extintro {
     margin-left: 70px;
     margin-top: 1px;
     }

jeremy . 16 . she/her

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

TEXT TEXT TEXT TEXT TEXT

ignore the text spam, it's only a placeholder. any extra tips on ways to improve/fix my code are appreciated!!

Body:
Hopefully this helps.  I wrapped your image into a div and assigned it the class pic1.  I then set it to float: left; (I also gave it a margin on top to make it a little more center vertically but this is optional. I also set your #whiteBox2 to display: inline-block; Take a look. Hopefully this works for you.

   #indexPic {
  margin-left: 51%;
  }

#whiteBox2 {
  background-color: white;
  color: black;
  margin-left: 25%;
  width: 24%;
  display: inline-block;
  }

  #rainbowdiv1 {
    margin-left: 30px;
    margin-top: 20px;
    }

    #rainbowdiv2 {
      margin-left: 30px;
      padding-bottom: 15px;
      }

 #introtext {
   margin-left: 115px;
   margin-bottom: 1px;
   }

   #extintro {
     margin-left: 70px;
     margin-top: 1px;
     }

     .pic1 {
       float: left;
       margin-top: 50px;
     }

<div id="whiteBox2">

<img id="rainbowdiv1" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">

<p id="introtext">jeremy . 16 . she/her</p>
<p id="extintro">TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT  <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT <br>
TEXT TEXT TEXT TEXT TEXT </p>
<img id="rainbowdiv2" src="https://66.media.tumblr.com/b8bcbd7471af04030ae8d6a782d4bdb9/tumblr_oceahwkbFj1vd6nw3o10_500.gifv" alt="A flashy rainbow star divider." width="302" height="8">
</div>
<div class="pic1">
<img id="indexPic" src="https://66.media.tumblr.com/7cba5035b14f88c9b76b6b7263fc9268/tumblr_plx1skKq6D1uo5v6f_1280.png" alt="An edited, rainbowcored version of Rimi Ushigome's Dreamfest card from BanG DREAM!! Girls Band Party." width="200" height="200">
</div>

<img src="https://66.media.tumblr.com/20dc40b763cbcab5b3f9eeb9cdcd4527/tumblr_pylupn2B431yqo9zko1_400.gifv" class="center">


问:
ansible to read openssl public key (.pem) content from user input and create a file on server
I m basically creating a playbook for creating pkcs12 file where in it asks for public key(.pem) and private key. my private key is on server so i can pass location of file. but my public key(.pem) is not residing on server nor i can copy paste from local.
so i want to create an ansible-playbook which can read public key content from user as a variable and create a file on the remote server to use in pkcs12 file creation.

my publickey content is spreaded across multiple lines like below.

```<code>-----BEGIN CERTIFICATE-----
(64-character alphanumeric content)
.
.
.
.
-----END CERTIFICATE-----
</code>```

can you suggest simple way to achieve this.
i am using copy module 'content' option, but unable to achieve this.

```<code>  tasks:
  - name: copy content
    copy:
     content: "{{ my_pub_key }}"
     dest: /tmp/{{file}}.pem

ansible-playbook abc.yaml -e "my_pub_key=
-----BEGIN CERTIFICATE-----
.
.
.
.
-----END CERTIFICATE-----
</code>```

"~
please suggest if there is any another way to achieve this ?

答:
Not exactly sure, what do you mean by below statement. From the question, guessing nothing was written to the destination file.

...but unable to achieve this...

Your task looks fine. However, to pass multiline string as a parameter, add quote (') to define variable value like this.

```<code>$ ansible-playbook abc.yaml -e "my_pub_key='
-----BEGIN CERTIFICATE-----
.
.
.
.
-----END CERTIFICATE-----'"
</code>```

Body:
I m basically creating a playbook for creating pkcs12 file where in it asks for public key(.pem) and private key. my private key is on server so i can pass location of file. but my public key(.pem) is not residing on server nor i can copy paste from local.
so i want to create an ansible-playbook which can read public key content from user as a variable and create a file on the remote server to use in pkcs12 file creation.

my publickey content is spreaded across multiple lines like below.

-----BEGIN CERTIFICATE-----
(64-character alphanumeric content)
.
.
.
.
-----END CERTIFICATE-----

can you suggest simple way to achieve this.
i am using copy module 'content' option, but unable to achieve this.

  tasks:
  - name: copy content
    copy:
     content: "{{ my_pub_key }}"
     dest: /tmp/{{file}}.pem

ansible-playbook abc.yaml -e "my_pub_key=
-----BEGIN CERTIFICATE-----
.
.
.
.
-----END CERTIFICATE-----

"~
please suggest if there is any another way to achieve this ?

Body:
Not exactly sure, what do you mean by below statement. From the question, guessing nothing was written to the destination file.

...but unable to achieve this...

Your task looks fine. However, to pass multiline string as a parameter, add quote (') to define variable value like this.

$ ansible-playbook abc.yaml -e "my_pub_key='
-----BEGIN CERTIFICATE-----
.
.
.
.
-----END CERTIFICATE-----'"


问:
Naming keys in resource files best practice
Does anyone have any recommendations on naming keys in resource files? For instance, do you base the name of your key on the text that needs to be localized or on the control that uses the text?

Say you have an edit button in several screens (one to edit a user, one to edit a group). You could use the following keys:

editUserButton.label=Edit User...

editGroupButton.label=Edit Group...

or

editUser=Edit User...

editGroup=Edit Group...

or

user.edit=Edit User...

group.edit=Edit Group...

What scheme do you prefer and why?

答:
I think that in the first place you should use some kind of XML files to store that kind of data.

Something like :

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>

<xml>

    <button>

        <edit>

            <user>***Edit User*</user>

            <group>Edit group</group>

        </edit>

    </button>

</xml>**

And then use a "translate" Class to get (and set/save) the text.

Something like :

myTranslateClass.load( 'translate.xml' );

myTranslateClass.get( 'button' , 'edit' , 'user' );

That's a simple example.

OwnerDisplayName: Christophe Herreman

ContentLicense: CC BY-SA 2.5


问:
Appfabric caching and recycling of application pool
Where is the appfabric cache stored in memory?

We have a web site that uses appfabric cache.

Appfabric cache is set up with high availability, enterprise edition of windows 2008 and secondary cache.

If we recycle the application pool that the web site uses by editing the web.config on all servers will be loose the cache?

答: AppFabric Cache is a distributed cache -- the optional local cache component is in-process and would be lost on application pool recycle, but the core AppFabric Cache service itself is a remotely-hosted cache. If you use Powershell to restart the cache cluster, or if you stop/start the service through Windows Service Manager, the caches on the cluster will lose all state, like recycling an app pool.

ContentLicense: CC BY-SA 3.0


问:
How to create a dictionary from a given list?
I am trying to create a dictionary from my given list, knowing that the key will be the first letter of that word, and those have the same first letter would be added up to 1 key correspondingly. Can you guys help me out, please?

words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']
```

答:
```<code>words= ['apple', 'bible','bird' ,'candy', 'day', 'elephant','friend']

def make_dict(words):
    di = {}
    for item in words:
        if item[0] in di:
            di[item[0]] += [item]
        else:
            di[item[0]] = [item]
    return di
</code>```


问:
How to add a custom button to the grapesjs toolbar?
How do you add a custom button to the grapesjs toolbar?

I have followed the instructions on this github issue and written the code below, but the button doesn't appear in the toolbar as expected.

What am I missing?

```<code>initToolbar() {
        const { em } = this;
        const model = this;
        const ppfx = (em && em.getConfig('stylePrefix')) || '';

        if (!model.get('toolbar')) {
            var tb = [];
            if (model.collection) {
                tb.push({
                    attributes: { class: 'fa fa-arrow-up' },
                    command: ed => ed.runCommand('core:component-exit', { force: 1 })
                });
            }
            if (model.get('draggable')) {
                tb.push({
                    attributes: {
                        class: `fa fa-arrows ${ppfx}no-touch-actions`,
                        draggable: true
                    },
                    //events: hasDnd(this.em) ? { dragstart: 'execCommand' } : '',
                    command: 'tlb-move'
                });
            }
            if (model.get('schedule')) {
                tb.push({
                    attributes: { class: 'fa fa-clock', },
                    command: 'tlb-settime'
                });
            }
            if (model.get('copyable')) {
                tb.push({
                    attributes: { class: 'fa fa-clone' },
                    command: 'tlb-clone'
                });
            }
            if (model.get('removable')) {
                tb.push({
                    attributes: { class: 'fa fa-trash-o' },
                    command: 'tlb-delete'
                });
            }
            model.set('toolbar', tb);
        }
    },
</code>```

答:
One way to add new toolbar icons is to add the button as each component is selected.

```<code>  // define this event handler after editor is defined
  // like in const editor = grapesjs.init({ ...config });
  editor.on('component:selected', () => {

    // whenever a component is selected in the editor

    // set your command and icon here
    const commandToAdd = 'tlb-settime';
    const commandIcon = 'fa fa-clock';

    // get the selected componnet and its default toolbar
    const selectedComponent = editor.getSelected();
    const defaultToolbar = selectedComponent.get('toolbar');

    // check if this command already exists on this component toolbar
    const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

    // if it doesn't already exist, add it
    if (!commandExists) {
      selectedComponent.set({
        toolbar: [ ...defaultToolbar, {  attributes: {class: commandIcon}, command: commandToAdd }]
      });
    }

  });
</code>```

If it's important to you that only components with the "schedule" attribute have this toolbar option show up, as in your example, you can access and check this from selectedComponent:

```<code>const selectedComponent = editor.getSelected();
const defaultToolbar = selectedComponent.get('toolbar');
const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

// add this
const hasScheduleAttribute = selectedComponent.attributes.schedule;

if (!commandExists && hasScheduleAttribute) { // ...set toolbar code
</code>```

Body:
How do you add a custom button to the grapesjs toolbar?

I have followed the instructions on this github issue and written the code below, but the button doesn't appear in the toolbar as expected.

What am I missing?

initToolbar() {
        const { em } = this;
        const model = this;
        const ppfx = (em && em.getConfig('stylePrefix')) || '';

        if (!model.get('toolbar')) {
            var tb = [];
            if (model.collection) {
                tb.push({
                    attributes: { class: 'fa fa-arrow-up' },
                    command: ed => ed.runCommand('core:component-exit', { force: 1 })
                });
            }
            if (model.get('draggable')) {
                tb.push({
                    attributes: {
                        class: `fa fa-arrows ${ppfx}no-touch-actions`,
                        draggable: true
                    },
                    //events: hasDnd(this.em) ? { dragstart: 'execCommand' } : '',
                    command: 'tlb-move'
                });
            }
            if (model.get('schedule')) {
                tb.push({
                    attributes: { class: 'fa fa-clock', },
                    command: 'tlb-settime'
                });
            }
            if (model.get('copyable')) {
                tb.push({
                    attributes: { class: 'fa fa-clone' },
                    command: 'tlb-clone'
                });
            }
            if (model.get('removable')) {
                tb.push({
                    attributes: { class: 'fa fa-trash-o' },
                    command: 'tlb-delete'
                });
            }
            model.set('toolbar', tb);
        }
    },

Body:
One way to add new toolbar icons is to add the button as each component is selected.

  // define this event handler after editor is defined
  // like in const editor = grapesjs.init({ ...config });
  editor.on('component:selected', () => {

    // whenever a component is selected in the editor

    // set your command and icon here
    const commandToAdd = 'tlb-settime';
    const commandIcon = 'fa fa-clock';

    // get the selected componnet and its default toolbar
    const selectedComponent = editor.getSelected();
    const defaultToolbar = selectedComponent.get('toolbar');

    // check if this command already exists on this component toolbar
    const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

    // if it doesn't already exist, add it
    if (!commandExists) {
      selectedComponent.set({
        toolbar: [ ...defaultToolbar, {  attributes: {class: commandIcon}, command: commandToAdd }]
      });
    }

  });

If it's important to you that only components with the "schedule" attribute have this toolbar option show up, as in your example, you can access and check this from selectedComponent:

const selectedComponent = editor.getSelected();
const defaultToolbar = selectedComponent.get('toolbar');
const commandExists = defaultToolbar.some(item => item.command === commandToAdd);

// add this
const hasScheduleAttribute = selectedComponent.attributes.schedule;

if (!commandExists && hasScheduleAttribute) { // ...set toolbar code


问:
Why does javascript import take so long?
I am importing a JSON file from my website's own directory on the front-end. After a user clicks a button, this code is executed in the browser:

```<code>const file = await import('./path-to-file')
</code>```

The file is exceptionally small - only 4KB. Yet using console.time() is showing that it takes about 300ms to execute this command. I have checked my own web speed which comes out at 74Mb/s. I am using Netlify to deploy the website and Bitcatcha is saying the server is 'exceptionally fast' with a response time of 133ms. I'm not sure exactly how the response time fits into all this - but all in all, 300ms seems absurdly long to be transferring just 4KB of data.

Why does it take so long, and what can be done to make it faster?

答:
Is this js from the browser or server side?

I'm assuming browser from context, the reason it's so slow is because it like it states, waits for the file to load. The accepted answer does make it faster, but the issue then is that the json file isn't guaranteed to be processed after that line of code.

Async code is a big thing in js and other languages so I recommend looking further into this but here's some examples:

Let's say this is the json file1

```<code>{
  count: 2
}
</code>```

Here's the js file

const data = import("path-to-json");
//it immediately goes to the next code
console.log(data.count);
// => undefined or error, since it hasn't finished resolving it
```

<p>if you wish to access it you would either have to use <code>.then</code> or <code>await</code></p>

<pre class="lang-js prettyprint-override"><code>let data;

import("path-to-json").then(d => {
  data = d;
  //now you can use data
  console.log(data.count)
  // => 2
});

//it has still moved on to the next code
//so you still can't use data here
console.log(data.count)
// => undefined or error
</code>```

Body:
I am importing a JSON file from my website's own directory on the front-end. After a user clicks a button, this code is executed in the browser:

const file = await import('./path-to-file')

The file is exceptionally small - only 4KB. Yet using console.time() is showing that it takes about 300ms to execute this command. I have checked my own web speed which comes out at 74Mb/s. I am using Netlify to deploy the website and Bitcatcha is saying the server is 'exceptionally fast' with a response time of 133ms. I'm not sure exactly how the response time fits into all this - but all in all, 300ms seems absurdly long to be transferring just 4KB of data.

Why does it take so long, and what can be done to make it faster?

Body:
Is this js from the browser or server side?

I'm assuming browser from context, the reason it's so slow is because it like it states, waits for the file to load. The accepted answer does make it faster, but the issue then is that the json file isn't guaranteed to be processed after that line of code.

Async code is a big thing in js and other languages so I recommend looking further into this but here's some examples:

Let's say this is the json file1

{
  count: 2
}

Here's the js file

const data = import("path-to-json");
//it immediately goes to the next code
console.log(data.count);
// => undefined or error, since it hasn't finished resolving it

if you wish to access it you would either have to use .then or await

let data;

import("path-to-json").then(d => {
  data = d;
  //now you can use data
  console.log(data.count)
  // => 2
});

//it has still moved on to the next code
//so you still can't use data here
console.log(data.count)
// => undefined or error


问:
cant create a trigger - sql server 2008
I'm trying the following :

```<code>CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO
</code>```

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

```<code>Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.
</code>```

答:
```<code>IF (SELECT GRADE FROM INSERTED) > 20
BEGIN
   UPDATE Enrollment
   SET GRADE = 3
   WHERE course = (SELECT COURSE FROM INSERTED),
   AND QYear = (SELECT QYear FROM INSERTED),
   AND SUID = (SELECT SUID FROM INSERTED),
   AND units = (SELECT UNITS FROM INSERTED)
END
</code>```

If i remember well you can't use more than one table in a update statement so @Joe Stefanelli' answer will not work as expected but the idea its correct.

Hope it works.

Title: cant create a trigger - sql server 2008

Body:
I'm trying the following :

CREATE TRIGGER checkgrade ON
[Homework4part3].[dbo].[Enrollment]
FOR INSERT
AS
    IF (NEW.grade > 20)
    BEGIN
    grade = 3
    END

GO

and my table looks like :

Enrollment(course#, QYear, SUID,
  units, Grade)

dont know why this error showing :

Msg 102, Level 15, State 1, Procedure checkgrade, Line 7
Incorrect syntax near 'grade'.

Body:
IF (SELECT GRADE FROM INSERTED) > 20
BEGIN
   UPDATE Enrollment
   SET GRADE = 3
   WHERE course = (SELECT COURSE FROM INSERTED),
   AND QYear = (SELECT QYear FROM INSERTED),
   AND SUID = (SELECT SUID FROM INSERTED),
   AND units = (SELECT UNITS FROM INSERTED)
END

If i remember well you can't use more than one table in a update statement so @Joe Stefanelli' answer will not work as expected but the idea its correct.

Hope it works.


问:
nodejs server app.post issue XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:
I followed a tutorial on YouTube to create a private user to user chat.

https://www.youtube.com/watch?v=Ozrm_xftcjQ

Everything on the chat works accept that i keep getting this Error:

```<code>XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:
</code>```

using firefox developer edition and chrome. if i click the stack trace link i get the following xml error:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
```Cannot GET /get_messages```
</body>
</html>
</code>```

but i have no GET calls at all..

The code looks as follows:

server.js file

```<code>var port = process.env.PORT || 3000;
//creating express instance
var express = require("express");
var app = express();

//creating http instance
var http = require("http").createServer(app);

//app.use(express.static(__dirname));

//creating socket instance
var io = require("socket.io")(http);

//create body parser instance
var bodyParser = require("body-parser");
app.use(bodyParser.json());

//enable url encode for POST requests
app.use(bodyParser.urlencoded({ extended : true }));

//create instance of mysql
var mysql = require('mysql');

//create mysql connection
//          connectionLimit: 100,debug: true
var connection = mysql.createConnection({
        host: 'localhost',
        user: 'xxx',
        password: 'xxx',
        database: 'chatio'
});

connection.connect(function(error){
if(error){
console.log(error);
return;
}
console.log('database connected');
})

//enable header request for post requests
app.use(function(request, result, next){
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})

//create api to return all messages
app.post("/get_messages", function(request, result){
console.log(request);
console.log(result);
connection.query("SELECT * FROM chat_messages WHERE (`from_id` = '"+request.body.sender+"' AND   `to_id` = '"+request.body.receiver+"') OR (`from_id` = '"+request.body.receiver+"' AND `to_id` = '"+request.body.sender+"')", function(error, messages){
if(error){
console.log(error);
return;
}
console.log(messages);
//response will be in JSON
result.end(JSON.stringify(messages));
});
})

io.on("connection", function(socket){
socket.on("send_message", function(data){
//send event to receiver
var socketId = users[data.receiver];

io.to(socketId).emit("new_message", data);

//save in database
connection.query("INSERT INTO chat_messages (`from_id`,`to_id`,`message`) VALUES ('"+data.sender+"', '"+data.receiver+"', '"+data.message+"')", function(error, result){

if(error){
console.log(error);
return;
}
console.log('message saved');
});
})
})

http.listen(port, function(){
console.log("server started");
})
</code>```

inde.php file code as follows:

```<code>//creating io connection
var io = io("http://localhost:3000");

var receiver = "johnny";
var sender = "steven";

function onUserSelected(){
$.ajax({
url: "http://localhost:3000/get_messages",
method:"POST",
cache: false,
data: {
"sender" : sender,
"receiver" : receiver
},
dataType: "json",
success: function(response){
var messages = response; //JSON.parse();
var html = "";
for(var i = 0; i < messages.length; i++){
html += "<li>" +messages[i].from_id + " says: " + messages[i].message + "</li>";
document.getElementById('messages').innerHTML += html;
}
}
});
return;
}
}
</code>```

答:
i figured it out..

the problem comes from this line:

```<code>result.end(JSON.stringify(messages));
</code>```

I dont exactly understand why, but i changed it to

```<code>result.send(JSON.stringify(messages));
</code>```

and now the bug is gone

Body:
I followed a tutorial on YouTube to create a private user to user chat.

https://www.youtube.com/watch?v=Ozrm_xftcjQ

Everything on the chat works accept that i keep getting this Error:

XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:

using firefox developer edition and chrome. if i click the stack trace link i get the following xml error:

<!DOCTYPE html>

<meta charset="utf-8">
<title>Error</title>

Cannot GET /get_messages

but i have no GET calls at all..

The code looks as follows:

server.js file

var port = process.env.PORT || 3000;
//creating express instance
var express = require("express");
var app = express();

//creating http instance
var http = require("http").createServer(app);

//app.use(express.static(__dirname));

//creating socket instance
var io = require("socket.io")(http);

//create body parser instance
var bodyParser = require("body-parser");
app.use(bodyParser.json());

//enable url encode for POST requests
app.use(bodyParser.urlencoded({ extended : true }));

//create instance of mysql
var mysql = require('mysql');

//create mysql connection
//          connectionLimit: 100,debug: true
var connection = mysql.createConnection({
        host: 'localhost',
        user: 'xxx',
        password: 'xxx',
        database: 'chatio'
});

connection.connect(function(error){
if(error){
console.log(error);
return;
}
console.log('database connected');
})

//enable header request for post requests
app.use(function(request, result, next){
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})

//create api to return all messages
app.post("/get_messages", function(request, result){
console.log(request);
console.log(result);
connection.query("SELECT * FROM chat_messages WHERE (`from_id` = '"+request.body.sender+"' AND   `to_id` = '"+request.body.receiver+"') OR (`from_id` = '"+request.body.receiver+"' AND `to_id` = '"+request.body.sender+"')", function(error, messages){
if(error){
console.log(error);
return;
}
console.log(messages);
//response will be in JSON
result.end(JSON.stringify(messages));
});
})

io.on("connection", function(socket){
socket.on("send_message", function(data){
//send event to receiver
var socketId = users[data.receiver];

io.to(socketId).emit("new_message", data);

//save in database
connection.query("INSERT INTO chat_messages (`from_id`,`to_id`,`message`) VALUES ('"+data.sender+"', '"+data.receiver+"', '"+data.message+"')", function(error, result){

if(error){
console.log(error);
return;
}
console.log('message saved');
});
})
})

http.listen(port, function(){
console.log("server started");
})

inde.php file code as follows:

//creating io connection
var io = io("http://localhost:3000");

var receiver = "johnny";
var sender = "steven";

function onUserSelected(){
$.ajax({
url: "http://localhost:3000/get_messages",
method:"POST",
cache: false,
data: {
"sender" : sender,
"receiver" : receiver
},
dataType: "json",
success: function(response){
var messages = response; //JSON.parse();
var html = "";
for(var i = 0; i < messages.length; i++){
html += "
" +messages[i].from_id + " says: " + messages[i].message + "
";
document.getElementById('messages').innerHTML += html;
}
}
});
return;
}
}

Body:
i figured it out..

the problem comes from this line:

result.end(JSON.stringify(messages));

I dont exactly understand why, but i changed it to

result.send(JSON.stringify(messages));

and now the bug is gone


问:
How do I save form response as an object in Django's database?
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

```<code>class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name
</code>```

This is my view in views.py file.

```<code>@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')
</code>```

This is my HTML code for the form.

```<code>{% extends 'authmain.html' %}

{% block content %}
<h3> <p class="text-center"> Create a new Course Blockchain: </p> </h3>

<div class="card border-dark mb-3 mx-auto" align="center" style="width: 40rem;">
  <div class="card-body">
    <h5 class="card-title">
      <form method='POST'>
        {% csrf_token %}
        <label for="year">Year: </label>
        <input type="text" id="year" name="year" value=""><br>
        <label for="code">Course Code: </label>
        <input type="text" id="code" name="code" value=""><br>
        <label for="name">Course Name: </label>
        <input type="text" id="name" name="name" value=""><br>
        <label for="slot">Slot: </label>
        <input type="text" id="slot" name="slot" value=""><br>
        <label for="sem">Semester: </label>
        <input type="text" id="sem" name="sem" value=""><br>
        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>
    </h5>
    </div>
</div>

{% endblock %}
</code>```

This is my urls.py.

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]
</code>```

This is the view function for success.

```<code>
@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})
</code>```

答:
You need to use a model form to achieve this

```<code>class MyForm(ModelForm):
     class Meta:
         model = MyModel
         fields = []
</code>```

And then you can do something like this:

```<code> form = MyForm(request.POST)
 if form.is_valid():
       new_item = form.save()
       ...
</code>```

And it will save directly to the database.

Body:
I am unable to save my form responses to the database as an object in Django.
Everytime I click on submit to submit my form, I am just logged out of my website and the object isnt saved in the database either.
Can anyone tell me where I am going wrong?
This is my models in models.py.

class Chain(models.Model):
    name = models.CharField(max_length=255)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    year = models.CharField(max_length=10, default="20XX")
    sem = models.CharField(max_length=30, default="Default Semester")
    code = models.CharField(max_length=10, default="SUB-CODE")
    slot = models.CharField(max_length=10, default="EX+EX")
    last_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

This is my view in views.py file.

@login_required(login_url='/')
def create_course(request):
    if request.method == 'GET':
        return render(request, 'create_course.html', {})
    elif request.method == 'POST':
        name=request.POST['name']
        year=request.POST['year']
        sem=request.POST['sem']
        code=request.POST['code']
        slot=request.POST['slot']
        newchain = Chain(
            name=name,
            year=year,
            sem=sem,
            code=code,
            slot=slot,
        )
        newchain.user = request.user
        newchain.save()
        return redirect('success')

This is my HTML code for the form.

{% extends 'authmain.html' %}

{% block content %}

 Create a new Course Blockchain:

      <form method='POST'>
        {% csrf_token %}
        Year:
        <input type="text" id="year" name="year" value="">

        Course Code:
        <input type="text" id="code" name="code" value="">

        Course Name:
        <input type="text" id="name" name="name" value="">

        Slot:
        <input type="text" id="slot" name="slot" value="">

        Semester:
        <input type="text" id="sem" name="sem" value="">

        <button class="btn btn-outline-primary" type="Submit"> Create </button>
      </form>

{% endblock %}

This is my urls.py.

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('register/', views.register, name="register"),
    path('logout/', views.logoutuser, name="logoutuser"),
    path('dashboard/', views.dashboard, name="dashboard"),
    path('create_course/', views.create_course, name="create_course"),
    path('success', views.success, name="success"),
]

This is the view function for success.

@login_required(login_url='/')
def success(request):
    return render(request, 'success.html', {})

Body:
You need to use a model form to achieve this

class MyForm(ModelForm):
     class Meta:
         model = MyModel
         fields = []

And then you can do something like this:

 form = MyForm(request.POST)
 if form.is_valid():
       new_item = form.save()
       ...

And it will save directly to the database.


问:
Adding script tags in Angular component template
Angular2 removes
```

A commonly suggested work around is to dynamically add script tags to the document via the ngAfterViewInit hook, but this is obviously not proper ng2 practice and will not work server side, which JSON-LD obviously needs to be able to do.

Are there any other workarounds that we can use to include

答:
I added js script loading dynamically with condition inside of component init life hook in next way:</p>

```<code>    private loadChatWithScript() {
    let chatScript = document.createElement("script");
    chatScript.type = "text/javascript";
    chatScript.async = true;
    chatScript.src = "https://chat-assets.frontapp.com/v1/chat.bundle.js";
    document.body.appendChild(chatScript);

    let chatScriptConfiguration = document.createElement("script");
    chatScriptConfiguration.type = "text/javascript";
    chatScriptConfiguration.async = true;
    chatScriptConfiguration.innerHTML = "window.FCSP = 'some-key-123'";
    document.body.appendChild(chatScriptConfiguration);
}
</code>```

Body:
Angular2 removes

A commonly suggested work around is to dynamically add script tags to the document via the ngAfterViewInit hook, but this is obviously not proper ng2 practice and will not work server side, which JSON-LD obviously needs to be able to do.

Are there any other workarounds that we can use to include

Body:
I added js script loading dynamically with condition inside of component init life hook in next way:

    private loadChatWithScript() {
    let chatScript = document.createElement("script");
    chatScript.type = "text/javascript";
    chatScript.async = true;
    chatScript.src = "https://chat-assets.frontapp.com/v1/chat.bundle.js";
    document.body.appendChild(chatScript);

    let chatScriptConfiguration = document.createElement("script");
    chatScriptConfiguration.type = "text/javascript";
    chatScriptConfiguration.async = true;
    chatScriptConfiguration.innerHTML = "window.FCSP = 'some-key-123'";
    document.body.appendChild(chatScriptConfiguration);
}


问:
What is wxPython doing to the locale to makes pandas crash?
When I try to import pandas into my wxPython application a "ValueError: unknown locale: en-US" exception is thrown.  I can avoid this by importing pandas before the application starts, but that seems like a silly requirement.

This is easily repeatable in a simple wx app:

```<code>import wx

class TestApp(wx.App):
    def __init__(self, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)
        import pandas

        self.frame = wx.Frame(None, size=wx.Size(670,670), title='Test App')
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.frame.SetSizer(self.sizer)

if __name__ == '__main__':
    app = TestApp()
    app.MainLoop()
</code>```

When I run this app from my virtual environment I get this stack trace:

```<code>(test) PS env_test> python .\test2.py                                                       Traceback (most recent call last):
  File ".\test2.py", line 16, in <module>
    app = TestApp()
  File ".\test2.py", line 8, in __init__
    import pandas
  File "E:\Envs\test\lib\site-packages\pandas\__init__.py", line 32, in <module>
    from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
  File "E:\Envs\test\lib\site-packages\pandas\_libs\__init__.py", line 3, in <module>
    from .tslibs import (
  File "E:\Envs\test\lib\site-packages\pandas\_libs\tslibs\__init__.py", line 3, in <module>
    from .conversion import localize_pydatetime, normalize_date
  File "pandas\_libs\tslibs\c_timestamp.pxd", line 7, in init pandas._libs.tslibs.conversion
  File "pandas\_libs\tslibs\c_timestamp.pyx", line 1, in init pandas._libs.tslibs.c_timestamp
  File "pandas\_libs\tslibs\tzconversion.pyx", line 1, in init pandas._libs.tslibs.tzconversion
  File "pandas\_libs\tslibs\timedeltas.pyx", line 1, in init pandas._libs.tslibs.timedeltas
  File "pandas\_libs\tslibs\offsets.pyx", line 1, in init pandas._libs.tslibs.offsets
  File "pandas\_libs\tslibs\ccalendar.pyx", line 13, in init pandas._libs.tslibs.ccalendar
  File "pandas\_libs\tslibs\strptime.pyx", line 625, in init pandas._libs.tslibs.strptime
  File "pandas\_libs\tslibs\strptime.pyx", line 530, in pandas._libs.tslibs.strptime.TimeRE.__init__
  File "pandas\_libs\tslibs\strptime.pyx", line 405, in pandas._libs.tslibs.strptime.LocaleTime.__init__
  File "pandas\_libs\tslibs\strptime.pyx", line 362, in pandas._libs.tslibs.strptime._getlang
  File "c:\python37\lib\locale.py", line 587, in getlocale
    return _parse_localename(localename)
  File "c:\python37\lib\locale.py", line 495, in _parse_localename
    raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: en-US
</code>```

I'm running a virtual environment on Windows 10 using python3.7.4 with minimal packages installed:

```<code>Package         Version
--------------- -------
numpy           1.18.4
pandas          1.0.3
Pillow          7.1.2
pip             20.1
python-dateutil 2.8.1
pytz            2020.1
setuptools      46.1.3
six             1.14.0
wheel           0.34.2
wxPython        4.1.0
</code>```

I can import pandas outside of the app just fine:

```<code>Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
>>> df = pandas.DataFrame()
>>>
</code>```

I'm flummoxed, and I've been unable to find answers elsewhere.  Other pandas "unknown locale" errors seem to be related to not having the locale exported on OSX.

答:
It is more like related to locale with wxpython, I got same exception when run locale.getlocale() inside wx app, no issue when run outside wx app.

When downgrade to 4.0.7 the error is gone, so for sure there is new change on 4.1.0 with restrict check on locale or even encoding UTF-8.

Body:
When I try to import pandas into my wxPython application a "ValueError: unknown locale: en-US" exception is thrown.  I can avoid this by importing pandas before the application starts, but that seems like a silly requirement.

This is easily repeatable in a simple wx app:

import wx

class TestApp(wx.App):
    def __init__(self, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)
        import pandas

        self.frame = wx.Frame(None, size=wx.Size(670,670), title='Test App')
        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.frame.SetSizer(self.sizer)

if __name__ == '__main__':
    app = TestApp()
    app.MainLoop()

When I run this app from my virtual environment I get this stack trace:

(test) PS env_test> python .\test2.py                                                       Traceback (most recent call last):
  File ".\test2.py", line 16, in <module>
    app = TestApp()
  File ".\test2.py", line 8, in __init__
    import pandas
  File "E:\Envs\test\lib\site-packages\pandas\__init__.py", line 32, in <module>
    from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib
  File "E:\Envs\test\lib\site-packages\pandas\_libs\__init__.py", line 3, in <module>
    from .tslibs import (
  File "E:\Envs\test\lib\site-packages\pandas\_libs\tslibs\__init__.py", line 3, in <module>
    from .conversion import localize_pydatetime, normalize_date
  File "pandas\_libs\tslibs\c_timestamp.pxd", line 7, in init pandas._libs.tslibs.conversion
  File "pandas\_libs\tslibs\c_timestamp.pyx", line 1, in init pandas._libs.tslibs.c_timestamp
  File "pandas\_libs\tslibs\tzconversion.pyx", line 1, in init pandas._libs.tslibs.tzconversion
  File "pandas\_libs\tslibs\timedeltas.pyx", line 1, in init pandas._libs.tslibs.timedeltas
  File "pandas\_libs\tslibs\offsets.pyx", line 1, in init pandas._libs.tslibs.offsets
  File "pandas\_libs\tslibs\ccalendar.pyx", line 13, in init pandas._libs.tslibs.ccalendar
  File "pandas\_libs\tslibs\strptime.pyx", line 625, in init pandas._libs.tslibs.strptime
  File "pandas\_libs\tslibs\strptime.pyx", line 530, in pandas._libs.tslibs.strptime.TimeRE.__init__
  File "pandas\_libs\tslibs\strptime.pyx", line 405, in pandas._libs.tslibs.strptime.LocaleTime.__init__
  File "pandas\_libs\tslibs\strptime.pyx", line 362, in pandas._libs.tslibs.strptime._getlang
  File "c:\python37\lib\locale.py", line 587, in getlocale
    return _parse_localename(localename)
  File "c:\python37\lib\locale.py", line 495, in _parse_localename
    raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: en-US

I'm running a virtual environment on Windows 10 using python3.7.4 with minimal packages installed:

Package         Version
--------------- -------
numpy           1.18.4
pandas          1.0.3
Pillow          7.1.2
pip             20.1
python-dateutil 2.8.1
pytz            2020.1
setuptools      46.1.3
six             1.14.0
wheel           0.34.2
wxPython        4.1.0

I can import pandas outside of the app just fine:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
>>> df = pandas.DataFrame()
>>>

I'm flummoxed, and I've been unable to find answers elsewhere.  Other pandas "unknown locale" errors seem to be related to not having the locale exported on OSX.


问:
Swing thread safety boilerplate
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

```<code>class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}
</code>```

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.

答: We used Spin in a project a few years back.</p>

Title: Swing thread safety boilerplate

Body:
For the sake of simplicity, imagine an application that downloads a file. There is a simple GUI with one label that displays progress. To avoid EDT violations, like every lawful citizen I download the file in one thread (main), and update GUI in another (EDT). So, here's the relevant chunk of pseudcode:

class Downloader {
    download() {
        progress.startDownload();
        while(hasMoreChunks()) {
            downloadChunk();
            progress.downloadedBytes(n);
        }
        progress.finishDownload();
    }
}

class ProgressDisplay extends JPanel {
    JLabel label;
    startDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download started");
            }
        });
    }
    downloadedBytes(int n) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Downloaded bytes: " + n);
            }
        });
    }
    finishDownload() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                label.setText("Download finished");
            }
        });
    }
}

I love the fact that Java does not support closures and the code is crystal clear to me. Jokes aside, I'm wondering... Am I doing it wrong? Is it possible to eliminate all this ugly boilerplate with SwingUtilities, anonymous implementation of Runnable in every method etc.?

My case is slightly more complicated than this, but I'm trying not to overengineer by implementing proxies or something like that.


问:
What is the problem with importing this module?
I have a module called sinfun:

```<code>#!/usr/bin/env python
#sinfun.py

def newsin(x):
   return sin(x)/x
</code>```

and I want to use it in this program:

```<code>#!/usr/bin/env python
from math import *
import sinfun

x = input("enter x: ")
x = float(x)
y = sinfun.newsin(x)
print(y)
</code>```

What is the problem in this example and what must be done to make the code work?

答:
As was previously mentioned, it's because sinfun.py doesn't have access to your math import in; presumably, your main. The quick solution is to move the math import into sinfun.

However, you could also move sinfun to another folder ('packages') called, say maths and add an __init__.py which only contains from math import *, then from your main you could import import maths.sinfun as sinfun and your function would work as intended.

```<code>|   main.py
|
\---maths
        sinfun.py
        __init__.py
</code>```

Body:
I have a module called sinfun:

#!/usr/bin/env python
#sinfun.py

def newsin(x):
   return sin(x)/x

and I want to use it in this program:

#!/usr/bin/env python
from math import *
import sinfun

x = input("enter x: ")
x = float(x)
y = sinfun.newsin(x)
print(y)

What is the problem in this example and what must be done to make the code work?

Body:
As was previously mentioned, it's because sinfun.py doesn't have access to your math import in; presumably, your main. The quick solution is to move the math import into sinfun.

However, you could also move sinfun to another folder ('packages') called, say maths and add an __init__.py which only contains from math import *, then from your main you could import import maths.sinfun as sinfun and your function would work as intended.

|   main.py
|
\---maths
        sinfun.py
        __init__.py


问:
Reading a XML file in C++ with TinyXML2
I'm pretty new to using XML in C++ and i'm trying to parse a list of files to download.
THe XML file I'm using is generated via PHP and looks like this :

```<code><?xml version="1.0"?>
<FileList>
  <File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>
</code>```

The code I'm using in C++ is the following, which I came up using some online tutorials (it's included in some global function):

```<code>tinyxml2::XMLDocument doc;

doc.LoadFile("file_listing.xml");
tinyxml2::XMLNode* pRoot = doc.FirstChild();
tinyxml2::XMLElement* pElement = pRoot->FirstChildElement("FileList");
if (pRoot == nullptr)
{
    QString text = QString::fromLocal8Bit("Error text in french");
    //other stuff
}
else
{
    tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
    while (pListElement != nullptr)
    {
        QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
        QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
        QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));

        QString currentPath = pathAttr.remove("path");
        QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
        QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);

        QFile currentFile(currentPath);

        if (md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists())
        {
            QString url = "url" + currentPath;
            this->downloadFile(url);
        }

        pListElement = pListElement->NextSiblingElement("File");
    }

</code>```

Problem is, I get an error like "Access violation, this was nullptr" on the following line :

tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");

Since I'm far from a pro when it comes to coding and I already searched the internet up and down, I hope that someone here can provide me some pointers.

Have a good day, folks.

答:
According to the reference for tinyxml2::XMLNodeFirstChild():

Get the first child node, or null if none exists.

This line will therefore get the root node:

```<code>tinyxml2::XMLNode* pRoot = doc.FirstChild();
</code>```

Meaning when you attempt to find a FileList node within the root node it returns null.

To avoid the access violation, check your pointers are valid before using them. There is an if check for pRoot but the line immediately before it tries to call a function on pRoot. There is no if check for pElement so this is why you get an access violation. As well as checking pointers are valid, consider adding else blocks with logging to say what went wrong (e.g. "could not find element X"). This will help you in the long run - XML parsing is a pain, even with a library like Tinyxml, there are always teething problems like this, so getting into the habit of checki g pointers and logging out helpful messages will definitely pay off.

Title: Reading a XML file in C++ with TinyXML2

Body:
I'm pretty new to using XML in C++ and i'm trying to parse a list of files to download.
THe XML file I'm using is generated via PHP and looks like this :

<?xml version="1.0"?>
<FileList>
  <File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>

The code I'm using in C++ is the following, which I came up using some online tutorials (it's included in some global function):

tinyxml2::XMLDocument doc;

doc.LoadFile("file_listing.xml");
tinyxml2::XMLNode* pRoot = doc.FirstChild();
tinyxml2::XMLElement* pElement = pRoot->FirstChildElement("FileList");
if (pRoot == nullptr)
{
    QString text = QString::fromLocal8Bit("Error text in french");
    //other stuff
}
else
{
    tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
    while (pListElement != nullptr)
    {
        QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
        QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
        QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));

        QString currentPath = pathAttr.remove("path");
        QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
        QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);

        QFile currentFile(currentPath);

        if (md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists())
        {
            QString url = "url" + currentPath;
            this->downloadFile(url);
        }

        pListElement = pListElement->NextSiblingElement("File");
    }

Problem is, I get an error like "Access violation, this was nullptr" on the following line :

tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");

Since I'm far from a pro when it comes to coding and I already searched the internet up and down, I hope that someone here can provide me some pointers.

Have a good day, folks.

Body:
According to the reference for tinyxml2::XMLNodeFirstChild():

Get the first child node, or null if none exists.

This line will therefore get the root node:

tinyxml2::XMLNode* pRoot = doc.FirstChild();

Meaning when you attempt to find a FileList node within the root node it returns null.

To avoid the access violation, check your pointers are valid before using them. There is an if check for pRoot but the line immediately before it tries to call a function on pRoot. There is no if check for pElement so this is why you get an access violation. As well as checking pointers are valid, consider adding else blocks with logging to say what went wrong (e.g. "could not find element X"). This will help you in the long run - XML parsing is a pain, even with a library like Tinyxml, there are always teething problems like this, so getting into the habit of checki g pointers and logging out helpful messages will definitely pay off.


问:
Is there a way to tell if a Jupyter notebook is frozen without killing the kernel?
I am working with a very large set of data and certain functions take a long time to run on my machine.  Is there a way to see if the function is still running or if the kernel is frozen without killing the cell?

The example below is being used to compare company names in two different dictionaries of distinct names as keys with a list of words in the name as values.   I have 650000 entries in one dictionary and 100000 in the other.

Example:

```<code>    def insert(df, entries):
       try:
          df.loc[max(df.index) + 1] = entries
    except ValueError:
          df.loc[0] = entries

    def check_for_matching_phrases(dict1, dict2):
        df = pd.DataFrame(columns=['filings_name', 'no_match_name', 'percent_match'])
        for key1, value1 in dict1.items():
            for key2, value2 in dict2.items():
                matches = 0
                for val_1 in value1:
                    if val_1 in value2:
                       matches += 1
                denominator = len(min(value1, value2))
                perc_match = matches / denominator
                insert(df, [key1, key2, perc_match])
        return df
</code>```

答:
You can easily see if the kernel is still active within the Jupyter notebook. Look at the top right of your browser window and see the little circle next to your kernel name? If it is solid black it is busy (screencap below) and if idle it will be a blank white circle. Hovering over the circle will also explicitly tell you the state. It's not as nice as a progress bar but it does give you some indication.

example of busy kernel

Body:
I am working with a very large set of data and certain functions take a long time to run on my machine.  Is there a way to see if the function is still running or if the kernel is frozen without killing the cell?

The example below is being used to compare company names in two different dictionaries of distinct names as keys with a list of words in the name as values.   I have 650000 entries in one dictionary and 100000 in the other.

Example:

    def insert(df, entries):
       try:
          df.loc[max(df.index) + 1] = entries
    except ValueError:
          df.loc[0] = entries

    def check_for_matching_phrases(dict1, dict2):
        df = pd.DataFrame(columns=['filings_name', 'no_match_name', 'percent_match'])
        for key1, value1 in dict1.items():
            for key2, value2 in dict2.items():
                matches = 0
                for val_1 in value1:
                    if val_1 in value2:
                       matches += 1
                denominator = len(min(value1, value2))
                perc_match = matches / denominator
                insert(df, [key1, key2, perc_match])
        return df


问:
Is there a Python library for handling and validating user input?
I have a project that involves asking for (for now, command-line) feedback from the user every so often while its main method runs.

So far I have been using input('{my_prompt}') to obtain this input from my user, but I have to quite annoyingly handle user input every time I invoke input(). This makes my code balloon to > 5 lines of code per user input line, which feels quite excessive. Some of my user input handling includes the below.

```<code>if input.lower() not in ['y', 'n']:
    raise ValueError('Not valid input! Please enter either "y" or "n"')
if input.lower() == 'y':
    input = True
else:
    input = False
</code>```

The above could be handled in 1 line of code if the user were passing command line arguments in and I could use argparse, but unfortunately the sheer volume of prompts prevents command line arguments from being a viable option.

I am familiar with the libraries cmd and click, but as far as I can tell, they both lack the functionality that I would like from argparse, which is namely to validate the user input.

In summary, I'm looking for a user input library that validates input and can return bool values without me having to implement the conversion every time.

答:
If all you need is to check "yes/no" prompts, click supports it natively with click.confirm:

if click.confirm("Do you want to do this thing?"):
    # ... do something here ....
```

There are a variety of other input-handling functions part of click, which are documented in the User Input Prompts section of the documentation.

Body:
I have a project that involves asking for (for now, command-line) feedback from the user every so often while its main method runs.

So far I have been using input('{my_prompt}') to obtain this input from my user, but I have to quite annoyingly handle user input every time I invoke input(). This makes my code balloon to > 5 lines of code per user input line, which feels quite excessive. Some of my user input handling includes the below.

if input.lower() not in ['y', 'n']:
    raise ValueError('Not valid input! Please enter either "y" or "n"')
if input.lower() == 'y':
    input = True
else:
    input = False

The above could be handled in 1 line of code if the user were passing command line arguments in and I could use argparse, but unfortunately the sheer volume of prompts prevents command line arguments from being a viable option.

I am familiar with the libraries cmd and click, but as far as I can tell, they both lack the functionality that I would like from argparse, which is namely to validate the user input.

In summary, I'm looking for a user input library that validates input and can return bool values without me having to implement the conversion every time.

Body:
If all you need is to check "yes/no" prompts, click supports it natively with click.confirm:

if click.confirm("Do you want to do this thing?"):
    # ... do something here ....

There are a variety of other input-handling functions part of click, which are documented in the User Input Prompts section of the documentation.