问:
Switch Logo color in Dark Mode issue
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

```<code><img class="nav_logo" src="assets/img/PR_logo.png" alt="original logo" />

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

</code>```

Using SVG

```<code>
 <img class="nav_logo" src="assets/img/PR_logo.svg" id="svg" alt="PR Logo">

.nav_logo {
    fill: currentColor;
}
</code>```

Unfortunately none of the above has worked.
Any suggestion?

答:
If you are considering a JS-based solution, you can use the approach I developed below. Clicking the toggle button changes both the src attribute of the  element and the background-color style of the  element.

let button = document.getElementById('toggleButton');
let logo = document.getElementById('logo');

let darkImageURL = "https://cdn-icons-png.flaticon.com/512/196/196685.png";
let lightImageURL = "https://cdn-icons-png.flaticon.com/512/169/169367.png";

button.addEventListener('click', function(event) {
  if(this.innerHTML === "Dark") {
    document.body.style.background = "black";
    this.innerHTML = "Light";
    logo.src = darkImageURL;
  }
  else {
    document.body.style.background = "white";
    this.innerHTML = "Dark";
    logo.src = lightImageURL;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button id="toggleButton">Dark</button>

  <img id="logo" class="nav_logo" src="https://cdn-icons-png.flaticon.com/512/169/169367.png" alt="original logo" width="100" height="100"/>
</body></code>```

Title: Switch Logo color in Dark Mode issue

Body:
I have a black color logo for my portfolio and i would like to switch it white when Dark Mode : https://www.paulinerouger.com/

I have tried:

Using CSS Variables

body {
  --nav_logo: url(PR_logo.png) no-repeat;

}

body[data-theme="dark"] {
  --nav_logo: url(PR_logo_white.png) no-repeat;
}

.nav_logo {
    background: var(--nav_logo);
  }

Using SVG

.nav_logo {
    fill: currentColor;
}

Unfortunately none of the above has worked.
Any suggestion?

Body:
If you are considering a JS-based solution, you can use the approach I developed below. Clicking the toggle button changes both the src attribute of the <img> element and the background-color style of the <body> element.

let button = document.getElementById('toggleButton');
let logo = document.getElementById('logo');

let darkImageURL = "https://cdn-icons-png.flaticon.com/512/196/196685.png";
let lightImageURL = "https://cdn-icons-png.flaticon.com/512/169/169367.png";

button.addEventListener('click', function(event) {
  if(this.innerHTML === "Dark") {
    document.body.style.background = "black";
    this.innerHTML = "Light";
    logo.src = darkImageURL;
  }
  else {
    document.body.style.background = "white";
    this.innerHTML = "Dark";
    logo.src = lightImageURL;
  }
});

<body>
  <button id="toggleButton">Dark</button>

  <img id="logo" class="nav_logo" src="https://cdn-icons-png.flaticon.com/512/169/169367.png" alt="original logo" width="100" height="100"/>
</body>


来源: stackexchange

问:
How to extract all 'href' tags from a div class?
I am working in Python web scrapping using beautiful soup. I couldn't extract 'href' tags and save them to a list.

```<code>[<div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/391/40439">React.js Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40438">Node JS Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40437">React Native Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/391/40436">Python Full Stack Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40435">SEO SPECIALIST</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40434">VR Designer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/469/40433">Automation Tester</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/403/40432">Junior Frontend Developer (ReactJS)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40431">Software Test Engineer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40430">Senior UI Developer (React )</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40429">UI/UX Senior architect</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40428">Front End Developer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/249/40427">Senior ADF & Power BI Expert</a></div>, <div
class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40426">Software Engineer/ Senior Software Engineer - Odoo</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40425">Team Lead - Php</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40424">Lead - Automation Testing</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40423">Software Engineer/ Senior Software Engineer - PHP</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40422">Software Engineer/Senior Software Engineer - Moodle</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40421">Senior Software Engineer - React Native</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40420">Team Lead-React</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40419">iOS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40418">Flutter Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40417">React Native Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40416">Full Stack Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40415">Angular Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40414">React JS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40413">Node JS Developers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/159/40412">Junior Business Development Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40411">Team Lead - Node</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40410">Team Lead- Ruby on Rails</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/304/40409">Facility in Charge</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40408">Software Engineer/ Senior Software Engineer - Vue</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40407">Lead- UI/UX Designer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40406">Software Engineer/ Senior Software Engineer - React
Js</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40405">Software Engineer/ Senior Software Engineer - Node </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40404">Team Lead - GoLang</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40403">Associate - Business Development.</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40402">Team Lead - React Native</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40401">Lead - Business Analyst</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40400">Software Engineer/Sr.Software Engineer- IOS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40399">Assistant Manager – Business Development </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40398">Marketing Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40397">Associate Software Engineer-Freshers</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40396">Software Engineer/Senior Software Engineer-Ruby on Rails</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40395">Senior Software Engineer/ Team Lead - Magento</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40394">Software Engineer/Senior Software Engineer - Java</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/290/40393">SENIOR FULL STACK ENIGNEER - NODEJS/REACTJS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/290/40392">Front End Developer – ReactJS</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/209/40391">Software Engineer/Senior Software Engineer - .Net</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/262/40390">Administration Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40389">HR Manager</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40388">MAGENTO DEVELOPER</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40387">PHP DEVELOPER(1-3 YEAR EXP)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40386">SERVER ADMINISTRATOR (1- 4 YEAR ) WITH LINUX EXPERIENCE</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40385">Server Admin- Fresher</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40384">TESTING ENGINEER - TEAM LEAD (4+ Years)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40383">TESTING ENGINEER (2
- 5 YEARS EXP)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40382">PHP DEVELOPER (3+ YEAR)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40381">LARAVEL DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40380">REACT JS DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40379">UI DEVELOPER (0-2 YEAR)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40378">UI Developer(Minimum 1 year)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40377">UI DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40376">UI/UX DESIGNER</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/334/40375">Full Stack Developer-Java, Angular, Spring boot, Microservices</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40374">GRAPHIC DESIGNER - TEAM LEAD</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40373">Digital Marketing - Head</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40372">Social Media Marketing Executive</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40371">Content Writer (Urgent requirement)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/396/40370">Senior React.Js Developer </a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40369">Content Writer - Team Lead (Urgent requirement)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40368">PERFORMANCE MARKETING (DIGITAL MARKETING)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40367">Social Media Executive (1 - 3+ Years</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40366">SEO ANALYST (0-1 Year)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40365">SEO ANALYST</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40364">REACT NATIVE DEVELOPER(URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40363">Magento Developers(Min 2 year exp)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/258/40362">ANDROID DEVELOPER (URGENT REQUIREMENT)</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40361">Talent Acquisition Specialist</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40360">Cloud Specialist</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/161/40359">Software Engineer</a></div>, <div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/com
</code>```

I tried the below code but It didn't work.

```<code>res = requests.get(website_url, verify=False)
soup = BeautifulSoup(res.text, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
url = [tag.get('href') for tag in Links]
</code>```

答:
You need to use find to find the a tag within the div tags and then get the value of href tag from it -

```<code>from bs4 import BeautifulSoup
html = '<html><body><div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div></body></html>'
soup = BeautifulSoup(html, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
urls = [tag.find('a')['href'] for tag in Links]
</code>```
```<code>>>> Links
[<div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div>]
>>> urls
['https://example.com/companies/company/company-jobs/358/40440']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am working in Python web scrapping using beautiful soup. I couldn't extract 'href' tags and save them to a list.

[
React JS Developer
,
React.js Developers
,
Node JS Developer
,
React Native Developer
,
Python Full Stack Developers
,
SEO SPECIALIST
,
VR Designer
,
Automation Tester
,
Junior Frontend Developer (ReactJS)
,
Software Test Engineer
,
Senior UI Developer (React )
,
UI/UX Senior architect
,
Front End Developer
,
Senior ADF & Power BI Expert
,
Software Engineer/ Senior Software Engineer - Odoo
,
Team Lead - Php
,
Lead - Automation Testing
,
Software Engineer/ Senior Software Engineer - PHP
,
Software Engineer/Senior Software Engineer - Moodle
,
Senior Software Engineer - React Native
,
Team Lead-React
,
iOS Developers
,
Flutter Developers
,
React Native Developers
,
Full Stack Developers
,
Angular Developers
,
React JS Developers
,
Node JS Developers
,
Junior Business Development Executive
,
Team Lead - Node
,
Team Lead- Ruby on Rails
,
Facility in Charge
,
Software Engineer/ Senior Software Engineer - Vue
,
Lead- UI/UX Designer
,
Software Engineer/ Senior Software Engineer - React
Js
,
Software Engineer/ Senior Software Engineer - Node
,
Team Lead - GoLang
,
Associate - Business Development.
,
Team Lead - React Native
,
Lead - Business Analyst
,
Software Engineer/Sr.Software Engineer- IOS
,
Assistant Manager – Business Development
,
Marketing Executive
,
Associate Software Engineer-Freshers
,
Software Engineer/Senior Software Engineer-Ruby on Rails
,
Senior Software Engineer/ Team Lead - Magento
,
Software Engineer/Senior Software Engineer - Java
,
SENIOR FULL STACK ENIGNEER - NODEJS/REACTJS
,
Front End Developer – ReactJS
,
Software Engineer/Senior Software Engineer - .Net
,
Administration Executive
,
HR Manager
,
MAGENTO DEVELOPER
,
PHP DEVELOPER(1-3 YEAR EXP)
,
SERVER ADMINISTRATOR (1- 4 YEAR ) WITH LINUX EXPERIENCE
,
Server Admin- Fresher
,
TESTING ENGINEER - TEAM LEAD (4+ Years)
,
TESTING ENGINEER (2
- 5 YEARS EXP)
,
PHP DEVELOPER (3+ YEAR)
,
LARAVEL DEVELOPER (URGENT REQUIREMENT)
,
REACT JS DEVELOPER (URGENT REQUIREMENT)
,
UI DEVELOPER (0-2 YEAR)
,
UI Developer(Minimum 1 year)
,
UI DEVELOPER (URGENT REQUIREMENT)
,
UI/UX DESIGNER
,
Full Stack Developer-Java, Angular, Spring boot, Microservices
,
GRAPHIC DESIGNER - TEAM LEAD
,
Digital Marketing - Head
,
Social Media Marketing Executive
,
Content Writer (Urgent requirement)
,
Senior React.Js Developer
,
Content Writer - Team Lead (Urgent requirement)
,
PERFORMANCE MARKETING (DIGITAL MARKETING)
,
Social Media Executive (1 - 3+ Years
,
SEO ANALYST (0-1 Year)
,
SEO ANALYST
,
REACT NATIVE DEVELOPER(URGENT REQUIREMENT)
,
Magento Developers(Min 2 year exp)
,
ANDROID DEVELOPER (URGENT REQUIREMENT)
,
Talent Acquisition Specialist
,
Cloud Specialist
,
Software Engineer
,
<a href="https://example.com/companies/company/com

I tried the below code but It didn't work.

res = requests.get(website_url, verify=False)
soup = BeautifulSoup(res.text, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
url = [tag.get('href') for tag in Links]

Body:
You need to use find to find the a tag within the div tags and then get the value of href tag from it -

from bs4 import BeautifulSoup
html = '<html><body><div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div></body></html>'
soup = BeautifulSoup(html, 'lxml')
Links = soup.find_all("div", {'class': 'col-xs-6 col-md-4 mt5'},)
urls = [tag.find('a')['href'] for tag in Links]

>>> Links
[<div class="col-xs-6 col-md-4 mt5"><a href="https://example.com/companies/company/company-jobs/358/40440">React JS Developer</a></div>]
>>> urls
['https://example.com/companies/company/company-jobs/358/40440']


问:
How to check the number of points <=10 in Cypress
```<code>cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)
</code>```

How to make a check  <=10 ? Maybe to.have.length.most()
DOM

```<code><div id="base-table-[object Object]-body">
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
    <div class = "MuiGrid-root jss505"> </div>
</div>
</code>```

答:
You can use these assertions:

cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .its('length')
  .then((len) => {
    expect(len).to.be.lte(10)
  })
```
<p>Or,</p>
<pre class="lang-js prettyprint-override"><code>cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .its('length')
  .then((len) => {
    expect(len).to.be.within(0, 10)
  })
</code>```

Body:
cy.get('div[id="base-table-\[object\ Object\]-body"] > .MuiGrid-root, .jss505').should('have.length', 10)

How to make a check  <=10 ? Maybe to.have.length.most()
DOM

Body:
You can use these assertions:

cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .its('length')
  .then((len) => {
    expect(len).to.be.lte(10)
  })

Or,

cy.get('div[id="base-table-[object Object]-body"] > .MuiGrid-root, .jss505')
  .its('length')
  .then((len) => {
    expect(len).to.be.within(0, 10)
  })


问:
Should or should not strong password contain user name
So the question is is good practice to have such rule to deny users to have UserName in Passwords?

For example if user type UserName User so he can not have password which would contain User, or is it would be too hard to users?

May be better to just deny users to have UserName equal to Password but allow password to contain UserName?

What do you think?

According with that MS link http://windows.microsoft.com/en-AU/windows-vista/Tips-for-creating-a-strong-password strong passwords should not contain username.

答:
May be better to just deny users to have UserName equal to Password but allow password to contain UserName?

Disallowing equality is a good thing.

Going further leads to the anti-solution (noted by glowcoder half an hour before I got here).

ContentLicense: CC BY-SA 3.0


问:
Am I setting up the useStates correctly in which these datas will be saved in Firestore?
The context is that I have a product name where there will be sizes, colors, and quantities. The user can also add more sizes, color, and quantities of the same product and I will be saving this in Firestore.

For example:

Product Name: Shirt

Size: Large

Color: Red, Qty: 10

Color: Blue, Qty: 5

Size: M

Color: Red, Qty: 10

Color: Blue, Qty: 5

So in the form, the user should be able to add a size, add more colors and qty.
This is what I did:

Codes:
Link: https://codesandbox.io/s/form-2-add-more-size-ddqqo?file=/demo.js:0-5210

```<code>import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "" }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "" }]);
  };

  // color
  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setColorList(list);
  };

  // const handleColorStocksChange = (e, index) => {
  //   const { name, value } = e.target;
  //   const list = [...colorList];
  //   list[index][name] = value;
  //   setColorList(list);
  //   // console.log(colorList);
  // };

  // const handleColorChange = (e, index) => {
  //   const { value } = e.target;

  //   const arr = [...colorList]; //Shallow copy the existing state
  //   arr[index].color = value; //Update the size to the selected size
  //   console.log(arr[index].value);
  //   setColorList([...arr]); //Set the updated array to be the new state
  // };

  // const handleColorStocksChange = (e, index) => {
  //   const { value } = e.target;
  //   console.log(value);
  //   const arr = [...colorList];
  //   arr[index].colorStocks = value;
  //   // console.log(arr)
  //   setColorList([...arr]);
  // };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = () => {
    setColorList([...colorList, { color: "", colorStocks: "" }]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (
          <div key={index}>
            <TextField
              label="Size"
              type="text"
              name={`size${index}`}
              id={`size${index}`}
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {colorList.map((singleColor, index) => (
              <div key={index}>
                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorChange(e, index)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}
                <br />
                {colorList.length - 1 === index && (
                  <Button onClick={handleColorAdd}>Add Color</Button>
                )}
                <br /> <br />
                {/* add or remove sizes */}
              </div>
            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}
          </div>
        ))}

        <br />
        <Button type="submit">Submit </Button>
      </form>

      <div className="output">
        <h2>Output</h2>
        <h3>Sizes:</h3>
        {sizeList &&
          sizeList.map((singleSize, index) => (
            <ul key={index}>{singleSize.size && <li>{singleSize.size}</li>}</ul>
          ))}

        <br />
        <h3>Color:</h3>
        {colorList &&
          colorList.map((singleSize, index) => (
            <ul key={index}>
              {singleSize.color && (
                <li>{singleSize.color + " - " + singleSize.colorStocks}</li>
              )}
            </ul>
          ))}
      </div>
    </Box>
  );
}
</code>```

答:
For dynamic forms like this I like to keep all the state together so it's easy to expand/reduce the lists. It's also really important to not use mutation anywhere.</p>
```<code>const colorInit = { color: "", stocks: 0 };

const init = { size: "", colors: [colorInit] };

const A = () => {
  const [sizeList, setSizeList] = useState([init]);

  const addSize = () => {
    setSizeList([...sizeList, init]);
  };

  const addColor = (i) => {
    setSizeList(
      sizeList.map((s, ii) =>
        ii === i ? { ...s, colors: [...s.colors, colorInit] } : s
      )
    );
  };

  // The other two remove from list functions

  const updateSize = (i, size) => {
    setSizeList(sizeList.map((s, ii) => (ii === i ? { ...s, size } : s)));
  };

  // The other two update functions, using immutability
};
</code>```

Body:
The context is that I have a product name where there will be sizes, colors, and quantities. The user can also add more sizes, color, and quantities of the same product and I will be saving this in Firestore.

For example:

Product Name: Shirt

Size: Large

Color: Red, Qty: 10

Color: Blue, Qty: 5

Size: M

Color: Red, Qty: 10

Color: Blue, Qty: 5

So in the form, the user should be able to add a size, add more colors and qty.
This is what I did:

Codes:
Link: https://codesandbox.io/s/form-2-add-more-size-ddqqo?file=/demo.js:0-5210

import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "" }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "" }]);
  };

  // color
  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index] = { ...list[index] }; // copy the item too
    list[index][name] = value;
    setColorList(list);
  };

  // const handleColorStocksChange = (e, index) => {
  //   const { name, value } = e.target;
  //   const list = [...colorList];
  //   list[index][name] = value;
  //   setColorList(list);
  //   // console.log(colorList);
  // };

  // const handleColorChange = (e, index) => {
  //   const { value } = e.target;

  //   const arr = [...colorList]; //Shallow copy the existing state
  //   arr[index].color = value; //Update the size to the selected size
  //   console.log(arr[index].value);
  //   setColorList([...arr]); //Set the updated array to be the new state
  // };

  // const handleColorStocksChange = (e, index) => {
  //   const { value } = e.target;
  //   console.log(value);
  //   const arr = [...colorList];
  //   arr[index].colorStocks = value;
  //   // console.log(arr)
  //   setColorList([...arr]);
  // };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = () => {
    setColorList([...colorList, { color: "", colorStocks: "" }]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (

            <TextField
              label="Size"
              type="text"
              name={`size${index}`}
              id={`size${index}`}
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {colorList.map((singleColor, index) => (

                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorChange(e, index)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}

                {colorList.length - 1 === index && (
                  <Button onClick={handleColorAdd}>Add Color</Button>
                )}

                {/* add or remove sizes */}

            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}

        ))}

        <Button type="submit">Submit </Button>
      </form>

Output

Sizes:

        {sizeList &&
          sizeList.map((singleSize, index) => (

{singleSize.size &&
{singleSize.size}
}

          ))}

Color:

        {colorList &&
          colorList.map((singleSize, index) => (

              {singleSize.color && (

{singleSize.color + " - " + singleSize.colorStocks}

              )}

          ))}

    </Box>
  );
}

