问:
How to get UIImage from AnyPublisher<UIImage?, Never> Swift 5 (Combine framework)
Im trying to figure how to use Reusable Image Cache in Swift with a UIImageView. I am trying to simply assign the ImageLoader() variable's, actual image to a UIImageView so I can use it as a UIImage.

Code:

```<code>let loader = ImageLoader()

myImage.image = loader.loadImage(from: myUrl)
</code>```

maybe:

```<code>loader.loadImage(from: myUrl)

myImage.image = loader(image)
</code>```

But this give a cannot call value of non-function type 'ImageLoader' error

Code:

```<code>final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
    if let image = cache[url] {
        return Just(image).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTaskPublisher(for: url)
        .map { UIImage(data: $0.data) }
        .catch { error in return Just(nil) }
        .handleEvents(receiveOutput: {[unowned self] image in
            guard let image = image else { return }
            self.cache[url] = image
        })
        .subscribe(on: DispatchQueue.global(qos: .background))
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}
}
</code>```

答:
You are trying to set the publisher result to the ImageView. You need to use something like this:</p>

```<code> class SomeTestClass {

    let imageView = UIImageView()
    var subscriptions = Set<AnyCancellable>()

    func loadImage() {

        ImageLoader().loadImage(from: URL(string: "someURL")!).sink { (image) in
            self.imageView.image = image
        }.store(in: &subscriptions)

    }
}
</code>```

Body:
Im trying to figure how to use Reusable Image Cache in Swift with a UIImageView. I am trying to simply assign the ImageLoader() variable's, actual image to a UIImageView so I can use it as a UIImage.

Code:

let loader = ImageLoader()

myImage.image = loader.loadImage(from: myUrl)

maybe:

loader.loadImage(from: myUrl)

myImage.image = loader(image)

But this give a cannot call value of non-function type 'ImageLoader' error

Code:

final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
    if let image = cache[url] {
        return Just(image).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTaskPublisher(for: url)
        .map { UIImage(data: $0.data) }
        .catch { error in return Just(nil) }
        .handleEvents(receiveOutput: {[unowned self] image in
            guard let image = image else { return }
            self.cache[url] = image
        })
        .subscribe(on: DispatchQueue.global(qos: .background))
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}
}

Body:
You are trying to set the publisher result to the ImageView. You need to use something like this:

 class SomeTestClass {

    let imageView = UIImageView()
    var subscriptions = Set<AnyCancellable>()

    func loadImage() {

        ImageLoader().loadImage(from: URL(string: "someURL")!).sink { (image) in
            self.imageView.image = image
        }.store(in: &subscriptions)

    }
}


来源: stackexchange

问:
Return nonexistent right table values as NULL
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');
```

<p>I want to be able to select properties for a <code>thing</code> based on their names, and return <code>NULL</code> if such a property doesn't exist. Here is what I have attempted:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';
</code>```

I wanted the result to be

```<code>  name |   age | foo
---------------------
'John' | '123' | NULL
</code>```

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

答:
You need to move the WHERE conditions on p1,  p2 and p3 into their respective JOIN conditions, otherwise it turns those LEFT JOINs into INNER JOINs (see the manual).

```<code>SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id AND p1.name = 'name'
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id AND p2.name = 'age'
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id AND p3.name = 'foo'
WHERE
  t.id = 1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two MySQL tables:

CREATE TABLE things (
  id INT
);

CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);

INSERT INTO things (id) VALUES (1);

INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');

I want to be able to select properties for a thing based on their names, and return NULL if such a property doesn't exist. Here is what I have attempted:

SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';

I wanted the result to be

  name |   age | foo
---------------------
'John' | '123' | NULL

But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.

How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.

Body:
You need to move the WHERE conditions on p1,  p2 and p3 into their respective JOIN conditions, otherwise it turns those LEFT JOINs into INNER JOINs (see the manual).

SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id AND p1.name = 'name'
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id AND p2.name = 'age'
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id AND p3.name = 'foo'
WHERE
  t.id = 1


问:
Bizarre directory delete behaviour on SSD drive
Directory c:\test has 50 or so files in it, no subdirectories.

```<code>    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If

    IO.Directory.CreateDirectory("C:\test")
</code>```

Drive C is Intel's X25-M80 SSD drive, OS is Windows 7 64 bit with TRIM support, Visual Studio is 2008 with target framework 3.5. When above code is executed, CreateDirectory breaks code execution without an (visible) exception. After much headache I found that Delete is not yet done by the time code execution gets to CreateDirectory. If I modify my code like this:

```<code>    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If
    Threading.Thread.Sleep(2000)
    IO.Directory.CreateDirectory("C:\test")
</code>```

then everything works as expected.

My questions beside the obvious WTF here are:

shouldn't IO.Directory.Delete be a blocking function call no matter what the drive is

is SSD "cheating" on delete due to enabled TRIM support?

答:
I suspect that you've found a race condition in NTFS that was previously not exposed since drives didn't exist that were fast enough to hit it. I don't think that TRIM has anything to do with it (though I reserve the right to be wrong!)

Either way, the proper way to handle this is to put the code in a Retry loop:

```<code>int retries = 3;
while(true) {
    try {
        doTheOperation();
        break;
    } catch (Exception ex) {
        retries--;
        if (retries == 0) {
            throw;
        }

        Thread.Sleep(100);
        continue;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Directory c:\test has 50 or so files in it, no subdirectories.

    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If

    IO.Directory.CreateDirectory("C:\test")

Drive C is Intel's X25-M80 SSD drive, OS is Windows 7 64 bit with TRIM support, Visual Studio is 2008 with target framework 3.5. When above code is executed, CreateDirectory breaks code execution without an (visible) exception. After much headache I found that Delete is not yet done by the time code execution gets to CreateDirectory. If I modify my code like this:

    If IO.Directory.Exists("C:\test") Then
        IO.Directory.Delete("C:\test", True)
    End If
    Threading.Thread.Sleep(2000)
    IO.Directory.CreateDirectory("C:\test")

then everything works as expected.

My questions beside the obvious WTF here are:

shouldn't IO.Directory.Delete be a blocking function call no matter what the drive is

is SSD "cheating" on delete due to enabled TRIM support?

Body:
I suspect that you've found a race condition in NTFS that was previously not exposed since drives didn't exist that were fast enough to hit it. I don't think that TRIM has anything to do with it (though I reserve the right to be wrong!)

Either way, the proper way to handle this is to put the code in a Retry loop:

int retries = 3;
while(true) {
    try {
        doTheOperation();
        break;
    } catch (Exception ex) {
        retries--;
        if (retries == 0) {
            throw;
        }

        Thread.Sleep(100);
        continue;
    }
}


问:
return type of generic, when to use <T>returnType<T> and when to just use returnType<T>?
In generic api, why sometimes a type parameter is written before the return type and sometimes it needs not?

Given the following two Steam API as example

```<code>Stream<T>   limit(long maxSize)
</code>```

and

```<code><R> Stream<R>   map(Function<? super T,? extends R> mapper)
</code>```

Why Stream.limit's return type can just be written as Stream<T> but not <T> Stream<T>?

When to use <T> returnType <T> and when to use returnType<T>?

答:
The T in the first example is the generic parameter of the Stream one is operating on, thus limit(...) returns a new Stream of same generic type like the stream one calls limit(...) on.

In the second example, the generic type of the resulting Stream may be changed, thus a separate generic parameter is needed. in this case, the type of the resulting Stream is influenced by the mapper-lambda. If Persons are mapped to their SocialSecurityNumber, for example, then the initial Stream would be a Stream<Person>, the mapper would be of type Function<Person, SocialSecurityNumber> and the resulting Stream would be a Stream<SocialSecurityNumber>.

Body:
In generic api, why sometimes a type parameter is written before the return type and sometimes it needs not?

Given the following two Steam API as example

Stream<T>   limit(long maxSize)

and

<R> Stream<R>   map(Function<? super T,? extends R> mapper)

Why Stream.limit's return type can just be written as Stream<T> but not <T> Stream<T>?

When to use <T> returnType <T> and when to use returnType<T>?


问:
Displaying the content of an input for several divs
I want to give all .firstname-show the content from the input but I don't know how to do it. Here's code:</p>

```<code>    <input type="text" id="firstname" name="firstname" placeholder="First name">
    <button id="firstname-btn" onclick="show()">SHOW</button>
    <div class="firstname-show"></div>
    <div class="firstname-show"></div>
</code>```

```<code>    function show() {
       var name = document.getElementById('firstname').value;
       document.querySelectorAll('.firstname-show').textContent = name;
    }
</code>```

答:
Query selector will return an array so you have to iterate using for loop. see below function.

```<code>function show() {
    var name = document.getElementById('firstname').value;
    var elements = document.querySelectorAll('.firstname-show');

    for(var i in elements){
        elements[i].textContent = name;
    }
}
</code>```

https://jsfiddle.net/kagf25c1/

Body:
I want to give all .firstname-show the content from the input but I don't know how to do it. Here's code:

    <input type="text" id="firstname" name="firstname" placeholder="First name">
    <button id="firstname-btn" onclick="show()">SHOW</button>

    function show() {
       var name = document.getElementById('firstname').value;
       document.querySelectorAll('.firstname-show').textContent = name;
    }

Body:
Query selector will return an array so you have to iterate using for loop. see below function.

function show() {
    var name = document.getElementById('firstname').value;
    var elements = document.querySelectorAll('.firstname-show');

    for(var i in elements){
        elements[i].textContent = name;
    }
}

https://jsfiddle.net/kagf25c1/


问:
Error in pkg-config when try to download git repository
I was trying to make a facial recognition app using Go and Kagami/go-face repository. It requires dlib-models. And I was used MSYS tool for get the distribution in windows.

But when I try to get the go repository using go get github.com/Kagami/go-face command and it gives an error:

# pkg-config --cflags -- dlib-1

Any one had this issue before in windows 10.

答:
As commented, the README lists the Windows pre-requisites, involving MSYS2.

This was from commit 968bbf9, following issue 5 "Windows support?"

Another approach would be to use Docker, with an Ubuntu image, which would come with dlib, where you can add Go and experiment there.


问:
Continuously sending data from Python Flask server to client through Websockets
I am setting up a dashboard which requires a Python Flask server to fetch public transport data once every few seconds or so and send this data to a client webpage through websockets. I am using FlaskSocketIO to achieve this.

I am able to send a message upon the 'connect' event, for example, but I've been unable to find a way to continuously update this message. This is my approach:

from flask import Flask, render_template, url_for, request
from flask_socketio import SocketIO, emit, send
import eventlet
eventlet.monkey_patch()

app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True)

def listen():
    while True:
        message = # some updating message
        emit('message', message)
        socketio.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    listen()

if __name__ == "__main__":
    socketio.run(app, debug=True)
```

<p>The logger says it sends the message. However, on the client side, no message is recieved. The client side JavaScript is:</p>

<pre class="lang-js prettyprint-override"><code>var socket = io();

socket.on('message', function(msg) {
    console.log(msg);
});
</code>```

答:
You cannot add a while True loop in the connect handler, as that will prevent the connect handler from returning and establishing the connection.

You can do this as a response to another event sent by the client after the connection is made, or you can also start a background task that implements this loop. The connect handler needs to return quickly to allow the connection to happen.

Body:
I am setting up a dashboard which requires a Python Flask server to fetch public transport data once every few seconds or so and send this data to a client webpage through websockets. I am using FlaskSocketIO to achieve this.

I am able to send a message upon the 'connect' event, for example, but I've been unable to find a way to continuously update this message. This is my approach:

from flask import Flask, render_template, url_for, request
from flask_socketio import SocketIO, emit, send
import eventlet
eventlet.monkey_patch()

app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True)

