问:
Scrape - How To Get Tag For Each Row
In this webpage I want to scrape the title and the URL for each row.

The tag for each row seems to be <div> but since there are a lot of divs, how do I ensure I am pulling the right one?

Screenshot of the multiple pages/articles attached
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/0mPXS.png

```<code>import requests
from bs4 import BeautifulSoup
from selenium import webdriver

productlinks=[]
url='https://journals.lww.com/ccmjournal/toc/2022/01001'

r=requests.get(url)
soup= BeautifulSoup(r.content,'html.parser')
content=soup.find_all('div')
for item in content:
    title=item.find('Title')
    link=item.find_element_by_css_selector('a').get_attribute('href')

</code>```

答:
Assuming you also want top two rows and not just the numbered articles you can use an attribute = value css selector with starts with operator to target the parent div element (for all listings), with id starting with itemListContainer, then specifically target the direct anchor tag children of h4 elements

```<code>import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
soup = bs(r.content, 'lxml')
d = {i.text.strip():i['href'] for i in soup.select('[id^=itemListContainer] h4 > a')}
</code>```

You can restrict to only numbered items with

```<code>d = {i.text.strip():i['href'] for i in soup.select('.ej-toc-subheader + div h4 > a')}
</code>```

The class selector gets you to the subheaders then the adjacent sibling combinator moves you, along with the type selector, to the immediately adjacent div. The h4 with child combinator (>) then a type selector  takes you to the target anchor tags.

If you want all results then you can set results to 100 per page then click next whilst that element is present. Use a pause to avoid being rate-limited:

```<code>from bs4 import BeautifulSoup as bs
from selenium import webdriver
import time

d = webdriver.Chrome()

d.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
results = {}

try:
    d.find_element_by_css_selector('.cookie-jar-content .button').click()
except:
    pass

d.find_element_by_css_selector('.js-items-on-page-selectize [value="100"]').click()

while True:
    soup = bs(d.page_source, 'lxml')

    for i in soup.select('.ej-toc-subheader + div h4 > a'):
        results[i.text.strip()] = i['href']

    next_page = soup.select_one('.element__nav--next')

    if next_page is None:
        break
    d.find_element_by_css_selector('.element__nav--next').click()
    time.sleep(1) # rate-limit
</code>```

Just with selenium

```<code>from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException

d = webdriver.Chrome()

d.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
results = {}

try:
    d.find_element_by_css_selector('.cookie-jar-content .button').click()
except NoSuchElementException:
    pass

d.find_element_by_css_selector('.js-items-on-page-selectize [value="100"]').click()

while True:

    for i in d.find_elements_by_css_selector('.ej-toc-subheader + div h4 > a'):
        results[i.text.strip()] = i.get_attribute('href')

    try:
        next_page = d.find_element_by_css_selector('.element__nav--next')

    except NoSuchElementException:
        break

    next_page.click()
    time.sleep(1) # rate-limit
d.close()
</code>```

Title: Scrape - How To Get Tag For Each Row

Body:
In this webpage I want to scrape the title and the URL for each row.

The tag for each row seems to be <div> but since there are a lot of divs, how do I ensure I am pulling the right one?

Screenshot of the multiple pages/articles attached
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/0mPXS.png

import requests
from bs4 import BeautifulSoup
from selenium import webdriver

productlinks=[]
url='https://journals.lww.com/ccmjournal/toc/2022/01001'

r=requests.get(url)
soup= BeautifulSoup(r.content,'html.parser')
content=soup.find_all('div')
for item in content:
    title=item.find('Title')
    link=item.find_element_by_css_selector('a').get_attribute('href')

Body:
Assuming you also want top two rows and not just the numbered articles you can use an attribute = value css selector with starts with operator to target the parent div element (for all listings), with id starting with itemListContainer, then specifically target the direct anchor tag children of h4 elements

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
soup = bs(r.content, 'lxml')
d = {i.text.strip():i['href'] for i in soup.select('[id^=itemListContainer] h4 > a')}

You can restrict to only numbered items with

d = {i.text.strip():i['href'] for i in soup.select('.ej-toc-subheader + div h4 > a')}

The class selector gets you to the subheaders then the adjacent sibling combinator moves you, along with the type selector, to the immediately adjacent div. The h4 with child combinator (>) then a type selector  takes you to the target anchor tags.

If you want all results then you can set results to 100 per page then click next whilst that element is present. Use a pause to avoid being rate-limited:

from bs4 import BeautifulSoup as bs
from selenium import webdriver
import time

d = webdriver.Chrome()

d.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
results = {}

try:
    d.find_element_by_css_selector('.cookie-jar-content .button').click()
except:
    pass

d.find_element_by_css_selector('.js-items-on-page-selectize [value="100"]').click()

while True:
    soup = bs(d.page_source, 'lxml')

    for i in soup.select('.ej-toc-subheader + div h4 > a'):
        results[i.text.strip()] = i['href']

    next_page = soup.select_one('.element__nav--next')

    if next_page is None:
        break
    d.find_element_by_css_selector('.element__nav--next').click()
    time.sleep(1) # rate-limit

Just with selenium

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException

d = webdriver.Chrome()

d.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
results = {}

try:
    d.find_element_by_css_selector('.cookie-jar-content .button').click()
except NoSuchElementException:
    pass

d.find_element_by_css_selector('.js-items-on-page-selectize [value="100"]').click()

while True:

    for i in d.find_elements_by_css_selector('.ej-toc-subheader + div h4 > a'):
        results[i.text.strip()] = i.get_attribute('href')

    try:
        next_page = d.find_element_by_css_selector('.element__nav--next')

    except NoSuchElementException:
        break

    next_page.click()
    time.sleep(1) # rate-limit
d.close()


来源: stackexchange

问:
Pointer to base virtual function vs direct call of base virtual function
Why do these two behave differently?

```<code>(obj.*lpfn)();
</code>```

vs

```<code>obj.Base::fn();
</code>```

I know when we directly call virtual member function (obj.fn()) it will do a virtual dispatch(find correct 'fn' implementation for type of obj, and call it). But why does a pointer to member function call that is set to Base implementation((obj.*lpfn)()) lead to virtual dispatch, and why does the same expression, except directly called (obj.Base::fn()) not do virtual dispatch? If anything, I would expect them both to do call base implementation of Print function(no virtualization)

```<code>#include <iostream>
class Base {
public:
    virtual void Print() { std::cout << "Base::Print();\n"; }
};
class Derived : public Base {
public:
    void Print() override { std::cout << "Derived::Print();\n"; }
};
int main() {
    Derived d;
    auto lpfn = &Base::Print;
    (d.*lpfn)();
    d.Base::Print();
}
</code>```

Output:

```<code>Derived::Print();
Base::Print();
</code>```

答:
But why does a pointer to member function call that is set to Base implementation((obj.*lpfn)()) lead to virtual dispatch

Because that's how the language is specified. Virtual dispatch is a useful tool, and so being able to use virtual dispatch through pointers to member functions is also useful.

why does the same expression, except directly called (obj.Base::fn()) not do virtual dispatch?

Because occasionally it's useful to be able to use static dispatch. And the way that the language was designed is that static dispatch can be done by specifying the static type with a qualified name.

There's no syntax in the language to use static dispatch through a pointer to virtual member function. I cannot tell you why that is, but I could guess that given that static dispatch of virtual function is rather rarely needed feature, and pointers to member functions are a rather rarely needed feature, it may be that their combination is so rarely needed that it wasn't really considered.

ContentLicense: CC BY-SA 4.0

Body:
Why do these two behave differently?

(obj.*lpfn)();