Body:
For dynamic forms like this I like to keep all the state together so it's easy to expand/reduce the lists. It's also really important to not use mutation anywhere.

const colorInit = { color: "", stocks: 0 };

const init = { size: "", colors: [colorInit] };

const A = () => {
  const [sizeList, setSizeList] = useState([init]);

  const addSize = () => {
    setSizeList([...sizeList, init]);
  };

  const addColor = (i) => {
    setSizeList(
      sizeList.map((s, ii) =>
        ii === i ? { ...s, colors: [...s.colors, colorInit] } : s
      )
    );
  };

  // The other two remove from list functions

  const updateSize = (i, size) => {
    setSizeList(sizeList.map((s, ii) => (ii === i ? { ...s, size } : s)));
  };

  // The other two update functions, using immutability
};


问:
Wordpress WP-Query issue when applying filters
I am trying apply filters to my Wordpress query. I am having issues with getting the author query to work. from my url I pass the name of the author however the filter is not working. I am still getting all post from all authors. Can someone point me in the right direction to query with author</p>
```<code>add_filter("wcra_pictures_callback", "wcra_pictures_callback_handler");

function wcra_pictures_callback_handler($param) {
  //$param = All GET/POST values will be received from endpoint

  // Get Posts
    $posts = get_posts([
        'post_type' => $param['post_type'],
        'author' => $param['author'],
        'orderby' => $param['orderby'],
        'order'   => $param['order'],
        'posts_per_page' => $param['posts_per_page'],
    ]);

  return $posts;
}
</code>```

