问:
HTML table with fixed headers?
Is there a cross-browser CSS/JavaScript technique to display a long HTML table such that the column headers stay fixed on-screen and do not scroll with the table body. Think of the "freeze panes" effect in Microsoft Excel.

I want to be able to scroll through the contents of the table, but to always be able to see the column headers at the top.

答:
Almost all modern browsers will support it!

// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width .
$(window).on("load resize ", function() {
  var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width();
  $('.tbl-header').css({
    'padding-right': scrollWidth
  });
}).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  font-weight: 300;
  text-align: center;
  margin-bottom: 15px;
}

table {
  width: 100%;
  table-layout: fixed;
}

.tbl-header {
  background-color: rgba(255, 255, 255, 0.3);
}

.tbl-content {
  height: 300px;
  overflow-x: auto;
  margin-top: 0px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

th {
  padding: 20px 15px;
  text-align: left;
  font-weight: 500;
  font-size: 12px;
  color: #fff;
  text-transform: uppercase;
}

td {
  padding: 15px;
  text-align: left;
  vertical-align: middle;
  font-weight: 300;
  font-size: 12px;
  color: #fff;
  border-bottom: solid 1px rgba(255, 255, 255, 0.1);
}

/* demo styles */

@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700);
body {
  background: -webkit-linear-gradient(left, #25c481, #25b7c4);
  background: linear-gradient(to right, #25c481, #25b7c4);
  font-family: 'Roboto', sans-serif;
}

section {
  margin: 50px;
}

/* follow me template */

.made-with-love {
  margin-top: 40px;
  padding: 10px;
  clear: left;
  text-align: center;
  font-size: 10px;
  font-family: arial;
  color: #fff;
}

.made-with-love i {
  font-style: normal;
  color: #F50057;
  font-size: 14px;
  position: relative;
  top: 2px;
}

.made-with-love a {
  color: #fff;
  text-decoration: none;
}

.made-with-love a:hover {
  text-decoration: underline;
}

/* for custom scrollbar for webkit browser*/

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

::-webkit-scrollbar-thumb {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}</code>```

Fixed Table header

          Code
          Company
          Price
          Change
          Change %

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

          AAC
          AUSTRALIAN COMPANY
          $1.38
          +2.01
          -0.36%

          AAD
          AUSENCO
          $2.38
          -0.01
          -1.36%

          AAX
          ADELAIDE
          $3.22
          +0.01
          +1.36%

          XXD
          ADITYA BIRLA
          $1.02
          -1.01
          +2.36%

```

OwnerDisplayName: Cheekysoft

ContentLicense: CC BY-SA 2.5

Title: HTML table with fixed headers?

Body:
Almost all modern browsers will support it!

// '.tbl-content' consumed little space for vertical scrollbar, scrollbar width depend on browser/os/platfrom. Here calculate the scollbar width .
$(window).on("load resize ", function() {
  var scrollWidth = $('.tbl-content').width() - $('.tbl-content table').width();
  $('.tbl-header').css({
    'padding-right': scrollWidth
  });
}).resize();

h1 {
  font-size: 30px;
  color: #fff;
  text-transform: uppercase;
  font-weight: 300;
  text-align: center;
  margin-bottom: 15px;
}

table {
  width: 100%;
  table-layout: fixed;
}

.tbl-header {
  background-color: rgba(255, 255, 255, 0.3);
}

.tbl-content {
  height: 300px;
  overflow-x: auto;
  margin-top: 0px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

th {
  padding: 20px 15px;
  text-align: left;
  font-weight: 500;
  font-size: 12px;
  color: #fff;
  text-transform: uppercase;
}

td {
  padding: 15px;
  text-align: left;
  vertical-align: middle;
  font-weight: 300;
  font-size: 12px;
  color: #fff;
  border-bottom: solid 1px rgba(255, 255, 255, 0.1);
}

/* demo styles */

@import url(https://fonts.googleapis.com/css?family=Roboto:400,500,300,700);
body {
  background: -webkit-linear-gradient(left, #25c481, #25b7c4);
  background: linear-gradient(to right, #25c481, #25b7c4);
  font-family: 'Roboto', sans-serif;
}

section {
  margin: 50px;
}

/* follow me template */

.made-with-love {
  margin-top: 40px;
  padding: 10px;
  clear: left;
  text-align: center;
  font-size: 10px;
  font-family: arial;
  color: #fff;
}

.made-with-love i {
  font-style: normal;
  color: #F50057;
  font-size: 14px;
  position: relative;
  top: 2px;
}

.made-with-love a {
  color: #fff;
  text-decoration: none;
}

.made-with-love a:hover {
  text-decoration: underline;
}

/* for custom scrollbar for webkit browser*/

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

::-webkit-scrollbar-thumb {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<section>
  <!--for demo wrap-->
  <h1>Fixed Table header</h1>
  <div class="tbl-header">
    <table cellpadding="0" cellspacing="0" border="0">
      <thead>
        <tr>
          <th>Code</th>
          <th>Company</th>
          <th>Price</th>
          <th>Change</th>
          <th>Change %</th>
        </tr>
      </thead>
    </table>
  </div>
  <div class="tbl-content">
    <table cellpadding="0" cellspacing="0" border="0">
      <tbody>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
        <tr>
          <td>AAC</td>
          <td>AUSTRALIAN COMPANY </td>
          <td>$1.38</td>
          <td>+2.01</td>
          <td>-0.36%</td>
        </tr>
        <tr>
          <td>AAD</td>
          <td>AUSENCO</td>
          <td>$2.38</td>
          <td>-0.01</td>
          <td>-1.36%</td>
        </tr>
        <tr>
          <td>AAX</td>
          <td>ADELAIDE</td>
          <td>$3.22</td>
          <td>+0.01</td>
          <td>+1.36%</td>
        </tr>
        <tr>
          <td>XXD</td>
          <td>ADITYA BIRLA</td>
          <td>$1.02</td>
          <td>-1.01</td>
          <td>+2.36%</td>
        </tr>
      </tbody>
    </table>
  </div>
</section>


来源: stackexchange

问:
ASP.NET Storing global variables - accessible from every page
I am building a large application and I ususally use a simple session to store private  global information however as the application could be rather large I belive this could be a problem due to the amount of memory sessions it could have.

Is there a better way to store such variables?

For example, when the user logs in I want to store data about that user and display it where needed without having to query the database each time.

答:
Sessions are the way to go here, they are intended to persist information about the current session across requests.  There is no other object in the ASP.NET framework that has this intention.

You could use the Cache, or store in the Application collection, but then the responsibility of uniquely identifying the individual session data is up to you.

What's also up to you is handling when the session terminates, and freeing up the instances that are stored in those collections (Cache or Application).

It's really a bad idea to start to ask these questions based on what you might "think" will happen.  This is a form of premature optimization, and you should avoid it.  Rather, use Sessions, as they were intended for this purpose, then measure where your bottlenecks are and address them, should performance be an issue when testing.

OwnerDisplayName: HenryH

LastEditorDisplayName: Rich B

OwnerDisplayName: casperOne


问:
Component is not rendered using useEffects
I have few Checkboxes in component of React application, but whenever I'm checking they are not working as they should work!

Whenever I click on any Checkbox from ColumnCheckBoxes Component it is getting appended in selectedColumns but selectedColumns are not displayed using DuplicateCheckBoxes component.

selectedColumn & duplicateColumn are states which is in useEffect so as soon as they change whole page needs to get re-rendered.

In backend I want to pass list of selectedColumn as well duplicateColumn(unique property will be applied to column while inserting data into SQL)

App.js

```<code>import { useEffect, useState } from 'react';
import ColumnCheckBoxes from './Components/CheckBoxes/ColumnCheckBoxes';
import DuplicateCheckBoxes from './Components/CheckBoxes/DuplicateCheckBoxes';

const App = () => {

  const [columns,setColumns]=useState([]);
  const [selectedColumn,setSelectedColumn] = useState([]);
  const [duplicateColumn, setDuplicateColumn]=useState([]);

  // componentDidMount
  useEffect(() => {
    console.log('Initial Rendering!');
    setColumns(['A','B','C','D']);
  },[]);

  // componentDidUpdate
  useEffect(() => {
    console.log('Selected Column',selectedColumn);
    console.log('Duplicate Columns',duplicateColumn);
  },[selectedColumn,duplicateColumn]);

  return (
    <div className='flex-col justify-center align-middle'>
      <div><ColumnCheckBoxes columns={columns} selectedColumn={selectedColumn} setSelectedColumn={setSelectedColumn}/></div>
      <div><DuplicateCheckBoxes selectedColumn={selectedColumn} duplicateColumn={duplicateColumn} setDuplicateColumn={setDuplicateColumn}/></div>
    </div>
  );
}

export default App;

</code>```

ColumnCheckBoxes

```<code>import React from 'react'

const ColumnCheckBoxes = ({columns, selectedColumn, setSelectedColumn}) => {

    const handleChange = (event,header) => {
        event.preventDefault();
        if(!(event.target.checked)) return;
        const localarr = selectedColumn;
        localarr.push(header.header);
        setSelectedColumn(localarr);
    }

  return (
    <div className='flex flex-col justify-center align-middle'>
        <h1>Columns :</h1>
        {columns.map ((header) => {
            return <div key={0} className='flex'>
                <label className='ml-2'>{header}</label>
                <input type='checkbox' className='ml-2'
                    checked={header.header in selectedColumn?true:false}
                    onChange={(e) => handleChange(e,{header})}
                />
            </div>
        })}
    </div>
  )
}

export default ColumnCheckBoxes;
</code>```

DuplicateCheckBoxes

```<code>import React from 'react';

const DuplicateCheckBoxes = ({selectedColumn, duplicateColumn, setDuplicateColumn}) => {

    const handleChange = (event,header) => {
        event.preventDefault();
        if(!(event.target.checked)) return;
        const localarr = duplicateColumn;
        localarr.push(header.header);
        setDuplicateColumn(localarr);
    }

  return (
        <div className='flex flex-col justify-center align-middle'>
            {selectedColumn.length === 0 ? <div></div> : <h1>Remove Duplicate Elements From Column</h1>}
            {selectedColumn.map ((header) => {
                return <div key={0} className='flex'>
                    <label>{header}</label>
                    <input type='checkbox' className='ml-2' onChange={(e) => handleChange(e,{header})}/>
                </div>
            })}
        </div>
  )
}

export default DuplicateCheckBoxes;
</code>```

答:
Instead of

```<code>const localarr = selectedColumn;
localarr.push(header.header);
setSelectedColumn(localarr);
</code>```

do this

```<code>setSelectedColumn(columns => [...columns,header.header])
</code>```

localarr is reference to selectedColumn or duplicateColumn so I was trying to change State without state changing method!

ContentLicense: CC BY-SA 4.0

Body:
I have few Checkboxes in component of React application, but whenever I'm checking they are not working as they should work!

Whenever I click on any Checkbox from ColumnCheckBoxes Component it is getting appended in selectedColumns but selectedColumns are not displayed using DuplicateCheckBoxes component.

selectedColumn & duplicateColumn are states which is in useEffect so as soon as they change whole page needs to get re-rendered.

In backend I want to pass list of selectedColumn as well duplicateColumn(unique property will be applied to column while inserting data into SQL)

App.js

import { useEffect, useState } from 'react';
import ColumnCheckBoxes from './Components/CheckBoxes/ColumnCheckBoxes';
import DuplicateCheckBoxes from './Components/CheckBoxes/DuplicateCheckBoxes';

const App = () => {

  const [columns,setColumns]=useState([]);
  const [selectedColumn,setSelectedColumn] = useState([]);
  const [duplicateColumn, setDuplicateColumn]=useState([]);

  // componentDidMount
  useEffect(() => {
    console.log('Initial Rendering!');
    setColumns(['A','B','C','D']);
  },[]);

  // componentDidUpdate
  useEffect(() => {
    console.log('Selected Column',selectedColumn);
    console.log('Duplicate Columns',duplicateColumn);
  },[selectedColumn,duplicateColumn]);

  return (

<ColumnCheckBoxes columns={columns} selectedColumn={selectedColumn} setSelectedColumn={setSelectedColumn}/>

<DuplicateCheckBoxes selectedColumn={selectedColumn} duplicateColumn={duplicateColumn} setDuplicateColumn={setDuplicateColumn}/>

  );
}

export default App;

ColumnCheckBoxes

import React from 'react'

const ColumnCheckBoxes = ({columns, selectedColumn, setSelectedColumn}) => {

    const handleChange = (event,header) => {
        event.preventDefault();
        if(!(event.target.checked)) return;
        const localarr = selectedColumn;
        localarr.push(header.header);
        setSelectedColumn(localarr);
    }

  return (

Columns :

        {columns.map ((header) => {
            return

                {header}
                <input type='checkbox' className='ml-2'
                    checked={header.header in selectedColumn?true:false}
                    onChange={(e) => handleChange(e,{header})}
                />

        })}

  )
}

export default ColumnCheckBoxes;

DuplicateCheckBoxes

import React from 'react';

const DuplicateCheckBoxes = ({selectedColumn, duplicateColumn, setDuplicateColumn}) => {

    const handleChange = (event,header) => {
        event.preventDefault();
        if(!(event.target.checked)) return;
        const localarr = duplicateColumn;
        localarr.push(header.header);
        setDuplicateColumn(localarr);
    }

  return (

            {selectedColumn.length === 0 ?

 :
Remove Duplicate Elements From Column
}
            {selectedColumn.map ((header) => {
                return

                    {header}
                    <input type='checkbox' className='ml-2' onChange={(e) => handleChange(e,{header})}/>

            })}

  )
}

export default DuplicateCheckBoxes;

Body:
Instead of

const localarr = selectedColumn;
localarr.push(header.header);
setSelectedColumn(localarr);

do this

setSelectedColumn(columns => [...columns,header.header])

localarr is reference to selectedColumn or duplicateColumn so I was trying to change State without state changing method!


问:
fsockopen(): unable to connect to ssl://smtp.gmail.com:465
```<code>$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com',
    'smtp_port' => '465',
    'smtp_user' => "xxxxxxx@gmail.com",
    'smtp_pass' => "xxxxxxx", // change it to yours
    'mailtype'  => 'html',
    'charset'   => 'utf8'
);

$this->load->library('email',$config);

$this->email->set_newline("\r\n");
$this->email->set_crlf( "\r\n" );

$this->email->from($config['smtp_user']);
$this->email->to($email['user_email']);
$this->email->subject($row['tplsubject']);
$this->email->message(html_entity_decode($email_subject));
$this->email->send();
</code>```

This code not working its showing error

A PHP Error was encountered

Severity: Warning

Message: fsockopen(): unable to connect to ssl://smtp.gmail.com:465
  (Unable to find the socket transport "ssl" - did you forget to enable
  it when you configured PHP?)

Filename: libraries/Email.php

Line Number: 1689

答: I have had the same issue was trying to connect with yandex smtp sever for sending email and it was showing fsockopen(): unable to connect to ssl://smtp.yandex.ru:465 using codeigniter framework. Adding $this->load->library('email'); before the email send function solved my problem.</p>

ContentLicense: CC BY-SA 3.0

Body:
$config = array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.gmail.com',
    'smtp_port' => '465',
    'smtp_user' => "xxxxxxx@gmail.com",
    'smtp_pass' => "xxxxxxx", // change it to yours
    'mailtype'  => 'html',
    'charset'   => 'utf8'
);

$this->load->library('email',$config);

$this->email->set_newline("\r\n");
$this->email->set_crlf( "\r\n" );

$this->email->from($config['smtp_user']);
$this->email->to($email['user_email']);
$this->email->subject($row['tplsubject']);
$this->email->message(html_entity_decode($email_subject));
$this->email->send();

This code not working its showing error

A PHP Error was encountered

Severity: Warning

Message: fsockopen(): unable to connect to ssl://smtp.gmail.com:465
  (Unable to find the socket transport "ssl" - did you forget to enable
  it when you configured PHP?)

Filename: libraries/Email.php

Line Number: 1689


问:
How to call functions as those?
I tried to download a video using this code;

```<code>from youtube_dl import YoutubeDL

def opts():
    url= "https://www.youtube.com/watch?v=ffcitRgiNDs"

    ydl_opts= {
        'format': '22'
    }
opts()

def download(url, ydl_opts):
    YoutubeDL(ydl_opts).download(url)
download()
</code>```

And I got this error!

```<code>TypeError: download() missing 2 required positional arguments: 'url' and 'ydl_opts'
</code>```

How to call fuctions like this. 'def download(url, ydl_opts)'.
Can't call 'download()'

答:
you can use Global variables

from youtube_dl import YoutubeDL

def opts():
    global url
    url= "https://www.youtube.com/watch?v=ffcitRgiNDs"

    global ydl_opts
    ydl_opts= {
        'format': '22'
    }
opts()

def download(url, ydl_opts):
    YoutubeDL(ydl_opts).download(url)
download(url,ydl_opts)
```

Title: How to call functions as those?

Body:
I tried to download a video using this code;

from youtube_dl import YoutubeDL

def opts():
    url= "https://www.youtube.com/watch?v=ffcitRgiNDs"

    ydl_opts= {
        'format': '22'
    }
opts()

def download(url, ydl_opts):
    YoutubeDL(ydl_opts).download(url)
download()

And I got this error!

TypeError: download() missing 2 required positional arguments: 'url' and 'ydl_opts'

How to call fuctions like this. 'def download(url, ydl_opts)'.
Can't call 'download()'


问:
How can i set the slack variables in cplex to 0?
When I go to see how cplex calculated the constraints, in some the slack variables are different from 0. For example if I have a constraint where, replacing the decision variables, it returns me 6 <= 15 as the slack variable it gives me 8. Or in equality constraints 1 == 0 gives me 1. I want to set them all to 0, is it possible?</p>

答: You can turn the relation off for variables:


问:
Write a SQL Server query to modify XML tag not value
In my table column I have a value like:

```<code>    <Config>
        <Aidgets>
            <widget condition="true" typesenums="1,2" templatetypes="a,b">
                <![CDATA[All]]>
            </widget>
            <widget condition="true" typesenums="1" templatetypes="a" >
                <![CDATA[pdfprints]]>
            </widget>
         <Aidgets>
    </Config>
</code>```

Here I have to replace the value of

```<code><widget condition="true" typesenums="1,2" templatetypes="a,b">
</code>```

with

```<code><widget condition="true" typesenums="1,2,3" templatetypes="a,b,c">
</code>```

I have tried this but not working

```<code>UPDATE column
SET table = REPLACE(CAST(table AS NVARCHAR(MAX)), "firstvalue", "newvalue")
WHERE id = 1

</code>```

答:
```<code>CREATE TABLE T (ID INT, X XML);

INSERT INTO T VALUES (1,
N'<Config>
   <Aidgets>
     <widget condition="true" typesenums="1,2" templatetypes="a,b">
        <![CDATA[All]]>
     </widget>
     <widget condition="true" typesenums="1" templatetypes="a" >
        <![CDATA[pdfprints]]>
     </widget>
   </Aidgets>
</Config>');

UPDATE T
   SET X.modify('replace value of (/Config/Aidgets/widget/@typesenums)[1] with "1, 2, 3"');
UPDATE T
   SET X.modify('replace value of (/Config/Aidgets/widget/@templatetypes)[1] with "a, b, c"');

SELECT * FROM T;
</code>```

Body:
In my table column I have a value like:

    <Config>
        <Aidgets>
            <widget condition="true" typesenums="1,2" templatetypes="a,b">
                <![CDATA[All]]>
            </widget>
            <widget condition="true" typesenums="1" templatetypes="a" >
                <![CDATA[pdfprints]]>
            </widget>
         <Aidgets>
    </Config>

Here I have to replace the value of

<widget condition="true" typesenums="1,2" templatetypes="a,b">

with

<widget condition="true" typesenums="1,2,3" templatetypes="a,b,c">

I have tried this but not working

UPDATE column
SET table = REPLACE(CAST(table AS NVARCHAR(MAX)), "firstvalue", "newvalue")
WHERE id = 1


问:
How to detect if the CMake script is being run in MSYS2 environment?
I want to detect if the CMakeLists.txt is being summoned inside an MSYS2 environment/shell:

```<code>$ uname
MSYS_NT-10.0-18363
</code>```

from here I have tried:

```<code>cmake_minimum_required(VERSION 3.10)

project(test_cmake)

if(MSYS) # yes I have also tried MSYS2 with the same result!
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()
</code>```

which returns the same result This is not MSYS both in Windows cmd and MSYS2 shell. I'm not actually surprised because MSYS2 and MSYS are two different beasts! Also from here, I tried:

```<code>message(${CMAKE_SYSTEM_NAME})
</code>```

which both in cmd and MSYS2 returns Windows! I would appreciate it if you could help me know how I can detect if the cmake command is being run from inside an MSYS2 shell. Thanks for your support in advance.

P.S.1. As a personal note for myself, this and this seem like good sources to look into.

P.S.2 Strangely enough the command

```<code>message(${CMAKE_HOST_SYSTEM_NAME})
</code>```

also returns Windows while on my MSYS2, according to the docuemntation, it must return the result of uname -s!

答:
What I found most reliable, considering all answers and comments up to now, and building upon them, is using

```<code>execute_process(COMMAND uname OUTPUT_VARIABLE uname)
if (uname MATCHES "^MSYS" OR uname MATCHES "^MINGW")
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()
</code>```

In my msys2, this is what I see in cmake

```<code>message("a ${MSYS}")                    --> prints a, MSYS does not exist
message("a ${CMAKE_SYSTEM_NAME}")       --> prints a, CMAKE_SYSTEM_NAME does not exist
message("a ${CMAKE_SYSTEM}")            --> prints a, CMAKE_SYSTEM does not exist
message("a ${CMAKE_HOST_SYSTEM_NAME}")  --> prints a MSYS_NT-10.0-19044-WOW64, could be used
</code>```

and

```<code>$ uname
MSYS_NT-10.0-19044-WOW64
</code>```

Body:
I want to detect if the CMakeLists.txt is being summoned inside an MSYS2 environment/shell:

$ uname
MSYS_NT-10.0-18363

from here I have tried:

cmake_minimum_required(VERSION 3.10)

project(test_cmake)

if(MSYS) # yes I have also tried MSYS2 with the same result!
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()

which returns the same result This is not MSYS both in Windows cmd and MSYS2 shell. I'm not actually surprised because MSYS2 and MSYS are two different beasts! Also from here, I tried:

message(${CMAKE_SYSTEM_NAME})

which both in cmd and MSYS2 returns Windows! I would appreciate it if you could help me know how I can detect if the cmake command is being run from inside an MSYS2 shell. Thanks for your support in advance.

P.S.1. As a personal note for myself, this and this seem like good sources to look into.

P.S.2 Strangely enough the command

message(${CMAKE_HOST_SYSTEM_NAME})

also returns Windows while on my MSYS2, according to the docuemntation, it must return the result of uname -s!

Body:
What I found most reliable, considering all answers and comments up to now, and building upon them, is using

execute_process(COMMAND uname OUTPUT_VARIABLE uname)
if (uname MATCHES "^MSYS" OR uname MATCHES "^MINGW")
    message("This is MSYS")
else()
    message("This is not MSYS")
endif()

In my msys2, this is what I see in cmake

message("a ${MSYS}")                    --> prints a, MSYS does not exist
message("a ${CMAKE_SYSTEM_NAME}")       --> prints a, CMAKE_SYSTEM_NAME does not exist
message("a ${CMAKE_SYSTEM}")            --> prints a, CMAKE_SYSTEM does not exist
message("a ${CMAKE_HOST_SYSTEM_NAME}")  --> prints a MSYS_NT-10.0-19044-WOW64, could be used

and

$ uname
MSYS_NT-10.0-19044-WOW64


答:
You are defining local variables in opts that don't affect the outer scope. You could use global variables (not recommended) or return values from opts.

```<code>def opts():
    url= "https://www.youtube.com/watch?v=ffcitRgiNDs"

    ydl_opts= {
        'format': '22'
    }
    return url, ydl_opts
</code>```

Now you can use

```<code>url, ydl_opts = opts()
download(url, ydl_opts)
</code>```

or

```<code>download(*opts())
</code>```

If you want download to take no parameters, call opts in download.

```<code>def download():
    url, ydl_opts = opts()
    YoutubeDL(ydl_opts).download(url)
</code>```

Title: How to call functions as those?

Body:
You are defining local variables in opts that don't affect the outer scope. You could use global variables (not recommended) or return values from opts.

def opts():
    url= "https://www.youtube.com/watch?v=ffcitRgiNDs"

    ydl_opts= {
        'format': '22'
    }
    return url, ydl_opts

Now you can use

url, ydl_opts = opts()
download(url, ydl_opts)

or

download(*opts())

If you want download to take no parameters, call opts in download.

def download():
    url, ydl_opts = opts()
    YoutubeDL(ydl_opts).download(url)


问:
difference between getting value from DataRow
Sample code:

```<code>    DataTable table = new DataTable();

    // ...
    // insert column to table

    table.Columns.Add("name");

    // ...
    // insert value to table

    foreach (DataRow row in table.Rows) {
         row["name"];
         row.Field<string>("name");
    }
</code>```

My question is:

Is there a difference between using row["name"] and row.Field<string>("name")? Of course, the second way cast value to some type, but is there another difference?

Which method is better to use?

答:
It depends on your purpose but if you look at a definition of both that may tell you;

DataRow.Item Property (DataColumn) row["name"]

DataRowExtensions.Field Method (DataRow, DataColumn) row.Field<string>("name")

Body:
Sample code:

    DataTable table = new DataTable();

    // ...
    // insert column to table

    table.Columns.Add("name");

    // ...
    // insert value to table

    foreach (DataRow row in table.Rows) {
         row["name"];
         row.Field<string>("name");
    }

My question is:

Is there a difference between using row["name"] and row.Field<string>("name")? Of course, the second way cast value to some type, but is there another difference?

Which method is better to use?


问:
NodeJS map Dtos to TypeORM Entities
I have a nodejs REST API backend running the nestjs framework, using typeORM as ORM for my entities.

Coming from a C#/Entity Framework background, I am very used to have my Dtos mapped to the database entities.

Is there a similar approach with typeORM?

I have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary...
Basically it would be amazing if I could :

```<code>let user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);
</code>```

What is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?

答:
I am using create method from getRepository

```<code>
export async function save(booking: CreateBookingDto) {
  const bookingRepository = getRepository(Booking);

  const bookingEntity = bookingRepository.create({ ...booking });
  return bookingRepository.save(bookingEntity);
}
</code>```

Title: NodeJS map Dtos to TypeORM Entities

Body:
I have a nodejs REST API backend running the nestjs framework, using typeORM as ORM for my entities.

Coming from a C#/Entity Framework background, I am very used to have my Dtos mapped to the database entities.

Is there a similar approach with typeORM?

I have seen the automapper-ts library, but those magic strings in the map declarations look kind of scary...
Basically it would be amazing if I could :

let user: TypeORMUserEntity = mapper.map<TypeORMUserEntity>(userDto);

What is the way to do this (or any alternative with same result) in nodejs/typeorm backend environment?

Body:
I am using create method from getRepository

export async function save(booking: CreateBookingDto) {
  const bookingRepository = getRepository(Booking);

  const bookingEntity = bookingRepository.create({ ...booking });
  return bookingRepository.save(bookingEntity);
}


问:
Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)
I know that RecyclerView has replaced the functionality of the old ListView and GridView. I am looking for a very basic example that shows a minimal grid setup using RecyclerView. I am not looking for long tutorial style explanations, just a minimal example. I imagine the simplest grid that mimics the old GridView would consist of the following features:

multiple cells per row

single view in each cell

responds to click events

答:
```<code>    There are 2 ways to achieve this

    - In Xml
     <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/list_amenities"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/_8sdp"
                            android:nestedScrollingEnabled="false"
 app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
                            app:spanCount="2"
app:layout_constraintEnd_toEndOf="@+id/text_parking_lot_amenities"                       app:layout_constraintStart_toStartOf="@+id/text_parking_lot_amenities"                  app:layout_constraintTop_toBottomOf="@id/text_parking_lot_amenities" />
</code>```

span count is used for grid columns

- In activity

```<code> listAmenities.layoutManager = GridLayoutManager(this, TWO)
 here TWO indicates number of grid columns
</code>```

Body:
    There are 2 ways to achieve this

    - In Xml
     <androidx.recyclerview.widget.RecyclerView
                            android:id="@+id/list_amenities"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="@dimen/_8sdp"
                            android:nestedScrollingEnabled="false"
 app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
                            app:spanCount="2"
app:layout_constraintEnd_toEndOf="@+id/text_parking_lot_amenities"                       app:layout_constraintStart_toStartOf="@+id/text_parking_lot_amenities"                  app:layout_constraintTop_toBottomOf="@id/text_parking_lot_amenities" />

span count is used for grid columns

- In activity

 listAmenities.layoutManager = GridLayoutManager(this, TWO)
 here TWO indicates number of grid columns


问:
Combining multiple columns/variables into a single column
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

```<code>Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

</code>```
```<code>v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

</code>```

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

```<code>My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA
</code>```

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

答:
Using max.col in base R -

```<code>df$vx <- df[cbind(1:nrow(df), max.col(!is.na(df)))]
df

#   v1 v2 v3 vx
#1   1 NA NA  1
#2   3 NA NA  3
#3   6 NA NA  6
#4  NA  5 NA  5
#5  NA  1 NA  1
#6  NA  3 NA  3
#7  NA NA  4  4
#8  NA NA  2  2
#9  NA NA  1  1
#10 NA NA NA NA
</code>```

max.col returns the index of max value in each row. With !is.na(df) we'll get the index of TRUE value in each row because TRUE > FALSE. We create a matrix with cbind to extract the max value from each row.

Body:
I have the following problem (I guess there is an easy answer to it, but I can't figure it out...).

I want to combine multiple columns into a single column. I have 3 variables and there are cases that answered variable 1, cases that answered variable 2, cases that answered variable 3 and cases that answered none of the variables.

Now, I want to combine them all in a single variable, that looks like column vx:

Ideal result:

  v1 v2 v3 vx
1   1 NA NA  1
2   3 NA NA  3
3   6 NA NA  6
4  NA  5 NA  5
5  NA  1 NA  1
6  NA  3 NA  3
7  NA NA  4  4
8  NA NA  2  2
9  NA NA  1  1
10 NA NA NA NA

v1 <- c(1, 3, 6, NA, NA, NA, NA, NA, NA, NA)
v2 <- c(NA, NA, NA, 5, 1, 3, NA, NA, NA, NA)
v3 <- c(NA, NA, NA, NA, NA, NA, 4, 2, 1, NA)

df <- data.frame(v1, v2, v3)

I tried it with df$vx <- paste(df$v1, df$v2, df$v3) but then I get the following result:

My result:

 v1 v2 v3       vx
1   1 NA NA  1 NA NA
2   3 NA NA  3 NA NA
3   6 NA NA  6 NA NA
4  NA  5 NA  NA 5 NA
5  NA  1 NA  NA 1 NA
6  NA  3 NA  NA 3 NA
7  NA NA  4  NA NA 4
8  NA NA  2  NA NA 2
9  NA NA  1  NA NA 1
10 NA NA NA NA NA NA

Can someone tell me how I get a result like the one above (ideal result) without the NAs (except if there are only NAs then I would like to have only one NA in column vx)

I hope I made clear what my issue is.

Thanks a lot!

Body:
Using max.col in base R -

df$vx <- df[cbind(1:nrow(df), max.col(!is.na(df)))]
df

#   v1 v2 v3 vx
#1   1 NA NA  1
#2   3 NA NA  3
#3   6 NA NA  6
#4  NA  5 NA  5
#5  NA  1 NA  1
#6  NA  3 NA  3
#7  NA NA  4  4
#8  NA NA  2  2
#9  NA NA  1  1
#10 NA NA NA NA

max.col returns the index of max value in each row. With !is.na(df) we'll get the index of TRUE value in each row because TRUE > FALSE. We create a matrix with cbind to extract the max value from each row.


问:
python regex text extraction
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

```<code>West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5
</code>```

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

```<code>['West Team', 'Eastern']
</code>```

What I currently have in mind is to use regex

```<code>result = re.sub("[\n^\s$\d]", "", text).split(",")
</code>```

this code results in this:

```<code>['WestTeam','Eastern']
</code>```

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

答:
So many ways this can be done, but looking at your data you could use rstrip() quite nicely:

```<code>s = 'West Team 4, Eastern 3\n'
lst = [x.rstrip('\n 0123456789') for x in s.split(', ')]
print(lst)
</code>```

Or maybe rather use:

```<code>from string import digits
s = 'West Team 4, Eastern 3\n'
lst = [x.rstrip(digits+'\n ') for x in s.split(', ')]
print(lst)
</code>```

Both options print:

```<code>['West Team', 'Eastern']
</code>```

Title: python regex text extraction

Body:
the text input is something like this
West Team 4, Eastern 3\n

-------Update--------

the input is a txt file containing team name and scores like a football game
the whole text file will be something like this, two names and scores:

West Team 4, Eastern 5
Nott Team 2, Eastern 3
West wood 1, Eathan 2
West Team 4, Eas 5

I am using with open to read file line by line therefore there will be \n at the end of the line.

I would like to extract this line of text in to something like:

['West Team', 'Eastern']

What I currently have in mind is to use regex

result = re.sub("[\n^\s$\d]", "", text).split(",")

this code results in this:

['WestTeam','Eastern']

I'm sure that my regex is not correct. I want to remove '\n' and any number including the space in front of the number but not the space in the middle of the name.

Open to any suggestion that to achieve this result, doesn't necessarily use regex.

Body:
So many ways this can be done, but looking at your data you could use rstrip() quite nicely:

s = 'West Team 4, Eastern 3\n'
lst = [x.rstrip('\n 0123456789') for x in s.split(', ')]
print(lst)

Or maybe rather use:

from string import digits
s = 'West Team 4, Eastern 3\n'
lst = [x.rstrip(digits+'\n ') for x in s.split(', ')]
print(lst)

Both options print:

['West Team', 'Eastern']


问:
to get a list of bools, .contain()
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

```<code>var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }
</code>```

EDIT

list of bools = list of true & false

答:
Make validation_errors an array and push the result of your validation into the array. If you don't check for failed validations (i.e. get rid of the ! in your first if statement), the validation_errors array will contain true only if validateForm returns true:

```<code>var validation_errors = [];
if(validateForm($(this))) {
    validation_errors.push(false);
}
else {
   var $input_container = $(this).parents('.input');
   $input_container.removeClass('success').addClass('error');
}
if(validationErrors.length > 0) {
    //Do some actions
}
</code>```

Alternatively (as I'm not 100% clear on what you're trying to do), you could just use a string:

```<code>var validation_errors = "";
if(validateForm($(this))) {
    validation_errors = "true";
}
else {
   var $input_container = $(this).parents('.input');
   $input_container.removeClass('success').addClass('error');
}
if(validation_errors = "true") {
    //Do some actions
}
</code>```

Title: to get a list of bools, .contain()

Body:
how do i do a list for bools in javascript. im doing a validation so i can have a list of bools and at the end i want to check that list if it contains any errors. im not sure how to add to the varable validations_errors (like a list). Plus i dont know how i can check if that list contains any true values.

what i got so far is this

var validation_errors;

            if (!validateForm($(this))) {
                validation_errors = false; //here i want to add the it to a list
                var $input_container = $(this).parents('.input');
                $input_container.removeClass('success').addClass('error');
            }

    //this is something what i want to do like (this code is c# based)
    if (validation_errors.contains(true)){
    // do some actions
    }

EDIT

list of bools = list of true & false

Body:
Make validation_errors an array and push the result of your validation into the array. If you don't check for failed validations (i.e. get rid of the ! in your first if statement), the validation_errors array will contain true only if validateForm returns true:

var validation_errors = [];
if(validateForm($(this))) {
    validation_errors.push(false);
}
else {
   var $input_container = $(this).parents('.input');
   $input_container.removeClass('success').addClass('error');
}
if(validationErrors.length > 0) {
    //Do some actions
}

Alternatively (as I'm not 100% clear on what you're trying to do), you could just use a string:

var validation_errors = "";
if(validateForm($(this))) {
    validation_errors = "true";
}
else {
   var $input_container = $(this).parents('.input');
   $input_container.removeClass('success').addClass('error');
}
if(validation_errors = "true") {
    //Do some actions
}


问:
How to manage a button with disabled attribute using Python Selenium?
Having this button:

```<code><button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>
</code>```

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

```<code>button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)
</code>```

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}
</code>```

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.

答: If it's automated tests that fail, running with a --headless option, you could enable print-screens in case of errors and then check if the button shows or not. Might be that the button is outside of the viewport. Or the automated testing does not wait long enough for the element to be rendered.

Body:
Having this button:

<button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.


问:
Redux toolkit filter() not working when wanting to display new array at the same time
I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.

so I've made a Slice for cart in redux. the 'addProduct' part works fine, but the 'deleteProduct' reducer which uses filter() doesn't work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)

my slice:

```<code>const selectedProductsSlice = createSlice({
    name:'selectedProducts',
    initialState:{
        productList:[],
        checkoutPrice:0,
    },
    reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
}});
</code>```

my button and handleDelete:

```<code><button className="btn-delete" onClick={handleDelete(product)}>Delete</button>

  function handleDelete(p) {
    console.log(p)
    dispatch(deleteProduct(p.product))
  }

</code>```

edit:
filter didnt work in every possible way i tried. so i changed my way and did this instead to work. but still i wonder why didnt filter() method work properly.

```<code>        deleteProduct: (state, { payload }) => {
            const foundIndex = state.productList.findIndex((p) => {
                return p.product.id === payload.id
            })
            state.productList.splice(foundIndex,1)

        }
</code>```

答:
The filter operation creates a new array without changing the existing instance. Therefore you need to assign it to state.

```<code>deleteProduct: (state, { payload }) => {
    return {
        ...state,
        productList: state.productList.filter(
            foundProduct => foundProduct.id !== payload.id
        )
    };
};
</code>```

You also need to change the way you call the handleDelete in the onClick handler.

```<code>onClick={() => handleDelete(product)}
</code>```

Body:
I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.

so I've made a Slice for cart in redux. the 'addProduct' part works fine, but the 'deleteProduct' reducer which uses filter() doesn't work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)

my slice:

const selectedProductsSlice = createSlice({
    name:'selectedProducts',
    initialState:{
        productList:[],
        checkoutPrice:0,
    },
    reducers: {
        addProduct:(state,{payload}) => {
            state.productList.push(payload)
            state.checkoutPrice += payload.price
        },
        deleteProduct:(state,{payload}) => {
            state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
        }
}});

my button and handleDelete:

<button className="btn-delete" onClick={handleDelete(product)}>Delete</button>

  function handleDelete(p) {
    console.log(p)
    dispatch(deleteProduct(p.product))
  }

edit:
filter didnt work in every possible way i tried. so i changed my way and did this instead to work. but still i wonder why didnt filter() method work properly.

        deleteProduct: (state, { payload }) => {
            const foundIndex = state.productList.findIndex((p) => {
                return p.product.id === payload.id
            })
            state.productList.splice(foundIndex,1)

        }

Body:
The filter operation creates a new array without changing the existing instance. Therefore you need to assign it to state.

deleteProduct: (state, { payload }) => {
    return {
        ...state,
        productList: state.productList.filter(
            foundProduct => foundProduct.id !== payload.id
        )
    };
};

You also need to change the way you call the handleDelete in the onClick handler.

onClick={() => handleDelete(product)}


问:
Problem posting image file using HttpWebRequest
I am posting an image file from the windows phone 7 platform to a remote server.For that firstly I have saved the image to the isolated storage using photochoosertask for further accessing.
for saving I have used the following code:

```<code>using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (isf.FileExists("myimage.jpg"))
        isf.DeleteFile("myimage.jpg");

    using (IsolatedStorageFileStream isfs = isf.CreateFile("myimage.jpg"))
    {
        var bmp = new WriteableBitmap(56, 56);
        bmp.SaveJpeg(isfs, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    }
}
</code>```

After that I am using the following code to post the file:

```<code>private void UploadFilesToRemoteUrl(string url, string files, string logpath1)
{

    long length = 0;
    string boundary = "----------------------------" +
    DateTime.Now.Ticks.ToString("x");

    HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest2.Method = "POST";
  //  httpWebRequest2.KeepAlive = true;

    //httpWebRequest2.Credentials =
    //System.Net.CredentialCache.DefaultCredentials;

    Stream memStream = new System.IO.MemoryStream();

    byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" +
    boundary + "\r\n");

    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    length += boundarybytes.Length;

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

    string header = string.Format(headerTemplate, "file", files);

    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

    memStream.Write(headerbytes, 0, headerbytes.Length);
    length += headerbytes.Length;
    char[] ch = new char[1];
    ch[0] = '\\';
    string[] flname = filename.Split(ch);
   // FileStream fileStream = new FileStream(files, FileMode.Open, FileAccess.Read);
    var store = IsolatedStorageFile.GetUserStoreForApplication();

    //IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(flname[6], FileMode.Open, store);
    System.IO.IsolatedStorage.IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(flname[6], FileMode.Open, store);

    byte[] buffer = new byte[1024];

    int bytesRead = 0;

    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        memStream.Write(buffer, 0, bytesRead);
        length += bytesRead;
    }

    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    length += boundarybytes.Length;

    fileStream.Close();

    //httpWebRequest2.ContentLength = memStream.Length;

    Stream requestStream = httpWebRequest2.GetRequestStream();

    memStream.Position = 0;
    byte[] tempBuffer = new byte[memStream.Length];
    memStream.Read(tempBuffer, 0, tempBuffer.Length);
    memStream.Close();
    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    requestStream.Close();

    WebResponse webResponse2 = httpWebRequest2.GetResponse();

    Stream stream2 = webResponse2.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);

   //MessageBox.Show(reader2.ReadToEnd());

    webResponse2.Close();
    httpWebRequest2 = null;
    webResponse2 = null;
}
</code>```

But I am getting the error in getting the response, I am getting null in response from WebResponse webResponse2 = httpWebRequest2.GetResponse();.

Please help me out.

答:
You have to do anything asynchronously. Here is a little example:</p>

```<code>public WebrequestExample()
{
    string url = "COPY YOUR URL HERE";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    // ...
    // Different settings, like content type or method...
    // ...

    request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}

public void GetRequestStreamCallback(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    Stream postStream = request.EndGetRequestStream(asyncResult);

    // Data writing
    // ...
    // postStream.Write(...)
    // ...

    // Start the async operation to get the response
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

public void GetResponseCallback(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); // Get the HttpWebResponse

    using (var stream = response.GetResponseStream())
    {
        using (var reader = new StreamReader(stream))
        {
            // Do something with the response
        }
    }
}
</code>```

Body:
I am posting an image file from the windows phone 7 platform to a remote server.For that firstly I have saved the image to the isolated storage using photochoosertask for further accessing.
for saving I have used the following code:

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if (isf.FileExists("myimage.jpg"))
        isf.DeleteFile("myimage.jpg");

    using (IsolatedStorageFileStream isfs = isf.CreateFile("myimage.jpg"))
    {
        var bmp = new WriteableBitmap(56, 56);
        bmp.SaveJpeg(isfs, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
    }
}

After that I am using the following code to post the file:

private void UploadFilesToRemoteUrl(string url, string files, string logpath1)
{

    long length = 0;
    string boundary = "----------------------------" +
    DateTime.Now.Ticks.ToString("x");

    HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest2.Method = "POST";
  //  httpWebRequest2.KeepAlive = true;

    //httpWebRequest2.Credentials =
    //System.Net.CredentialCache.DefaultCredentials;

    Stream memStream = new System.IO.MemoryStream();

    byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" +
    boundary + "\r\n");

    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    length += boundarybytes.Length;

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

    string header = string.Format(headerTemplate, "file", files);

    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

    memStream.Write(headerbytes, 0, headerbytes.Length);
    length += headerbytes.Length;
    char[] ch = new char[1];
    ch[0] = '\\';
    string[] flname = filename.Split(ch);
   // FileStream fileStream = new FileStream(files, FileMode.Open, FileAccess.Read);
    var store = IsolatedStorageFile.GetUserStoreForApplication();

    //IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(flname[6], FileMode.Open, store);
    System.IO.IsolatedStorage.IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(flname[6], FileMode.Open, store);

    byte[] buffer = new byte[1024];

    int bytesRead = 0;

    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        memStream.Write(buffer, 0, bytesRead);
        length += bytesRead;
    }

    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    length += boundarybytes.Length;

    fileStream.Close();

    //httpWebRequest2.ContentLength = memStream.Length;

    Stream requestStream = httpWebRequest2.GetRequestStream();

    memStream.Position = 0;
    byte[] tempBuffer = new byte[memStream.Length];
    memStream.Read(tempBuffer, 0, tempBuffer.Length);
    memStream.Close();
    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    requestStream.Close();

    WebResponse webResponse2 = httpWebRequest2.GetResponse();

    Stream stream2 = webResponse2.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);

   //MessageBox.Show(reader2.ReadToEnd());

    webResponse2.Close();
    httpWebRequest2 = null;
    webResponse2 = null;
}