def listen():
    while True:
        message = # some updating message
        emit('message', message)
        socketio.sleep(1)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def handle_connect():
    listen()

if __name__ == "__main__":
    socketio.run(app, debug=True)

The logger says it sends the message. However, on the client side, no message is recieved. The client side JavaScript is:

var socket = io();

socket.on('message', function(msg) {
    console.log(msg);
});


答:
I've had problems with this before, but this is not specific to SSD drives.  You would be far better off doing a move then delete:

```<code>if(Directory.Exists(dirpath))
{
    string temppath = dirpath + ".deleted";
    Directory.Move(dirpath, temppath);
    Directory.Delete(temppath, true);
}
Directory.Create(dirpath);
</code>```

The other way to deal with it is to loop until complete:

```<code>if(Directory.Exists(dirpath))
{
    Directory.Delete(dirpath, true);
    int limit = 100;
    while(Directory.Exists(dirpath) && limit-- > 0)
        Thread.Sleep(0);
}
Directory.Create(dirpath);
</code>```

Title: Bizarre directory delete behaviour on SSD drive

Body:
I've had problems with this before, but this is not specific to SSD drives.  You would be far better off doing a move then delete:

if(Directory.Exists(dirpath))
{
    string temppath = dirpath + ".deleted";
    Directory.Move(dirpath, temppath);
    Directory.Delete(temppath, true);
}
Directory.Create(dirpath);

The other way to deal with it is to loop until complete:

if(Directory.Exists(dirpath))
{
    Directory.Delete(dirpath, true);
    int limit = 100;
    while(Directory.Exists(dirpath) && limit-- > 0)
        Thread.Sleep(0);
}
Directory.Create(dirpath);


问:
How do I extract the information from the website?
I am trying to gather information of all the vessels from this website:
https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7

This is my code right now:

```<code>import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome(executable_path=r"C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\chromedriver.exe")
browser.get(url)

browser.implicitly_wait(100)
Vessel_link = browser.find_element_by_class_name("ag-cell-content-link")
Vessel_link.click()

browser.implicitly_wait(30)
imo = browser.find_element_by_xpath('//*[@id="imo"]')
print(imo)
</code>```

My output

I am using selenium, which isn't going to work because. I have several thousands of ships to extract data from and it just isn't going to be efficient. (Also, I only need to extract information from Cargo Vessels (U can find that using the filter or by looking at green signs on the vessel type column.) and I need to extract the country name(flag), the Imo and the Vessels name.

What should I use? Selenium or Bs4 + requests or other libraries? And How? I just started web scraping...

I can't get the Imo nor anything! The HTML structure is very weird.

I would appreciate any help. Thank You! :)

答:
Instead of clicking each vessel to open up the details, you can get the information you're searching for from the results page.  This will get each vessel, pull the info you wanted and click to the next page if there are more vessels:

```<code>import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome('C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\')
browser.get(url)
browser.implicitly_wait(5)

checking_for_vessels = True
vessel_count = 0

while checking_for_vessels:
    vessel_left_container = browser.find_element_by_class_name('ag-pinned-left-cols-container')
    vessels_left = vessel_left_container.find_elements_by_css_selector('div[role="row"]')

    vessel_right_container = browser.find_element_by_class_name("ag-body-container")
    vessels_right = vessel_right_container.find_elements_by_css_selector('div[role="row"]')

    for i in range(len(vessels_left)):
        vessel_count += 1
        vessel_country_list = vessels_left[i].find_elements_by_class_name('flag-icon')

        if len(vessel_country_list) == 0:
            vessel_country = 'Unknown'
        else:
            vessel_country = vessel_country_list[0].get_attribute('title')

        vessel_name = vessels_left[i].find_element_by_class_name('ag-cell-content-link').text
        vessel_imo = vessels_right[i].find_element_by_css_selector('[col-id="imo"] .ag-cell-content div').text

        print('Vessel #' + str(vessel_count) + ': ' + vessel_name + ', ' + vessel_country + ', ' + vessel_imo)

    pagination_container = browser.find_element_by_class_name('MuiTablePagination-actions')
    page_number = pagination_container.find_element_by_css_selector('input').get_attribute('value')
    max_page_number = pagination_container.find_element_by_class_name('MuiFormControl-root').get_attribute('max')

    if page_number == max_page_number:
        checking_for_vessels = False
    else:
        next_page_button = pagination_container.find_element_by_css_selector('button[title="Next page"]')
        next_page_button.click()
</code>```

There was one vessel that did not display a flag, so there's a check for that and the country is replaced with 'Unknown' if no flag found.  The same kind of check can be done for the vessel name and imo.

The implicit wait was reduced to 5 because of the known issue of missing a flag on one vessel and waiting 100 seconds for this to be figured out was excessive.  This number can be adjusted higher if you find there's issues waiting long enough to find elements.

It appears you are using a windows machine.  You can place the path of your chromedriver in the PATH variable on your machine and then you don't have to use the path when you instantiate your browser driver.  Obviously, your path to your chromedriver is different than mine, so hopefully what you provided is correct or else this won't work.

Body:
I am trying to gather information of all the vessels from this website:
https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7

This is my code right now:

import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome(executable_path=r"C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\chromedriver.exe")
browser.get(url)