答:
author expects you to pass the author ID, which is an int, and not the author name, if you want to query using author name, you should use author_name in which case you should pass the user_nicename and not the actual name of the author.

Ex.

```<code>$posts = get_posts([
  'post_type'      => $param['post_type'],
  'author_name'    => $param['author'], // the name must match the user_nice name in their profile
  'orderby'        => $param['orderby'],
  'order'          => $param['order'],
  'posts_per_page' => $param['posts_per_page'],
]);
</code>```

Body:
I am trying apply filters to my Wordpress query. I am having issues with getting the author query to work. from my url I pass the name of the author however the filter is not working. I am still getting all post from all authors. Can someone point me in the right direction to query with author

add_filter("wcra_pictures_callback", "wcra_pictures_callback_handler");

function wcra_pictures_callback_handler($param) {
  //$param = All GET/POST values will be received from endpoint

  // Get Posts
    $posts = get_posts([
        'post_type' => $param['post_type'],
        'author' => $param['author'],
        'orderby' => $param['orderby'],
        'order'   => $param['order'],
        'posts_per_page' => $param['posts_per_page'],
    ]);

  return $posts;
}

Body:
author expects you to pass the author ID, which is an int, and not the author name, if you want to query using author name, you should use author_name in which case you should pass the user_nicename and not the actual name of the author.

Ex.

$posts = get_posts([
  'post_type'      => $param['post_type'],
  'author_name'    => $param['author'], // the name must match the user_nice name in their profile
  'orderby'        => $param['orderby'],
  'order'          => $param['order'],
  'posts_per_page' => $param['posts_per_page'],
]);


问:
CSS React-bootsrap nav - width greater than browser width
This is bugging me because it only moves right to left slightly and everything is offset to the right because the width is flowing over.

I have set to my navbar properties:

```<code>.navbar{
    background: rgb(7, 102, 197);
    background: linear-gradient(0deg, rgba(7,101,195,1) 0%, rgba(0,72,144,1) 100%);
    padding:0;
    width: 100%;
}
</code>```

within index.css i also have width 100%

From the second image you can see it is greater

I did try applying:

```<code>overflow-x:hidden;
</code>```

But this doesn't remove the issue

答:
Have you set the width to 'device-width' in the HTML?

Because this 100% width is subjective to our device- your code works fine with the following tag added in HTML:

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

Body:
This is bugging me because it only moves right to left slightly and everything is offset to the right because the width is flowing over.

I have set to my navbar properties:

.navbar{
    background: rgb(7, 102, 197);
    background: linear-gradient(0deg, rgba(7,101,195,1) 0%, rgba(0,72,144,1) 100%);
    padding:0;
    width: 100%;
}

within index.css i also have width 100%

From the second image you can see it is greater

I did try applying:

overflow-x:hidden;

But this doesn't remove the issue


问:
How do you handle a mouse cursor in the FPS game?
I'm making an FPS game. In the FPS game, the mouse cursor is in the middle of the screen. So I put the mouse cursor in the center with the next code. But how can I solve this problem when the camera stutters very much every time I move the mouse?

SetCursorPos(CRenderMgr::GetInst()->GetResolution().fWidth / 2, CRenderMgr::GetInst()->GetResolution().fHeight / 2);
```

CRenderMgr::GetInst()->GetResolution() is Screen Width and height

答:
What you are doing is referred to as 'relative mode' mouse movement.

For classic Win32, this is typically done using "raw input". See this article.

If you want "raw input" to also to work in a Remote Desktop, see this code. In Remote Desktop, you don't get MOUSE_MOVE_RELATIVE data, and in normal desktop scenarios you never get MOUSE_MOVE_ABSOLUTE data.

For UWP, this is implemented as mentioned in this article.

You can see the Mouse class in the DirectX Tool Kit.

Body:
I'm making an FPS game. In the FPS game, the mouse cursor is in the middle of the screen. So I put the mouse cursor in the center with the next code. But how can I solve this problem when the camera stutters very much every time I move the mouse?

SetCursorPos(CRenderMgr::GetInst()->GetResolution().fWidth / 2, CRenderMgr::GetInst()->GetResolution().fHeight / 2);

CRenderMgr::GetInst()->GetResolution() is Screen Width and height


问:
MySQL: GROUP_CONCAT with an ORDER BY COUNT?
Is this possible ?

Let's say I have a list of addresses, with a lot of duplicate entries. I need to filter out all the duplicates, because some addresses have slightly different names but the same postalcode and telephone number.

First I do a GROUP BY on postalcode and telephone.

```<code>SELECT name, address, postalcode, place, phone
FROM addresses
GROUP BY postalcode, phone
</code>```

But then I get random names. I would like to get the best name, that is, the name with the most entries per postalcode/phone.

So I thought of the following. Here I use the SUBSTRING_INDEX function to only get the first item in the group_concat (there are no names with the string '~~' in it):

```<code>SELECT SUBSTRING_INDEX(
         GROUP_CONCAT(DISTINCT name ORDER BY COUNT(name) DESC SEPARATOR '~~')
       , '~~', 1),
       address,
       postalcode,
       place,
       phone