But I am getting the error in getting the response, I am getting null in response from WebResponse webResponse2 = httpWebRequest2.GetResponse();.

Please help me out.

Body:
You have to do anything asynchronously. Here is a little example:

public WebrequestExample()
{
    string url = "COPY YOUR URL HERE";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

    // ...
    // Different settings, like content type or method...
    // ...

    request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}

public void GetRequestStreamCallback(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    Stream postStream = request.EndGetRequestStream(asyncResult);

    // Data writing
    // ...
    // postStream.Write(...)
    // ...

    // Start the async operation to get the response
    request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

public void GetResponseCallback(IAsyncResult asyncResult)
{
    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); // Get the HttpWebResponse

    using (var stream = response.GetResponseStream())
    {
        using (var reader = new StreamReader(stream))
        {
            // Do something with the response
        }
    }
}


问:
How to check if an element exists and only then run a test with Cypress?
I want to execute some function only when certain element is present using its data-test id.

Below is what I am trying to do:

```<code>cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}
</code>```

Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".

How can I fix this? Could someone please help me with this?

答:
You want to follow this pattern Element existence

cy.get('body')
  .then(($body) => {
    // synchronously query from body
    // to find which element was created
    if ($body.find('[data-testid="checkbox-id"]').length) {
      // checkbox-id was found
      cy.tableSelectAll()
    }
  })