browser.implicitly_wait(100)
Vessel_link = browser.find_element_by_class_name("ag-cell-content-link")
Vessel_link.click()

browser.implicitly_wait(30)
imo = browser.find_element_by_xpath('//*[@id="imo"]')
print(imo)

My output

I am using selenium, which isn't going to work because. I have several thousands of ships to extract data from and it just isn't going to be efficient. (Also, I only need to extract information from Cargo Vessels (U can find that using the filter or by looking at green signs on the vessel type column.) and I need to extract the country name(flag), the Imo and the Vessels name.

What should I use? Selenium or Bs4 + requests or other libraries? And How? I just started web scraping...

I can't get the Imo nor anything! The HTML structure is very weird.

I would appreciate any help. Thank You! :)

Body:
Instead of clicking each vessel to open up the details, you can get the information you're searching for from the results page.  This will get each vessel, pull the info you wanted and click to the next page if there are more vessels:

import selenium.webdriver as webdriver

url = "https://www.marinetraffic.com/en/data/?asset_type=vessels&columns=flag,shipname,photo,recognized_next_port,reported_eta,reported_destination,current_port,imo,ship_type,show_on_live_map,time_of_latest_position,lat_of_latest_position,lon_of_latest_position&ship_type_in|in|Cargo%20Vessels|ship_type_in=7"