FROM addresses
GROUP BY postalcode, telephone
</code>```

but I get an 'invalid use of group function'.

How do I get the GROUP_CONCAT to order by the number of times the name occurs ?

答:
Found a solution myself, with a subquery:

```<code>SELECT
  SUBSTRING_INDEX(
    GROUP_CONCAT(DISTINCT name ORDER BY CountName DESC SEPARATOR '||')
  , '||', 1),
  address,
  postalcode,
  place,
  phone
FROM (

  SELECT name, address, postalcode, place, phone , COUNT(name) AS CountName
  FROM addresses
  GROUP BY name, postalcode, phone
  ORDER BY COUNT(name) DESC

) as a
GROUP BY postalcode, phone
</code>```

I wonder if it can be done without a subquery.

Body:
Is this possible ?

Let's say I have a list of addresses, with a lot of duplicate entries. I need to filter out all the duplicates, because some addresses have slightly different names but the same postalcode and telephone number.

First I do a GROUP BY on postalcode and telephone.

SELECT name, address, postalcode, place, phone
FROM addresses
GROUP BY postalcode, phone

But then I get random names. I would like to get the best name, that is, the name with the most entries per postalcode/phone.

So I thought of the following. Here I use the SUBSTRING_INDEX function to only get the first item in the group_concat (there are no names with the string '~~' in it):

SELECT SUBSTRING_INDEX(
         GROUP_CONCAT(DISTINCT name ORDER BY COUNT(name) DESC SEPARATOR '~~')
       , '~~', 1),
       address,
       postalcode,
       place,
       phone
FROM addresses
GROUP BY postalcode, telephone

but I get an 'invalid use of group function'.

How do I get the GROUP_CONCAT to order by the number of times the name occurs ?

Body:
Found a solution myself, with a subquery:

SELECT
  SUBSTRING_INDEX(
    GROUP_CONCAT(DISTINCT name ORDER BY CountName DESC SEPARATOR '||')
  , '||', 1),
  address,
  postalcode,
  place,
  phone
FROM (

  SELECT name, address, postalcode, place, phone , COUNT(name) AS CountName
  FROM addresses
  GROUP BY name, postalcode, phone
  ORDER BY COUNT(name) DESC

) as a
GROUP BY postalcode, phone

I wonder if it can be done without a subquery.


问:
Getting same response thrice using beautifulsoup
I'm trying to grab the email for a school project from this webpage, which I am successfully able to along with the name of the organization but now I'm having a new problem. Looks like its grabbing it 3 times, which is causing an issue to my lists. Removing Dupes in Post is not ideal in this situation. Anybody have any idea how I can just grab the email & organization name just 1 time?

Is it an issue with my for loop?

Code:

```<code>U4Etest1 = ['http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=26045','http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=36914']
email_list = []
org_name_list = []

for u in U4Etest1:
    url2 = u
    driver.get(url2)
    time.sleep(3)
    html = urlopen(url2)
    soup = BeautifulSoup(html, 'lxml')
    emailsoup = soup.find('table', class_="table table-striped")

    for es in emailsoup:
        org_name2 = emailsoup.find('h3').text
        org_name_list.append(org_name2)

        try:
            malito = emailsoup.find('a', {'target':'_top'})['href']
            email_list.append(malito)
        except:
            email_list.append('N/A')
        print(f'''
        Org Name: {org_name2}
        Email: {malito}
        ''')
</code>```

Output:

```<code>Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from
</code>```

答:
Firstly, why are you even using a for loop for html? Or Selenium, if you are not using it? Secondly, please always add imports and variables along with code.

Following code works for me:

```<code>import time
from bs4 import BeautifulSoup
from urllib.request import urlopen

urls = ['http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=26045',
        'http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=36914']
email_list = []
org_name_list = []

for url in urls:
    time.sleep(3)
    html = urlopen(url)
    soup = BeautifulSoup(html, 'lxml')
    email_soup = soup.find('table', class_="table table-striped")
    org_name = email_soup.find('h3').text
    org_name_list.append(org_name)
    try:
        malito = email_soup.find('a', {'target': '_top'})['href']
        email_list.append(malito)
        print(f'Org Name: {org_name} \nEmail: {malito}')
    except:
        email_list.append('N/A')
</code>```

Body:
I'm trying to grab the email for a school project from this webpage, which I am successfully able to along with the name of the organization but now I'm having a new problem. Looks like its grabbing it 3 times, which is causing an issue to my lists. Removing Dupes in Post is not ideal in this situation. Anybody have any idea how I can just grab the email & organization name just 1 time?

Is it an issue with my for loop?

Code:

U4Etest1 = ['http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=26045','http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=36914']
email_list = []
org_name_list = []

for u in U4Etest1:
    url2 = u
    driver.get(url2)
    time.sleep(3)
    html = urlopen(url2)
    soup = BeautifulSoup(html, 'lxml')
    emailsoup = soup.find('table', class_="table table-striped")

    for es in emailsoup:
        org_name2 = emailsoup.find('h3').text
        org_name_list.append(org_name2)

        try:
            malito = emailsoup.find('a', {'target':'_top'})['href']
            email_list.append(malito)
        except:
            email_list.append('N/A')
        print(f'''
        Org Name: {org_name2}
        Email: {malito}
        ''')

Output:

Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Eastern Elite
Email: mailto:julie_sherbeyn@ivcc.edu&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Org Name: Corpus Christi Legacy Volleyball Club
Email: mailto:cclegacyvc@gamil.com&cc=mnydam@clubvolleyballgear.com&subject=Club Volleyball Inquiry from

Body:
Firstly, why are you even using a for loop for html? Or Selenium, if you are not using it? Secondly, please always add imports and variables along with code.

Following code works for me:

import time
from bs4 import BeautifulSoup
from urllib.request import urlopen

urls = ['http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=26045',
        'http://www.usavolleyballclubs.com/VolleyballClubDirectory.asp?Customer_ID=36914']
email_list = []
org_name_list = []

for url in urls:
    time.sleep(3)
    html = urlopen(url)
    soup = BeautifulSoup(html, 'lxml')
    email_soup = soup.find('table', class_="table table-striped")
    org_name = email_soup.find('h3').text
    org_name_list.append(org_name)
    try:
        malito = email_soup.find('a', {'target': '_top'})['href']
        email_list.append(malito)
        print(f'Org Name: {org_name} \nEmail: {malito}')
    except:
        email_list.append('N/A')


问:
is there a way to display images in other php page?
I hope i am going to be clear with my problem. I am working on a project where I need to annotate images of vials with defects. I am at the stage where i have created a folder which contains the image's paths and is created based on the batch number. So each folder will be named differently dependig on the batch number. Now once all the images are uploaded, i want to retrieve them by running some queries so i get displayed in thumbnails all the images related to that batch. Now comes the tricky part (at least for me). I want to be able to click to the thumbnail and get redirected to the test.php page where i can see the image bigger, put in onto a canvas and make some annotation, but for some reason i am not able to retrieve the images. I am really desperate, any help would me much appreciated

<?php

require('db.php');

if (isset($_POST['mostra'])) {

    $batch_number = stripslashes($_REQUEST['batch_number']);
    $batch_number = mysqli_real_escape_string($con, $batch_number);
    $product_name = stripslashes($_REQUEST['product_name']);
    $product_name = mysqli_real_escape_string($con, $product_name);
    $vial_size = stripslashes($_REQUEST['vial_size']);
    $vial_size = mysqli_real_escape_string($con, $vial_size);
    $Sterile = $_POST['Sterile'];
    $Macchina = $_POST['Macchina'];

    if (!empty($batch_number)) {

        $select = mysqli_query($con, "SELECT vial_image FROM info_flaconi WHERE batch_number = '$batch_number' ");
        if(mysqli_num_rows($select)) {

            while($row=$select->fetch_assoc()){

                echo

                "";

            }

        }else{
            echo '
 No data available
';
        }
    }
}

?>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Import Immagini</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style_3.css">

</head>
<body>

<header>

    <div class="wrapper">
        <div class="logo">
            <img src="biotech.png" alt="">
        </div>
    <ul class="nav-area">
    <li>Home</li>
    <li>Contatti</li>
    <li>Logout</li>
    </ul>
    </div>
    <div class = "caricamento">
    <form action="" method="POST" enctype="multipart/form-data">

            <label> carica immagini flaconi: </label>

            <label> Inserisci numero batch: </label><input type = "text" name= "batch_number" placeholder="batch number">

            <label> Inserisci prodotto: </label><input type = "text" name= "product_name" placeholder="product name">

            <label> Inserisci grandezza flacone: </label><input type = "text" name= "vial_size" placeholder="vial size">

            <input type="submit" name="mostra" value="Mostra flaconi">
            <select name= "Sterile">
                <option value="" >--Select--</option>
                <option value="Sterile Area 1" >Sterile Area 1</option>
                <option value="Sterile Area 2" >Sterile Area 2</option>
                <option value="Sterile Area 3" >Sterile Area 3</option>
                <option value="Sterile Area 4" >Sterile Area 4</option>
                <option value="Sterile Area 5" >Sterile Area 5</option>
                <option value="Sterile Area 6" >Sterile Area 6</option>
                <option value="PDS" >PDS</option>
            </select>

            <select name= "Macchina">
                <option value="" >--Select--</option>
                <option value="Sedeneider" >Sedeneider</option>
                <option value="Groheninger" >Groheninger</option>
                <option value="Optrel400" >Optrel400</option>
            </select>

    </div>

    </form>
    <?php include 'scegli_immagine.php';?>

</header>
</body>

</html>  </code>```