```

Body:
I want to execute some function only when certain element is present using its data-test id.

Below is what I am trying to do:

cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}

Here I am expecting it to execute tableSelectAll() only if there is an element. But this fails saying it couldn't find an element with id "checkbox-id".

How can I fix this? Could someone please help me with this?


问:
CSS pseudo element positioning - partial border above header
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

```<code> <img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">            <h2 class="sub-title">Test English subtitle</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p> <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis. <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}
</code>```

答:
Since you want the text to go to the bottom of the photo, you used this method and the h2 tag covers the entire container, so the first h2 is the beginning of the photo.

```<code>h2.sub-title {font-size:28px;display: block;position: relative;}
h2.sub-title::before{ position: absolute; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}
</code>```

Get width and margin-right img by JavaScript and set to style left ::before, and
before is absolute

Body:
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

Test English subtitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.

Donec mattis vulputate tellus, vel tincidunt purus condimentum vel.
Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}

Body:
Since you want the text to go to the bottom of the photo, you used this method and the h2 tag covers the entire container, so the first h2 is the beginning of the photo.

h2.sub-title {font-size:28px;display: block;position: relative;}
h2.sub-title::before{ position: absolute; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

Get width and margin-right img by JavaScript and set to style left ::before, and
before is absolute


问:
Does "auto" keyword always evaluates floating point value as double?
Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?

As people suggested I modified the code by adding "f" suffix to floating-point values.

```<code>#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