browser = webdriver.Chrome('C:\Users\CSA\OneDrive - College Sainte-Anne\Programming\PYTHON\Learning\WS\chromedriver_win32 (1)\')
browser.get(url)
browser.implicitly_wait(5)

checking_for_vessels = True
vessel_count = 0

while checking_for_vessels:
    vessel_left_container = browser.find_element_by_class_name('ag-pinned-left-cols-container')
    vessels_left = vessel_left_container.find_elements_by_css_selector('div[role="row"]')

    vessel_right_container = browser.find_element_by_class_name("ag-body-container")
    vessels_right = vessel_right_container.find_elements_by_css_selector('div[role="row"]')

    for i in range(len(vessels_left)):
        vessel_count += 1
        vessel_country_list = vessels_left[i].find_elements_by_class_name('flag-icon')

        if len(vessel_country_list) == 0:
            vessel_country = 'Unknown'
        else:
            vessel_country = vessel_country_list[0].get_attribute('title')

        vessel_name = vessels_left[i].find_element_by_class_name('ag-cell-content-link').text
        vessel_imo = vessels_right[i].find_element_by_css_selector('[col-id="imo"] .ag-cell-content div').text

        print('Vessel #' + str(vessel_count) + ': ' + vessel_name + ', ' + vessel_country + ', ' + vessel_imo)

    pagination_container = browser.find_element_by_class_name('MuiTablePagination-actions')
    page_number = pagination_container.find_element_by_css_selector('input').get_attribute('value')
    max_page_number = pagination_container.find_element_by_class_name('MuiFormControl-root').get_attribute('max')

    if page_number == max_page_number:
        checking_for_vessels = False
    else:
        next_page_button = pagination_container.find_element_by_css_selector('button[title="Next page"]')
        next_page_button.click()

There was one vessel that did not display a flag, so there's a check for that and the country is replaced with 'Unknown' if no flag found.  The same kind of check can be done for the vessel name and imo.

The implicit wait was reduced to 5 because of the known issue of missing a flag on one vessel and waiting 100 seconds for this to be figured out was excessive.  This number can be adjusted higher if you find there's issues waiting long enough to find elements.

It appears you are using a windows machine.  You can place the path of your chromedriver in the PATH variable on your machine and then you don't have to use the path when you instantiate your browser driver.  Obviously, your path to your chromedriver is different than mine, so hopefully what you provided is correct or else this won't work.


问:
good way to make navbar responsive
i have a navbar with 3 buttons on the left hand side and a search bar on the right hand side. i believe i wrote bad(not the proper way) code to make them responsive but still they are not responsive for medium and smaller screens. i am just trying to figure out the good way to make them responsive. i am trying to make a page as shown in the below image.

stackblitz link

  .searchbar{
    width: 400px;
  }
    .btn-primary{
    background-color: #002B42;
    padding:10px;
    font-size: 12px;
    border-radius: 4px;
    margin-left: 3px;
    font-family: Arial, Helvetica, sans-serif;
  }
  .btn-light{
     margin-left: 30px;
    padding:10px;

    background-color: transparent;
    border: none;
    color: black;
    font-size: 13px;
    outline: none;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">

<ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <button type="button" class="btn btn-primary"><i class="fa fa-bars" aria-hidden="true">  SAVED LISTS</i></button>      </li>
      <li class="nav-item">
        <button class="btn btn-light"> <i class="fa fa-filter" aria-hidden="true">   SAVED FILTER</i>  </button>
      </li>
      <li class="nav-item">
        <button class="btn btn-light"> <i class="fa fa-history" aria-hidden="true">   SEARCH HISTORY</i>  </button>
      </li>
    </ul>

  <div class="ml-auto">
    <input class="form-control searchbar" name="search" [(ngModel)]="search" type="search" placeholder="Search" />
  </div>
</nav</code>```

答:
First of all, you don't need to set the width 400px for the .searchbar class.
By setting a media query, unfix the navbar for smaller widths. This is more suitable for the user experience.

In my opinion, the most standard is the one Bootstrap itself suggests.
It's best to insert your
 into the
 and place a button as navbar toggler.
And use the my-2 my-md-0 class instead of the ml-auto class for search wrapper
 as below

body{
    padding-top: 60px;
}
.search-wrapper{
    flex-grow: 1;

}
    .btn-primary{
    background-color: #002B42;
    font-size: 12px;
    border-radius: 4px;
    font-family: Arial, Helvetica, sans-serif;
  }
  .btn-light{
    background-color: transparent;
    border: none;
    color: black;
    font-size: 13px;
    outline: none;
  }

  .items{
      margin-top: ;
  }

  @media only screen and (max-width: 768px) {
      body{
          padding-top: 0!important;
      }
    .navbar{
        position: relative;
    }
    .navbar-nav{
        align-items: center;
        margin: 15px 0;
    }
    .nav-item{
        margin:10px 0;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">

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

          <div class="collapse navbar-collapse" id="my-navbar">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <button type="button" class="btn btn-primary"><i class="fa fa-bars" aria-hidden="true">  SAVED LISTS</i></button>      </li>
                <li class="nav-item">
                  <button class="btn btn-light"> <i class="fa fa-filter" aria-hidden="true">   SAVED FILTER</i>  </button>
                </li>
                <li class="nav-item">
                  <button class="btn btn-light"> <i class="fa fa-history" aria-hidden="true">   SEARCH HISTORY</i>  </button>
                </li>
              </ul>
          </div>

          <div class="my-2 my-md-0 search-wrapper">
            <input class="form-control searchbar" name="search" [(ngModel)]="search" type="search" placeholder="Search" />
          </div>
        </nav>

        <div class="items">
            <ol>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
            </ol>
        </div>

        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html></code>```

Title: good way to make navbar responsive

Body:
i have a navbar with 3 buttons on the left hand side and a search bar on the right hand side. i believe i wrote bad(not the proper way) code to make them responsive but still they are not responsive for medium and smaller screens. i am just trying to figure out the good way to make them responsive. i am trying to make a page as shown in the below image.

stackblitz link

  .searchbar{
    width: 400px;
  }
    .btn-primary{
    background-color: #002B42;
    padding:10px;
    font-size: 12px;
    border-radius: 4px;
    margin-left: 3px;
    font-family: Arial, Helvetica, sans-serif;
  }
  .btn-light{
     margin-left: 30px;
    padding:10px;

    background-color: transparent;
    border: none;
    color: black;
    font-size: 13px;
    outline: none;
  }

        <button type="button" class="btn btn-primary">  SAVED LISTS</button>

        <button class="btn btn-light">    SAVED FILTER  </button>

        <button class="btn btn-light">    SEARCH HISTORY  </button>

    <input class="form-control searchbar" name="search" [(ngModel)]="search" type="search" placeholder="Search" />

</nav

Body:
First of all, you don't need to set the width 400px for the .searchbar class.
By setting a media query, unfix the navbar for smaller widths. This is more suitable for the user experience.

In my opinion, the most standard is the one Bootstrap itself suggests.
It's best to insert your <ul class="navbar-nav mr-auto"> into the <div class="collapse navbar-collapse" id="my-navbar"> and place a button as navbar toggler.
And use the my-2 my-md-0 class instead of the ml-auto class for search wrapper
 as below

body{
    padding-top: 60px;
}
.search-wrapper{
    flex-grow: 1;

}
    .btn-primary{
    background-color: #002B42;
    font-size: 12px;
    border-radius: 4px;
    font-family: Arial, Helvetica, sans-serif;
  }
  .btn-light{
    background-color: transparent;
    border: none;
    color: black;
    font-size: 13px;
    outline: none;
  }

  .items{
      margin-top: ;
  }

  @media only screen and (max-width: 768px) {
      body{
          padding-top: 0!important;
      }
    .navbar{
        position: relative;
    }
    .navbar-nav{
        align-items: center;
        margin: 15px 0;
    }
    .nav-item{
        margin:10px 0;
    }
  }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>

    <nav class="navbar navbar-expand-md navbar-light fixed-top bg-light">

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

          <div class="collapse navbar-collapse" id="my-navbar">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <button type="button" class="btn btn-primary"><i class="fa fa-bars" aria-hidden="true">&nbsp;&nbsp;SAVED LISTS</i></button>      </li>
                <li class="nav-item">
                  <button class="btn btn-light"> <i class="fa fa-filter" aria-hidden="true">&nbsp;&nbsp; SAVED FILTER</i>  </button>
                </li>
                <li class="nav-item">
                  <button class="btn btn-light"> <i class="fa fa-history" aria-hidden="true">&nbsp;&nbsp; SEARCH HISTORY</i>  </button>
                </li>
              </ul>
          </div>

          <div class="my-2 my-md-0 search-wrapper">
            <input class="form-control searchbar" name="search" [(ngModel)]="search" type="search" placeholder="Search" />
          </div>
        </nav>

        <div class="items">
            <ol>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
                <li>dhsiudshdsds</li>
            </ol>
        </div>

        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>
</html>


问:
Executing reboot command over SSH using Paramiko
I use Paramiko for establishing SSH connection with some target device and I want to execute reboot command.

```<code>ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(zip_hostname, username=username, password=password, timeout=1)
try:
    stdin, stdout, stderr = ssh.exec_command("/sbin/reboot -f")
    # .........
    # some code
    # .........
except AuthenticationException, e:
    print ''
finally:
    ssh.close()
</code>```

But after executing ssh.exec_command("/sbin/reboot -f") "some code" does not execute because program is stuck in exec_command (the disconnection takes place caused by rebooting). What should I do to solve my problem?

答:
In case you or anyone else gets stuck trying to reboot host with sudo using forwarding agents (ssh keys) or in my case (yubikey)

If you look at this as bash you would reboot a host as non root user like this.

```<code>ssh -t -A user@hostname sudo /sbin/reboot
</code>```

For the -A flag, from ssh man page

Enables forwarding of the authentication agent connection.  This can also be specified on a per-host basis in a
               configuration file.
               Agent forwarding should be enabled with caution.  Users with the ability to bypass file permissions on the
               remote host (for the agent’s Unix-domain socket) can access the local agent through the forwarded connection.
               An attacker cannot obtain key material from the agent, however they can perform operations on the keys that
               enable them to authenticate using the identities loaded into the agent.*

For the -t flag, from ssh man page

Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine,
               which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even
               if ssh has no local tty.*

So lets break this down into how you would do this in paramiko

```<code>ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=username)
s = ssh.get_transport().open_session()
paramiko.agent.AgentRequestHandler(s)

ssh.exec_command("sudo /sbin/reboot", get_pty=True)
</code>```

For authentication forwarding (-A flag in bash ssh command) for paramiko

```<code>ssh = paramiko.SSHClient() #'ssh' is client variable
s = ssh.get_transport().open_session() #get 'ssh' transport and open sessions assigned to 's' variable
paramiko.agent.AgentRequestHandler(s) #call in 's' to the forwarding agent for current ssh session
</code>```

Now for force pseudo-tty allocation (-t flag in bash ssh command) for paramiko

```<code>ssh.exec_command("sudo /sbin/reboot", get_pty=True)
</code>```

Adding 'get_pty=True' to exec_command will allow you execute sudo /sbin/reboot

Hope this helps, everyone's environments are different but this should work as it the exact same thing as if you ran it as bash.

Body:
I use Paramiko for establishing SSH connection with some target device and I want to execute reboot command.

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(zip_hostname, username=username, password=password, timeout=1)
try:
    stdin, stdout, stderr = ssh.exec_command("/sbin/reboot -f")
    # .........
    # some code
    # .........
except AuthenticationException, e:
    print ''
finally:
    ssh.close()

But after executing ssh.exec_command("/sbin/reboot -f") "some code" does not execute because program is stuck in exec_command (the disconnection takes place caused by rebooting). What should I do to solve my problem?

Body:
In case you or anyone else gets stuck trying to reboot host with sudo using forwarding agents (ssh keys) or in my case (yubikey)

If you look at this as bash you would reboot a host as non root user like this.

ssh -t -A user@hostname sudo /sbin/reboot

For the -A flag, from ssh man page

Enables forwarding of the authentication agent connection.  This can also be specified on a per-host basis in a
               configuration file.
               Agent forwarding should be enabled with caution.  Users with the ability to bypass file permissions on the
               remote host (for the agent’s Unix-domain socket) can access the local agent through the forwarded connection.
               An attacker cannot obtain key material from the agent, however they can perform operations on the keys that
               enable them to authenticate using the identities loaded into the agent.*

For the -t flag, from ssh man page

Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a remote machine,
               which can be very useful, e.g. when implementing menu services.  Multiple -t options force tty allocation, even
               if ssh has no local tty.*

So lets break this down into how you would do this in paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=username)
s = ssh.get_transport().open_session()
paramiko.agent.AgentRequestHandler(s)

ssh.exec_command("sudo /sbin/reboot", get_pty=True)

For authentication forwarding (-A flag in bash ssh command) for paramiko

ssh = paramiko.SSHClient() #'ssh' is client variable
s = ssh.get_transport().open_session() #get 'ssh' transport and open sessions assigned to 's' variable
paramiko.agent.AgentRequestHandler(s) #call in 's' to the forwarding agent for current ssh session

Now for force pseudo-tty allocation (-t flag in bash ssh command) for paramiko

ssh.exec_command("sudo /sbin/reboot", get_pty=True)

Adding 'get_pty=True' to exec_command will allow you execute sudo /sbin/reboot

Hope this helps, everyone's environments are different but this should work as it the exact same thing as if you ran it as bash.


问:
How to get cropped image from cropper js?
I am trying to get cropped image result from cropperjs but I dont know how to get it. I tried to search online but couldn't find a solution.

My code is as given below.

```<code>$(function ()
  {

  $image=null;

  var img = document.createElement("IMG");
  img.src = "";
  img.setAttribute('id', "showImage");
  document.getElementById("img-container").appendChild(img);

  var url = canvas.toDataURL();
  canvasImage.src = url;
  console.log(canvasImage);

  document.getElementById("showImage").src=canvasImage.src;
  $image = $('#showImage');
  $image.cropper({
    movable: true,
    zoomable: false,
    rotatable: false,
    scalable: false
  });

  $('#replace').on('click', function () {
    var croppedimage = new Image();
    var cropBoxData = $image.cropper('getCropBoxData');
    croppedimage=$image.data('cropper');
    // croppedimage= this.cropper.
    console.log($image);
  });
});
</code>```

答:
```<code>$('#replace').on('click', function () {
    var croppedimage = $image.getCroppedCanvas().toDataURL("image/png");
    console.log(croppedimage);
});
</code>```

you can get base64

Body:
I am trying to get cropped image result from cropperjs but I dont know how to get it. I tried to search online but couldn't find a solution.

My code is as given below.

$(function ()
  {

  $image=null;

  var img = document.createElement("IMG");
  img.src = "";
  img.setAttribute('id', "showImage");
  document.getElementById("img-container").appendChild(img);

  var url = canvas.toDataURL();
  canvasImage.src = url;
  console.log(canvasImage);

  document.getElementById("showImage").src=canvasImage.src;
  $image = $('#showImage');
  $image.cropper({
    movable: true,
    zoomable: false,
    rotatable: false,
    scalable: false
  });

  $('#replace').on('click', function () {
    var croppedimage = new Image();
    var cropBoxData = $image.cropper('getCropBoxData');
    croppedimage=$image.data('cropper');
    // croppedimage= this.cropper.
    console.log($image);
  });
});

Body:
$('#replace').on('click', function () {
    var croppedimage = $image.getCroppedCanvas().toDataURL("image/png");
    console.log(croppedimage);
});

you can get base64


问:
Create a flag column based on condition pandas
I have a dataframe as shown below

```<code>ID      Price      Duration
1       100        60
2       200        2
3       1          366
4       1          365
</code>```

I would like to create a flag column based on condition in Price column and Duration column.

Steps:

If Price is less than 20 flag it as False else flag it as True

If Duration is less than 30 flag it as False else flag it as True

Expected Output:

```<code>ID      Price      Duration     Price_Flag      Duration_Flag
1       100        60           True            True
2       200        2            True            False
3       1          366          False           True
4       10         365          False           True
</code>```

答:
One idea is compare by list by order of columns name ['Price','Duration'] by DataFrame.gt:

```<code>df[['Price_Flag','Duration_Flag']] = df[['Price','Duration']].gt([20,30])
</code>```

Or use Series.gt for each column separately:

```<code>df['Price_Flag'] = df['Price'].gt(20)
df['Duration_Flag'] = df['Duration'].gt(30)
</code>```

Or use DataFrame.assign:

```<code>df = df.assign(Price_Flag = df['Price'].gt(20),
               Duration_Flag = df['Duration'].gt(30))
</code>```

```<code>print (df)
   ID  Price  Duration  Price_Flag  Duration_Flag
0   1    100        60        True           True
1   2    200         2        True          False
2   3      1       366       False           True
3   4      1       365       False           True
</code>```

Body:
I have a dataframe as shown below

ID      Price      Duration
1       100        60
2       200        2
3       1          366
4       1          365

I would like to create a flag column based on condition in Price column and Duration column.

Steps:

If Price is less than 20 flag it as False else flag it as True

If Duration is less than 30 flag it as False else flag it as True

Expected Output:

ID      Price      Duration     Price_Flag      Duration_Flag
1       100        60           True            True
2       200        2            True            False
3       1          366          False           True
4       10         365          False           True

Body:
One idea is compare by list by order of columns name ['Price','Duration'] by DataFrame.gt:

df[['Price_Flag','Duration_Flag']] = df[['Price','Duration']].gt([20,30])

Or use Series.gt for each column separately:

df['Price_Flag'] = df['Price'].gt(20)
df['Duration_Flag'] = df['Duration'].gt(30)

Or use DataFrame.assign:

df = df.assign(Price_Flag = df['Price'].gt(20),
               Duration_Flag = df['Duration'].gt(30))

print (df)
   ID  Price  Duration  Price_Flag  Duration_Flag
0   1    100        60        True           True
1   2    200         2        True          False
2   3      1       366       False           True
3   4      1       365       False           True


问:
I can't Update my prefab at Unity because the option from override are blacked out
I'm a beginner at unity and  I have had a little problem in my unity project. I can't update  my prefab because the option from override are blacked out, look the image below:

Image of my unity project

ok,  Unity said that there's a invalid script which is contained in Prefab. But I don't what's the script and how to exclude it from Prefab, therefore I don't know how to resolve the issue. Can someone help me???

答:
You have 2 scripts that cannot be loaded.

Open console - yiu probably have some script errors. Fix them in your code. The errors are not necessarily in that exactly scripts

If error thill occurs, enter prefab mode (press on a little arrow in hierarchy right to your prefab) and delete those scripts


问:
Passing current_user from Flask-Login to Plotly Dash app
I am trying to build a Dash app which is integrated in Flask app. Everything seems to be working fine but when I try to show logged user in the Dash app it comes out as 'None'.

My app structure is as below:

```<code>example/
example/
  dashapp/
    static/
      custom-css.css
    templates/
      base.html
      home.html
      login.html
    __init__.py
    app1.py
    forms.py
    models.py
    routes.py
  application.py
  config.py
  users.db
</code>```

My Dash app is in app1.py. I've tried several ways to pass current_user but no success. It comes out fine in home.html though. I guess the problem is with my app being in separate file and not in the routes.py.

Here is the code for app.py:

```<code>import dash
import dash_html_components as html
from dashapp import application
from flask_login import login_required, current_user

app1 = dash.Dash(__name__, server = application, routes_pathname_prefix = '/app1/', assets_folder = 'static', assets_url_path = '/static')
app1.scripts.config.serve_locally = True
app1.css.config.serve_locally = True

app1.layout = html.Div(
    children = '{}'.format(current_user)
)

for view_func in app1.server.view_functions:
    if view_func.startswith('/app1/'):
        app1.server.view_functions[view_func] = login_required(app1.server.view_functions[view_func])
</code>```

routes.py code:

```<code>from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from dashapp import application, db
from dashapp.forms import LoginForm
from dashapp.models import User
from dashapp import app1

@application.route('/')
@application.route('/home')
@login_required
def home():
    return render_template('home.html')

@application.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('home')
        return redirect(next_page)
    return render_template('login.html', form=form)

@application.route('/app1/')

@application.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))
</code>```

Other scripts are pretty much standard and I won't include them in the question unless they are really needed.

Please suggest how to overcome my problem. Thanks!

答:
Faced the same problem. I guess the problem is that current user hasn't been initialised when the 'application' registers Dash app. Nice workaround, though seems a bit insecure since Flask sessions are just encoded.

https://github.com/RafaelMiquelino/dash-flask-login/blob/master/app.py - more robust solution in my opinion. It checks current_user in the callbacks and uses contents of the page as Input, so the callbacks are called on page load. You can also skip the protection of the views if user experience isn't an issue.

Here's a simplified example of how I used it:

```<code>@app.callback(
    Output('graph-wrapper', 'children'),
    [Input('page-content', 'children')])
def load_graph(input1):
    if current_user.is_authenticated:
        return dcc.Graph() # Dash Graph populated with current_user data from db
    else:
        return ''
</code>```

Body:
I am trying to build a Dash app which is integrated in Flask app. Everything seems to be working fine but when I try to show logged user in the Dash app it comes out as 'None'.

My app structure is as below:

example/
example/
  dashapp/
    static/
      custom-css.css
    templates/
      base.html
      home.html
      login.html
    __init__.py
    app1.py
    forms.py
    models.py
    routes.py
  application.py
  config.py
  users.db

My Dash app is in app1.py. I've tried several ways to pass current_user but no success. It comes out fine in home.html though. I guess the problem is with my app being in separate file and not in the routes.py.

Here is the code for app.py:

import dash
import dash_html_components as html
from dashapp import application
from flask_login import login_required, current_user

app1 = dash.Dash(__name__, server = application, routes_pathname_prefix = '/app1/', assets_folder = 'static', assets_url_path = '/static')
app1.scripts.config.serve_locally = True
app1.css.config.serve_locally = True

app1.layout = html.Div(
    children = '{}'.format(current_user)
)

for view_func in app1.server.view_functions:
    if view_func.startswith('/app1/'):
        app1.server.view_functions[view_func] = login_required(app1.server.view_functions[view_func])

routes.py code:

from flask import render_template, flash, redirect, url_for, request
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from dashapp import application, db
from dashapp.forms import LoginForm
from dashapp.models import User
from dashapp import app1

@application.route('/')
@application.route('/home')
@login_required
def home():
    return render_template('home.html')

@application.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('home')
        return redirect(next_page)
    return render_template('login.html', form=form)

@application.route('/app1/')

@application.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('login'))