vs

obj.Base::fn();

I know when we directly call virtual member function (obj.fn()) it will do a virtual dispatch(find correct 'fn' implementation for type of obj, and call it). But why does a pointer to member function call that is set to Base implementation((obj.*lpfn)()) lead to virtual dispatch, and why does the same expression, except directly called (obj.Base::fn()) not do virtual dispatch? If anything, I would expect them both to do call base implementation of Print function(no virtualization)

#include <iostream>
class Base {
public:
    virtual void Print() { std::cout << "Base::Print();\n"; }
};
class Derived : public Base {
public:
    void Print() override { std::cout << "Derived::Print();\n"; }
};
int main() {
    Derived d;
    auto lpfn = &Base::Print;
    (d.*lpfn)();
    d.Base::Print();
}

Output:

Derived::Print();
Base::Print();


问:
Bootstrap/CSS Newbie: Dropdown not opening when clicked on (CDN should be installed correctly)
As title suggested, I cannot seem to get my Bootstrap dropdown to toggle correctly. Checked the other supports and it was suggested that CDN was not imported correctly. However, in my script, the JS is placed last. What may I be doing wrong? Tried with different browsers as well. Thanks for your help!

.Jumbotron {
  background-color: rgb(211, 211, 211);
  padding: 50px;
}

.my_modal {
  margin: 50px;
  background-color: green;
  border-color: green;
}

.my_modal:hover {
  background-color: darkgreen;
  border-color: darkgreen;
}