versus

```<code>#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}
</code>```

The result is exactly the same - output differs between two versions.
So does it mean that "auto" always evaluates floating point value to "double" type?

答:
The issue is that your code is using ::sin instead of std::sin (and the same for cos). That is, you’re using the sin function found in the global namespace.

std::sin is overloaded for float. But ::sin isn’t, and it always returns a double (because ::sin is the legacy C function, and C doesn’t have function overloading).

Use std::sin and std::cos in your code to fix the issue.

Body:
Continuing the question, which was closed:
C++: "auto" keyword affects math calculations?

As people suggested I modified the code by adding "f" suffix to floating-point values.

#include <cmath>
unsigned int nump=12u;
auto inner=2.5f;
auto outer=6.0f;
auto single=2.f*3.14159265359f/nump;
auto avg=0.5f*inner+0.5f*outer;
for (auto i=0u;i<nump;++i){
    auto theta=i*single;
    auto px=avg*sin(theta);
    auto py=avg*cos(theta);
    auto tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

versus

#include <cmath>
unsigned int nump=12u;
float inner=2.5f;
float outer=6.0f;
float single=2.f*3.14159265359f/nump;
float avg=0.5f*inner+0.5f*outer;
for (unsigned int i=0u;i<nump;++i){
    float theta=i*single;
    float px=avg*sin(theta);
    float py=avg*cos(theta);
    float tw=17.f;
    int v1=std::round(1.f+px-tw/2.0f);
    int v2=std::round(2.f+py-tw/2.0f);
    std::cout<<"#"<<i<<":"<<v1<<";"<<v2<<std::endl;
}

The result is exactly the same - output differs between two versions.
So does it mean that "auto" always evaluates floating point value to "double" type?


问:
Multidimensional array printing wrong values in cpp
I've been struggling with a simple class representing a matrix in C++. Instead of using a multidimensional array, I've decided to use a flat array and access the values by calculating the index of the according cell by [row * x_dim + col]. I want to use 2D matrices only.
Ideally, I would also create getter and setter functions, but as I am already having troubles I skipped those for now.
The main problem is, that after setting values, those values seem to be corrupted somewhere along the way as when printing them out again, I'm reading different values then what I've actually stored.
Here's the (simplified) header MyMatrix.h:

```<code>class MyMatrix{
    public:
        int x_dim, y_dim;

        float *my_matrix;

        MyMatrix(int x, int y);
        ~MyMatrix();
};
</code>```

Here is MyMatrix.cpp:

```<code>#include "MyMatrix.h"

MyMatrix::MyMatrix(int x, int y){
    x_dim = x;
    y_dim = y;

    my_matrix = new float[x * y];
}

MyMatrix::~MyMatrix(){
    delete[] my_matrix;
}
</code>```

Now when creating a new instance of MyMatrix, filling the array with ascending numbers and then printing the values again, I am getting different values for some cells in the (flat) matrix. Here's what I did:

```<code>#include "MyMatrix.h"
#include <iostream>

int main(){

    MyMatrix test(3, 4);

    //filling the array in test with ascending numbers
    for(int row = 0; row < test.x_dim; row++){
        for(int col = 0; col < test.y_dim; col++){
            test.my_matrix[row * test.x_dim + col] = col+1;
        }
    }

    for(int row = 0; row < test.x_dim; row++){
        std::cout << "Row " << row << ": ";
        for(int col = 0; col < test.y_dim; col++){
            std::cout  << test.my_matrix[row * test.x_dim + col] << "  ";
        }
        std::cout << std::endl;
    }
}
</code>```

So what my output should look like is this:

```<code>Row 0: 1  2  3  4
Row 1: 1  2  3  4
Row 2: 1  2  3  4
</code>```

But instead, it looks like this:

```<code>Row 0: 1  2  3  1
Row 1: 1  2  3  1
Row 2: 1  2  3  4
</code>```

As one can see, the first two rows have a 1 instead of a 4 in column 3.
I've really been struggling with identifying the underlying issue here and I can't figure it out so I would appreciate any help!
Thanks!

I am using clang version 13.0.0 on an M1 Pro and the g++ compiler.

答:
This is the wrong index:

```<code> row * test.x_dim + col
</code>```

Suppose you are in the last iteration of the outer loop then row == x_dim-1 and you get:

```<code> (x_dim-1) * x_dim + col
</code>```

while it should be (supposed x is rows):

```<code> (y_dim-1) * x_dim + col
</code>```

Tip: Your variable naming col vs x_dim and row vs y_dim can be made better. x, x_dim and y, y_dim  or col, num_columns and row, num_rows would be less errorprone.

Body:
I've been struggling with a simple class representing a matrix in C++. Instead of using a multidimensional array, I've decided to use a flat array and access the values by calculating the index of the according cell by [row * x_dim + col]. I want to use 2D matrices only.
Ideally, I would also create getter and setter functions, but as I am already having troubles I skipped those for now.
The main problem is, that after setting values, those values seem to be corrupted somewhere along the way as when printing them out again, I'm reading different values then what I've actually stored.
Here's the (simplified) header MyMatrix.h:

class MyMatrix{
    public:
        int x_dim, y_dim;

        float *my_matrix;

        MyMatrix(int x, int y);
        ~MyMatrix();
};

Here is MyMatrix.cpp:

#include "MyMatrix.h"

MyMatrix::MyMatrix(int x, int y){
    x_dim = x;
    y_dim = y;

    my_matrix = new float[x * y];
}

MyMatrix::~MyMatrix(){
    delete[] my_matrix;
}

Now when creating a new instance of MyMatrix, filling the array with ascending numbers and then printing the values again, I am getting different values for some cells in the (flat) matrix. Here's what I did:

#include "MyMatrix.h"
#include <iostream>

int main(){

    MyMatrix test(3, 4);

    //filling the array in test with ascending numbers
    for(int row = 0; row < test.x_dim; row++){
        for(int col = 0; col < test.y_dim; col++){
            test.my_matrix[row * test.x_dim + col] = col+1;
        }
    }

    for(int row = 0; row < test.x_dim; row++){
        std::cout << "Row " << row << ": ";
        for(int col = 0; col < test.y_dim; col++){
            std::cout  << test.my_matrix[row * test.x_dim + col] << "  ";
        }
        std::cout << std::endl;
    }
}

So what my output should look like is this:

Row 0: 1  2  3  4
Row 1: 1  2  3  4
Row 2: 1  2  3  4

But instead, it looks like this:

Row 0: 1  2  3  1
Row 1: 1  2  3  1
Row 2: 1  2  3  4

As one can see, the first two rows have a 1 instead of a 4 in column 3.
I've really been struggling with identifying the underlying issue here and I can't figure it out so I would appreciate any help!
Thanks!

I am using clang version 13.0.0 on an M1 Pro and the g++ compiler.

Body:
This is the wrong index:

 row * test.x_dim + col

Suppose you are in the last iteration of the outer loop then row == x_dim-1 and you get:

 (x_dim-1) * x_dim + col

while it should be (supposed x is rows):

 (y_dim-1) * x_dim + col

Tip: Your variable naming col vs x_dim and row vs y_dim can be made better. x, x_dim and y, y_dim  or col, num_columns and row, num_rows would be less errorprone.


问:
How to detect when a phone call is triggered when the application is up?
My application is a coupon shopping,users will download the coupons in phone and when completed they will be directed for the automatic cash payment.
If a user downloads 5 coupons and inbetween gets a call as it is iOS4 it goes to background.
So when we press the home button also the application goes to background by this behaviour.I have save few data and restore the coupons when the user quits the application by homebutton.
But in iOS 4 behaviour homebutton press and phone call interruptions shows the same behaviour and calls the same functions,how i could differentiate between the 2.
Please this is a tedious function,please help me.......</p>

答:
Without multi-tasking: For applications that do not support background execution or are linked against iOS 3.x or earlier, applicationWillTerminate: method is always called when the user quits the application. For applications that support background execution, this method is generally not called when the user quits the application because the application simply moves to the background in that case.

With multi-tasking: You can implement applicationWillResignActive:delegate method in your app delegate, which gets called during temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

```<code>- (void)applicationWillResignActive:(UIApplication *)application {

    flag = YES;
    [self doCleanUp];
}

- (void)applicationWillTerminate:(UIApplication *)application {

    if (!flag) [self doCleanUp];
}
</code>```

Body:
Without multi-tasking: For applications that do not support background execution or are linked against iOS 3.x or earlier, applicationWillTerminate: method is always called when the user quits the application. For applications that support background execution, this method is generally not called when the user quits the application because the application simply moves to the background in that case.

With multi-tasking: You can implement applicationWillResignActive:delegate method in your app delegate, which gets called during temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

- (void)applicationWillResignActive:(UIApplication *)application {

    flag = YES;
    [self doCleanUp];
}

- (void)applicationWillTerminate:(UIApplication *)application {

    if (!flag) [self doCleanUp];
}


问:
How to create cgi.FieldStorage for testing purposes?
I am creating a utility to handle file uploads in webob-based applications. I want to write some unit tests for it.

My question is - as webob uses cgi.FieldStorage for uploaded files I would like to create a FieldStorage instance in a simple way (without emulating a whole request). What it the minimum code I need to do it (nothing fancy, emulating upload of a text file with "Lorem ipsum" content would be fine). Or is it a better idea to mock it?

答:
I was doing something like this, since in my script i'm using

```<code>import cgi

form = cgi.FieldStorage()

>>> # which result:
>>> FieldStorage(None, None, [])

</code>```

When your URL contains query string it will look like this:

```<code># URL: https://..../index.cgi?test=only
FieldStorage(None, None, [MiniFieldStorage('test', 'only')])
</code>```

So i was just pushing manually MiniFieldStorage into the form variable

```<code>import cgi

fs = cgi.MiniFieldStorage('test', 'only')
>>> fs
MiniFieldStorage('test', 'only')

form = cgi.FieldStorage()
form.list.append(fs)

>>> form
>>> FieldStorage(None, None, [MiniFieldStorage('test', 'only')])

# Now you can call it with same functions
>>> form.getfirst('test')
'only'
</code>```

Body:
I was doing something like this, since in my script i'm using

import cgi

form = cgi.FieldStorage()

>>> # which result:
>>> FieldStorage(None, None, [])

When your URL contains query string it will look like this:

# URL: https://..../index.cgi?test=only
FieldStorage(None, None, [MiniFieldStorage('test', 'only')])

So i was just pushing manually MiniFieldStorage into the form variable

import cgi

fs = cgi.MiniFieldStorage('test', 'only')
>>> fs
MiniFieldStorage('test', 'only')

form = cgi.FieldStorage()
form.list.append(fs)

>>> form
>>> FieldStorage(None, None, [MiniFieldStorage('test', 'only')])

# Now you can call it with same functions
>>> form.getfirst('test')
'only'


问:
Python program, list not printing
I have the following program which seeks to check the similarity between two lists. However, the originalword (list) prints correctly the first time but not the second therefore the code doesn't work to check equivalence.

https://trinket.io/python3/b3b7827717

Can anyone spot the error? If so, could a solution be posted
a) using lists
b) Not introducing any new skills (e.g. string slicing)