Other scripts are pretty much standard and I won't include them in the question unless they are really needed.

Please suggest how to overcome my problem. Thanks!

Body:
Faced the same problem. I guess the problem is that current user hasn't been initialised when the 'application' registers Dash app. Nice workaround, though seems a bit insecure since Flask sessions are just encoded.

https://github.com/RafaelMiquelino/dash-flask-login/blob/master/app.py - more robust solution in my opinion. It checks current_user in the callbacks and uses contents of the page as Input, so the callbacks are called on page load. You can also skip the protection of the views if user experience isn't an issue.

Here's a simplified example of how I used it:

@app.callback(
    Output('graph-wrapper', 'children'),
    [Input('page-content', 'children')])
def load_graph(input1):
    if current_user.is_authenticated:
        return dcc.Graph() # Dash Graph populated with current_user data from db
    else:
        return ''


问:
Lift a key’s values to top level whilst preserving rest of object using Ramda
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

```<code>{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}
</code>```

The result I am after:

```<code>{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}
</code>```

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

答:
You can use R.chain with R.merge and R.prop to flatten a key's content by merging it with the original object, and then you can omit the original key.

const { pipe, chain, merge, prop, omit } = R

const fn = key => pipe(
  chain(merge, prop(key)), // flatten the key's content
  omit([key]) // remove the key
)