.my_modal:onclick {
  border-color: darkgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0 shrink-to-fit=no">
    <title>Bootstrap</title>

    <!-- Need this to run bootstrap that runs using CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <!-- Add style.css -->
    <link rel="stylesheet" href="style.css">
  </head>

  <body>

    <!-- Add A Navbar taken from Bootstrap -->
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container-fluid">
        Navbar
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
              Home
            </li>
            <li class="nav-item">
              Link
            </li>
            <li class="nav-item dropdown">

                Dropdown

              <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                <li>Action</li>
                <li>Another action</li>
                <li>
                  <hr class="dropdown-divider">
                </li>
                <li>Something else here</li>
              </ul>
            </li>
            <li class="nav-item">
              Disabled
            </li>
          </ul>
          <form class="d-flex">
            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success" type="submit">Search</button>
          </form>
        </div>
      </div>
    </nav>

    <!-- Add Jumbotron from Bootstrap -->
    <div class="Jumbotron">
      <h1 class="display-3">Hello World!</h1>
      <p class="lead">This is a simple hero unit, a simple jumbotron-style component
        for calling extra attention to featured content or information.</p>
      <hr class="my-4">
      <p>It uses utility classes for typography and spacing to space content out within
        the larger container.
      </p>
      <p class="lead">

          Learn more
      </p>
    </div>

    <!-- Add Modal from Bootstrap  -->
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary my_modal" data-bs-toggle="modal" data-bs-target="#exampleModal">
      Launch demo modal
    </button>

    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Need this to run bootstrap that runs using JS (lower priority than CSS) -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>

</html></code>```

答:
You are importing Bootstrap 4, however you are using the Bootstrap 5 dropdown.

You need to replace:

data-bs-toggle="dropdown"

With:

data-toggle="dropdown"

So, you will finally have:

```<code><button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>
</code>```

Bootstrap 4 Docs: https://getbootstrap.com/docs/4.6/components/dropdowns

Body:
As title suggested, I cannot seem to get my Bootstrap dropdown to toggle correctly. Checked the other supports and it was suggested that CDN was not imported correctly. However, in my script, the JS is placed last. What may I be doing wrong? Tried with different browsers as well. Thanks for your help!

.Jumbotron {
  background-color: rgb(211, 211, 211);
  padding: 50px;
}

.my_modal {
  margin: 50px;
  background-color: green;
  border-color: green;
}

.my_modal:hover {
  background-color: darkgreen;
  border-color: darkgreen;
}

.my_modal:onclick {
  border-color: darkgreen;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0 shrink-to-fit=no">
    <title>Bootstrap</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" href="style.css">

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

        </button>

              Home

              Link

                Dropdown

Action

Another action

Something else here

              Disabled

          <form class="d-flex">
            <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success" type="submit">Search</button>
          </form>

Hello World!

This is a simple hero unit, a simple jumbotron-style component
        for calling extra attention to featured content or information.

It uses utility classes for typography and spacing to space content out within
        the larger container.

          Learn more

    <button type="button" class="btn btn-primary my_modal" data-bs-toggle="modal" data-bs-target="#exampleModal">
      Launch demo modal
    </button>

Modal title

            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

            ...

            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>

Body:
You are importing Bootstrap 4, however you are using the Bootstrap 5 dropdown.

You need to replace:

data-bs-toggle="dropdown"

With:

data-toggle="dropdown"

So, you will finally have:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
  <span class="navbar-toggler-icon"></span>
</button>

Bootstrap 4 Docs: https://getbootstrap.com/docs/4.6/components/dropdowns


问:
My sprite cover the edges of other sprite Unity 2D
I'm working on a procedural world generation in Unity 2D. But when It spawns my blocks, blocks cover each other. What could be the possible problem? How can I fix it?

Thanks for your help.

Screenshot:
screenshot

答:
Okay, finally managed to solve it. For future people, here's the solution:

So when you export your sprite from Photoshop or whatever program you use, you export it with a preferred size (ex. 128×128 px).

What you need to do is, go ahead and click your .png file in Unity. In the inspector window, you will see an option called "Pixels Per Unit". You have to enter the correct sprite size there.

Apply the changes, and there you go!


问:
Deciding Which Class to Return in Factory
I'm  creating  a Product  abstract  class,  which  is supposed  to  be
subclassed  according  to  the   product  category  (each  category  has
different internal  logic but same interface,  hence I chose to  go with
abstraction model).  However, I want the  user to call a  factory method
which decides  what subclass to  return automatically. First, is  it bad
practice to include this factory method in the abstract class itself?

```<code>abstract class Product
{
    abstract public function getDescription();
    abstract public function getValue();

    public static function
    createProduct($category)
    {
        return # ...
    }
}
</code>```

How can I decide which subclass to return? Of course I could do a
switch-case:

```<code>switch($category) {
    case PROD_BOOK:
        return new Book();
        break;
    case PROD_FOOD:
        return new Food();
        break;
}
</code>```

But this kind of hard codes the  classes. When adding a new product, I'd
have to  add the new  constant for the  category and modify  the factory
logic. I'd like  to keep the factory  logic intact. Is there  any way to
make a table of category keys and class references as values? So I could
do something like:

```<code>return new ($classes[$category])();
</code>```

Then  I  just need  to  update  the  $classes  array when  adding  new
products.

答:
This is an already old and answered thread, but as I was looking for something similar, I post the solution I have found: For such an abstract class factory method, one could also use get_called_class() which would return the name of the sub class on which createProduct() was called.

```<code><?php
namespace Whatever;

abstract class Product
{
    public static function createProduct() {
        $class = get_called_class();
        /** @var  $inst Product */
        $inst = new $class();
        return $inst;
    }
}

class Book extends Product
{
}

class Food extends Product
{
}

$product = Book::createProduct();
var_dump($product);
</code>```

with such approach, there is no need for a map of sub classes in the abstract base class.

ContentLicense: CC BY-SA 3.0

Body:
I'm  creating  a Product  abstract  class,  which  is supposed  to  be
subclassed  according  to  the   product  category  (each  category  has
different internal  logic but same interface,  hence I chose to  go with
abstraction model).  However, I want the  user to call a  factory method
which decides  what subclass to  return automatically. First, is  it bad
practice to include this factory method in the abstract class itself?

abstract class Product
{
    abstract public function getDescription();
    abstract public function getValue();

    public static function
    createProduct($category)
    {
        return # ...
    }
}

How can I decide which subclass to return? Of course I could do a
switch-case:

switch($category) {
    case PROD_BOOK:
        return new Book();
        break;
    case PROD_FOOD:
        return new Food();
        break;
}

But this kind of hard codes the  classes. When adding a new product, I'd
have to  add the new  constant for the  category and modify  the factory
logic. I'd like  to keep the factory  logic intact. Is there  any way to
make a table of category keys and class references as values? So I could
do something like:

return new ($classes[$category])();

Then  I  just need  to  update  the  $classes  array when  adding  new
products.

Body:
This is an already old and answered thread, but as I was looking for something similar, I post the solution I have found: For such an abstract class factory method, one could also use get_called_class() which would return the name of the sub class on which createProduct() was called.

<?php
namespace Whatever;

abstract class Product
{
    public static function createProduct() {
        $class = get_called_class();
        /** @var  $inst Product */
        $inst = new $class();
        return $inst;
    }
}

class Book extends Product
{
}

class Food extends Product
{
}

$product = Book::createProduct();
var_dump($product);

with such approach, there is no need for a map of sub classes in the abstract base class.


问:
Embed a Powerpoint in a Web Page
Is there any way to embed a PowerPoint slide show in an HTML page using just the standard tags etc? I tried using a iframe, but that just results in the PowerPoint being downloaded.

```<code><iframe src="Chapter1.pptx">Your browser does not support.</iframe>
</code>```

I am looking for a way to show the slide show using only standard stuff. I realize I could use google docs or flash or something, but I'd rather have a simple implementation.

Does the web just not know how to process a PowerPoint presentation?

答:
Web browsers don't understand power point, but there are solutions besides Flash.

You could export it to HTML or a PDF.  Or you could also upload to site like slideshare and make use of their players which are built for this problem.

Title: Embed a Powerpoint in a Web Page

Body:
Is there any way to embed a PowerPoint slide show in an HTML page using just the standard tags etc? I tried using a iframe, but that just results in the PowerPoint being downloaded.

Your browser does not support.

I am looking for a way to show the slide show using only standard stuff. I realize I could use google docs or flash or something, but I'd rather have a simple implementation.

Does the web just not know how to process a PowerPoint presentation?


问:
Flutter Web with Authorization Code Flow - working example wanted
I am trying to get a Flutter v2 application working for Android, iOS and Web.  I have user logins working successfully, integrating with Auth0 using the Authorization Code Flow.

However, for the web version I have tried several libraries and guides. But I haven't been able to get it working and can't find a full working example.

Libraries and guides I've tried:

https://pub.dev/packages/openid_client

https://pub.dev/packages/simple_auth

https://github.com/MaikuB/flutter_appauth/issues/70

https://pub.dev/packages/flutter_appauth

https://pub.dev/packages/oauth2

https://robinjanke1.medium.com/oauth2-with-flutter-web-e7a2b0dac7f3

Are there any example working applications I could use as template/starting point?

答:
1. Example #1 with package: flutter_web_auth: ^0.4.0

example/lib/main.dart

```<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io' show HttpServer;

import 'package:flutter_web_auth/flutter_web_auth.dart';

const html = """
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Grant Access to Flutter</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html, body { margin: 0; padding: 0; }

    main {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
    }

    #icon {
      font-size: 96pt;
    }

    #text {
      padding: 2em;
      max-width: 260px;
      text-align: center;
    }

    #button a {
      display: inline-block;
      padding: 6px 12px;
      color: white;
      border: 1px solid rgba(27,31,35,.2);
      border-radius: 3px;
      background-image: linear-gradient(-180deg, #34d058 0%, #22863a 90%);
      text-decoration: none;
      font-size: 14px;
      font-weight: 600;
    }

    #button a:active {
      background-color: #279f43;
      background-image: none;
    }
  </style>
</head>
<body>
  <main>
    <div id="icon">🏇</div>
    <div id="text">Press the button below to sign in using your Localtest.me account.</div>
    <div id="button"><a href="foobar://success?code=1337">Sign in</a></div>
  </main>
</body>
</html>
""";

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _status = '';

  @override
  void initState() {
    super.initState();
    startServer();
  }

  Future<void> startServer() async {
    final server = await HttpServer.bind('127.0.0.1', 43823);

    server.listen((req) async {
      setState(() { _status = 'Received request!'; });

      req.response.headers.add('Content-Type', 'text/html');
      req.response.write(html);
      req.response.close();
    });
  }

  void authenticate() async {
    final url = 'http://localtest.me:43823/';
    final callbackUrlScheme = 'foobar';

    try {
      final result = await FlutterWebAuth.authenticate(url: url, callbackUrlScheme: callbackUrlScheme);
      setState(() { _status = 'Got result: $result'; });
    } on PlatformException catch (e) {
      setState(() { _status = 'Got error: $e'; });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Web Auth example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Status: $_status\n'),
              const SizedBox(height: 80),
              ElevatedButton(
                child: Text('Authenticate'),
                onPressed: () { this.authenticate(); },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

2. Example #2 with package: openidconnect

example/lib/main.dart

```<code>import 'package:flutter/material.dart';
import 'package:openidconnect_example/choose.dart';

void main() {
  runApp(MyApp());
}

//Credentials gathered from the playground
//login: dull-moth@example.com
//password: Yawning-Octopus-58

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChoosePage(),
    );
  }
}
</code>```

Body:
1. Example #1 with package: flutter_web_auth: ^0.4.0

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:io' show HttpServer;

import 'package:flutter_web_auth/flutter_web_auth.dart';

const html = """
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Grant Access to Flutter</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html, body { margin: 0; padding: 0; }

    main {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 100vh;
      font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
    }

    #icon {
      font-size: 96pt;
    }

    #text {
      padding: 2em;
      max-width: 260px;
      text-align: center;
    }

    #button a {
      display: inline-block;
      padding: 6px 12px;
      color: white;
      border: 1px solid rgba(27,31,35,.2);
      border-radius: 3px;
      background-image: linear-gradient(-180deg, #34d058 0%, #22863a 90%);
      text-decoration: none;
      font-size: 14px;
      font-weight: 600;
    }

    #button a:active {
      background-color: #279f43;
      background-image: none;
    }
  </style>
</head>
<body>
  <main>
    <div id="icon">&#x1F3C7;</div>
    <div id="text">Press the button below to sign in using your Localtest.me account.</div>
    <div id="button"><a href="foobar://success?code=1337">Sign in</a></div>
  </main>
</body>
</html>
""";

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _status = '';

  @override
  void initState() {
    super.initState();
    startServer();
  }

  Future<void> startServer() async {
    final server = await HttpServer.bind('127.0.0.1', 43823);

    server.listen((req) async {
      setState(() { _status = 'Received request!'; });

      req.response.headers.add('Content-Type', 'text/html');
      req.response.write(html);
      req.response.close();
    });
  }

  void authenticate() async {
    final url = 'http://localtest.me:43823/';
    final callbackUrlScheme = 'foobar';

    try {
      final result = await FlutterWebAuth.authenticate(url: url, callbackUrlScheme: callbackUrlScheme);
      setState(() { _status = 'Got result: $result'; });
    } on PlatformException catch (e) {
      setState(() { _status = 'Got error: $e'; });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Web Auth example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Status: $_status\n'),
              const SizedBox(height: 80),
              ElevatedButton(
                child: Text('Authenticate'),
                onPressed: () { this.authenticate(); },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

2. Example #2 with package: openidconnect

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:openidconnect_example/choose.dart';

void main() {
  runApp(MyApp());
}

//Credentials gathered from the playground
//login: dull-moth@example.com
//password: Yawning-Octopus-58

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ChoosePage(),
    );
  }
}


问:
DMARC without SPF
Although it is not possible to implement a complete DMARC policy with only SPF, due to forwarded emails, is it still possibible to implement a proper DMARC policy with only DKIM?</p>

答:
Yes, it's possible to protect an e-mail domain via DMARC policy solely with the DKIM digital signing technique in place.

The reason is that DMARC requires either SPF OR DKIM checks to pass, not necessarily both.

For more details see: https://datatracker.ietf.org/doc/html/rfc7489#section-2.1 or this similar question: https://serverfault.com/q/812367/268257

However such setup would limit DMARC policy protection only to "header From:" addresses that are typically visible to recipients.

To protect also the invisible "envelope sender" addresses (aka MAIL FROM or Return-Path), used for receiving bounces (Non-Delivery Reports), it's recommended to use the SPF, which is focused on that.

The SPF is also useful when sending emails to recipients that are lacking DMARC support as it gives them at least some hints about sender's authorization.

Thus the best setup is to combine both DKIM and SPF.

Title: DMARC without SPF


问:
Set the value of a textArea Aframe to a variable
I'm wondering how using JavaScript, I can set the text="" value of a textArea in A-frame to a variable. For example, the textArea should start out with the default text value set to it, but I've created a variable called txtValue, what should happen is when the button is clicked at the top, the text will update to the value of the variable called txtValue. So the textarea text will change from the default text to whatever value txtValue is set to. How can this be done? Fiddle with code: https://jsfiddle.net/AidanYoung/9ma1j7gy/6/

答:
You should originally set the Value attribute of your input property to be whatever you want it to be. lets say your variable: textValue. Then add an eventlistener to listen on on "change" event.
alike:</p>
```<code>------HTML
<label>Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>
------------JS
<div class="result"></div>
const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});
</code>```

Body:
You should originally set the Value attribute of your input property to be whatever you want it to be. lets say your variable: textValue. Then add an eventlistener to listen on on "change" event.
alike:

------HTML
<label>Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>
------------JS
<div class="result"></div>
const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});


问:
Internet Explorer 9 and Chrome don't handle set-cookie headers
I am testing my website which works fine with Iron, Firefox and Opera, now using Internet Explorer 9, and Chrome. It sets two important cookies in every browser, except for IE9 and Chrome. It seems the set-cookie headers are ignored by these browsers. Until I lowered security and privacy settings, Facebook's cookies were missing too in Internet Explorer (except for cookies from skype.com, there weren't any cookies at all inside IE).

The cookies are set for the domain modern-iq.appspot.com (the alpha version of this project is accessible at http://modern-iq.appspot.com). It doesn't contain underscores and it looks standard-compliant to me.

Independent of the actual path, I always choose "/" for my cookies.
The domain is always modern-iq.appspot.com (no cross-domain cookies). There are no iframes.

UPDATE: I did the following tests:

work

Iron 12.0.750.0 (88853) on Ubuntu (64-bit): cookies work

Firefox 6.0 on Ubuntu (64-bit): cookies work

Firefox 3.6.13 on Windows XP: cookies work

Firefox (unknown version) on Windows 7: cookies work

don't work

Internet Explorer 9 on Windows 7: cookies don't work

Chrome 13.0.782.112 m on Windows XP: cookies don't work

UPDATE: Request logs of failing Chrome and working Iron:

requestlog-chrome.har (cookies ignored)

requestlog-chrome.txt (cookies ignored)

requestlog-iron.har (cookies kept)

requestlog-iron.txt (cookies kept)

The questionable cookies are fb_user and fb_access_token at the end of the request chain.

set_cookie calls (Python):

```<code>set_cookie(self.response, FACEBOOK_USER_COOKIE_NAME, str(profile["id"]), domain='modern-iq.appspot.com',
                   expires=time.time() + COOKIE_EXPIRY_SPAN) #30 * 86400)
set_cookie(self.response, FACEBOOK_ACCESS_TOKEN_COOKIE_NAME, str(access_token), domain='modern-iq.appspot.com',
                   expires=time.time() + COOKIE_EXPIRY_SPAN) #30 * 86400)
</code>```

set_cookie (Python):

```<code>def set_cookie(response, name, value, domain=None, path="/", expires=None):
    """Generates and signs a cookie for the give name/value"""
    for domain in domain, : #'localhost':
        logging.info('DOING COOKIE OF DOMAIN '+repr(domain)+'...')
        timestamp = str(int(time.time()))
        value = base64.b64encode(value)
        signature = cookie_signature(value, timestamp)
        cookie = Cookie.BaseCookie()
        cookie[name] = "|".join([value, timestamp, signature])
        cookie[name]["path"] = path
        if domain: cookie[name]["domain"] = domain
        if expires:
            cookie[name]["expires"] = email.utils.formatdate(
                expires, localtime=False, usegmt=True)
        response.headers._headers.append(("Set-Cookie", cookie.output()[12:]))
</code>```

答:
You need to set a P3P header that reflects the privacy policies related to the cookie.
http://blogs.msdn.com/b/ieinternals/archive/2010/06/05/understanding-internet-explorer-cookie-controls.aspx</p>

Body:
I am testing my website which works fine with Iron, Firefox and Opera, now using Internet Explorer 9, and Chrome. It sets two important cookies in every browser, except for IE9 and Chrome. It seems the set-cookie headers are ignored by these browsers. Until I lowered security and privacy settings, Facebook's cookies were missing too in Internet Explorer (except for cookies from skype.com, there weren't any cookies at all inside IE).

The cookies are set for the domain modern-iq.appspot.com (the alpha version of this project is accessible at http://modern-iq.appspot.com). It doesn't contain underscores and it looks standard-compliant to me.

Independent of the actual path, I always choose "/" for my cookies.
The domain is always modern-iq.appspot.com (no cross-domain cookies). There are no iframes.

UPDATE: I did the following tests:

work

Iron 12.0.750.0 (88853) on Ubuntu (64-bit): cookies work

Firefox 6.0 on Ubuntu (64-bit): cookies work

Firefox 3.6.13 on Windows XP: cookies work

Firefox (unknown version) on Windows 7: cookies work

don't work

Internet Explorer 9 on Windows 7: cookies don't work

Chrome 13.0.782.112 m on Windows XP: cookies don't work

UPDATE: Request logs of failing Chrome and working Iron:

requestlog-chrome.har (cookies ignored)

requestlog-chrome.txt (cookies ignored)

requestlog-iron.har (cookies kept)

requestlog-iron.txt (cookies kept)

The questionable cookies are fb_user and fb_access_token at the end of the request chain.

set_cookie calls (Python):

set_cookie(self.response, FACEBOOK_USER_COOKIE_NAME, str(profile["id"]), domain='modern-iq.appspot.com',
                   expires=time.time() + COOKIE_EXPIRY_SPAN) #30 * 86400)
set_cookie(self.response, FACEBOOK_ACCESS_TOKEN_COOKIE_NAME, str(access_token), domain='modern-iq.appspot.com',
                   expires=time.time() + COOKIE_EXPIRY_SPAN) #30 * 86400)

set_cookie (Python):

def set_cookie(response, name, value, domain=None, path="/", expires=None):
    """Generates and signs a cookie for the give name/value"""
    for domain in domain, : #'localhost':
        logging.info('DOING COOKIE OF DOMAIN '+repr(domain)+'...')
        timestamp = str(int(time.time()))
        value = base64.b64encode(value)
        signature = cookie_signature(value, timestamp)
        cookie = Cookie.BaseCookie()
        cookie[name] = "|".join([value, timestamp, signature])
        cookie[name]["path"] = path
        if domain: cookie[name]["domain"] = domain
        if expires:
            cookie[name]["expires"] = email.utils.formatdate(
                expires, localtime=False, usegmt=True)
        response.headers._headers.append(("Set-Cookie", cookie.output()[12:]))


问:
Is there a way to call a java method that extends a webdriver class?
I am working with the WebDriverManager java library. It provides a generic manager that can be parameterized to act as a specific manager (for Chrome, Firefox, etc.). I am using it with Selenium Webdriver and Junit 5's @Parameterized and @ValueSource annotations so that I can run my tests on multiple browsers.
I created an implementation as per the WebDriverManager documentation:

```<code> public class WebTest {

 WebDriver driver = null;

 @ParameterizedTest
 @ValueSource(classes = { ChromeDriver.class, FirefoxDriver.class })
 public void navigateToUrl(String url, Class<? extends WebDriver> webDriverClass) { //WebDriver class gets extended
 driver = WebDriverManager.getInstance(webDriverClass).create();
 driver.manage().window().maximize();
 driver.get(url);
</code>```

In the class containing my Cucumber step definitions, I tried calling the navigateToUrl method, but there was a compilation error like this:

```<code>  public class WebAppStepDefinitions {
  private final WebTest webTest = new WebTest();

  @Given("^I have navigated to the web url \"([^\"]*)\"$")
  public void navigateToUrl(String url) {
  webTest.navigateToUrl(url, Class<? extends WebDriver > webDriverClass); //error on this line: `Cannot resolve symbol webDriverClass`
  }
</code>```

How Do I correctly call the navigateToUrl located in the WebTest class?

答:
According to the @ValueSource documentation, you cannot use this annotation to pass instances of some class. This annotation can be used only to pass primitive values, strings, and CLASSES (not objects). You can use the classes to test if some method or some object is an instance of the parameter class. You cannot use it to pass instances to a method.

INSTEAD, what you can do is use the @MethodSource API to pass the name of the method that can provide (return) those instances for you (look for the paragraph talking about multiple arguments). For example, I think you can do something like this:

```<code>@ParameterizedTest
@MethodSource("getWebDrivers")
public void navigateToUrl(String url, List<WebDriver> drivers) {
 driver = WebDriverManager.getInstance(webDriverClass).create();
 driver.manage().window().maximize();
 driver.get(url);
}

public Stream<Arguments> getWebDriversAndUrl() {
    List<WebDrivers> drivers = new ArrayList<>();
    ... // Here you need to instantiate your drivers (skip if you have them already instantiated and set as global variables.
    drivers.add(chromeDriver);
    drivers.add(firefoxDriver);
    return return Stream.of(
        arguments("url1", drivers),
        arguments("url2", drivers);
}
</code>```

UPDATE:

Your implementation has a compile error because you failed to declare the parameter for the web driver class in the step definition. The step definition has only one argument. This line

```<code>webTest.navigateToUrl(String url, Class<? extends WebDriver > webDriverClass);
</code>```

needs to be

```<code>webTest.navigateToUrl(url, webDriverClass);
</code>```

The problem is that you have an URL that you are passing as an argument in the step definition, but not a Class object.

If you are calling the method from inside the step definition, you don't even need to use @ValueSource. All you need is a data table and pass the parameters that way directly from the step definition:

```<code>@Given("^I have navigated to the web url$")
public void navigateToUrl(DataTable table) {
    List<list> data = table.raw();
    // iterate thru list and call driver.get(url);

}
</code>```

Your test step should be something like this:

```<code>Given I have navigated to the web url
| url | chrome |
| url | firefox |
</code>```

Since you cannot pass the Class instance directly because it is not a data type supported by Cucumber, and creating a custom type is more trouble than it is worth for this use case. You will use the WebDriverManager to getIntance() using the browser name instead of the driver class.

Body:
I am working with the WebDriverManager java library. It provides a generic manager that can be parameterized to act as a specific manager (for Chrome, Firefox, etc.). I am using it with Selenium Webdriver and Junit 5's @Parameterized and @ValueSource annotations so that I can run my tests on multiple browsers.
I created an implementation as per the WebDriverManager documentation:

 public class WebTest {

 WebDriver driver = null;

 @ParameterizedTest
 @ValueSource(classes = { ChromeDriver.class, FirefoxDriver.class })
 public void navigateToUrl(String url, Class<? extends WebDriver> webDriverClass) { //WebDriver class gets extended
 driver = WebDriverManager.getInstance(webDriverClass).create();
 driver.manage().window().maximize();
 driver.get(url);

In the class containing my Cucumber step definitions, I tried calling the navigateToUrl method, but there was a compilation error like this:

  public class WebAppStepDefinitions {
  private final WebTest webTest = new WebTest();

  @Given("^I have navigated to the web url \"([^\"]*)\"$")
  public void navigateToUrl(String url) {
  webTest.navigateToUrl(url, Class<? extends WebDriver > webDriverClass); //error on this line: `Cannot resolve symbol webDriverClass`
  }

How Do I correctly call the navigateToUrl located in the WebTest class?

Body:
According to the @ValueSource documentation, you cannot use this annotation to pass instances of some class. This annotation can be used only to pass primitive values, strings, and CLASSES (not objects). You can use the classes to test if some method or some object is an instance of the parameter class. You cannot use it to pass instances to a method.

INSTEAD, what you can do is use the @MethodSource API to pass the name of the method that can provide (return) those instances for you (look for the paragraph talking about multiple arguments). For example, I think you can do something like this:

@ParameterizedTest
@MethodSource("getWebDrivers")
public void navigateToUrl(String url, List<WebDriver> drivers) {
 driver = WebDriverManager.getInstance(webDriverClass).create();
 driver.manage().window().maximize();
 driver.get(url);
}

public Stream<Arguments> getWebDriversAndUrl() {
    List<WebDrivers> drivers = new ArrayList<>();
    ... // Here you need to instantiate your drivers (skip if you have them already instantiated and set as global variables.
    drivers.add(chromeDriver);
    drivers.add(firefoxDriver);
    return return Stream.of(
        arguments("url1", drivers),
        arguments("url2", drivers);
}

UPDATE:

Your implementation has a compile error because you failed to declare the parameter for the web driver class in the step definition. The step definition has only one argument. This line

webTest.navigateToUrl(String url, Class<? extends WebDriver > webDriverClass);

needs to be

webTest.navigateToUrl(url, webDriverClass);

The problem is that you have an URL that you are passing as an argument in the step definition, but not a Class object.

If you are calling the method from inside the step definition, you don't even need to use @ValueSource. All you need is a data table and pass the parameters that way directly from the step definition:

@Given("^I have navigated to the web url$")
public void navigateToUrl(DataTable table) {
    List<list> data = table.raw();
    // iterate thru list and call driver.get(url);

}

Your test step should be something like this:

Given I have navigated to the web url
| url | chrome |
| url | firefox |

Since you cannot pass the Class instance directly because it is not a data type supported by Cucumber, and creating a custom type is more trouble than it is worth for this use case. You will use the WebDriverManager to getIntance() using the browser name instead of the driver class.


问:
I switched my project to x64 and got an error
I have this project that I'm working on for a while now, and it was working just fine before I switched from releasing an x86 version to an x64 one.

This is the line of code where the error appeared:

```<code>ReadProcessMemory(a.hProcess, LPCVOID(b->Ebx + 8), LPVOID(&c), 4, 0);
</code>```

I don't understand assembly but when the Error appeared at b->Ebx I changed it to b->Rbx. and it compiled and run but it didn't do the job it was supposed to do.

Am I using the wrong register?

After a little bit of debugging

```<code>pe_dos_h = PIMAGE_DOS_HEADER(pe_image);

pe_nt_h = PIMAGE_NT_HEADERS(DWORD(pe_image) + pe_dos_h->e_lfanew);

//error when trying to assign a value or access the signature in nt-headers
//ERROR: read access violation
IMAGE_NT_HEADERS* pe_nt_h->Signature == IMAGE_NT_SIGNATURE;//0x00004550-PE00
</code>```

The pe_image is raw data copied from a PE(.exe) file. Is the difference is in handling x86 PE image vs x64 one?

This is a simplified version of the code. If you think the problem is out of the scope of this piece of code let me know.

答:
The problem was in the way I was defining the IMAGE_SECTION_HEADER, In x64 architecture, I had to use the x64-specific datatype IMAGE_SECTION_HEADER64.

and also when casting pe_nt_h = PIMAGE_NT_HEADERS(DWORD_PTR(pe_image) + pe_dos_h->e_lfanew);

I had to use DWORD_PTR instead of just DWORD because it was missing some bits.

here is the solution code for the simplified version I provided in the post:

```<code>  PIMAGE_DOS_HEADER pe_dos_h = PIMAGE_DOS_HEADER(pe_image);

  PIMAGE_NT_HEADERS64 pe_nt_h = PIMAGE_NT_HEADERS(DWORD_PTR(pe_image) + pe_dos_h->e_lfanew);

</code>```

Body:
I have this project that I'm working on for a while now, and it was working just fine before I switched from releasing an x86 version to an x64 one.

This is the line of code where the error appeared:

ReadProcessMemory(a.hProcess, LPCVOID(b->Ebx + 8), LPVOID(&c), 4, 0);

I don't understand assembly but when the Error appeared at b->Ebx I changed it to b->Rbx. and it compiled and run but it didn't do the job it was supposed to do.

Am I using the wrong register?

After a little bit of debugging

pe_dos_h = PIMAGE_DOS_HEADER(pe_image);

pe_nt_h = PIMAGE_NT_HEADERS(DWORD(pe_image) + pe_dos_h->e_lfanew);

//error when trying to assign a value or access the signature in nt-headers
//ERROR: read access violation
IMAGE_NT_HEADERS* pe_nt_h->Signature == IMAGE_NT_SIGNATURE;//0x00004550-PE00

The pe_image is raw data copied from a PE(.exe) file. Is the difference is in handling x86 PE image vs x64 one?

This is a simplified version of the code. If you think the problem is out of the scope of this piece of code let me know.

Body:
The problem was in the way I was defining the IMAGE_SECTION_HEADER, In x64 architecture, I had to use the x64-specific datatype IMAGE_SECTION_HEADER64.

and also when casting pe_nt_h = PIMAGE_NT_HEADERS(DWORD_PTR(pe_image) + pe_dos_h->e_lfanew);

I had to use DWORD_PTR instead of just DWORD because it was missing some bits.

here is the solution code for the simplified version I provided in the post:

  PIMAGE_DOS_HEADER pe_dos_h = PIMAGE_DOS_HEADER(pe_image);

  PIMAGE_NT_HEADERS64 pe_nt_h = PIMAGE_NT_HEADERS(DWORD_PTR(pe_image) + pe_dos_h->e_lfanew);


问:
Can I use a .NET attribute without depending on the assembly that defines it?
I am unclear about the rules regarding attributes and assembly dependencies.

Is it possible (and not a terrible idea) to annotate the types in an assembly with custom attributes from a NuGet package without introducing a run-time dependency on that NuGet package?  Could clients use the types in the assembly without also needing to have the custom package's assemblies present?

I ask because My .NET application uses two packages:

A third party NuGet package called YamlDotNet for serializing types to YAML.  It lets you control YAML serialization with custom attributes analogous to Microsoft's XML attributes (e.g. it has YamlIgnoreAttribute like MS' XmlIgnoreAttribute)

My own package, PackageA which does not depend upon YamlDotNet.

I want my app to serialize my types from PackageA using YamlDotNet.  But they will not serialize correctly unless I do one of the following:

annotate the types in PackageA with YamlDotNet custom attributes

create annotated wrappers for PackageA types in the App to do the serialization for me.

I can do #2, but it would be easier to do #1.   But I do not want to introduce a run-time dependency on YamlDotNet for all clients of PackageA.  Ideally, I would like anybody using PackageA who also happens to be using YamlDotNet to get those attibutes for free and for them to be invisible to anyone else.

Is what I want possible?

答:
Attributes are a compile-time feature, you will always need reference to YamlDotNet in order to use one of its types as compile-time type metadata, unless you are open to doing things like generating your model classes in run-time (which is quite probably way more troublesome than having a one extra package reference).

This is a general problem where using attribute-driven features of a serializer pollutes the target assembly and couples it with that serializer.

There are three ways to address this:

Accept this as a compromise

Move YamlDotNet-specific into a separate assembly

Have a separate serialization model

The first point should be quite clear - this is what you don't want and your first ssuggestion.

The second point could be creating YamlDotNet-specific type wrappers or type converters (if it supports such things) in a separate assembly so that the core assembly stays clean. This is your second suggestion, just with a twist of converters that may be more pleasant than wrapping everything from consumer perspective.

The third point is about creating DTOs/payloads in the core assembly so that you never have to use any serializer-specific attributes and the serialization just works out of the box. If you need to [YamlIgnore] properties, the model used for serialization probably also serves other purposes so this is basically just a separation of concerns. If you serialize your application model, you might find it impossible to provide backwards compatibility without affecting business logic at various places as a result.


问:
curl is downloading the html rather than the actual zip file from gitlab
ever time i try and download my artifact from GitLab i seen to get the html in a file rather than the xip files it's self.

I have found loads of similar stuff on here but none of the solutions work.

i have tried -l, -O -o changed the oupt file using --ouptput filename.zip, and it always download an html file.

link...

https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build

how do i change the command so it downloads the actual file?

full command :

```<code>curl  https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build --output filename.zip
</code>```

tried this with an access toke setup

```<code>curl 'https://gitlab.com/dafabe/example/-/jobs/artifacts/master/raw/build/hello?job=build&private_token=<private token here>'
</code>```

I get this responce...

```<code><html><body>You are being <a href="https://gitlab.com/users/sign_in">redirected</a>.</body></html>
</code>```

most recent attempt and results...

ubuntu-trusty-64:~/stuff$ curl -L -H "PRIVATE-TOKEN:> xxxxx"
  https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build
  --output filename.zip   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed 100    98  100    98    0     0    189      0 --:--:-- --:--:--
  --:--:--   189   0     0    0 19509    0     0  23717      0 --:--:-- --:--:-- --:--:--  168k vagrant@vagrant-ubuntu-trusty-64:~/stuff$ ls filename.zip vagrant@vagrant-ubuntu-trusty-64:~/stuff$ file -b
  filename.zip HTML document, UTF-8 Unicode text, with very long lines
  vagrant@vagrant-ubuntu-trusty-64:~/stuff$

答:
Another approach would be to use the Gitlab API https://docs.gitlab.com/ee/api/job_artifacts.html#download-the-artifacts-archive

Using the following script:

```<code>#!/bin/bash

ACCESS_TOKEN=$1
PROJECT_ID=$2
BRANCH=$3

PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN"  "https://gitlab.com/api/v4/projects/$PROJECT_ID/pipelines?ref=$BRANCH" | jq '.[0].id')
JOB_ID=$(curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/pipelines/$PIPELINE_ID/jobs" | jq '.[] | select(.name=="build") | .id')

wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: $ACCESS_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/jobs/$JOB_ID/artifacts" -O artifacts.zip
</code>```

This script takes 3 arguments

Your private access token

Your Project ID

The target Branch

Add returns the artifacts as artifacts.zip for the latest execution for the job build

Body:
ever time i try and download my artifact from GitLab i seen to get the html in a file rather than the xip files it's self.

I have found loads of similar stuff on here but none of the solutions work.

i have tried -l, -O -o changed the oupt file using --ouptput filename.zip, and it always download an html file.

link...

https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build

how do i change the command so it downloads the actual file?

full command :

curl  https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build --output filename.zip

tried this with an access toke setup

curl 'https://gitlab.com/dafabe/example/-/jobs/artifacts/master/raw/build/hello?job=build&private_token=<private token here>'

I get this responce...

You are being redirected.

most recent attempt and results...

ubuntu-trusty-64:~/stuff$ curl -L -H "PRIVATE-TOKEN:> xxxxx"
  https://gitlab.com/dafabe/example/-/jobs/artifacts/master/download?job=build
  --output filename.zip   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed 100    98  100    98    0     0    189      0 --:--:-- --:--:--
  --:--:--   189   0     0    0 19509    0     0  23717      0 --:--:-- --:--:-- --:--:--  168k vagrant@vagrant-ubuntu-trusty-64:~/stuff$ ls filename.zip vagrant@vagrant-ubuntu-trusty-64:~/stuff$ file -b
  filename.zip HTML document, UTF-8 Unicode text, with very long lines
  vagrant@vagrant-ubuntu-trusty-64:~/stuff$

Body:
Another approach would be to use the Gitlab API https://docs.gitlab.com/ee/api/job_artifacts.html#download-the-artifacts-archive

Using the following script:

#!/bin/bash

ACCESS_TOKEN=$1
PROJECT_ID=$2
BRANCH=$3

PIPELINE_ID=$(curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN"  "https://gitlab.com/api/v4/projects/$PROJECT_ID/pipelines?ref=$BRANCH" | jq '.[0].id')
JOB_ID=$(curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/pipelines/$PIPELINE_ID/jobs" | jq '.[] | select(.name=="build") | .id')

wget -U "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.17 (KHTML,like Gecko) Ubuntu/11.04 Chromium/11.0.654.0 Chrome/11.0.654.0 Safari/534.17" --header "PRIVATE-TOKEN: $ACCESS_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID/jobs/$JOB_ID/artifacts" -O artifacts.zip

This script takes 3 arguments

Your private access token

Your Project ID

The target Branch

Add returns the artifacts as artifacts.zip for the latest execution for the job build


问:
Android Studio, center image and detect where tapped area inside image
I'm trying to create a centered image on top of the title screen of the app. It should be like a pop-up sort of, and when the user taps on the bottom 1/4 image the app should open a URL, and tapping on the top 3/4 should do nothing. This is the view layout:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgBeach"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:scaleType="fitCenter"
        app:srcCompat="@drawable/adpopup_test_image" />

</RelativeLayout>
</code>```

I've attached an onTouchListener to the imgBeach which checks the position of the touch-event.

```<code>imgBeach.setOnTouchListener(this);

//..

@Override
public boolean onTouch(View v, MotionEvent event) {

    // set value to dataobject and set possibly corrected value in textview
    if (v == imgBeach) {

        // where clicked in image, get image position
        int x = (int)event.getX();
        int y = (int)event.getY();

        if (y > (imgBeach.getHeight() * 3) / 4) {
            Log.d("My Title Screen", "BOTTOM 1/4!!");
            // open website..
            //Uri uriUrl = Uri.parse(getString(R.string.adpopupurl));
            //Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
            //startActivity(launchBrowser);
        } else {
            Log.d("My Title Screen", "TOP 3/4!!");
        }
    }

    return false;
}
</code>```

However, the problem is that the view for the image is extended to the top and bottom of the containing view, see yellow rectangle in screenshot below. So when onTouch gets called, then how can I detect if it's inside or outside the image? Or is it possible to designate touchAreas or something like that to the image?

答: You can put button  on image in bottom and in xml  :android:background="@null"</p>

Body:
I'm trying to create a centered image on top of the title screen of the app. It should be like a pop-up sort of, and when the user taps on the bottom 1/4 image the app should open a URL, and tapping on the top 3/4 should do nothing. This is the view layout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgBeach"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:scaleType="fitCenter"
        app:srcCompat="@drawable/adpopup_test_image" />

</RelativeLayout>

I've attached an onTouchListener to the imgBeach which checks the position of the touch-event.

imgBeach.setOnTouchListener(this);

//..

@Override
public boolean onTouch(View v, MotionEvent event) {

    // set value to dataobject and set possibly corrected value in textview
    if (v == imgBeach) {

        // where clicked in image, get image position
        int x = (int)event.getX();
        int y = (int)event.getY();

        if (y > (imgBeach.getHeight() * 3) / 4) {
            Log.d("My Title Screen", "BOTTOM 1/4!!");
            // open website..
            //Uri uriUrl = Uri.parse(getString(R.string.adpopupurl));
            //Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
            //startActivity(launchBrowser);
        } else {
            Log.d("My Title Screen", "TOP 3/4!!");
        }
    }

    return false;
}

However, the problem is that the view for the image is extended to the top and bottom of the containing view, see yellow rectangle in screenshot below. So when onTouch gets called, then how can I detect if it's inside or outside the image? Or is it possible to designate touchAreas or something like that to the image?


问:
Hide/Show Form Elements Not Working on Android App
I'm trying to create an interactive form. Your selections determine the next questions that appear. I'm using jQuery Mobile and it is working fine on the PC using Dreamweaver but when I build to Android the java scripts aren't working. This seems like simple code so I'm not sure why it's not working on Android. Can someone tell me where I'm going wrong?

Here's the code:

Javascript:

```<code>function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
</code>```

HTML:

```<code><div id=SkillSet data-role="fieldcontain">
      <fieldset data-role="controlgroup" data-type="horizontal">
        <legend>Skill Set:</legend>
        <a onclick="toggle_visibility('AV');"><input type="checkbox" name="SkillSet" id="SkillSet_0" class="custom" value="" /></a>
        <label for="SkillSet_0">AV</label>
        <a onclick="toggle_visibility('IT');"><input type="checkbox" name="SkillSet" id="SkillSet_1" class="custom" value="" /></a>
        <label for="SkillSet_1">IT</label>
      </fieldset>
    </div>

   <div id="IT" style="display:none">
    <hr>

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

答:
Try attaching the functions to window.

```<code>window.toggle_visibility = function(id) {
   var e = document.getElementById(id).style.display;
   e=="block" ? e="none" : e="block";
}
</code>```

Although I'm sure there is something simpler with jquery for something like that.

Also, why are your check boxes inside of a tags?

Body:
I'm trying to create an interactive form. Your selections determine the next questions that appear. I'm using jQuery Mobile and it is working fine on the PC using Dreamweaver but when I build to Android the java scripts aren't working. This seems like simple code so I'm not sure why it's not working on Android. Can someone tell me where I'm going wrong?

Here's the code:

Javascript:

function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}

HTML:

      <fieldset data-role="controlgroup" data-type="horizontal">
        <legend>Skill Set:</legend>
        <input type="checkbox" name="SkillSet" id="SkillSet_0" class="custom" value="" />
        AV
        <input type="checkbox" name="SkillSet" id="SkillSet_1" class="custom" value="" />
        IT
      </fieldset>

    Blah Blah Blah

Body:
Try attaching the functions to window.

window.toggle_visibility = function(id) {
   var e = document.getElementById(id).style.display;
   e=="block" ? e="none" : e="block";
}

Although I'm sure there is something simpler with jquery for something like that.

Also, why are your check boxes inside of a tags?


问:
Flutter: How to change the height of the cusror in the TextField

There is a property for changing the weight of the TextField cursor. Same I want to increase the height of the TextField cursor. Is there any way to do it ??

Here is the sample code of my TextField.

TextField(
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Username',
  ),
)

```

答:
Guess the accepted answer is outdated...</p>
```<code>TextField (style: TextStyle(height: 1.2))

</code>```

Body:
Guess the accepted answer is outdated...

TextField (style: TextStyle(height: 1.2))


问:
free shipping ... if shopping chart total is greater than $35 ... user input unless total is more $35 in JavaScript
I m not sure what i m doing wrong. Thanks in advance for helping me in this matter.

var sum = 0;
var pricecheck = 35;
while (sum < pricecheck) {
  var userinput = prompt("Please enter the cost of the item...");
  var num1 = parseInt(userinput);
  submitprice.push(num1);
  for (i = 0; i < submitprice.length; i++) {
    sum += submitprice[i];
  }
}
alert("free shipping.");```

答:
I took a look at this assignment again to refresh on what was asked for this question. You do not need to have that for loop at all within the while loop. Within each iteration of the while loop, you are asking the user for the price of their next item, adding it to the shopping cart, and also adding it to a running total (this total being your "sum"). This running total does not need to be re-calculated each time inside of the while loop because you would have done that in a single line. You are trying to calculate the price, starting at 0, each time you loop through the while loop (using your for loop). But this is not needed as you already have a running total that can be added to each time the user enters a value.

"Austin Caron" explained it well but for this assignment we do not need to do user authentication.

P.S. Try your best to avoid asking questions directly about an assignment and ask more general questions about a concept or idea you are struggling with.


问:
Why is the first method working but second isn't?
First Method:

```<code>const getWeatherIcon = (iconParameter) => {
   const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png`
   return <img src={icon} alt={iconParameter} />
  }
</code>```

```<code><div className="weathericon">
       {getWeatherIcon(weather.weather[0].icon)} //Ex: weather.weather[0].icon=50n
</div>
</code>```

Second Method:

```<code>const getWeatherIcon = (iconParameter) => {
    const icon = `assets/weather/${iconParameter}.svg`
    return <img src={icon} alt={iconParameter} />
  }
</code>```

```<code><div className="weathericon">
     {getWeatherIcon(weather.weather[0].main)} //Ex: weather.weather[0].main=Haze
</div>
</code>```

Here Is My Project Directory

```<code>src
│   App.js
│   index.css
│   index.js
│
└───assets
    └───weather
    |  |    Haze.svg
    │  |    Clear.svg
    │  |    Rain.svg
    |
    └───bg
        |   file111.png
        |   file112.png
</code>```

Ignore following

It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.

答: You file path is not correct try to use ./assets/weather to give proper path</p>

Body:
First Method:

const getWeatherIcon = (iconParameter) => {
   const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png`
   return
  }

       {getWeatherIcon(weather.weather[0].icon)} //Ex: weather.weather[0].icon=50n

Second Method:

const getWeatherIcon = (iconParameter) => {
    const icon = `assets/weather/${iconParameter}.svg`
    return
  }

     {getWeatherIcon(weather.weather[0].main)} //Ex: weather.weather[0].main=Haze

Here Is My Project Directory

src
│   App.js
│   index.css
│   index.js
│
└───assets
    └───weather
    |  |    Haze.svg
    │  |    Clear.svg
    │  |    Rain.svg
    |
    └───bg
        |   file111.png
        |   file112.png

Ignore following

It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.


问:
Problems with POST on DRF
Django Rest Framework, PostgreSQL.

Models:

class Manufacturer(models.Model):
    name = models.CharField(max_length=128)

class Product(models.Model):
    name = models.CharField(max_length=64)
    manufacturer = models.ForeignKey(
        Manufacturer, on_delete=models.CASCADE, related_name="products"
    )
```
<p>Serializers:</p>
<pre class="lang-py prettyprint-override"><code>class ManufacturerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Manufacturer
        fields = "__all__"

class ProductSerializer(serializers.ModelSerializer):
    manufacturer = ManufacturerSerializer(read_only=True)

    class Meta:
        model = Product
        fields = "__all__"
</code>```

Then I send a GET-request, I get the following response:

{
    "id": 1,
    "manufacturer": {
        "id": 1,
        "name": "Manufacturer 1"
    },
    "name": "Product 1"
}
```
<p>But then I send a POST-request,</p>
<pre class="lang-json prettyprint-override"><code>{
    "name": "Product 2",
    "manufacturer_id": 1
}
</code>```

I get the error:

```<code>null value in column "manufacturer_id" of relation "api_product" violates not-null constraint
DETAIL:  Failing row contains (2, Product 2, null).
</code>```

How to properly compose post-request?

答:
For your POST send this:

```<code>{
    "name": "Product 2",
    "manufacturer": 1
}
</code>```

You might also need to delete the whole row manufacturer = ManufacturerSerializer(read_only=True).

Title: Problems with POST on DRF

Body:
Django Rest Framework, PostgreSQL.

Models:

class Manufacturer(models.Model):
    name = models.CharField(max_length=128)

class Product(models.Model):
    name = models.CharField(max_length=64)
    manufacturer = models.ForeignKey(
        Manufacturer, on_delete=models.CASCADE, related_name="products"
    )

Serializers:

class ManufacturerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Manufacturer
        fields = "__all__"

class ProductSerializer(serializers.ModelSerializer):
    manufacturer = ManufacturerSerializer(read_only=True)

    class Meta:
        model = Product
        fields = "__all__"

Then I send a GET-request, I get the following response:

{
    "id": 1,
    "manufacturer": {
        "id": 1,
        "name": "Manufacturer 1"
    },
    "name": "Product 1"
}

But then I send a POST-request,

{
    "name": "Product 2",
    "manufacturer_id": 1
}

I get the error:

null value in column "manufacturer_id" of relation "api_product" violates not-null constraint
DETAIL:  Failing row contains (2, Product 2, null).

How to properly compose post-request?

Body:
For your POST send this:

{
    "name": "Product 2",
    "manufacturer": 1
}

You might also need to delete the whole row manufacturer = ManufacturerSerializer(read_only=True).


问:
Is there an addon which you can test css selectors in firefox?
I was wondering if there is such an addon in firefox where you can test out css paths to check if they are finding the correct element?  I was looking for something similar to xpather for xpath locations.</p>

答:
FireFinder is good, but I started with and prefer FirePath for Firebug. It works similarly, but can give you an expanded view of the HTML around the matching elements w/o need to click inspect, FriendlyFire, etc.

The field where you test the locator also has syntax checker where field turns red if syntax is bad. Just click eval to test the locator and matches show below with additional HTML around the matching elements.

But for testing CSS locator, you'd want the drop down option of "Sizzle" rather than CSS in FirePath. The CSS option only works for simple CSS selectors, complex ones only work under Sizzle (l mode, such as:

div.namedService.photoService > div.photoBrowserContainer:nth-child(3) > div.albumName:contains('someName')

ContentLicense: CC BY-SA 2.5