```<code>def palindromechecker():
  print("----Palindrome Checker---")

  word=input("Enter word:")

  #empty list for reversed word
  originalword=[]
  reversedword=[]

  #put each letter in word in the list originallist
  for i in range(len(word)):
    originalword.append(word[i])
  print("Print original word in order:",originalword)

  #reverse the word
  for i in range(len(word)):
    reversedword.append(originalword.pop())
  print("Reversed word:",reversedword)
  print("Original word:",originalword)

  #are original word and reversed word the same?

  if originalword==reversedword:
    print("--Palindrome Found--")
  else:
    print("--Not a Palindrome---")

palindromechecker()
</code>```

答:
If you use .pop() method, it will update the existing list by removing the last element from the list. So it is exhausting your originalword list.

I read that you don't want to use string[::-1]. Here is a similar but not the same workaround. You have to run the loop in reverse.

```<code>  #reverse the word
  for i in range(len(word)-1, -1, -1):
    reversedword.append(originalword[i])
</code>```

Title: Python program, list not printing

Body:
I have the following program which seeks to check the similarity between two lists. However, the originalword (list) prints correctly the first time but not the second therefore the code doesn't work to check equivalence.

https://trinket.io/python3/b3b7827717

Can anyone spot the error? If so, could a solution be posted
a) using lists
b) Not introducing any new skills (e.g. string slicing)