const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }

const result = fn('record')(data)

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script></code>```

Body:
I would like to build it into my compose function so that record’s values go to the top level of the object, whilst the rest of the keys stay in tact:

{
  record: {
    seasons: [
      1
    ],
    colors: [
      2
    ]
  },
  tag_ids: [
    2091
  ]
}

The result I am after:

{
  seasons: [
    1
  ],
  colors: [
    2
  ],
  tag_ids: [
    2091
  ]
}

Any of the keys may or may not exist.

I have always scratched my head with the ramda way to do it in a compose function. Currently I am looking at toPairs and doing some pretty long winded transforms with no luck.

Body:
You can use R.chain with R.merge and R.prop to flatten a key's content by merging it with the original object, and then you can omit the original key.

const { pipe, chain, merge, prop, omit } = R

const fn = key => pipe(
  chain(merge, prop(key)), // flatten the key's content
  omit([key]) // remove the key
)

const data = { record: { seasons: [1], colors: [2] }, tag_ids: [2091] }

const result = fn('record')(data)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>


问:
How to use Body Parser with import and not required? ES6
I am working on a project that uses strictly imports, disabling me from using required statements. I am wondering how I can read the contents of a post request to my server using the import for Body Parser.

'''

```<code>//jshint esversion:6

// Require the needed NPMs

import Radar from "radar-sdk-js";
import express from "express";
import bodyParser from "body-parser";
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

/*app.use(bodyParser.json({
        verify: (req, res, buf) => {
        req.rawBody = buf;
     }
})*/

app.get("/", function(req, res) {

  res.sendFile(__dirname + "/public/index.html");

});