The above code is needed in order to fetch all the images in thumbnails and be able to click on them

<?php

require('db.php');
include('upload.php');

$result=$_GET['vial'];
echo "";

if (isset($_REQUEST['submit'])) {
    $difetto = stripslashes ($_REQUEST['difetto']);
    $difetto = mysqli_real_escape_string($con, $difetto);
    $commenti = stripslashes($_REQUEST['commenti']);
    $commenti = mysqli_real_escape_string($con, $commenti);
    $query    = "INSERT INTO `annota` (difetto, commenti) VALUES ('$difetto', '$commenti')";
    $result   = mysqli_query($con, $query);
    if ($result) {
      echo "

Annotazione registrata correttamente

Clicca qui per una nuova annotazione.

";
    } else {
        echo "

Qualcosa è andato storto.

Clicca qui per riprovare di nuovo.

";
    }
}

?>

```

With this bit of code i am trying to display the image bigger but with no success

答:
This forum is not targeted for such a broad question, but here goes.  Come back when you have something more specific.

Write a web page that helps the user load a 'batch' into a directory.  (PHP has the functions for such.)  This page should create file names for each image.

Run through the files to build images to build thumbnails.  (See the image* routines.)  Suggest putting the thumbnails in the same directories, but with slightly different names.  (A suggestion: prefix the file name with t for thumbnail.)

Write another web page to show the list of batches; the user picks one; then the page shows the thumbnails in that batch.

The user picks a thumbnail and arrives at a page to allow annotation of the full image.  This may involve a 'canvas' with a background image (the file).  I don't know the details of how to annotate, but canvas has lots of capability.

Upon clicking a button, the canvas is written to a new file somewhere.

Steps 4 and 5 may be better done by some image editing produce -- "gimp" or any of several others.

I assumed that it is trivial to bring up an image in the 'next' page in a sequence, as your title asks about.  Here is a little more detail on it:

On the page where you click, say, a thumbnail, you use something like this once per image:

```<code><a href=step5.php?pic=t1234.jpg>
    <img src=t1234.jpg>
</a>
</code>```

I suggest stringing out the thumbnails using

```<code><my-wrap style='display:flex; flex-wrap:wrap'>
   ((many anchors and imgs as above))