def palindromechecker():
  print("----Palindrome Checker---")

  word=input("Enter word:")

  #empty list for reversed word
  originalword=[]
  reversedword=[]

  #put each letter in word in the list originallist
  for i in range(len(word)):
    originalword.append(word[i])
  print("Print original word in order:",originalword)

  #reverse the word
  for i in range(len(word)):
    reversedword.append(originalword.pop())
  print("Reversed word:",reversedword)
  print("Original word:",originalword)

  #are original word and reversed word the same?

  if originalword==reversedword:
    print("--Palindrome Found--")
  else:
    print("--Not a Palindrome---")

palindromechecker()

Body:
If you use .pop() method, it will update the existing list by removing the last element from the list. So it is exhausting your originalword list.

I read that you don't want to use string[::-1]. Here is a similar but not the same workaround. You have to run the loop in reverse.

  #reverse the word
  for i in range(len(word)-1, -1, -1):
    reversedword.append(originalword[i])


问:
Python error "OSError: [Errno 22] Invalid argument"
I found this function that allows me to remove the last character from a file:

```<code>def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()
</code>```

And it is working when I test it oh a file alone.
But when I use it on my program I don't know why it gives me this error "OSError: [Errno 22] Invalid argument".

Here's my program:

```<code>import os
def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()
grades = {'Mathématiques': '20.0', 'Français': '20.0', 'ALE': '20.0', 'Espagnole': '20.0', 'Anglais': '20.0', 'SVT': '20.0', 'SPC': '20.0', 'Technologie': '20.0', 'HGPF': '20.0', 'EMC': '20.0', 'EPS': '20.0', 'Art': '20.0'}
coef = {'Mathématiques': '4', 'Français': '4', 'ALE': '1', 'Espagnole': '1', 'Anglais': '2', 'SVT': '2', 'SPC': '2', 'Technologie': '1', 'HGPF': '2', 'EMC': '1', 'EPS': '1', 'Art': '1'}
def foo(l):
    return list(map(float, l))

Complete_name2 = "D:/Users/Jean Paul/OneDrive/Programming/Programs/Prog 2 - Moyenne de Notes/recalculating.py"

f = open(Complete_name2, "w+")
gradev = foo(list(grades.values()))
coefv = foo(list(coef.values()))
r = 0
a = 0
while r < len(foo(list(grades.values()))):
    print("calculation" + str(r) + " = " + "(" + str(gradev[a]) + " * " + str(coefv[a]) + ")", file = f)
    r = r + 1
    a = a + 1
</code>```