app.post("/", function(req, res) {

      console.log(req.body);
      console.log(req.body.trackedName);
</code>```

'''

答: Your form is using multipart/form-data as the content-type, but you don't have any middleware for that content-type and there's no reason to use that more complicated content-type unless you are also uploading files.  You can switch the content-type to either one of the two that your middleware does support, application/json or application/x-www-form-urlencoded so it will match your middleware.

Body:
I am working on a project that uses strictly imports, disabling me from using required statements. I am wondering how I can read the contents of a post request to my server using the import for Body Parser.

'''

//jshint esversion:6

// Require the needed NPMs

import Radar from "radar-sdk-js";
import express from "express";
import bodyParser from "body-parser";
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

/*app.use(bodyParser.json({
        verify: (req, res, buf) => {
        req.rawBody = buf;
     }
})*/

app.get("/", function(req, res) {

  res.sendFile(__dirname + "/public/index.html");

});

app.post("/", function(req, res) {

      console.log(req.body);
      console.log(req.body.trackedName);

'''


问:
PHP Constant Conventions
Greetings StackOverflow

I'm doing some house cleaning and thought I would ask for some suggested practices in PHP as I re-factor my classes.  In particular, I have some class constants which fall into categories and I would like to know some good ways to group the ones which share a common purpose.

An Example:

```<code>class MySquare {
  // Colors
  const COLOR_GREEN = "green";
  const COLOR_RED = "red";

  // Widths
  const WIDTH_SMALL = 100;
  const WIDTH_MEDIUM = 500;
  const WIDTH_BIG = 1000;

  // Heights
  const HEIGHT_SMALL = 100;
  const HEIGHT_MEDIUM = 300;
  const HEIGHT_BIG = 500;
}
</code>```

Obviously this works, but it seems like there are probably plenty of options when it comes to grouping related constants, and I bet this is inferior to most.  How would you do it?

答: Since PHP doesn't have enums your way to do it is perfectly fine.</p>

Title: PHP Constant Conventions

Body:
Greetings StackOverflow

I'm doing some house cleaning and thought I would ask for some suggested practices in PHP as I re-factor my classes.  In particular, I have some class constants which fall into categories and I would like to know some good ways to group the ones which share a common purpose.

An Example:

class MySquare {
  // Colors
  const COLOR_GREEN = "green";
  const COLOR_RED = "red";

  // Widths
  const WIDTH_SMALL = 100;
  const WIDTH_MEDIUM = 500;
  const WIDTH_BIG = 1000;

  // Heights
  const HEIGHT_SMALL = 100;
  const HEIGHT_MEDIUM = 300;
  const HEIGHT_BIG = 500;
}

Obviously this works, but it seems like there are probably plenty of options when it comes to grouping related constants, and I bet this is inferior to most.  How would you do it?


问:
Do I need to unsubscribe the Observable within a Promise?

Do I need to unsubscribe any of the above Observables? What does take(1) really do? Lastly, how do you use async-await in this context? (Is it better to use async-await?)

New to Angular. Please help. Thank you.

答:
If you need take(1) really depends on what getPassengersByBid does. If this method returns an Observable that emits just one item and then completes you don't need to use take(1) because it completes itself. For example httpClient.get() makes one next and one complete so you don't need to chain it with take(1).

If  getPassengersByBid is an infinite Observable that never completes then it makes sense to use take(1) if you want just one value.

Second thing is that you don't need to wrap Observables with Promises and you can use just toPromise(). However, be aware that with toPromise() the source Observable has to complete and that the Promise will be resolved with the most recent value (but if you use take(1) you'll have the same behavior to what you have right now even with Observables that emit multiple items).


问:
Angular - Adding Bazel Won't Create WORKSPACE or BUILD File
I've just created a new Angular Application by running ng new name
After this finished I ran (as described in the documentation: https://angular.io/guide/bazel)

```<code>ng add @angular/bazel
</code>```

to add Bazel to my project.

But after this command finished, there is no WORKSPACE file or any BUILD file in my project.
I am relatively new to Bazel, but I am sure that those files should be there?!

What is also strange is that when running ng add @angular/bazel, I often get this error:

```<code>An unhandled exception occurred: npm WARN npm npm does not support Node.js v10.15.2
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN tar write after end
npm ERR! cb() never called!

npm ERR! This is an error with npm itself. Please report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/flo/.npm/_logs/2020-02-13T09_42_26_044Z-debug.log
Package install failed, see above.
See "/tmp/ng-3enaGH/angular-errors.log" for further details.
</code>```

答:
By default, the WORKSPACE and BUILD.bazel are only created when needed - during a build or when ng serve is running.

See the advanced section in the document you referenced above for how to change the defaults:

```<code>ng build --leaveBazelFilesOnDisk
</code>```

For your second question, I had to upgrade node+angular to the latest LTS version before it worked for me.

Body:
I've just created a new Angular Application by running ng new name
After this finished I ran (as described in the documentation: https://angular.io/guide/bazel)

ng add @angular/bazel

to add Bazel to my project.

But after this command finished, there is no WORKSPACE file or any BUILD file in my project.
I am relatively new to Bazel, but I am sure that those files should be there?!

What is also strange is that when running ng add @angular/bazel, I often get this error:

An unhandled exception occurred: npm WARN npm npm does not support Node.js v10.15.2
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9.
npm WARN npm You can find the latest version at https://nodejs.org/
npm WARN tar write after end
npm ERR! cb() never called!

npm ERR! This is an error with npm itself. Please report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/flo/.npm/_logs/2020-02-13T09_42_26_044Z-debug.log
Package install failed, see above.
See "/tmp/ng-3enaGH/angular-errors.log" for further details.

Body:
By default, the WORKSPACE and BUILD.bazel are only created when needed - during a build or when ng serve is running.

See the advanced section in the document you referenced above for how to change the defaults:

ng build --leaveBazelFilesOnDisk

For your second question, I had to upgrade node+angular to the latest LTS version before it worked for me.


问:
why cant I get this if statement to show?
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:</p>

```<code>#the main function
def main():
    print   #prints a blank line
    age = getAge ()
    weight = getWeight()
    birthMonth = getMonth()
    print
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if age <= 25:
        print 'Congratulations, the age is 25 or less.'

    if weight >= 128:
        print 'Congatulations, the weight is 128 or more.'

    if birthMonth == 'April':
        print 'Congratulations, the birth month is April.'

#calls main
main()
</code>```

答:
input() function returns a string. Before performing the integer comparison you are trying to do, you have to convert string.

For example:

```<code>def getAge():
    age = input('Enter your guess for age: ')
    return int(age)
</code>```

Body:
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:

#the main function
def main():
    print   #prints a blank line
    age = getAge ()
    weight = getWeight()
    birthMonth = getMonth()
    print
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if age <= 25:
        print 'Congratulations, the age is 25 or less.'

    if weight >= 128:
        print 'Congatulations, the weight is 128 or more.'

    if birthMonth == 'April':
        print 'Congratulations, the birth month is April.'

#calls main
main()

Body:
input() function returns a string. Before performing the integer comparison you are trying to do, you have to convert string.

For example:

def getAge():
    age = input('Enter your guess for age: ')
    return int(age)


问:
How to release the player of the Exoplayer PlayerView?
I use two different instances of PlayerView (com.google.android.exoplayer2.ui.PlayerView) in two fragments in my app. Both of these Playerview instances use the same SimpleExoPlayer instance for the player. In fragment1 the playerView1 works fine and also when I go to the fragment2 the playerView2 which uses the same SimpleExoPlayer instace works fine. The problem is when I go back to the fragment1 the playerView1 doesn't show anything. I think before going back to the 1st fragment I should release the player of the playerView2 but I don't know how.

In fragment1 (kotlin):

```<code>playerView1.player = myGlobalSimpleExoPlayer
</code>```

In fragment2 (kotlin):

```<code>playerView2.player = myGlobalSimpleExoPlayer
</code>```

答:
After trying different methods finally I found the solution. I share the solution here maybe it would be useful for others with the same problem.

In each fragment before setting the player of the PlayerView I set null value for the player (You should do this each time you switch the fragments, not only the first time):

```<code>playerView.player = null // add this before setting the actual player
playerView.player = myGlobalSimpleExoPlayer
</code>```

Body:
I use two different instances of PlayerView (com.google.android.exoplayer2.ui.PlayerView) in two fragments in my app. Both of these Playerview instances use the same SimpleExoPlayer instance for the player. In fragment1 the playerView1 works fine and also when I go to the fragment2 the playerView2 which uses the same SimpleExoPlayer instace works fine. The problem is when I go back to the fragment1 the playerView1 doesn't show anything. I think before going back to the 1st fragment I should release the player of the playerView2 but I don't know how.

In fragment1 (kotlin):

playerView1.player = myGlobalSimpleExoPlayer

In fragment2 (kotlin):

playerView2.player = myGlobalSimpleExoPlayer

Body:
After trying different methods finally I found the solution. I share the solution here maybe it would be useful for others with the same problem.

In each fragment before setting the player of the PlayerView I set null value for the player (You should do this each time you switch the fragments, not only the first time):

playerView.player = null // add this before setting the actual player
playerView.player = myGlobalSimpleExoPlayer


问:
Can't query semi-structured data using lateral flatten etc
I've got some data in a table, and one of the columns is a Variant which contains a ree of JSON data. I can successfully flatten arrays, and arrays within arrays to access data therein but I'm struggling with flattening key-value pairs to access the value for a given key.

I've seen the docs at https://docs.snowflake.net/manuals/user-guide/json-basics-tutorial.html mapping this onto my use case results in NULL values in the results.

My variant is show in part below - In particular it's values like MatchStatus and the key/values under Variables that I'm interested in extracting.

Thanks for any helpful suggestions.

答:
The described JSON has a simple path-like structure with objects at various levels (and no arrays).

Per Snowflake's semi-structured data documentation, use the dot notation to extract a value following a (flatly nested) path:

```<code>Insert a colon : between the VARIANT column name
and any first-level element: <column>:<level1_element>.

Use dot notation to traverse a path in a JSON object:
<column>:<level1_element>.<level2_element>.<level3_element>.
</code>```

An example would be (note the chained use of dots in the third and fourth lines):

SELECT
  badminton_odds:Id as id,
  badminton_odds:PricingRequest.MatchStatus as match_status,
  badminton_odds:PricingRequest.Variables.Dispersion as var_dispersion
FROM odds_table
```

You do not require FLATTEN for simple, singular value extraction. Use FLATTEN when you have a need to explode some series data into multiple rows (such as in case of arrays).

For example, if the described JSON in the question is how a single array element looks in a long array of such objects, you may use FLATTEN to first break the whole array into rows, and then apply path style extraction to retrieve the value from each row.

Body:
The described JSON has a simple path-like structure with objects at various levels (and no arrays).

Per Snowflake's semi-structured data documentation, use the dot notation to extract a value following a (flatly nested) path:

Insert a colon : between the VARIANT column name
and any first-level element: <column>:<level1_element>.

Use dot notation to traverse a path in a JSON object:
<column>:<level1_element>.<level2_element>.<level3_element>.

An example would be (note the chained use of dots in the third and fourth lines):

SELECT
  badminton_odds:Id as id,
  badminton_odds:PricingRequest.MatchStatus as match_status,
  badminton_odds:PricingRequest.Variables.Dispersion as var_dispersion
FROM odds_table

You do not require FLATTEN for simple, singular value extraction. Use FLATTEN when you have a need to explode some series data into multiple rows (such as in case of arrays).

For example, if the described JSON in the question is how a single array element looks in a long array of such objects, you may use FLATTEN to first break the whole array into rows, and then apply path style extraction to retrieve the value from each row.


问:
flag provided but not defined: -test.v
Unit test for the following code fails:

This is my main code:

```<code>package locprovider

import (
    "encoding/json"
    "fmt"
    "net/http"

    "api/domain/location"
    "api/utils/error"
    "github.com/mercadolibre/golang-restclient/rest"
)

const (
    getCountryUrl = "https://api.mercadolibre.com/countries/%s"
)

func GetCountry(countryId string) (*location.Country, *error.ApiError) {

    response := rest.Get(fmt.Sprintf(getCountryUrl, countryId))
    if response == nil || response.Response == nil {
        return nil, &error.ApiError {
            Status: http.StatusInternalServerError,
            Message: fmt.Sprintf("invalid restclient response when trying to get country %s", countryId),
        }
    }

    if response.StatusCode > 299 {
        var apiError error.ApiError
        if err := json.Unmarshal(response.Bytes(), &apiError); err != nil {
            return nil, &error.ApiError {
                Status: http.StatusInternalServerError,
                Message: fmt.Sprintf("invalid error response when getting country %s", countryId),
            }
        }
        return nil, &apiError
    }

    var result location.Country
    if err := json.Unmarshal(response.Bytes(), &result); err != nil {
        return nil, &error.ApiError {
            Status: http.StatusInternalServerError,
            Message: fmt.Sprintf("error when trying to unmarshal country data for %s", countryId),
        }
    }

    return &result, nil
}
</code>```

This is my unit test code:

```<code>package locprovider

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGetCountryRestClientError(t *testing.T) {
    // Execution:
    country, err := GetCountry("AR")

    // Validation:
    assert.Nil(t, country)
    assert.NotNil(t, err)
    assert.EqualValues(t, 500, err.Status)
    assert.EqualValues(t, "invalid restclient response when trying to get country AR", err.Message)
}
</code>```

When I execute this unit test, I run into following error and I am not sure why it is happening.

I have few other unit tests from other go package, and they work fine without this error.

GOROOT=/usr/local/Cellar/go/1.13.3/libexec #gosetup
      GOPATH=/Users/abc/go-testing #gosetup
      /usr/local/Cellar/go/1.13.3/libexec/bin/go test -c -o /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider api/provider/locprovider #gosetup
      /usr/local/Cellar/go/1.13.3/libexec/bin/go tool test2json -t /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider -test.v -test.run ^TestGetCountryRestClientError$ #gosetup
      flag provided but not defined: -test.v
      Usage of /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider:
        -mock
  Use 'mock' flag to tell package rest that you would like to use mockups.
  Process finished with exit code 1

答:
That seems similar to golang/go issue 33869, which in turn pointed to go/issue 31859 "testing: panic in Init if flag.Parse has already been called " and this Go 1.13 instruction

Testing flags are now registered in the new Init function, which is invoked by the generated main function for the test.

As a result, testing flags are now only registered when running a test binary, and packages that call flag.Parse during package initialization may cause tests to fail.

As noted by Sachin Raut in the comments:

The problem seems to be with the external library (github.com/mercadolibre/golang-restclient/rest).

As of now (July 2020), this "golang-restclient/rest" library does not support the latest versions of Go.

It works well with GO VERSIONS <= 1.12

Title: flag provided but not defined: -test.v

Body:
Unit test for the following code fails:

This is my main code:

package locprovider

import (
    "encoding/json"
    "fmt"
    "net/http"

    "api/domain/location"
    "api/utils/error"
    "github.com/mercadolibre/golang-restclient/rest"
)

const (
    getCountryUrl = "https://api.mercadolibre.com/countries/%s"
)

func GetCountry(countryId string) (*location.Country, *error.ApiError) {

    response := rest.Get(fmt.Sprintf(getCountryUrl, countryId))
    if response == nil || response.Response == nil {
        return nil, &error.ApiError {
            Status: http.StatusInternalServerError,
            Message: fmt.Sprintf("invalid restclient response when trying to get country %s", countryId),
        }
    }

    if response.StatusCode > 299 {
        var apiError error.ApiError
        if err := json.Unmarshal(response.Bytes(), &apiError); err != nil {
            return nil, &error.ApiError {
                Status: http.StatusInternalServerError,
                Message: fmt.Sprintf("invalid error response when getting country %s", countryId),
            }
        }
        return nil, &apiError
    }

    var result location.Country
    if err := json.Unmarshal(response.Bytes(), &result); err != nil {
        return nil, &error.ApiError {
            Status: http.StatusInternalServerError,
            Message: fmt.Sprintf("error when trying to unmarshal country data for %s", countryId),
        }
    }

    return &result, nil
}

This is my unit test code:

package locprovider

import (
    "testing"

    "github.com/stretchr/testify/assert"
)

func TestGetCountryRestClientError(t *testing.T) {
    // Execution:
    country, err := GetCountry("AR")

    // Validation:
    assert.Nil(t, country)
    assert.NotNil(t, err)
    assert.EqualValues(t, 500, err.Status)
    assert.EqualValues(t, "invalid restclient response when trying to get country AR", err.Message)
}

When I execute this unit test, I run into following error and I am not sure why it is happening.

I have few other unit tests from other go package, and they work fine without this error.

GOROOT=/usr/local/Cellar/go/1.13.3/libexec #gosetup
      GOPATH=/Users/abc/go-testing #gosetup
      /usr/local/Cellar/go/1.13.3/libexec/bin/go test -c -o /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider api/provider/locprovider #gosetup
      /usr/local/Cellar/go/1.13.3/libexec/bin/go tool test2json -t /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider -test.v -test.run ^TestGetCountryRestClientError$ #gosetup
      flag provided but not defined: -test.v
      Usage of /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider:
        -mock
  Use 'mock' flag to tell package rest that you would like to use mockups.
  Process finished with exit code 1


问:
Firefox CSS spacing issues cross-os
I'm having an issue with Firefox. It displays differently in Windows than on OSX. It looks to be a font spacing issue, or font size, but I can't figure it out. Both use the exact same properties.

Top Window: Mac OSX, Bottom: WinXP

Here's the basic HTML/Computed Style:

Any ideas from anyone?

答:
If you're hoping to build the best cross-browser experience, a few CSS tweaks will make for a more forgiving layout and lessen any font rendering differences.

For example, to improve your current markup you should:

Float or absolutely position
 to the top, right of its parent element

Right align all the text within topNav

This will ensure that your top navigation will always grow to the left, and not go beyond the page to the right (as pictured in the bottom Windows XP/Firefox screenshot).

After this change, the font differences will be lessened, since the layout can grown or expand gracefully while changes the cartNav won't break the layout.

While you're making these changes, you might consider combining the sub-nav icons into a CSS Sprite.

As Web Developers, we're accustomed to browser testing and rendering inconsistencies, but consider that it's highly unlikely anyone except yourself (perhaps of course a fellow developer, or client) would ever compare the way the site renders between browsers or operating systems.

Title: Firefox CSS spacing issues cross-os

Body:
If you're hoping to build the best cross-browser experience, a few CSS tweaks will make for a more forgiving layout and lessen any font rendering differences.

For example, to improve your current markup you should:

Float or absolutely position <div class="topNav"> to the top, right of its parent element

Right align all the text within topNav

This will ensure that your top navigation will always grow to the left, and not go beyond the page to the right (as pictured in the bottom Windows XP/Firefox screenshot).

After this change, the font differences will be lessened, since the layout can grown or expand gracefully while changes the cartNav won't break the layout.

While you're making these changes, you might consider combining the sub-nav icons into a CSS Sprite.

As Web Developers, we're accustomed to browser testing and rendering inconsistencies, but consider that it's highly unlikely anyone except yourself (perhaps of course a fellow developer, or client) would ever compare the way the site renders between browsers or operating systems.


问:
Constant ripple effect in android
What I'm trying to do is to have a constant ripple effect on the background of a LinearLayout. Why? Basically, this LinearLayout indicates live users watching this item. So I want the background to have a constant ripple animation similar to some apps that have a live indicator with a ripple effect on the background of that indicator. I hope my question was clear.

Example:
I want this effect to be happing constantly

答:
Hi i tried to code something like this and below is what i come close to. You can always tweek numbers to slow down the animation and other things.

1) Create a ripple drawable background in your res/drawable named temp_ripple.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimary"
    >
    <item android:id="@android:id/mask"
        android:drawable="@android:color/holo_green_dark"
        >
    </item>
    <item
        android:drawable="@android:color/holo_orange_dark">
    </item>

</ripple>
</code>```

2) assign the background to possible view candidate like below, here AppCompatButton to android:background="@drawable/temp_ripple"

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnLive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:background="@drawable/temp_ripple"
        android:foreground="?selectableItemBackground"
        android:text="12.5k Live"
        android:textColor="@android:color/white" />

</RelativeLayout>
</code>```

3) Get the ripple drawable from the view and create a runnable running after 2 sec to repeat the animation by setting the states of the ripple drawable in click listener of the button