</my-wrap>
</code>```

Body:
I hope i am going to be clear with my problem. I am working on a project where I need to annotate images of vials with defects. I am at the stage where i have created a folder which contains the image's paths and is created based on the batch number. So each folder will be named differently dependig on the batch number. Now once all the images are uploaded, i want to retrieve them by running some queries so i get displayed in thumbnails all the images related to that batch. Now comes the tricky part (at least for me). I want to be able to click to the thumbnail and get redirected to the test.php page where i can see the image bigger, put in onto a canvas and make some annotation, but for some reason i am not able to retrieve the images. I am really desperate, any help would me much appreciated

<?php

require('db.php');

if (isset($_POST['mostra'])) {

    $batch_number = stripslashes($_REQUEST['batch_number']);
    $batch_number = mysqli_real_escape_string($con, $batch_number);
    $product_name = stripslashes($_REQUEST['product_name']);
    $product_name = mysqli_real_escape_string($con, $product_name);
    $vial_size = stripslashes($_REQUEST['vial_size']);
    $vial_size = mysqli_real_escape_string($con, $vial_size);
    $Sterile = $_POST['Sterile'];
    $Macchina = $_POST['Macchina'];

    if (!empty($batch_number)) {

        $select = mysqli_query($con, "SELECT vial_image FROM info_flaconi WHERE batch_number = '$batch_number' ");
        if(mysqli_num_rows($select)) {

            while($row=$select->fetch_assoc()){

                echo

                "";

            }

        }else{
            echo '
 No data available
';
        }
    }
}

?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Import Immagini</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style_3.css">

Home

Contatti

Logout

    <form action="" method="POST" enctype="multipart/form-data">

             carica immagini flaconi:

             Inserisci numero batch: <input type = "text" name= "batch_number" placeholder="batch number">

             Inserisci prodotto: <input type = "text" name= "product_name" placeholder="product name">

             Inserisci grandezza flacone: <input type = "text" name= "vial_size" placeholder="vial size">

            <input type="submit" name="mostra" value="Mostra flaconi">
            <select name= "Sterile">
                <option value="" >--Select--</option>
                <option value="Sterile Area 1" >Sterile Area 1</option>
                <option value="Sterile Area 2" >Sterile Area 2</option>
                <option value="Sterile Area 3" >Sterile Area 3</option>
                <option value="Sterile Area 4" >Sterile Area 4</option>
                <option value="Sterile Area 5" >Sterile Area 5</option>
                <option value="Sterile Area 6" >Sterile Area 6</option>
                <option value="PDS" >PDS</option>
            </select>

            <select name= "Macchina">
                <option value="" >--Select--</option>
                <option value="Sedeneider" >Sedeneider</option>
                <option value="Groheninger" >Groheninger</option>
                <option value="Optrel400" >Optrel400</option>
            </select>

    </form>
    <?php include 'scegli_immagine.php';?>

The above code is needed in order to fetch all the images in thumbnails and be able to click on them

<?php

require('db.php');
include('upload.php');

$result=$_GET['vial'];
echo "";

if (isset($_REQUEST['submit'])) {
    $difetto = stripslashes ($_REQUEST['difetto']);
    $difetto = mysqli_real_escape_string($con, $difetto);
    $commenti = stripslashes($_REQUEST['commenti']);
    $commenti = mysqli_real_escape_string($con, $commenti);
    $query    = "INSERT INTO `annota` (difetto, commenti) VALUES ('$difetto', '$commenti')";
    $result   = mysqli_query($con, $query);
    if ($result) {
      echo "

Annotazione registrata correttamente

Clicca qui per una nuova annotazione.

";
    } else {
        echo "

Qualcosa è andato storto.

Clicca qui per riprovare di nuovo.

";
    }
}

?>

With this bit of code i am trying to display the image bigger but with no success

Body:
This forum is not targeted for such a broad question, but here goes.  Come back when you have something more specific.

Write a web page that helps the user load a 'batch' into a directory.  (PHP has the functions for such.)  This page should create file names for each image.

Run through the files to build images to build thumbnails.  (See the image* routines.)  Suggest putting the thumbnails in the same directories, but with slightly different names.  (A suggestion: prefix the file name with t for thumbnail.)

Write another web page to show the list of batches; the user picks one; then the page shows the thumbnails in that batch.

The user picks a thumbnail and arrives at a page to allow annotation of the full image.  This may involve a 'canvas' with a background image (the file).  I don't know the details of how to annotate, but canvas has lots of capability.

Upon clicking a button, the canvas is written to a new file somewhere.

Steps 4 and 5 may be better done by some image editing produce -- "gimp" or any of several others.

I assumed that it is trivial to bring up an image in the 'next' page in a sequence, as your title asks about.  Here is a little more detail on it:

On the page where you click, say, a thumbnail, you use something like this once per image:

<a href=step5.php?pic=t1234.jpg>
    <img src=t1234.jpg>
</a>

I suggest stringing out the thumbnails using

<my-wrap style='display:flex; flex-wrap:wrap'>
   ((many anchors and imgs as above))
</my-wrap>


问:
Git diff for n'th modified file?
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js
```
<p>and run</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/assets/stylesheets/application.scss
</code>```

then

git diff app/javascript/packs/application.js
```
<p>and so on..</p>
<pre class="lang-sh prettyprint-override"><code>git diff app/views/layouts/application.html.erb
</code>```

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

答:
You can use the search capability of less. That is, you type

```<code>git diff
</code>```

as always, then type /^diff to search for the hunk headers, then type n until you arrive at the file you are interested in. Type N to search backwards.

less remembers recently used search patterns. Next time around it suffices to type n. Use up- and down-arrows to cycle through recently used patterns.

Title: Git diff for n'th modified file?

Body:
Suppose we change several files, and want to view the diff for one at a time, I know we can use something like this

git status

Changes not staged for commit:
 directory)
    modified:   app/assets/stylesheets/application.scss
    modified:   app/javascript/packs/application.js
    modified:   app/views/layouts/application.html.erb
    modified:   config/webpack/environment.js

and run

git diff app/assets/stylesheets/application.scss

then

git diff app/javascript/packs/application.js

and so on..

git diff app/views/layouts/application.html.erb

To view each of the files' diffs one by one (one by one is desired here, but all the typing of file paths isn't, even with tab to auto complete).

Question

Is there a way to achieve the same (i.e. view git diff for a single file at a time) but without having to type (manually, nor with tab autocomplete) the full path to the changed file? (e.g. can we reference somehow, pseudo-code: git diff --mod_file 1, git diff --mod_file 2 etc) ?

Body:
You can use the search capability of less. That is, you type

git diff

as always, then type /^diff to search for the hunk headers, then type n until you arrive at the file you are interested in. Type N to search backwards.

less remembers recently used search patterns. Next time around it suffices to type n. Use up- and down-arrows to cycle through recently used patterns.


问:
Using createMany in Laravel returns null error when array used is populated
I have a $new collection which consists of an array, which I collect to allow me to run various filters using the Collection functions.

Using Log:info($new) my final collection prints out the following:

```<code>local.INFO: {"1":{"name":"11","position":1},"2":{"name":"22","position":2},"3":{"name":"33","position":3}}
</code>```

Once this is completed I use the following following method to create those records in my QueueLane model:

```<code>$new_records = $business->queue_lanes()->createMany($new);
</code>```

You can see I do this by inserting via a relationship from my $business variable which is just a Business model. The queue_lanes() is the name of my related relationship to the Business model.

When executing this line I get the following error:

[2022-01-29 06:18:01] local.ERROR: SQLSTATE[23502]: Not null
violation: 7 ERROR:  null value in column "name" violates not-null
constraint DETAIL:  Failing row contains (19, null, null, null,
2022-01-29 06:18:01, 2022-01-29 06:18:01, 1, 4, null). (SQL: insert
into "queue_lanes" ("name", "position", "business_id", "updated_at",
"created_at") values (?, 1, 4, 2022-01-29 06:18:01, 2022-01-29
06:18:01) returning "id") {"userId":4,"exception":"[object]
(Illuminate\Database\QueryException(code: 23502): SQLSTATE[23502]:
Not null violation: 7 ERROR:  null value in column "name" violates
not-null constraint DETAIL:  Failing row contains (19, null, null,
null, 2022-01-29 06:18:01, 2022-01-29 06:18:01, 1, 4, null). (SQL:
insert into "queue_lanes" ("name", "position", "business_id",
"updated_at", "created_at") values (?, 1, 4, 2022-01-29 06:18:01,
2022-01-29 06:18:01) returning "id") at
/Users/Username/Sites/test-app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:712)

The QueueLane model has a name and position attribute that should be populated but it looks like it isnt; and I can't tell why looking at the $new input array. The only possible cause I can think of is possible the array keys are what are being read as the column names instead of the nested arrays.

I also have the name attribute in my $fillable variable in my QueueLane model.

Edit:

I have tried running $new->each(function ($row, $key) use ($business) and inserting each $row record but this still brings up the same issue.

Second Edit:

My Business.php model

```<code>class Business extends Model
{
    protected $fillable = [
        'name',
        'business_type_id',
        'vanity_url',
        'allow_self_check_in',
        'enable_self_check_in',
        'enable_multi_queue',
        'multi_queue_active',
        'accept_new_entrants',
        'enable_shortest_option',
        'default_shortest',
    ];

    protected $casts = [
        'is_active'                 => 'boolean',
        'enable_sms_sender_id'      => 'boolean',
        'enable_self_check_in'      => 'boolean',
        'multi_queue_active'        => 'boolean',
        'allow_self_check_in'       => 'boolean',
        'accept_new_entrants'       => 'boolean',
        'enable_shortest_option'    => 'boolean',
        'default_shortest'          => 'boolean',
    ];
...
</code>```

QueueLane.php

```<code>...
class QueueLane extends Model
{

    use SoftDeletes;

    protected $fillable = [
        'name',
        'min_head_count',
        'max_head_count',
        'position',
        'business_id'
    ];
...
    const DEFAULT_QUEUE = '#Default';

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value == 'Default Queue' ? QueueLane::DEFAULT_QUEUE : $this->name;
    }

</code>```

I don't have a protected variable in my Business or QueueLane model.

答: Please check your QueueLane model where you have the setNameAttribute mutator which is causing the problem setting the name attribute value to null. In a mutator $this->name will return null.

Body:
I have a $new collection which consists of an array, which I collect to allow me to run various filters using the Collection functions.

Using Log:info($new) my final collection prints out the following:

local.INFO: {"1":{"name":"11","position":1},"2":{"name":"22","position":2},"3":{"name":"33","position":3}}

Once this is completed I use the following following method to create those records in my QueueLane model:

$new_records = $business->queue_lanes()->createMany($new);

You can see I do this by inserting via a relationship from my $business variable which is just a Business model. The queue_lanes() is the name of my related relationship to the Business model.

When executing this line I get the following error:

[2022-01-29 06:18:01] local.ERROR: SQLSTATE[23502]: Not null
violation: 7 ERROR:  null value in column "name" violates not-null
constraint DETAIL:  Failing row contains (19, null, null, null,
2022-01-29 06:18:01, 2022-01-29 06:18:01, 1, 4, null). (SQL: insert
into "queue_lanes" ("name", "position", "business_id", "updated_at",
"created_at") values (?, 1, 4, 2022-01-29 06:18:01, 2022-01-29
06:18:01) returning "id") {"userId":4,"exception":"[object]
(Illuminate\Database\QueryException(code: 23502): SQLSTATE[23502]:
Not null violation: 7 ERROR:  null value in column "name" violates
not-null constraint DETAIL:  Failing row contains (19, null, null,
null, 2022-01-29 06:18:01, 2022-01-29 06:18:01, 1, 4, null). (SQL:
insert into "queue_lanes" ("name", "position", "business_id",
"updated_at", "created_at") values (?, 1, 4, 2022-01-29 06:18:01,
2022-01-29 06:18:01) returning "id") at
/Users/Username/Sites/test-app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:712)

The QueueLane model has a name and position attribute that should be populated but it looks like it isnt; and I can't tell why looking at the $new input array. The only possible cause I can think of is possible the array keys are what are being read as the column names instead of the nested arrays.

I also have the name attribute in my $fillable variable in my QueueLane model.

Edit:

I have tried running $new->each(function ($row, $key) use ($business) and inserting each $row record but this still brings up the same issue.

Second Edit:

My Business.php model

class Business extends Model
{
    protected $fillable = [
        'name',
        'business_type_id',
        'vanity_url',
        'allow_self_check_in',
        'enable_self_check_in',
        'enable_multi_queue',
        'multi_queue_active',
        'accept_new_entrants',
        'enable_shortest_option',
        'default_shortest',
    ];

    protected $casts = [
        'is_active'                 => 'boolean',
        'enable_sms_sender_id'      => 'boolean',
        'enable_self_check_in'      => 'boolean',
        'multi_queue_active'        => 'boolean',
        'allow_self_check_in'       => 'boolean',
        'accept_new_entrants'       => 'boolean',
        'enable_shortest_option'    => 'boolean',
        'default_shortest'          => 'boolean',
    ];
...

QueueLane.php

...
class QueueLane extends Model
{

    use SoftDeletes;

    protected $fillable = [
        'name',
        'min_head_count',
        'max_head_count',
        'position',
        'business_id'
    ];
...
    const DEFAULT_QUEUE = '#Default';

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value == 'Default Queue' ? QueueLane::DEFAULT_QUEUE : $this->name;
    }

I don't have a protected variable in my Business or QueueLane model.


问:
Google Maps V2 API Pegman (Streetview)
How can I add the Pegman (little orange guy) to a google map using V2 API, so I can drag him from the google controls onto the map to switch to street view. I can see how to do this in the V3 API but cannot see how to do this in V2</p>

答: Although there may be some way to do it, pegman support was only added in Google Maps API v3 according to http://googlegeodevelopers.blogspot.com/2010/05/they-grow-up-so-fast.html.  So even if you figure out a way to do it, I wouldn't rely on it being robust.  Best thing to do, if you need pegman, is to upgrade to API v3.</p>

Title: Google Maps V2 API Pegman (Streetview)


问:
Using Kafka for batch job replacement
I am newbie with Kafka. Want to explore possibility of using Kafka to replace our batch job system currently in place.
Current system:
We get lots of feeds  EVERYDAY in flat files (CSVs, JSONs,TXTs and binary) from external vendors using FTPS, SFTP, Emails, fileshare etc.  I am ashamed to say that currently all logic resides in stored procedures and vbscript. I am trying to modernize whole pipeline using Apache Kafka to ingest all these feeds. I have explored Kafka and found that I can use Kafka Connect and KSQL and SpoolDir connector for this purpose however  I am not very clear on how to go about this.

Question:
I want to device system wherein I am able to ingest all incoming flat files (flat files mentioned earlier) using Kafka. I got that we can use Kafka connectors and KSQL or Streaming APIs to achiev this. Part I am not clear is how do I turn it into repetitive task using Kafka. Like every morning I get flat file feed in specific folder, how do I automate this process using Kafka like scheduling reading of files at specific time of day and every day? Do I need any kind of service (windows service or cron job) to constantly keep eye on folder to watch incoming files and process it? Is there any reasonable solution to go about it?

答:
Reminder that Kafka is not meant for file transfers. You can ingest data about the files (locations and sizes, for example, or extract data from them to produce rather than whole files), but you'll want to store and process their full contents elsewhere

Spooldir connector will work for local filesystems, but not over FTP. For that, there's another kafka-connect-fs project

However, I generally recommend combining Apache Nifi ListenFTP processors with ProduceKafka actions for something like this.

Nifi also has Email (IMAP/POP3) and NFS/Samba (fileshare) getters that can be scheduled, and it'll handle large files much better than Kafka.

KSQL and Streams API only work once the data is in Kafka

Title: Using Kafka for batch job replacement


问:
How to determine width of text in OpenSCAD?
In OpenSCAD, I want to be able to create a module which accepts a string then create a 3-D object with that string embedded in the surface as a text.  I want the object to be slightly larger than the text, so I need to know how wide the text is in order to create a properly-sized object.

I'm not sure how to query the width of the text (the height is set by an input variable), or if that's even possible.

If it's not possible, is there a function that will accept a string and a font and predict the width of the rendered text?

答:
I have found a way to determine the widths of text characters in OpenSCAD. I made a JavaScript thing that lets you input a font name and style, and it outputs an array of width proportions for ascii and extended ascii characters (codes 0-255). Then for any given character, you multiply this proportion by the font size to get the width of an individual character. From there it's trivial to get the width of a string, or the angular widths of characters wrapped around a cylinder.

The tool to generate the OpenSCAD width array is here: https://codepen.io/amatulic/pen/eYeBLva

...and the code is reproduced below, which you can run from this reply, or paste into your own HTML file and load into your browser locally.

Just input the font properties, click the button, and scroll down to see usage instructions.

The secret sauce lies in the fact that JavaScript's 'canvas' support has a  'measureText()' method that measures the pixel length of any text for a given font, used like this:

```<code>canvasContext.measureText(string).width
</code>```

So what this code does is use a dummy canvas on the page to get a context to which a font is assigned, arbitrarily 20 pixels in size. Then it generates an array of widths for every character from 0 to 255, dividing each by 20 to get a unitless width proportion compared to font size. It then outputs a line of OpenSCAD code that you can paste into your OpenSCAD script. Then you use OpenSCAD's ord() function to convert any character to a numeric code, which then serves as an index of the width array. You then multiply this width by the font size to get the character width.

OpenSCAD proportional font widths

  <form>
    <fieldset>
      <legend>Identify the font</legend>
      <input type="text" id="fontname" name="fontname" value="Liberation Sans">
      Font name

      <input type="text" id="fontstyle" name="fontstyle" value="bold">
      Font style (bold, italic, etc. or leave blank)

    </fieldset>
    <input type="button" onclick="generate()" value="Generate OpenSCAD font width proportions">
  </form>

Copy and paste this code into OpenSCAD

  <canvas id="canvas"></canvas>

```

Body:
I have found a way to determine the widths of text characters in OpenSCAD. I made a JavaScript thing that lets you input a font name and style, and it outputs an array of width proportions for ascii and extended ascii characters (codes 0-255). Then for any given character, you multiply this proportion by the font size to get the width of an individual character. From there it's trivial to get the width of a string, or the angular widths of characters wrapped around a cylinder.

The tool to generate the OpenSCAD width array is here: https://codepen.io/amatulic/pen/eYeBLva

...and the code is reproduced below, which you can run from this reply, or paste into your own HTML file and load into your browser locally.

Just input the font properties, click the button, and scroll down to see usage instructions.

The secret sauce lies in the fact that JavaScript's 'canvas' support has a  'measureText()' method that measures the pixel length of any text for a given font, used like this:

canvasContext.measureText(string).width

So what this code does is use a dummy canvas on the page to get a context to which a font is assigned, arbitrarily 20 pixels in size. Then it generates an array of widths for every character from 0 to 255, dividing each by 20 to get a unitless width proportion compared to font size. It then outputs a line of OpenSCAD code that you can paste into your OpenSCAD script. Then you use OpenSCAD's ord() function to convert any character to a numeric code, which then serves as an index of the width array. You then multiply this width by the font size to get the character width.

<html>
<!--
by Alex Matulich, February 2022
Thingiverse: https://www.thingiverse.com/amatulic/designs
Website: https://www.nablu.com
-->
<head>
  <script type="text/javascript">
    var sctx;

    function initialize() {
      var canvas = document.getElementById("canvas");
      sctx = canvas.getContext("2d");
    }

    function charwidth(fontname, style) {
      sctx.font = (style + " 20px " + fontname).trim();
      var charlen = [];
      for (i = 0; i < 256; ++i) //{ charlen[i] = 10; console.log(i); }
        charlen[i] = sctx.measureText(String.fromCharCode(i)).width / 20;
      return charlen;
    }

    function generate() {
      var fontname = document.getElementById("fontname").value;
      var fontstyle = document.getElementById("fontstyle").value;
      var widths = charwidth(fontname, fontstyle);
      var arrayname = toCamelCase(fontname) + toCamelCase(fontstyle);
      var outputhtml = arrayname + " = [<br/>\n" + widths[0].toString();
      var len = widths.length;
      for (i = 1; i < len; ++i) outputhtml += ', ' + widths[i].toString();
      outputhtml += "<br/>\n];\n";
      document.getElementById("output").innerHTML = outputhtml;
      document.getElementById('usage').innerHTML = "<h3>Usage</h3>\n<p>The array above shows character width as a multiple of font size. To get the width of a character <code>&lt;char&gt;</code> given font size <code>&lt;fontsize&gt;</code> using the font \"" + fontname + " " + fontstyle + "\":</p>\n<p><code>&nbsp; charwidth = " + arrayname + "[ord(char)] * fontsize;<code></p>\n";
      document.getElementById('sample').innerHTML = "<h3>Font sample</h3>\n<p style=\"font: " + fontstyle + " 20px " + fontname + ";\">" + fontname + " " + fontstyle + ": 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</p>\n";
    }
    // convert the input array to camel case
    function toCamelCase(stringinput) {
      if (stringinput.length == 0) return '';
      var inputArray = stringinput.match(/[A-Z\xC0-\xD6\xD8-\xDE]?[a-z\xDF-\xF6\xF8-\xFF]+|[A-Z\xC0-\xD6\xD8-\xDE]+(?![a-z\xDF-\xF6\xF8-\xFF])|\d+/g);
      result = "";
      for (let i = 0, len = inputArray.length; i < len; i++) {
        let currentStr = inputArray[i];
        let tempStr = currentStr.toLowerCase();
        // convert first letter to upper case (the word is in lowercase)
        tempStr = tempStr.substr(0, 1).toUpperCase() + tempStr.substr(1);
        result += tempStr;
      }
      return result;
    }
  </script>
</head>

<body onload="initialize()">
  <h1>OpenSCAD proportional font widths</h1>
  <form>
    <fieldset>
      <legend>Identify the font</legend>
      <input type="text" id="fontname" name="fontname" value="Liberation Sans">
      <label for="fontname">Font name</label><br />
      <input type="text" id="fontstyle" name="fontstyle" value="bold">
      <label for="fontstyle">Font style (bold, italic, etc. or leave blank)<br />
    </fieldset>
    <input type="button" onclick="generate()" value="Generate OpenSCAD font width proportions">
  </form>
  <h2>Copy and paste this code into OpenSCAD</h2>
  <div id="output" style="border:5px ridge silver; padding:1em; font-family:monospace;">
  </div>
  <div id="usage">
  </div>
  <div id="sample">
  </div>
  <canvas id="canvas"></canvas>
</body>
</html>


问:
In Pytorch F.nll_loss() Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'
Why does this error occur.

I am trying to write a custom loss function, that finally has a negative log likelihood.

As per my understanding the NLL is calculated between two probability values?

```<code>>>> loss = F.nll_loss(sigm, trg_, ignore_index=250, weight=None, size_average=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home//lib/python3.5/site-packages/torch/nn/functional.py", line 1332, in nll_loss
    return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'
</code>```

The inputs here being the following:

```<code>>>> sigm.size()
torch.Size([151414, 80])
>>> sigm
tensor([[ 0.3283,  0.6472,  0.8278,  ...,  0.6756,  0.2168,  0.5659],
        [ 0.6603,  0.5957,  0.8375,  ...,  0.2274,  0.4523,  0.4665],
        [ 0.5262,  0.4223,  0.5009,  ...,  0.5734,  0.3151,  0.2076],
        ...,
        [ 0.4083,  0.2479,  0.5996,  ...,  0.8355,  0.6681,  0.7900],
        [ 0.6373,  0.3771,  0.6568,  ...,  0.4356,  0.8143,  0.4704],
        [ 0.5888,  0.4365,  0.8587,  ...,  0.2233,  0.8264,  0.5411]])
</code>```

And my target tensor is:

```<code>>>> trg_.size()
torch.Size([151414])
>>> trg_
tensor([-7.4693e-01,  3.5152e+00,  2.9679e-02,  ...,  1.6316e-01,
         3.6594e+00,  1.3366e-01])
</code>```

If I convert this to long I loose all data:

```<code>>>> sigm.long()
tensor([[ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        ...,
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0]])
>>> trg_.long()
tensor([ 0,  3,  0,  ...,  0,  3,  0])
</code>```

If I convert the raw values of target tensor to sigmoid too:

```<code>>>> F.sigmoid(trg_)
tensor([ 0.3215,  0.9711,  0.5074,  ...,  0.5407,  0.9749,  0.5334])
>>> loss = F.nll_loss(sigm, F.sigmoid(trg_), ignore_index=250, weight=None, size_average=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lib/python3.5/site-packages/torch/nn/functional.py", line 1332, in nll_loss
    return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'
</code>```

This does calculate the loss happily, but it is again just make belief as I have lost data in the long conversion:

```<code>>>> loss = F.nll_loss(sigm, F.sigmoid(trg_).long(), ignore_index=250, weight=None, size_average=True)
>>> loss
tensor(-0.5010)

>>> F.sigmoid(trg_).long()
tensor([ 0,  0,  0,  ...,  0,  0,  0])
</code>```

答: running the code in Tensorflow 2 resolved it for me</p>

Body:
Why does this error occur.

I am trying to write a custom loss function, that finally has a negative log likelihood.

As per my understanding the NLL is calculated between two probability values?

>>> loss = F.nll_loss(sigm, trg_, ignore_index=250, weight=None, size_average=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home//lib/python3.5/site-packages/torch/nn/functional.py", line 1332, in nll_loss
    return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'

The inputs here being the following:

>>> sigm.size()
torch.Size([151414, 80])
>>> sigm
tensor([[ 0.3283,  0.6472,  0.8278,  ...,  0.6756,  0.2168,  0.5659],
        [ 0.6603,  0.5957,  0.8375,  ...,  0.2274,  0.4523,  0.4665],
        [ 0.5262,  0.4223,  0.5009,  ...,  0.5734,  0.3151,  0.2076],
        ...,
        [ 0.4083,  0.2479,  0.5996,  ...,  0.8355,  0.6681,  0.7900],
        [ 0.6373,  0.3771,  0.6568,  ...,  0.4356,  0.8143,  0.4704],
        [ 0.5888,  0.4365,  0.8587,  ...,  0.2233,  0.8264,  0.5411]])

And my target tensor is:

>>> trg_.size()
torch.Size([151414])
>>> trg_
tensor([-7.4693e-01,  3.5152e+00,  2.9679e-02,  ...,  1.6316e-01,
         3.6594e+00,  1.3366e-01])

If I convert this to long I loose all data:

>>> sigm.long()
tensor([[ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        ...,
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0],
        [ 0,  0,  0,  ...,  0,  0,  0]])
>>> trg_.long()
tensor([ 0,  3,  0,  ...,  0,  3,  0])

If I convert the raw values of target tensor to sigmoid too:

>>> F.sigmoid(trg_)
tensor([ 0.3215,  0.9711,  0.5074,  ...,  0.5407,  0.9749,  0.5334])
>>> loss = F.nll_loss(sigm, F.sigmoid(trg_), ignore_index=250, weight=None, size_average=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lib/python3.5/site-packages/torch/nn/functional.py", line 1332, in nll_loss
    return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'

This does calculate the loss happily, but it is again just make belief as I have lost data in the long conversion:

>>> loss = F.nll_loss(sigm, F.sigmoid(trg_).long(), ignore_index=250, weight=None, size_average=True)
>>> loss
tensor(-0.5010)

>>> F.sigmoid(trg_).long()
tensor([ 0,  0,  0,  ...,  0,  0,  0])


问:
How to send email in Hotmail's INBOX instead of JUNK using PHP?
As my question says, is there any possible way to send an email from your script into the inbox than junk ?
I used mail() and very variations with headers, then a lot of tests with PHPMailer , set SMTP etc but nothing. All of the emails are sent into the Junk folder.

I am curious on how I get so many newsletters or simple emails from blogs into my inbox and I can not send properly an email notification about a purchase that a user made.

I am using shared hosting on bluehost.

Please share me your thoughts or code (if there is any).

答:
Getting mail past the big mail provider's spam filters reliably requires more work and access than any single developer has.

You can start with things you can control, like RDNS records for your IP, SPF records for the mail server, setting up DomainKeys, etc. That'll help.

But you'll never negotiate the whitelist access legitimate e-mail companies have to get their mail to these clients and the daily work they do to stay on those whitelists and remove their IPs from blacklists.

The short answer: If you want programmatically sent mail to reach inboxes reliably, then use the services of someone in that business.

http://www.sendgrid.com

http://www.postmarkapp.com

http://aws.amazon.com/ses


问:
I need to write a trigger in oracle before insert statement using 2 tables
Table 1
RPA_DUTY_BUDGET

```<code>column : material
column : duty_budget
</code>```

Table 2
RPA_IMPORTS

```<code>column : material
column : grn
column : amount
column : duty_actuals
column : duty_budget
</code>```

When I need to insert the data into RPA_IMPORTS then I need to search for the material and its corresponding duty_budget from RPA_DUTY_BUDGET and insert those values.

I could easily achieve this by using a join, however the since the duty changes periodically it will take the latest duty, that is the reason, I need to store in RPA_IMPORTS for further calcualtion.

答:
This doesn't even require a join.

```<code>create or replace trigger trg_biu_imp
  before insert or update on rpa_imports
  for each row
begin
  select d.duty_budget
    into :new.duty_budget
    from rpa_imports i
    where i.material = :new.material;
end;
/
</code>```

Body:
Table 1
RPA_DUTY_BUDGET

column : material
column : duty_budget

Table 2
RPA_IMPORTS

column : material
column : grn
column : amount
column : duty_actuals
column : duty_budget

When I need to insert the data into RPA_IMPORTS then I need to search for the material and its corresponding duty_budget from RPA_DUTY_BUDGET and insert those values.

I could easily achieve this by using a join, however the since the duty changes periodically it will take the latest duty, that is the reason, I need to store in RPA_IMPORTS for further calcualtion.

Body:
This doesn't even require a join.

create or replace trigger trg_biu_imp
  before insert or update on rpa_imports
  for each row
begin
  select d.duty_budget
    into :new.duty_budget
    from rpa_imports i
    where i.material = :new.material;
end;
/


问:
FileHandler double logs string in a file
```<code>import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')

for handler in logger.handlers:
    handler.close()

logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')
</code>```

I am trying to understand why the above code logs B! string in logloglog.log file twice. It confuses me, since I log both A! and B! only one time. Can you help me?

答:
When a new log message arrives the file handler will automatically reopen the file.
so

```<code>for handler in logger.handlers:
    handler.close()
    logger.removeHandler(handler) // add this line.
</code>```

see the ref.

Body:
import logging

logger = logging.getLogger(__name__)
logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('A!')

for handler in logger.handlers:
    handler.close()

logger.addHandler(logging.FileHandler(filename='logloglog.log'))
logger.critical('B!')

I am trying to understand why the above code logs B! string in logloglog.log file twice. It confuses me, since I log both A! and B! only one time. Can you help me?

Body:
When a new log message arrives the file handler will automatically reopen the file.
so

for handler in logger.handlers:
    handler.close()
    logger.removeHandler(handler) // add this line.

see the ref.