Here is the part that isn't working (I am trying to print at the end of the file "str(eval(<first variables that has been created earlier> + <second> + <third> + ...))):

```<code>print("")
myprint = "average_p1 = eval("
r2 = 0
while r2 < r:
    myprint = myprint + "calculation" + str(r2) + "+"
    r2 = r2 + 1
removelast(Complete_name2)
</code>```

recalculating.py has been created:

```<code>calculation0 = (20.0 * 4.0)
calculation1 = (20.0 * 4.0)
calculation2 = (20.0 * 1.0)
calculation3 = (20.0 * 1.0)
calculation4 = (20.0 * 2.0)
calculation5 = (20.0 * 2.0)
calculation6 = (20.0 * 2.0)
calculation7 = (20.0 * 1.0)
calculation8 = (20.0 * 2.0)
calculation9 = (20.0 * 1.0)
calculation10 = (20.0 * 1.0)
calculation11 = (20.0 * 1.0)
</code>```

Output:

```<code>Traceback (most recent call last):
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 29, in <module>
    removelast(Complete_name2)
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 4, in removelast
    filehandle.seek(-1, os.SEEK_END)
OSError: [Errno 22] Invalid argument
</code>```

答:
This error mostly comes when you are entering a wrong or invalid file path.
Check your file paths -