```<code>package com.example.android.treasureHunt

import android.content.res.ColorStateList
import android.graphics.drawable.RippleDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.temp_activity.*

class TempActivity : AppCompatActivity(R.layout.temp_activity) {

    val handler = Handler()
    lateinit var runnable: Runnable
    var count = 0
    lateinit var rippleDrawable: RippleDrawable

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        rippleDrawable = btnLive.background as RippleDrawable
        setLiveCountListener()
        btnLive.setOnClickListener {
            Log.d("TAG++", "button clicked")
            rippleDrawable.state = intArrayOf(
                android.R.attr.state_pressed,
                android.R.attr.state_enabled
            )
        }
    }

    private fun setLiveCountListener() {
        runnable = Runnable {
            rippleDrawable.state = intArrayOf()
            btnLive.performClick()
            //to perform another runnable after some time creating a race condition
            handler.postDelayed(runnable, 2000)
            //condition to breakout from loop
            if (count == 10) {
                handler.removeCallbacks(runnable)
            }
            Log.d("TAG++", "Loop running")
        }
        //trigger the start of the ui thread
        handler.postDelayed(runnable, 2000)
    }

}
</code>```

Title: Constant ripple effect in android

Body:
Hi i tried to code something like this and below is what i come close to. You can always tweek numbers to slow down the animation and other things.

1) Create a ripple drawable background in your res/drawable named temp_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@color/colorPrimary"
    >
    <item android:id="@android:id/mask"
        android:drawable="@android:color/holo_green_dark"
        >
    </item>
    <item
        android:drawable="@android:color/holo_orange_dark">
    </item>

</ripple>

2) assign the background to possible view candidate like below, here AppCompatButton to android:background="@drawable/temp_ripple"

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnLive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:background="@drawable/temp_ripple"
        android:foreground="?selectableItemBackground"
        android:text="12.5k Live"
        android:textColor="@android:color/white" />

</RelativeLayout>

3) Get the ripple drawable from the view and create a runnable running after 2 sec to repeat the animation by setting the states of the ripple drawable in click listener of the button

package com.example.android.treasureHunt

import android.content.res.ColorStateList
import android.graphics.drawable.RippleDrawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.temp_activity.*

class TempActivity : AppCompatActivity(R.layout.temp_activity) {

    val handler = Handler()
    lateinit var runnable: Runnable
    var count = 0
    lateinit var rippleDrawable: RippleDrawable

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        rippleDrawable = btnLive.background as RippleDrawable
        setLiveCountListener()
        btnLive.setOnClickListener {
            Log.d("TAG++", "button clicked")
            rippleDrawable.state = intArrayOf(
                android.R.attr.state_pressed,
                android.R.attr.state_enabled
            )
        }
    }

    private fun setLiveCountListener() {
        runnable = Runnable {
            rippleDrawable.state = intArrayOf()
            btnLive.performClick()
            //to perform another runnable after some time creating a race condition
            handler.postDelayed(runnable, 2000)
            //condition to breakout from loop
            if (count == 10) {
                handler.removeCallbacks(runnable)
            }
            Log.d("TAG++", "Loop running")
        }
        //trigger the start of the ui thread
        handler.postDelayed(runnable, 2000)
    }

}