Add r before your file path. This might help -
The leading r denotes a python raw string. It treats \ as a literal character.

Add r before your file path to make it like -
open(r"C:\folder\yourfile.txt","r")

Body:
I found this function that allows me to remove the last character from a file:

def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()

And it is working when I test it oh a file alone.
But when I use it on my program I don't know why it gives me this error "OSError: [Errno 22] Invalid argument".

Here's my program:

import os
def removelast(myfile):
    with open(myfile, 'rb+') as filehandle:
        filehandle.seek(-1, os.SEEK_END)
        filehandle.truncate()
grades = {'Mathématiques': '20.0', 'Français': '20.0', 'ALE': '20.0', 'Espagnole': '20.0', 'Anglais': '20.0', 'SVT': '20.0', 'SPC': '20.0', 'Technologie': '20.0', 'HGPF': '20.0', 'EMC': '20.0', 'EPS': '20.0', 'Art': '20.0'}
coef = {'Mathématiques': '4', 'Français': '4', 'ALE': '1', 'Espagnole': '1', 'Anglais': '2', 'SVT': '2', 'SPC': '2', 'Technologie': '1', 'HGPF': '2', 'EMC': '1', 'EPS': '1', 'Art': '1'}
def foo(l):
    return list(map(float, l))

Complete_name2 = "D:/Users/Jean Paul/OneDrive/Programming/Programs/Prog 2 - Moyenne de Notes/recalculating.py"

f = open(Complete_name2, "w+")
gradev = foo(list(grades.values()))
coefv = foo(list(coef.values()))
r = 0
a = 0
while r < len(foo(list(grades.values()))):
    print("calculation" + str(r) + " = " + "(" + str(gradev[a]) + " * " + str(coefv[a]) + ")", file = f)
    r = r + 1
    a = a + 1

Here is the part that isn't working (I am trying to print at the end of the file "str(eval(<first variables that has been created earlier> + <second> + <third> + ...))):

print("")
myprint = "average_p1 = eval("
r2 = 0
while r2 < r:
    myprint = myprint + "calculation" + str(r2) + "+"
    r2 = r2 + 1
removelast(Complete_name2)

recalculating.py has been created:

calculation0 = (20.0 * 4.0)
calculation1 = (20.0 * 4.0)
calculation2 = (20.0 * 1.0)
calculation3 = (20.0 * 1.0)
calculation4 = (20.0 * 2.0)
calculation5 = (20.0 * 2.0)
calculation6 = (20.0 * 2.0)
calculation7 = (20.0 * 1.0)
calculation8 = (20.0 * 2.0)
calculation9 = (20.0 * 1.0)
calculation10 = (20.0 * 1.0)
calculation11 = (20.0 * 1.0)

Output:

Traceback (most recent call last):
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 29, in <module>
    removelast(Complete_name2)
  File "d:\Users\Jean Paul\OneDrive\Programming\tests python\test3.py", line 4, in removelast
    filehandle.seek(-1, os.SEEK_END)
OSError: [Errno 22] Invalid argument


问:
Excel: Listing Numbers In Between 2 Numbers
I was wondering if anyone knew of a formula to list all the numbers between 2 values, so for example if cell F2 had 12 in it and G2 had 17 in it I'd like a formula that would show 13,14,15,16  In cell H2.

Thanks

答:
In Office 365 it is very easy to do with the CONCAT-function, e.g. between 10 and 20:

```<code>=CONCAT(ROW(10:20)&",")
</code>```

Sadly, Office 2016 and onwards do not have this function.

Body:
In Office 365 it is very easy to do with the CONCAT-function, e.g. between 10 and 20:

=CONCAT(ROW(10:20)&",")

Sadly, Office 2016 and onwards do not have this function.


问:
Fitting a data with asymmetric errors on both axis in Python
I have data in the form of 6 parameters: x, y, x+ error, x- error, y+ error, y- error. I want to find the best fit for this dataset. I'm trying to use scipy.optimize.curve_fit but it does not let me choose the error in the data (I think). I tried to figure out a way and I found that there is a function called sigma in curve_fit that does something similar but it's only for error on one axis. Is there any way I can find the best fit for the data while considering the error in the data points?

I want to fit those red scatter dots in the following plot:

Here is the code for scipy fit without error bars in case it helps:

#Import the Data
obs0x,xerr0_plus,xerr0_minus,obs0y,yerr_plus,yerr_minus=np.loadtxt("Mhratioz6",unpack='true')

#define the function to fit
def func(x, a, b):
    return (np.log10(a)+(b*(x-12))+np.log10(10**(8+c)))
    return ((x/1e12)**a)*(b)*(10**(8+c))
    return a+(b*x)

#define the data to be fit
xdata=np.log10(obs0x)
ydata=np.log10(obs0y)
 p0=[-1,1.65,0]

#Fit for the parameters a, b, c of the function func:
popt, pcov = curve_fit(func, xdata, ydata)
print("[a,b]=",popt)

plt.figure(figsize=(5,5))
plt.loglog(10**xdata, 10**func(xdata, *popt), 'r-',label='scipy fit')
#plt.loglog(m, func(m, *popt), 'r-',label='Scipy-fit')
plt.scatter(obs0x,obs0y,s=2)
plt.ylim(1e6,1e11)
plt.xlim(1e11,1e14)
plt.xlabel('x')
plt.ylabel('y')
plt.title("z=0 Observations")
plt.legend()
plt.show()
```

答:
curve_fit can handle fit just with uncertainty on the y axis: It is unable to perform fit if you have uncertainty both on the x axis and y axis.
If you want to manage noise on the x axis, you have to use odr.

```<code>from scipy import odr

#Firstly you have to create a RealData object

data = odr.RealData(x_var,y_var,sx = x_err, sy = y_err)

#Model object

quad_model = odr.Model(test_func)

#test_func is the function you want to use as model for your fitting

#Set up ODR with the model and data

odr = odr.ODR(data, quad_model,beta0 =[])

#beta0 is a list which contains the initial value of the parameters

#Run the regression.
out = odr.run()

out.beta
#out.beta is a list which contains the values of the parameters popped out from the fitting

out.sd_beta

#out.sd_beta is a list which contains the values of the errors of the parameters
</code>```

Body:
curve_fit can handle fit just with uncertainty on the y axis: It is unable to perform fit if you have uncertainty both on the x axis and y axis.
If you want to manage noise on the x axis, you have to use odr.

from scipy import odr

#Firstly you have to create a RealData object

data = odr.RealData(x_var,y_var,sx = x_err, sy = y_err)

#Model object

quad_model = odr.Model(test_func)

#test_func is the function you want to use as model for your fitting

#Set up ODR with the model and data

odr = odr.ODR(data, quad_model,beta0 =[])

#beta0 is a list which contains the initial value of the parameters

#Run the regression.
out = odr.run()

out.beta
#out.beta is a list which contains the values of the parameters popped out from the fitting

out.sd_beta

#out.sd_beta is a list which contains the values of the errors of the parameters


问:
How to use Glide library in android to display image from url? Glide Usage
EDIT

If I try to use glide, and import an image ( https://mega.nz/#!nJ8yECaR!wHK3fz1xPEx9VMjTPuxzao6XDemAXy0T5s7KBUCsffs) the image button goes to the all screen, while the picture is the right position. And if I "click", the button see in all the screen.Anyone can tell me the right method step-by-step?

答:
Library Setup

Add to your app/build.gradle file:

```<code>dependencies {
  implementation 'com.github.bumptech.glide:glide:4.12.0'
  // Glide v4 uses this new annotation processor -- see https://bumptech.github.io/glide/doc/generatedapi.html
  annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
}
</code>```

Make sure to create a MyAppGlideModule that simply extends from AppGlideModule and has the @GlideModule annotation.

```<code>import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule

// new since Glide v4
@GlideModule
class MyAppGlideModule : AppGlideModule() {

}
</code>```

Usage

```<code>Glide.with(context)
    .load("URL")
    .into(ivImg)
</code>```

Body:
Library Setup

Add to your app/build.gradle file:

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.12.0'
  // Glide v4 uses this new annotation processor -- see https://bumptech.github.io/glide/doc/generatedapi.html
  annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
}

Make sure to create a MyAppGlideModule that simply extends from AppGlideModule and has the @GlideModule annotation.

import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule

// new since Glide v4
@GlideModule
class MyAppGlideModule : AppGlideModule() {

}

Usage

Glide.with(context)
    .load("URL")
    .into(ivImg)