问:
Google picker authentication issue
The google picker dialog keeps asking to authenticate even after authenticating.
This is what it shows:
https://i.stack.imgur.com/PC4xD.png
When the sign-in button is clicked the authentication popup disappears immediately after showing for like a millisecond.

The First thing I tried was following the Google Picker API documentation at https://developers.google.com/drive/picker/guides/overview
Though I ran into a problem with that example.

```<code> tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: 'YOUR_CLIENT_ID',
          scope: 'YOUR_SCOPES',
          callback: '', // defined later
        });
        gisInited = true;
</code>```

the snippet above won't work because the property "accounts" no longer exists on the object "google". For some reason, the documentation is not up to date.

My second idea was to use the "gapi" library to handle the authentication process but then I ran in into the current issue.
Is there something I am missing?
(Current Code)

```<code>`  gapi.load('client:auth2', () => {
            initClient();
        });

    const initClient = () => {

        try {
            gapi.client.init({
                apiKey: google_devkey,
                clientId: google_client_id,
                discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
                scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
            }).then(() => {
                gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
                updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
            })
        } catch (e) {
            console.error("Auth Init ERROR:", e)
        }

    };

   const updateSigninStatus = (isSignedIn) => {
        console.error("isSignedIn::", isSignedIn)
        if (isSignedIn) {
            console.error("init Create Picker")
            createPicker();
        } else {
            // prompt user to sign in
            handleAuth();
        }
    };

 const handleAuth = (event) => {
        gapi.auth2.authorize({
            client_id: settings.google_client_id,
            scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
        }, () => { })
    };

 function createPicker() {
let accessToken =  gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token || null
        console.error("TOKEN:", accessToken)
        if (accessToken) {
            const picker = new window.google.picker.PickerBuilder()
                .addView(window.google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
                .setOAuthToken(accessToken)
                .setDeveloperKey(google_devkey)
                .setCallback(pickerCallback)
                .build();
            picker.setVisible(true);
        }

    }
`
</code>```

Title: Google picker authentication issue

Body:
The google picker dialog keeps asking to authenticate even after authenticating.
This is what it shows:
https://i.stack.imgur.com/PC4xD.png
When the sign-in button is clicked the authentication popup disappears immediately after showing for like a millisecond.

The First thing I tried was following the Google Picker API documentation at https://developers.google.com/drive/picker/guides/overview
Though I ran into a problem with that example.

 tokenClient = google.accounts.oauth2.initTokenClient({
          client_id: 'YOUR_CLIENT_ID',
          scope: 'YOUR_SCOPES',
          callback: '', // defined later
        });
        gisInited = true;

the snippet above won't work because the property "accounts" no longer exists on the object "google". For some reason, the documentation is not up to date.

My second idea was to use the "gapi" library to handle the authentication process but then I ran in into the current issue.
Is there something I am missing?
(Current Code)

`  gapi.load('client:auth2', () => {
            initClient();
        });

    const initClient = () => {

        try {
            gapi.client.init({
                apiKey: google_devkey,
                clientId: google_client_id,
                discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/drive/v3/rest'],
                scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
            }).then(() => {
                gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
                updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
            })
        } catch (e) {
            console.error("Auth Init ERROR:", e)
        }

    };

   const updateSigninStatus = (isSignedIn) => {
        console.error("isSignedIn::", isSignedIn)
        if (isSignedIn) {
            console.error("init Create Picker")
            createPicker();
        } else {
            // prompt user to sign in
            handleAuth();
        }
    };

 const handleAuth = (event) => {
        gapi.auth2.authorize({
            client_id: settings.google_client_id,
            scope: 'https://www.googleapis.com/auth/drive.metadata.readonly',
        }, () => { })
    };

 function createPicker() {
let accessToken =  gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token || null
        console.error("TOKEN:", accessToken)
        if (accessToken) {
            const picker = new window.google.picker.PickerBuilder()
                .addView(window.google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
                .setOAuthToken(accessToken)
                .setDeveloperKey(google_devkey)
                .setCallback(pickerCallback)
                .build();
            picker.setVisible(true);
        }

    }
`


来源: stackexchange

问:
Load view-source:myURL in Selenium 4 and get page source
Using selenium 4 webdriver and .Net 6, I got:

```<code>webDriver.Navigate().GoToUrl('https://example.com');
string pageSource_1= webDriver.PageSource;
</code>```

In order to load the page content quickly and no need to JS contents, I tried to load only html source code of the url, so I used this:

```<code>webDriver.Navigate().GoToUrl('view-source:https://example.com');
string pageSource_2= webDriver.PageSource;
</code>```

The latter sends only 1 request to server instead of 25 requests!
The problem is working on pageSource_2. For example HTML code in PageSource_1:

```<code> <tr>
    <td>Abu Dhabi</td>
    <td class='text-right'> No Appointments Available</td>
</tr>
</code>```

Is converting to this in PageSource_2:

```<code>    <tr>
      <td class="line-number" value="287"></td>
      <td class="line-content">
        <span class="html-tag"><td></span>Abu Dhabi <span class="html-tag"></td></span>
      </td>
    </tr>
         // removed for simplicity .    .    .
    <tr>
      <td class="line-number" value="289"></td>
      <td class="line-content">No Appointments Available</td>
    </tr>
</code>```

Question: is there any way to load view-source:myURL and get the page source correctly ?

Extra Info: I tried

disabling JS and Css in selenium driver to load my url faster, but page doesn't load in this way.

using httpclient to load the url and get the content of the page, but because of authentication on the url I couldn't find  a good example of login to a page (cookie based) and get the html content in C#.

manipulating the Pagesource_2 with Html-Agility but finding the desired element/node in PageSource_2 format is impossible, cause no element Id/class/attribute available like PageSource_1 which is easy to use html format. (The value attribute is different in each server response).

Any hint to load only source code of a url using selenium 4 or any other third party or other libraries is appreciable. Something like html agility to convert pageSource_2 to HTML like PageSource_1.

ContentLicense: CC BY-SA 4.0

Body:
Using selenium 4 webdriver and .Net 6, I got:

webDriver.Navigate().GoToUrl('https://example.com');
string pageSource_1= webDriver.PageSource;

In order to load the page content quickly and no need to JS contents, I tried to load only html source code of the url, so I used this:

webDriver.Navigate().GoToUrl('view-source:https://example.com');
string pageSource_2= webDriver.PageSource;

The latter sends only 1 request to server instead of 25 requests!
The problem is working on pageSource_2. For example HTML code in PageSource_1:

    Abu Dhabi
     No Appointments Available

Is converting to this in PageSource_2:

        Abu Dhabi

         // removed for simplicity .    .    .

      No Appointments Available

Question: is there any way to load view-source:myURL and get the page source correctly ?

Extra Info: I tried

disabling JS and Css in selenium driver to load my url faster, but page doesn't load in this way.

using httpclient to load the url and get the content of the page, but because of authentication on the url I couldn't find  a good example of login to a page (cookie based) and get the html content in C#.

manipulating the Pagesource_2 with Html-Agility but finding the desired element/node in PageSource_2 format is impossible, cause no element Id/class/attribute available like PageSource_1 which is easy to use html format. (The value attribute is different in each server response).

Any hint to load only source code of a url using selenium 4 or any other third party or other libraries is appreciable. Something like html agility to convert pageSource_2 to HTML like PageSource_1.


问:
How to count number of appointments per day in SharePoint
I have a shared SharePoint calendar with a team. The purpose of the calendar is for individuals to post when they will be out of office. The posts are both single day or multi-day appointments.

I would like to count the total number of appointments per day so that I can see if there is a discernable trend for days spent out of office.

How can I count the total number of appointments for each day? I would ultimately like to visualize the data like this enter image description here

I tried exporting the data as a standard list but am not able to account for the days where a scheduled appointment spans multiple days - ex. 12/5-12/9. In this case, it would be exported as a single event but I would need to see that it counts towards the total number of events scheduled for each day - 12/5, 12/6, 12/7, 12/8, and 12/9.


问:
Uncaught ReferenceError: hydepark is not defined at leaflet.js
I'm very new to leaflet and js and I need some help plotting some points in the map. I just cannot comprehend how this is not working.

Html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Miniprojeto2</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.2/dist/leaflet.css" integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14=" crossorigin=""/>
    <link rel="stylesheet" href="leaflet.css">
    <!-- Make sure you put this AFTER Leaflet's CSS -->
    <script src="https://unpkg.com/leaflet@1.9.2/dist/leaflet.js"></script>
    <script src="leaflet.js" defer> </script>
    <script src="hydepark.geojson" type="text/javascript" defer></script>

    </script>
</head>
<body>
    <div id="mapDIV">i</div>
    <script>

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

JS

```<code>let map=L.map(document.getElementById("mapDIV"),{
    center:[42.349541638743574, -71.0599072324557],
    zoom: 13
});
let basemap= L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{});
    basemap.addTo(map);

var crimes = L.geoJSON().addTo(map);
crimes.addData(hydepark);
crimes.bindTooltip('Crimes Boston');
crimes
</code>```

Crime

```<code>var hydepark = {
"type": "FeatureCollection",
"name": "hydepark",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "businessname": "20TH CENTRY BOWLING LANES", "dbaname": "", "legalowner": "COVITZ", "namelast": "COVITZ", "namefirst": "RONALD", "licenseno": 18671, "issdttm": "25/01/2012 13:39", "expdttm": "31/12/2020 23:59", "licstatus": "Active", "licensecat": "FT", "descript": "Eating & Drinking w/ Take Out", "result": "HE_Fail", "resultdttm": "07/07/2008 13:14", "violation": "15-4-202.16", "viollevel": "*", "violdesc": "Non-Food Contact Surfaces", "violdttm": "08/07/2008 08:44", "violstatus": "Fail", "statusdate": "", "comments": "Peeling paint in Men's Room  and on shelves in the basement", "address": "1231   Hyde Park AVE", "city": "Hyde Park", "state": "MA", "zip": 2136, "property_id": 77089, "y": 42.25682, "x": -71.12411 }, "geometry": { "type": "Point", "coordinates": [ -71.12411, 42.25682 ] } },
....................................................
...
</code>```

I followed the tutorial on the leaflet but it didn't much improvement.

Body:
I'm very new to leaflet and js and I need some help plotting some points in the map. I just cannot comprehend how this is not working.

Html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Miniprojeto2</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.2/dist/leaflet.css" integrity="sha256-sA+zWATbFveLLNqWO2gtiw3HL/lh1giY/Inf1BJ0z14=" crossorigin=""/>
    <link rel="stylesheet" href="leaflet.css">

    </script>

i

JS

let map=L.map(document.getElementById("mapDIV"),{
    center:[42.349541638743574, -71.0599072324557],
    zoom: 13
});
let basemap= L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{});
    basemap.addTo(map);

var crimes = L.geoJSON().addTo(map);
crimes.addData(hydepark);
crimes.bindTooltip('Crimes Boston');
crimes

Crime

var hydepark = {
"type": "FeatureCollection",
"name": "hydepark",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "businessname": "20TH CENTRY BOWLING LANES", "dbaname": "", "legalowner": "COVITZ", "namelast": "COVITZ", "namefirst": "RONALD", "licenseno": 18671, "issdttm": "25/01/2012 13:39", "expdttm": "31/12/2020 23:59", "licstatus": "Active", "licensecat": "FT", "descript": "Eating & Drinking w/ Take Out", "result": "HE_Fail", "resultdttm": "07/07/2008 13:14", "violation": "15-4-202.16", "viollevel": "*", "violdesc": "Non-Food Contact Surfaces", "violdttm": "08/07/2008 08:44", "violstatus": "Fail", "statusdate": "", "comments": "Peeling paint in Men's Room  and on shelves in the basement", "address": "1231   Hyde Park AVE", "city": "Hyde Park", "state": "MA", "zip": 2136, "property_id": 77089, "y": 42.25682, "x": -71.12411 }, "geometry": { "type": "Point", "coordinates": [ -71.12411, 42.25682 ] } },
....................................................
...

I followed the tutorial on the leaflet but it didn't much improvement.


问:
403 Forbidden You don't have permission to access this ressources, Apache/2.4.52 (Ubuntu) Server at cermel.org Port 443
I have a vps on OVH and I tried to access it by ftp by wanting to configure a Proftpd server, I tried several tutorials without success and I wanted to start from scratch on the installation of said Proftpd too, I 've removed the packages and dependencies.

But after that, my website does not launch anymore, I have the following error: 403 Forbidden You don't have permission to access this resources, Apache/2.4.52 (Ubuntu) Server at cermel.org Port 443,

Could someone here help me please, thank you in advance.

Ulrich

I tried to give the rights to the user and the group but it doesn't change anything, I reviewed the configuration file of the virtual server but it still doesn't work.


问:
Using keyframes as proxy for scenes in videos
I am trying to implement a very basic scene detection using keyframes as proxy for scenes - it is good enough for our needs. Granted it doesn't have the sophistication of pyscenedetect or other scene detection approaches, but it appears to be good enough for our needs. Is there a further filtering approach that allows to remove duplicate keyframes (scenes) since keyframes can be duplicated?

```<code> scenes = []
 for frame in video:
    if frame.is_keyframe:
       scenes.append(frame)

</code>```

Body:
I am trying to implement a very basic scene detection using keyframes as proxy for scenes - it is good enough for our needs. Granted it doesn't have the sophistication of pyscenedetect or other scene detection approaches, but it appears to be good enough for our needs. Is there a further filtering approach that allows to remove duplicate keyframes (scenes) since keyframes can be duplicated?

 scenes = []
 for frame in video:
    if frame.is_keyframe:
       scenes.append(frame)


问:
AudioQueueNewInput callback data is all 0 on macOS app
I try to receive audio data from BlackHole2ch or other loop audio plugins on macOS.

I run this test code for macOS app. It callback with all 0 data.

```<code>#import "ViewController.h"
@implementation ViewController
#define DEVICE_UID "BlackHole2ch_UID"
static AudioQueueRef s_queue;
static AudioQueueBufferRef s_buffers[3];

- (void)viewDidLoad {
    [super viewDidLoad];
    [self audioInit];
    [self audioStart];
}

- (void) audioInit
{
    AudioStreamBasicDescription format;
    format.mSampleRate       = 44100;
    format.mFormatID         = kAudioFormatLinearPCM;
    format.mFormatFlags      = kLinearPCMFormatFlagIsSignedInteger;
    format.mBitsPerChannel   = 16;
    format.mChannelsPerFrame = 1;
    format.mBytesPerFrame    = 2 * format.mChannelsPerFrame;
    format.mFramesPerPacket  = 1;
    format.mBytesPerPacket   = format.mBytesPerFrame * format.mFramesPerPacket;
    format.mReserved         = 0;

    OSStatus err = AudioQueueNewInput(&format, virtual_speaker_callback, (__bridge void *)(self),
                                  CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &s_queue);
    NSLog(@"AudioQueueNewInput err=%d AudioQueue=%p", err, s_queue);

    CFStringRef deviceUID = CFStringCreateWithCString(kCFAllocatorDefault, DEVICE_UID, kCFStringEncodingMacRoman);
    err = AudioQueueSetProperty(s_queue, kAudioQueueProperty_CurrentDevice, &deviceUID, sizeof(deviceUID));
    NSLog(@"Set target device:%@ err=%d", deviceUID, err);

    for (int i = 0; i < NUM_BUFFERS; i++)
    {
        err = AudioQueueAllocateBuffer(s_queue, BUFFER_SIZE, &s_buffers[i]);
        NSLog(@"AudioQueueAllocateBuffer err=%d", err);
        err = AudioQueueEnqueueBuffer (s_queue, s_buffers[i], 0, NULL);
        NSLog(@"AudioQueueEnqueueBuffer err=%d", err);
    }
}

- (void) audioStart
{
    OSStatus err = AudioQueueStart(s_queue, NULL);
    NSLog(@"AudioQueueStart err=%d", err);
}

static void virtual_speaker_callback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription *inPacketDescs)
{
    uint8_t *p = (uint8_t*)inBuffer->mAudioData;
    int64_t sum = 0;
    for(int i=0;i<inBuffer->mAudioDataBytesCapacity;++i) {
        sum += p[i];
    }
    if (sum == 0) {
        NSLog(@"virtual_speaker_callback all Zero ptr=%p data[]=%d %d ...", p, p[0], p[1]);
    } else {
        NSLog(@"virtual_speaker_callback valid data ptr=%p data[]=%d %d ...", p, p[0], p[1]);
    }
    OSStatus err = AudioQueueEnqueueBuffer(s_queue, inBuffer, 0, nil);
    NSLog(@"AudioQueueEnqueueBuffer err=%d", err);
}
@end
</code>```

I also try console app with same kind of code. It works with valid callback data.

I enabled "Audio Input" on Xcode capabilities settings.
MacOS:13.0.1 Ventura
Xcode:14.1 (14B47b)

Body:
I try to receive audio data from BlackHole2ch or other loop audio plugins on macOS.

I run this test code for macOS app. It callback with all 0 data.

#import "ViewController.h"
@implementation ViewController
#define DEVICE_UID "BlackHole2ch_UID"
static AudioQueueRef s_queue;
static AudioQueueBufferRef s_buffers[3];

- (void)viewDidLoad {
    [super viewDidLoad];
    [self audioInit];
    [self audioStart];
}

- (void) audioInit
{
    AudioStreamBasicDescription format;
    format.mSampleRate       = 44100;
    format.mFormatID         = kAudioFormatLinearPCM;
    format.mFormatFlags      = kLinearPCMFormatFlagIsSignedInteger;
    format.mBitsPerChannel   = 16;
    format.mChannelsPerFrame = 1;
    format.mBytesPerFrame    = 2 * format.mChannelsPerFrame;
    format.mFramesPerPacket  = 1;
    format.mBytesPerPacket   = format.mBytesPerFrame * format.mFramesPerPacket;
    format.mReserved         = 0;

    OSStatus err = AudioQueueNewInput(&format, virtual_speaker_callback, (__bridge void *)(self),
                                  CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &s_queue);
    NSLog(@"AudioQueueNewInput err=%d AudioQueue=%p", err, s_queue);

    CFStringRef deviceUID = CFStringCreateWithCString(kCFAllocatorDefault, DEVICE_UID, kCFStringEncodingMacRoman);
    err = AudioQueueSetProperty(s_queue, kAudioQueueProperty_CurrentDevice, &deviceUID, sizeof(deviceUID));
    NSLog(@"Set target device:%@ err=%d", deviceUID, err);

    for (int i = 0; i < NUM_BUFFERS; i++)
    {
        err = AudioQueueAllocateBuffer(s_queue, BUFFER_SIZE, &s_buffers[i]);
        NSLog(@"AudioQueueAllocateBuffer err=%d", err);
        err = AudioQueueEnqueueBuffer (s_queue, s_buffers[i], 0, NULL);
        NSLog(@"AudioQueueEnqueueBuffer err=%d", err);
    }
}

- (void) audioStart
{
    OSStatus err = AudioQueueStart(s_queue, NULL);
    NSLog(@"AudioQueueStart err=%d", err);
}

static void virtual_speaker_callback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer, const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions, const AudioStreamPacketDescription *inPacketDescs)
{
    uint8_t *p = (uint8_t*)inBuffer->mAudioData;
    int64_t sum = 0;
    for(int i=0;i<inBuffer->mAudioDataBytesCapacity;++i) {
        sum += p[i];
    }
    if (sum == 0) {
        NSLog(@"virtual_speaker_callback all Zero ptr=%p data[]=%d %d ...", p, p[0], p[1]);
    } else {
        NSLog(@"virtual_speaker_callback valid data ptr=%p data[]=%d %d ...", p, p[0], p[1]);
    }
    OSStatus err = AudioQueueEnqueueBuffer(s_queue, inBuffer, 0, nil);
    NSLog(@"AudioQueueEnqueueBuffer err=%d", err);
}
@end

I also try console app with same kind of code. It works with valid callback data.

I enabled "Audio Input" on Xcode capabilities settings.
MacOS:13.0.1 Ventura
Xcode:14.1 (14B47b)


问:
Explicitly calling named functions inside solidity proxy contracts
I am referencing the the Gnosis-safe proxy function here https://github.com/safe-global/safe-contracts/blob/main/contracts/proxies/SafeProxy.sol:

```<code>// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
    function masterCopy() external view returns (address);
}

/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
    // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
    // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
    address internal singleton;

    /// @dev Constructor function sets address of singleton contract.
    /// @param _singleton Singleton address.
    constructor(address _singleton) {
        require(_singleton != address(0), "Invalid singleton address provided");
        singleton = _singleton;
    }

    /// @dev Fallback function forwards all transactions and returns all received return data.
    fallback() external payable {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
            // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
            if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                mstore(0, _singleton)
                return(0, 0x20)
            }
            calldatacopy(0, 0, calldatasize())
            let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if eq(success, 0) {
                revert(0, returndatasize())
            }
            return(0, returndatasize())
        }
    }
}
</code>```

There are no named functions inside GnosisSafeProxy, and all calls to the Proxy will direct to fallback. In my use case, I'd like to have a few named functions inside the proxy, for example, I may want to do:

```<code>function namedFn(address _alice){
    /// in pseudo-code:
    /// call contract@singleton.namedFn(_alice)
}

</code>```

I assume this is possible, if not an anti-pattern. But what would be the syntax for referencing contract@singleton.namedFn?

If I want GnosisSafeProxy to be Initializable, and let's assume GnosisSafeProxy is proxying an GnosisSafeUpgradeable,  so that I can do an initialization of GnosisSafeProxy with:

```<code>    function initGnosisSafeProxy(address _singleton, address _alice, address _bob ) initializer public {
         singleton = _singleton;
         contract@singleton.initialize(_alice,_bob);
    }

</code>```

This would also be possible assuming I can reference contract@singleton correct? What would be the syntax here, and is there some egregious error that I'm committing here conceptually?

Body:
I am referencing the the Gnosis-safe proxy function here https://github.com/safe-global/safe-contracts/blob/main/contracts/proxies/SafeProxy.sol:

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain
/// @author Richard Meissner - <richard@gnosis.io>
interface IProxy {
    function masterCopy() external view returns (address);
}

/// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <stefan@gnosis.io>
/// @author Richard Meissner - <richard@gnosis.io>
contract GnosisSafeProxy {
    // singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.
    // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`
    address internal singleton;

    /// @dev Constructor function sets address of singleton contract.
    /// @param _singleton Singleton address.
    constructor(address _singleton) {
        require(_singleton != address(0), "Invalid singleton address provided");
        singleton = _singleton;
    }

    /// @dev Fallback function forwards all transactions and returns all received return data.
    fallback() external payable {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
            // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
            if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {
                mstore(0, _singleton)
                return(0, 0x20)
            }
            calldatacopy(0, 0, calldatasize())
            let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if eq(success, 0) {
                revert(0, returndatasize())
            }
            return(0, returndatasize())
        }
    }
}

There are no named functions inside GnosisSafeProxy, and all calls to the Proxy will direct to fallback. In my use case, I'd like to have a few named functions inside the proxy, for example, I may want to do:

function namedFn(address _alice){
    /// in pseudo-code:
    /// call contract@singleton.namedFn(_alice)
}

I assume this is possible, if not an anti-pattern. But what would be the syntax for referencing contract@singleton.namedFn?

If I want GnosisSafeProxy to be Initializable, and let's assume GnosisSafeProxy is proxying an GnosisSafeUpgradeable,  so that I can do an initialization of GnosisSafeProxy with:

    function initGnosisSafeProxy(address _singleton, address _alice, address _bob ) initializer public {
         singleton = _singleton;
         contract@singleton.initialize(_alice,_bob);
    }

This would also be possible assuming I can reference contract@singleton correct? What would be the syntax here, and is there some egregious error that I'm committing here conceptually?


问:
facial Emotion Detection I have a problem when I do epochs
new_model.fit(x,y, epochs =6)

is not working in my code

how can I make it work
tried many thing but it still not working

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


问:
Appending item to list
I am trying to append an item (card) to a list (player_hand) however it is giving me an error stating "TypeError: 'NoneType' object is not iterable"

My code:

```<code>def player_turn(player_hand, deck):

hand_value = get_hand_value(player_hand)
print('Player:', hand_value)
cards.display_cards(player_hand)

if hand_value == MAX:
    choice = None

if hand_value < MAX:
    choice = get_player_choice()

while choice == HIT:
    player_hand = player_hand.append(deck.pop())
    hand_value = get_hand_value(player_hand)
    if hand_value <= MAX:
        print(f"Player: {hand_value}")
        get_player_choice()
    else:
        print(f"Player: {hand_value}, BUSTED!")
</code>```

Cpde for the get_hand_value function:

```<code>def get_hand_value(hand):

total = 0
for card in hand:
    total += card.value

for card in hand:
    if total > MAX:
        if card.is_ace():
            total -= 10

return total
</code>```

error i am receiving:

```<code>in player_turn
hand_value = get_hand_value(player_hand)

hand = None

def get_hand_value(hand):

    total = 0
>       for card in hand:
E       TypeError: 'NoneType' object is not iterable

blackjack.py:72: TypeError
</code>```

Title: Appending item to list

Body:
I am trying to append an item (card) to a list (player_hand) however it is giving me an error stating "TypeError: 'NoneType' object is not iterable"

My code:

def player_turn(player_hand, deck):

hand_value = get_hand_value(player_hand)
print('Player:', hand_value)
cards.display_cards(player_hand)

if hand_value == MAX:
    choice = None

if hand_value < MAX:
    choice = get_player_choice()

while choice == HIT:
    player_hand = player_hand.append(deck.pop())
    hand_value = get_hand_value(player_hand)
    if hand_value <= MAX:
        print(f"Player: {hand_value}")
        get_player_choice()
    else:
        print(f"Player: {hand_value}, BUSTED!")

Cpde for the get_hand_value function:

def get_hand_value(hand):

total = 0
for card in hand:
    total += card.value

for card in hand:
    if total > MAX:
        if card.is_ace():
            total -= 10

return total

error i am receiving:

in player_turn
hand_value = get_hand_value(player_hand)

hand = None

def get_hand_value(hand):

    total = 0
>       for card in hand:
E       TypeError: 'NoneType' object is not iterable

blackjack.py:72: TypeError


问:
ssh_exchange_identification read connection reset by peer (Cent OS 8)
I have a CentOS 8 with a local IP 192.168.1.19, I am able to able to ssh into it without a problem. I then NAT or port forward the same IP -> 1.1.1.9 but I get this error

```<code>Kex_exchange_identification read: Connection closed by remote host
</code>```

I have scratched my head for a while, and changed the server to an Ubuntu instance and it worked. Did a look up and found this article but it didn't help much either

Body:
I have a CentOS 8 with a local IP 192.168.1.19, I am able to able to ssh into it without a problem. I then NAT or port forward the same IP -> 1.1.1.9 but I get this error

Kex_exchange_identification read: Connection closed by remote host

I have scratched my head for a while, and changed the server to an Ubuntu instance and it worked. Did a look up and found this article but it didn't help much either


问:
Aggregate and match multiple subdocuments in mongoDB
So I have the following document structure:

```<code>{
    "id": 0,
    "users": [
      {
        "name": "bob",
        "id": 1000
      },
      {
        "name": "sally",
        "id": 2000
      }
    ],
    "comments": [
      {
        "commentor_index": 0,
        "comment": "foo",
        "emoji": "smile"
      },
      {
        "commentor_index": 0,
        "comment": "bar",
        "emoji": "heart"
      },
      {
        "commentor_index": 1,
        "comment": "zee",
        "emoji": "heart"
      }
    ]
  }
</code>```

The comments have the users index in the array.

I would like to be able to get how many comments each user id left across all documents.

I have gotten so far to realize I need to unwind both users and comments with includeArrayIndex for users, but I have trouble rejoining them.

Body:
So I have the following document structure:

{
    "id": 0,
    "users": [
      {
        "name": "bob",
        "id": 1000
      },
      {
        "name": "sally",
        "id": 2000
      }
    ],
    "comments": [
      {
        "commentor_index": 0,
        "comment": "foo",
        "emoji": "smile"
      },
      {
        "commentor_index": 0,
        "comment": "bar",
        "emoji": "heart"
      },
      {
        "commentor_index": 1,
        "comment": "zee",
        "emoji": "heart"
      }
    ]
  }

The comments have the users index in the array.

I would like to be able to get how many comments each user id left across all documents.

I have gotten so far to realize I need to unwind both users and comments with includeArrayIndex for users, but I have trouble rejoining them.


问:
Whole width on a element on flexbox navbar?
When I create navbar in flexbox layout hover is not fill whole width of a link only where text is on a element, how can i make to be whole width?

I tried several things but it wont work


问:
How to resolve python OSError 64 raised by dispy
I am having troubles tracking down a mysterious error message in Python 3.8. We're using dispy, and we randomly get the error message OSError: 64:

```<code>pycos - uncaught exception in tcp_req:
Traceback (most recent call last):
  File "venv38\Lib\site-packages\dispy/dispynode.py", line 1698, in tcp_req
    msg = yield conn.recv_msg()
  File "venv38\lib\site-packages\pycos\__init__.py", line 3767, in _schedule
    retval = task._generator.throw(*exc)
  File "venv38\lib\site-packages\pycos\__init__.py", line 984, in _async_recv_msg
    data = yield self.recvall(n)
OSError: 64
</code>```

We're starting dispynode (version 4.15.2), running on a VM with Windows Server 2016) with the following arguments:  --clean --cpus=32 --client_shutdown --ping_interval=15 --daemon --zombie_interval=60

The crashes appear to happen in the middle of the night, and it doesn't matter if the node is actively running a job or not.

I can't for the life of me figure out what OSError 64 means; all SO and google searches seem to think I'm asking about 64-bits, even if I specifically exlude the word "bits".

Body:
I am having troubles tracking down a mysterious error message in Python 3.8. We're using dispy, and we randomly get the error message OSError: 64:

pycos - uncaught exception in tcp_req:
Traceback (most recent call last):
  File "venv38\Lib\site-packages\dispy/dispynode.py", line 1698, in tcp_req
    msg = yield conn.recv_msg()
  File "venv38\lib\site-packages\pycos\__init__.py", line 3767, in _schedule
    retval = task._generator.throw(*exc)
  File "venv38\lib\site-packages\pycos\__init__.py", line 984, in _async_recv_msg
    data = yield self.recvall(n)
OSError: 64

We're starting dispynode (version 4.15.2), running on a VM with Windows Server 2016) with the following arguments:  --clean --cpus=32 --client_shutdown --ping_interval=15 --daemon --zombie_interval=60

The crashes appear to happen in the middle of the night, and it doesn't matter if the node is actively running a job or not.

I can't for the life of me figure out what OSError 64 means; all SO and google searches seem to think I'm asking about 64-bits, even if I specifically exlude the word "bits".


问:
Why is my implementation of the generic interface not accepted here? (Error: CS0311)
I have an interface which uses a generic type extending another interface with the where clause. Example:

```<code>public interface IEntityDataExtractor<T> where T : IEntity
{
    public string[] ExtractRawStringData(T entity);
}
</code>```

The IEntity interface and a type extending this interface look like this:

```<code>public interface IEntity
{
    int Id { get; set; }
}

public class Tender : IEntity
{
    ...
}
</code>```

When i try to implement a concrete EntityDataExtractor for the Tender entity, i get the error that:

I do not understand why it is not accepted. I declare that the generic types used for the implementations should be of type IEntity some time down the hierarchy with the where clause. Tender implements, and therefore is an, IEntity. Now i understand that i could solve this by simply having a completely unrestricted generic type T, but the reason i am doing all this is because i need to store a list of the generic IEntityDataExtractor interfaces, with the assigned ones being specific, because i want the type to be known within the specific implementation (e.g. TenderDataExtractor) so i do not have to use forced casts or type conversion in the ExtractRawStringData method. The result i need to achieve should look somewhat like this logic wise:

```<code>public class SomeClass
{
    public List<IEntityDataExtractor<IEntity>> extractors { get; set; }
}

...Instantiating code

public void buildSomeClass()
{
    List<IEntityDataExtractor<IEntity>> extractors = new();
    extractors.Add(new TenderDataExtractor());
    extractors.Add(new SomeOtherDataExtractor()); // etc.
    SomeClass someClass = new();
    someClass.extractors = extractors;
    return someClass;
}

...Example of the tender data extractor

public class TenderDataExtractor : IEntityDataExtractor<Tender>
{
    public string[] ExtractRawStringData(Tender entity)
    {
        // I can directly access members of Tender, not just IEntity,
        // without having to do manual casts or type conversions here
    }
}
</code>```

The thing is, i cannot need to know the specific type at time of declaration (list in SomeClass for example), but will know it at time of assignment. For SomeClass it should just hand over any object of type IEntity to them, but the actual implementation called should know at compile them as shown above. The exact case is a bit different for the declaration part, but for brevity i made a simpler example. Is this not possible in C#?

Body:
I have an interface which uses a generic type extending another interface with the where clause. Example:

public interface IEntityDataExtractor<T> where T : IEntity
{
    public string[] ExtractRawStringData(T entity);
}

The IEntity interface and a type extending this interface look like this:

public interface IEntity
{
    int Id { get; set; }
}

public class Tender : IEntity
{
    ...
}

When i try to implement a concrete EntityDataExtractor for the Tender entity, i get the error that:

I do not understand why it is not accepted. I declare that the generic types used for the implementations should be of type IEntity some time down the hierarchy with the where clause. Tender implements, and therefore is an, IEntity. Now i understand that i could solve this by simply having a completely unrestricted generic type T, but the reason i am doing all this is because i need to store a list of the generic IEntityDataExtractor interfaces, with the assigned ones being specific, because i want the type to be known within the specific implementation (e.g. TenderDataExtractor) so i do not have to use forced casts or type conversion in the ExtractRawStringData method. The result i need to achieve should look somewhat like this logic wise:

public class SomeClass
{
    public List<IEntityDataExtractor<IEntity>> extractors { get; set; }
}

...Instantiating code

public void buildSomeClass()
{
    List<IEntityDataExtractor<IEntity>> extractors = new();
    extractors.Add(new TenderDataExtractor());
    extractors.Add(new SomeOtherDataExtractor()); // etc.
    SomeClass someClass = new();
    someClass.extractors = extractors;
    return someClass;
}

...Example of the tender data extractor

public class TenderDataExtractor : IEntityDataExtractor<Tender>
{
    public string[] ExtractRawStringData(Tender entity)
    {
        // I can directly access members of Tender, not just IEntity,
        // without having to do manual casts or type conversions here
    }
}

The thing is, i cannot need to know the specific type at time of declaration (list in SomeClass for example), but will know it at time of assignment. For SomeClass it should just hand over any object of type IEntity to them, but the actual implementation called should know at compile them as shown above. The exact case is a bit different for the declaration part, but for brevity i made a simpler example. Is this not possible in C#?


问:
Point, but not line, in plotly.line_mapbox
I am new to Python so there is probably an easy answer, but I am trying to figure out why I cannot get a line to draw between gps points on mapbox using plotly.  I have two datasets, one a df of oil and gas wells and one is user generated gps coordinates for oil and gas pipeline.  The user generated data is written to a csv file with its only columns being Leg, Lat and Lon.  Data is read for both sets from csv and then well data is displayed in scatter graph and pipeline should be via line graph.

```<code>import plotly.express as px
import plotly.graph_objects as go

#Add NM Well data in scatterbox with wellname, type and PLSS segment
fig1 = px.scatter_mapbox(oil_wells, lat="latitude", lon="longitude", color="type", hover_name='name', hover_data=["ulstr", "id"])

#Add pipeline in line
fig2 = px.line_mapbox(pipeline, lat="Lat", lon="Lon", color="Leg")

#Combine plots

fig3 = go.Figure(data=fig1.data + fig2.data)

fig3.update_layout(mapbox_style="white-bg",
                  mapbox_layers=[
                      {
                          "below": 'traces',
                          "sourcetype": "raster",
                          "sourceattribution": "United States Geological Survey",
                          "source": [
                              "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
                          ]
                      }],
                  mapbox_zoom=12,
                  mapbox_center_lat = 32.1233832, mapbox_center_lon = -103.62026)

fig3.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig3.show()

</code>```

Points will show for all coordinates and mapbox legend will show a line based on Leg, but will not draw a line between points.   The line graph code was based upon https://plotly.com/python/mapbox-layers/ which actually prints lines based on only single sets of gps coords.

I have tried setting line thickness and changing the line_mapbox instruction.  I have tried, but been unable to come up with a code that would add the Lat, Lon from each successive line of the csv file as End_Lat and End_Lon to the prior line on the basis that maybe mapbox is looking for both starting and end points.  That doesn't seem to be required based on the csv data in the plotly website sample, which only has individual points

Body:
I am new to Python so there is probably an easy answer, but I am trying to figure out why I cannot get a line to draw between gps points on mapbox using plotly.  I have two datasets, one a df of oil and gas wells and one is user generated gps coordinates for oil and gas pipeline.  The user generated data is written to a csv file with its only columns being Leg, Lat and Lon.  Data is read for both sets from csv and then well data is displayed in scatter graph and pipeline should be via line graph.

import plotly.express as px
import plotly.graph_objects as go

#Add NM Well data in scatterbox with wellname, type and PLSS segment
fig1 = px.scatter_mapbox(oil_wells, lat="latitude", lon="longitude", color="type", hover_name='name', hover_data=["ulstr", "id"])

#Add pipeline in line
fig2 = px.line_mapbox(pipeline, lat="Lat", lon="Lon", color="Leg")

#Combine plots

fig3 = go.Figure(data=fig1.data + fig2.data)

fig3.update_layout(mapbox_style="white-bg",
                  mapbox_layers=[
                      {
                          "below": 'traces',
                          "sourcetype": "raster",
                          "sourceattribution": "United States Geological Survey",
                          "source": [
                              "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
                          ]
                      }],
                  mapbox_zoom=12,
                  mapbox_center_lat = 32.1233832, mapbox_center_lon = -103.62026)

fig3.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

fig3.show()

Points will show for all coordinates and mapbox legend will show a line based on Leg, but will not draw a line between points.   The line graph code was based upon https://plotly.com/python/mapbox-layers/ which actually prints lines based on only single sets of gps coords.

I have tried setting line thickness and changing the line_mapbox instruction.  I have tried, but been unable to come up with a code that would add the Lat, Lon from each successive line of the csv file as End_Lat and End_Lon to the prior line on the basis that maybe mapbox is looking for both starting and end points.  That doesn't seem to be required based on the csv data in the plotly website sample, which only has individual points


问:
App in custom mount point loses track of SQL server timed out connections
I have app1 mounted in http://hostname/ in a VM, and a staging version of the same app1 mounted in http://hostname/foo in the same VM. I use Nginx, Uwsgi, Flask and SQLAlchemy.

Upon request, app1 queries a MySQL database, gets information and returns an answer.

Both apps do their job correctly as long as connections are alive on SQL sever. Strangely, when the SQL server starts killing timed out connections (3600 seconds in this case), the staging version seems to lose track of such. Therefore it tries to reuse phased out connections and throws:

```<code>CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
</code>```

On the other hand, the version of the app mounted in http://hostname/ works flawlessly and does not attempt to reuse timedout connections (creates new ones or reuses alive ones).

Same app, same code, only different mount point.

Any clue what is going on?

relevant code of main.py file with the sqlalchemy settings:

```<code>engine = create_engine(cfg.ENG, pool_pre_ping = True, pool_recycle = 250)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

app = Flask(__name__)
</code>```

Body:
I have app1 mounted in http://hostname/ in a VM, and a staging version of the same app1 mounted in http://hostname/foo in the same VM. I use Nginx, Uwsgi, Flask and SQLAlchemy.

Upon request, app1 queries a MySQL database, gets information and returns an answer.

Both apps do their job correctly as long as connections are alive on SQL sever. Strangely, when the SQL server starts killing timed out connections (3600 seconds in this case), the staging version seems to lose track of such. Therefore it tries to reuse phased out connections and throws:

CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')

On the other hand, the version of the app mounted in http://hostname/ works flawlessly and does not attempt to reuse timedout connections (creates new ones or reuses alive ones).

Same app, same code, only different mount point.

Any clue what is going on?

relevant code of main.py file with the sqlalchemy settings:

engine = create_engine(cfg.ENG, pool_pre_ping = True, pool_recycle = 250)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import models
    Base.metadata.create_all(bind=engine)

app = Flask(__name__)


问:
How to Auto populate a textarea field from a specific class element on the same page? It has to be a class and not an ID
I am trying to auto populate a textarea field from a specific class element on the page.

For example

```<code><div class="text-1">Hello</div>

<textarea value="" id="textarea"></textarea>
</code>```

When the form is loaded the textarea needs to auto populate with the class above as text and auto populate the value as well. So for this example Hello will become the value and the text shown in the textarea field.

I tried using getElementsByClassName and assigned a variable for the div and then assigned a variable to the textarea using getElementById. That is as far as I got.

Body:
I am trying to auto populate a textarea field from a specific class element on the page.

For example

Hello

<textarea value="" id="textarea"></textarea>

When the form is loaded the textarea needs to auto populate with the class above as text and auto populate the value as well. So for this example Hello will become the value and the text shown in the textarea field.

I tried using getElementsByClassName and assigned a variable for the div and then assigned a variable to the textarea using getElementById. That is as far as I got.


问:
Nested loop help needed in Pinescript TradingView
Loops is my weakness unfortunately... and I need to build a nested loop, unless it can be done differently somehow. Also this is in TradingView Pinescript v5.

So I have automated trendlines and I can capture crossings of each up or down at any point and time
top_red_trendline_up_cross = ta.crossover(high, top_red_trendline_coordinates)

If I want to check previous candle high if it crosses that same line I would do:
top_red_trendline_up_cross = ta.crossover(high[1], top_red_trendline_coordinates)

Or if previous candle high crosses 3 trend lines ago:
top_red_trendline_up_cross = ta.crossover(high[1], top_red_trendline_coordinates[3])

And so on... FYI: each trend line becomes obsolete at some point one it is broken and new one is drawn, so the coordinates of the line change every time it happens.

Basically I want to write a loop which will look for these based on the input provided.
The logic is:
1,1 | 1,2 | 1,3 | 1,4 | 2,x

2,1 | 2,2 | 2,3 | 2,4 | 2,x

y,1 | y,2 | y,3 | y,4 | y,a

How would I put it into the loop? Or nested loop?
Tried this, but it shows these crossings at obviously wrong places =/

```<code>top_red_trendline_up_cross = false
for x = 0 to 10
    for y = 0 to 10
        top_red_trendline_up_cross := ta.crossover(high[x], top_red_trendline_coordinates[y])

plotshape(top_red_trendline_up_cross, style=shape.xcross, color=color.red, size=size.normal, location=location.abovebar)

</code>```

I already got pretty advanced into Pinescript, but loops always kill me and you can't go around loops with such task..
Appreciate any help/suggestions!

Body:
Loops is my weakness unfortunately... and I need to build a nested loop, unless it can be done differently somehow. Also this is in TradingView Pinescript v5.

So I have automated trendlines and I can capture crossings of each up or down at any point and time
top_red_trendline_up_cross = ta.crossover(high, top_red_trendline_coordinates)

If I want to check previous candle high if it crosses that same line I would do:
top_red_trendline_up_cross = ta.crossover(high[1], top_red_trendline_coordinates)

Or if previous candle high crosses 3 trend lines ago:
top_red_trendline_up_cross = ta.crossover(high[1], top_red_trendline_coordinates[3])

And so on... FYI: each trend line becomes obsolete at some point one it is broken and new one is drawn, so the coordinates of the line change every time it happens.

Basically I want to write a loop which will look for these based on the input provided.
The logic is:
1,1 | 1,2 | 1,3 | 1,4 | 2,x

2,1 | 2,2 | 2,3 | 2,4 | 2,x

y,1 | y,2 | y,3 | y,4 | y,a

How would I put it into the loop? Or nested loop?
Tried this, but it shows these crossings at obviously wrong places =/

top_red_trendline_up_cross = false
for x = 0 to 10
    for y = 0 to 10
        top_red_trendline_up_cross := ta.crossover(high[x], top_red_trendline_coordinates[y])

plotshape(top_red_trendline_up_cross, style=shape.xcross, color=color.red, size=size.normal, location=location.abovebar)

I already got pretty advanced into Pinescript, but loops always kill me and you can't go around loops with such task..
Appreciate any help/suggestions!


问:
How can I ensure my fragment retains its state when navigating away from and back to it in an Android app written in Kotlin?
I am building an android app by using Kotlin. The app contains a bottom navBar. when you move between fragments of the app, I want the app can save the state of the previous fragment, it means if there is a EditText which is contains a text, the text shouldn't clear when we move between fragments. In terms of UX it is important. Any one has the best practice for it.

I would appreciate it if you can give me a explanation containing a code example.


问:
No serviceName defined in either JAAS or Kafka config in KRaft Mode Kafka
I am trying to use SASL_SSL for external clients, connecting to controller as an authentication mechanism, but its erring out.

docker-compose.yml

```<code>    version: "2"

    services:
      kafka:
        image: bitnami/kafka:latest
        ports:
          - 9092:9092
          - 2181:2181
        volumes:
          - "kafka_data:/bitnami/kafka"
        environment:
          - KAFKA_ENABLE_KRAFT=yes
          - KAFKA_CFG_PROCESS_ROLES=broker,controller
          - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:SASL_SSL,PLAINTEXT:PLAINTEXT
          - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:2181
          - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092
          - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER
          - KAFKA_CFG_SASL_ENABLED_MECHANISMS=PLAIN,SCRAM-SHA-256,SCRAM-SHA-512
          - KAFKA_CLIENTS_USER=user
          - KAFKA_CLIENTS_PASSWORD=password
          - KAFKA_TLS_CLIENT_AUTH=none
          - KAFKA_CFG_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM=
          - KAFKA_CERTIFICATE_PASSWORD=password
          - KAFKA_BROKER_ID=1
          - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@127.0.0.1:2181
          - ALLOW_PLAINTEXT_LISTENER=yes
        volumes:
          - './kafka.keystore.jks:/opt/bitnami/kafka/config/certs/kafka.keystore.jks:ro'
          - './kafka.truststore.jks:/opt/bitnami/kafka/config/certs/kafka.truststore.jks:ro'
          - './kafka_jaas.conf:/opt/bitnami/kafka/conf/kafka_jaas.conf:ro'

    volumes:
      kafka_data:
        driver: local
</code>```

kafka_jaas.conf

```<code>    KafkaServer {
        org.apache.kafka.common.security.plain.PlainLoginModule required
        username="kafka"
        password="password";
    };
</code>```

Error

```<code>41-kafka-1  | [2022-12-05 21:28:08,493] ERROR Exiting Kafka due to fatal exception (kafka.Kafka$)
41-kafka-1  | org.apache.kafka.common.KafkaException: java.lang.IllegalArgumentException: No serviceName defined in either JAAS or Kafka config
</code>```

Full log with error

I tried,

No serviceName defined in either JAAS or Kafka config (not Kerberos)

https://github.com/bitnami/bitnami-docker-kafka/issues/204

Body:
I am trying to use SASL_SSL for external clients, connecting to controller as an authentication mechanism, but its erring out.

docker-compose.yml

    version: "2"

    services:
      kafka:
        image: bitnami/kafka:latest
        ports:
          - 9092:9092
          - 2181:2181
        volumes:
          - "kafka_data:/bitnami/kafka"
        environment:
          - KAFKA_ENABLE_KRAFT=yes
          - KAFKA_CFG_PROCESS_ROLES=broker,controller
          - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=CONTROLLER:SASL_SSL,PLAINTEXT:PLAINTEXT
          - KAFKA_CFG_LISTENERS=PLAINTEXT://:9092,CONTROLLER://:2181
          - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://127.0.0.1:9092
          - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER
          - KAFKA_CFG_SASL_ENABLED_MECHANISMS=PLAIN,SCRAM-SHA-256,SCRAM-SHA-512
          - KAFKA_CLIENTS_USER=user
          - KAFKA_CLIENTS_PASSWORD=password
          - KAFKA_TLS_CLIENT_AUTH=none
          - KAFKA_CFG_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM=
          - KAFKA_CERTIFICATE_PASSWORD=password
          - KAFKA_BROKER_ID=1
          - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@127.0.0.1:2181
          - ALLOW_PLAINTEXT_LISTENER=yes
        volumes:
          - './kafka.keystore.jks:/opt/bitnami/kafka/config/certs/kafka.keystore.jks:ro'
          - './kafka.truststore.jks:/opt/bitnami/kafka/config/certs/kafka.truststore.jks:ro'
          - './kafka_jaas.conf:/opt/bitnami/kafka/conf/kafka_jaas.conf:ro'

    volumes:
      kafka_data:
        driver: local

kafka_jaas.conf

    KafkaServer {
        org.apache.kafka.common.security.plain.PlainLoginModule required
        username="kafka"
        password="password";
    };

Error

41-kafka-1  | [2022-12-05 21:28:08,493] ERROR Exiting Kafka due to fatal exception (kafka.Kafka$)
41-kafka-1  | org.apache.kafka.common.KafkaException: java.lang.IllegalArgumentException: No serviceName defined in either JAAS or Kafka config

Full log with error

I tried,

No serviceName defined in either JAAS or Kafka config (not Kerberos)

https://github.com/bitnami/bitnami-docker-kafka/issues/204


问:
Client WebSocket not connecting to server in JavaScript
I've followed every tutorial known to StackOverflow and it seems like none of them have done the trick. I'm trying to connect a client to a server with WebSockets and it keeps giving me the WebSocket connection to 'ws://localhost:6000/' failed. It has to be something on my client side because I get no errors on my server

Server:

```<code>const express = require("express");
const app = express();
const http = require('http')
const server = http.createServer(app)
const WebSocket = require('ws')

var wss = new WebSocket.Server({ port: 6000 })
wss.on('connection', function connection(ws) {
    console.log('Connected WebSocket')
    ws.on('message', function incoming(message) {
        console.log(message)
    })
})
</code>```

Client:

```<code>var socket = new WebSocket("ws://localhost:6000");

socket.onmessage = function(event) {
  console.log(event.data)
}
</code>```

I am using Glitch to host my website if that helps!

Body:
I've followed every tutorial known to StackOverflow and it seems like none of them have done the trick. I'm trying to connect a client to a server with WebSockets and it keeps giving me the WebSocket connection to 'ws://localhost:6000/' failed. It has to be something on my client side because I get no errors on my server

Server:

const express = require("express");
const app = express();
const http = require('http')
const server = http.createServer(app)
const WebSocket = require('ws')

var wss = new WebSocket.Server({ port: 6000 })
wss.on('connection', function connection(ws) {
    console.log('Connected WebSocket')
    ws.on('message', function incoming(message) {
        console.log(message)
    })
})

Client:

var socket = new WebSocket("ws://localhost:6000");

socket.onmessage = function(event) {
  console.log(event.data)
}

I am using Glitch to host my website if that helps!


问:
Use the Material Theme colors on custom Angular components
I think I must be missing something fundamental here (its been a long day). I have an Angular app set up using a material theme (indigo-pink) which works fine on the material components.

I am now setting up a custom component and I'd just like to use the colors from the material theme to style it up a bit. This seems like it should be simple but everything I read pushes me back to the docs and creating mixins and defining themes.

Do I have to define a theme? I just want to use the primary theme color on my custom component.

I guess I'm maybe misunderstanding something about the nature of themes but is there a simple way to do this?

Cheers all


问:
How to replicate "download a snapshot" functionality in sharepoint 2016
sharepoint 2013 excel services has a feature "download a snapshot" that let the user download an excel file with data only, for the current state of the file in the browser (ex: you filter the sheet on some value, when you download a snapshot, the XLSX it produces only contains the filtered data)
This option is not present in the Web UI for sharepoint 2016 - but I found that the sharepoint excel web services does have a GetWorkbook method that will output a snapshot of the excel file at the specified URL. However, our users normally filter the data in the browser and then download a snapshot that they send to external customers.
Is there a method of replicating this functionality since it is no longer available in the browser?
from: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-get-an-entire-workbook-or-a-snapshot</p>
```<code>                byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.PublishedItemsSnapshot, out status);```
</code>```

Body:
sharepoint 2013 excel services has a feature "download a snapshot" that let the user download an excel file with data only, for the current state of the file in the browser (ex: you filter the sheet on some value, when you download a snapshot, the XLSX it produces only contains the filtered data)
This option is not present in the Web UI for sharepoint 2016 - but I found that the sharepoint excel web services does have a GetWorkbook method that will output a snapshot of the excel file at the specified URL. However, our users normally filter the data in the browser and then download a snapshot that they send to external customers.
Is there a method of replicating this functionality since it is no longer available in the browser?
from: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-get-an-entire-workbook-or-a-snapshot

                byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.PublishedItemsSnapshot, out status);```


问:
Should the sqlalchemy Base class be imported in the models file before using it to create tables?
Following this tutorial on how to use sqlalchemy with FastAPI, I found that they do the following:

Define a database.py file that contains the engine creation, session making and most importantly the Base class that all sqlalchemy models should inherit from.

In models.py they import the Base class to use it for models creation.

In main.py they import models then use the following line of code to create all tables in db:
models.Base.metadata.create_all(bind=engine)
My question is, why use models.Base instead of importing Base directly from database.py and use it? Does this affect the metadata object in some way? Does this affect the way the database is created ?


问:
sleep() function not functioning the right way in a loop (in tkinter project)
in the main loop i call the sleep() function but when i execute my code, it just wait 300 times 0.01 seconds and it then displays the last frame for i=299.

```<code>from tkinter import *
from time import *
#Those are functions a friend gave me in order to darw stuff pixel by pixel
tk=Tk()
tk.attributes('-fullscreen',True)
canvas=Canvas(tk, width=1366, height=768, background='#fff')
canvas.pack()
colors=[[(255, 255, 255) for i in range(223)] for i in range(321)]
def color(a,b,c):
    if a<10:
        va='0'+str(a)
    else:
        va=hex(a%256).replace('0x','')
    if b<10:
        vb='0'+str(b)
    else:
        vb=hex(b%256).replace('0x','')
    if c<10:
        vc='0'+str(c)
    else:
        vc=hex(c%256).replace('0x','')
    return '#%s'%(va+vb+vc)

def colr(lis):
    a=lis[0]
    b=lis[1]
    c=lis[2]
    if a%256<10:
        va='0'+str(a%256)
    else:
        va=hex(a%256).replace('0x','')
    if b%256<10:
        vb='0'+str(b%256)
    else:
        vb=hex(b%256).replace('0x','')
    if c%256<10:
        vc='0'+str(c%256)
    else:
        vc=hex(c%256).replace('0x','')
    return '#%s'%(va+vb+vc)

def fill_rect(a,b,c,d,e):
    a=a+683
    b=-b+384
    if type(e)==str:
        canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=e,outline='')
    else:
        canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=colr(e),outline='')
    #modifie la valeur de la couleur au pixel x,y
    for x in range(c):
        for y in range(d):
            if (a+x)>=0 and (a+x)<=320 and (b+y)>=0 and (b+y)<=222:
                colors[a+x][b+y]=e

def set_pixel(a,b,e):
    fill_rect(a,b,1,1,e)

def get_pixel(x,y):
    if x>=0 and x<=320 and y>=0 and y<=222:
        return colors[x][y]
    else:
        return (0,0,0)

#This is where my code starts
def draw_line(xa,ya,xb,yb):
    canvas.create_line(round(xa)+683,-round(ya)+384,round(xb)+683,-round(yb)+384, fill="black", width=1)
#The increment are just so the landmark is at the center of the screen

focal_length=100
def dproj(xa,ya,za,xb,yb,zb):
    draw_line(focal_length*xa/za,focal_length*ya/za,focal_length*xb/zb,focal_length*yb/zb)

#Vertex table of the cube
a=[-1,-1,1]
b=[1,-1,1]
c=[1,1,1]
d=[-1,1,1]
e=[-1,-1,3]
f=[1,-1,3]
g=[1,1,3]
h=[-1,1,3]
for i in range(300):
    canvas.delete("all")
    focal_length=i
#Edges table
    dproj(a[0],a[1],a[2],b[0],b[1],b[2])
    dproj(a[0],a[1],a[2],d[0],d[1],d[2])
    dproj(a[0],a[1],a[2],e[0],e[1],e[2])
    dproj(c[0],c[1],c[2],b[0],b[1],b[2])
    dproj(c[0],c[1],c[2],d[0],d[1],d[2])
    dproj(c[0],c[1],c[2],g[0],g[1],g[2])
    dproj(f[0],f[1],f[2],b[0],b[1],b[2])
    dproj(f[0],f[1],f[2],e[0],e[1],e[2])
    dproj(f[0],f[1],f[2],g[0],g[1],g[2])
    dproj(h[0],h[1],h[2],d[0],d[1],d[2])
    dproj(h[0],h[1],h[2],e[0],e[1],e[2])
    dproj(h[0],h[1],h[2],g[0],g[1],g[2])
    sleep(0.01)

</code>```

i wanted to make some kind of 3D render of a cube with the focal lenght slowly changing to make kind of a zoom in effect.
I also tried sys.stdout.flush() but same issue although maybe this only applies for prints in terminal.

Body:
in the main loop i call the sleep() function but when i execute my code, it just wait 300 times 0.01 seconds and it then displays the last frame for i=299.

from tkinter import *
from time import *
#Those are functions a friend gave me in order to darw stuff pixel by pixel
tk=Tk()
tk.attributes('-fullscreen',True)
canvas=Canvas(tk, width=1366, height=768, background='#fff')
canvas.pack()
colors=[[(255, 255, 255) for i in range(223)] for i in range(321)]
def color(a,b,c):
    if a<10:
        va='0'+str(a)
    else:
        va=hex(a%256).replace('0x','')
    if b<10:
        vb='0'+str(b)
    else:
        vb=hex(b%256).replace('0x','')
    if c<10:
        vc='0'+str(c)
    else:
        vc=hex(c%256).replace('0x','')
    return '#%s'%(va+vb+vc)

def colr(lis):
    a=lis[0]
    b=lis[1]
    c=lis[2]
    if a%256<10:
        va='0'+str(a%256)
    else:
        va=hex(a%256).replace('0x','')
    if b%256<10:
        vb='0'+str(b%256)
    else:
        vb=hex(b%256).replace('0x','')
    if c%256<10:
        vc='0'+str(c%256)
    else:
        vc=hex(c%256).replace('0x','')
    return '#%s'%(va+vb+vc)

def fill_rect(a,b,c,d,e):
    a=a+683
    b=-b+384
    if type(e)==str:
        canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=e,outline='')
    else:
        canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=colr(e),outline='')
    #modifie la valeur de la couleur au pixel x,y
    for x in range(c):
        for y in range(d):
            if (a+x)>=0 and (a+x)<=320 and (b+y)>=0 and (b+y)<=222:
                colors[a+x][b+y]=e

def set_pixel(a,b,e):
    fill_rect(a,b,1,1,e)

def get_pixel(x,y):
    if x>=0 and x<=320 and y>=0 and y<=222:
        return colors[x][y]
    else:
        return (0,0,0)

#This is where my code starts
def draw_line(xa,ya,xb,yb):
    canvas.create_line(round(xa)+683,-round(ya)+384,round(xb)+683,-round(yb)+384, fill="black", width=1)
#The increment are just so the landmark is at the center of the screen

focal_length=100
def dproj(xa,ya,za,xb,yb,zb):
    draw_line(focal_length*xa/za,focal_length*ya/za,focal_length*xb/zb,focal_length*yb/zb)

#Vertex table of the cube
a=[-1,-1,1]
b=[1,-1,1]
c=[1,1,1]
d=[-1,1,1]
e=[-1,-1,3]
f=[1,-1,3]
g=[1,1,3]
h=[-1,1,3]
for i in range(300):
    canvas.delete("all")
    focal_length=i
#Edges table
    dproj(a[0],a[1],a[2],b[0],b[1],b[2])
    dproj(a[0],a[1],a[2],d[0],d[1],d[2])
    dproj(a[0],a[1],a[2],e[0],e[1],e[2])
    dproj(c[0],c[1],c[2],b[0],b[1],b[2])
    dproj(c[0],c[1],c[2],d[0],d[1],d[2])
    dproj(c[0],c[1],c[2],g[0],g[1],g[2])
    dproj(f[0],f[1],f[2],b[0],b[1],b[2])
    dproj(f[0],f[1],f[2],e[0],e[1],e[2])
    dproj(f[0],f[1],f[2],g[0],g[1],g[2])
    dproj(h[0],h[1],h[2],d[0],d[1],d[2])
    dproj(h[0],h[1],h[2],e[0],e[1],e[2])
    dproj(h[0],h[1],h[2],g[0],g[1],g[2])
    sleep(0.01)

i wanted to make some kind of 3D render of a cube with the focal lenght slowly changing to make kind of a zoom in effect.
I also tried sys.stdout.flush() but same issue although maybe this only applies for prints in terminal.


问:
MongoDb trigger on delete
I'm completely new to Mongo, and I'm working with MongoDb Atlas in my .NET application.

I have set a TTL on one of my collections, so that a new item is deleted after a certain amount of time. Now I want to set an after delete trigger on this collection, so that when an item is deleted in this collection, an int property in a different collection in the same database is decremented, based on an ID. How would I do this? I know how to set up a trigger, but I do not know how to write the function properly.

Example: Two collections, Movies :

```<code>_id: 63471150bd41ac8d5eb3af71
Name: "Terminator"
LoanedCopies: 10
</code>```

and MovieLoans:

```<code>_id: 638e66b2a846af288845d052
MovieId: "63471150bd41ac8d5eb3af71"
</code>```

Now, when a MovieLoan gets deleted by the TTL, I want the given Movie to decrement its LoanedCopies value by 1.

Title: MongoDb trigger on delete

Body:
I'm completely new to Mongo, and I'm working with MongoDb Atlas in my .NET application.

I have set a TTL on one of my collections, so that a new item is deleted after a certain amount of time. Now I want to set an after delete trigger on this collection, so that when an item is deleted in this collection, an int property in a different collection in the same database is decremented, based on an ID. How would I do this? I know how to set up a trigger, but I do not know how to write the function properly.

Example: Two collections, Movies :

_id: 63471150bd41ac8d5eb3af71
Name: "Terminator"
LoanedCopies: 10

and MovieLoans:

_id: 638e66b2a846af288845d052
MovieId: "63471150bd41ac8d5eb3af71"

Now, when a MovieLoan gets deleted by the TTL, I want the given Movie to decrement its LoanedCopies value by 1.


问:
Filter only one row per one date for different priority
From query which returns multiple rows with different data priority. I need to create subtable with only one date with highest priority. My approach was to just do multiple queries and return query.first(). But this will fire database connection x times, where x is number of different days.

```<code>list_of_queries = []
for date in dates list:
        list_of_queries.append(
            self.get_queryset().filter(date).order_by(
                Case(
                    *[When(priority__iexact=priority, then=Value(i))
                     for i, priority in enumerate(priority_list)],
                    default=None
                ).asc()))
</code>```

Table 1.

ID
DATE
PRIORITY

1
2022/11/1
1

2
2022/11/1
2

3
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
1

6
2022/11/3
3

Table 2.

ID
DATE
PRIORITY

1
2022/11/1
1

4
2022/11/2
2

5
2022/11/3
1

I think I could use some other approach and just gather all rows with date__lte to date__gte and from this subquery in some way just take only one date. But any idea how to do this in Django ORM? Or I have to do multiple queries with filter = date?

Body:
From query which returns multiple rows with different data priority. I need to create subtable with only one date with highest priority. My approach was to just do multiple queries and return query.first(). But this will fire database connection x times, where x is number of different days.

list_of_queries = []
for date in dates list:
        list_of_queries.append(
            self.get_queryset().filter(date).order_by(
                Case(
                    *[When(priority__iexact=priority, then=Value(i))
                     for i, priority in enumerate(priority_list)],
                    default=None
                ).asc()))

Table 1.

ID
DATE
PRIORITY

1
2022/11/1
1

2
2022/11/1
2

3
2022/11/1
3

4
2022/11/2
2

5
2022/11/3
1

6
2022/11/3
3

Table 2.

ID
DATE
PRIORITY

1
2022/11/1
1

4
2022/11/2
2

5
2022/11/3
1

I think I could use some other approach and just gather all rows with date__lte to date__gte and from this subquery in some way just take only one date. But any idea how to do this in Django ORM? Or I have to do multiple queries with filter = date?


问:
Passing logged in user to a database in DRF
I'm wondering how I can pass a logged in user to a database if I have a foreign key.

In my application I use JWT token for authentication. I'm not sure if a front end should send me the logged in user id or should I get the logged in user id in DRF? If the front end should send me the id should I compare the id with an id of logged in user in DRF?

In the case below, I assume I should get the information from the DRF. Is this the right way? Can I pass data this way?

```<code>class EmployerDetail(viewsets.ViewSet):
    queryset = Employer.objects.all()
    serializer_class = EmployerSerializer

    def create(self, request):
        data = request.data | {"user": self.request.user.id}
        serializer = self.serializer_class(data=data)

        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
</code>```

Model

```<code>class Employer(models.Model):
    USER = settings.AUTH_USER_MODEL

    user = models.OneToOneField(USER, on_delete=models.CASCADE, blank=True, null=True)
    company_name = models.CharField(max_length=200)
    company_size = models.IntegerField(default=0)
    website = models.URLField(max_length=200)

    class Meta:
        unique_together = ['website', 'user']
</code>```

Thanks

Body:
I'm wondering how I can pass a logged in user to a database if I have a foreign key.

In my application I use JWT token for authentication. I'm not sure if a front end should send me the logged in user id or should I get the logged in user id in DRF? If the front end should send me the id should I compare the id with an id of logged in user in DRF?

In the case below, I assume I should get the information from the DRF. Is this the right way? Can I pass data this way?

class EmployerDetail(viewsets.ViewSet):
    queryset = Employer.objects.all()
    serializer_class = EmployerSerializer

    def create(self, request):
        data = request.data | {"user": self.request.user.id}
        serializer = self.serializer_class(data=data)

        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

Model

class Employer(models.Model):
    USER = settings.AUTH_USER_MODEL

    user = models.OneToOneField(USER, on_delete=models.CASCADE, blank=True, null=True)
    company_name = models.CharField(max_length=200)
    company_size = models.IntegerField(default=0)
    website = models.URLField(max_length=200)

    class Meta:
        unique_together = ['website', 'user']

Thanks


问:
flutter how to remove default Home screen option?
My device navigation style is swipe and I made my flutter app.

I don't want use samsung pay while i use my app.

how can solve this problem?

[[enter image description here](https://i.stack.imgur.com/HjIvW.jpg)](https://i.stack.imgur.com/Y1Hd1.jpg)

this button is disappear and swipe center home button go home in mobile


问:
Auto scalling policy for wordfreq application by aws
I am pretty new to cloud and I have been trying to improve my skills. I came accross the word freq application which basically returns the top 10 words with highest freq from a document. I am trying to deploy the same application on aws with an auto scaling group but I am not able to decide what performance metrics to use for scaling out or scaling in.
Any help would be great.

I am not sure what performance metrics is good for this task. I tried using sum CPU utilization but I am not sure if that is the right metric to use in this case.


问:
Intermitent "The signature key was not found" error
I've read plenty of articles and Q&As regarding this and similar errors, but the scenario I face is truly puzzling, so I'm creating this question to, at the very least put my thoughts in order:

We have a .NET 6.0 which is set-up to use bearer JWT tokens as follows:

```<code>services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        RequireExpirationTime = true,
        ValidIssuer = Configuration["JwtIssuer"],
        ValidAudience = Configuration["JwtAudience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JwtKey"])),
        ClockSkew = TimeSpan.Zero
    };
    ...
}
</code>```

We have a /Login endpoint which internally uses System.IdentityModel.Tokens.Jwt.JwtSecurityToken(...) which uses the following as Signing Credentials:

```<code>    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
</code>```

While working locally, with a launchSettings.json which is configured with the same values (copied from Azure's KUDU AppSettings) as one of our environment's variables, everything works OK. In other environments that we have deployed, everything works OK too.

However, in one of our environments X, when we're passing our token in the header as "Authorization: bearer ey..." we're getting a 401 error claiming that "The signature key was not found". What's even more puzzling is that if we generate a token running the app locally configured with the same values as X, then if we pass it in the Authoriation header calling X directly, it works as well as using it locally, however if we try to use the token generated by calling the real X, we get a 401 error (either there or in localhost).

I've tried comparing the environments to no avail and I'm out of ideas on what to compare (I'm tempted to torch that environment down and just create a new one with the same configs to see if that works).

Body:
I've read plenty of articles and Q&As regarding this and similar errors, but the scenario I face is truly puzzling, so I'm creating this question to, at the very least put my thoughts in order:

We have a .NET 6.0 which is set-up to use bearer JWT tokens as follows:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        RequireExpirationTime = true,
        ValidIssuer = Configuration["JwtIssuer"],
        ValidAudience = Configuration["JwtAudience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JwtKey"])),
        ClockSkew = TimeSpan.Zero
    };
    ...
}

We have a /Login endpoint which internally uses System.IdentityModel.Tokens.Jwt.JwtSecurityToken(...) which uses the following as Signing Credentials:

    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

While working locally, with a launchSettings.json which is configured with the same values (copied from Azure's KUDU AppSettings) as one of our environment's variables, everything works OK. In other environments that we have deployed, everything works OK too.

However, in one of our environments X, when we're passing our token in the header as "Authorization: bearer ey..." we're getting a 401 error claiming that "The signature key was not found". What's even more puzzling is that if we generate a token running the app locally configured with the same values as X, then if we pass it in the Authoriation header calling X directly, it works as well as using it locally, however if we try to use the token generated by calling the real X, we get a 401 error (either there or in localhost).

I've tried comparing the environments to no avail and I'm out of ideas on what to compare (I'm tempted to torch that environment down and just create a new one with the same configs to see if that works).


问:
Check if a enpoint exists despite CORS error
Is there a way to simply check if an endpoint exists while ignoring the cors error thrown?

I'm testing urls that would either be http or https, to figure out what they are i want to test the https url first and then the http url. The problem during this however is that the responses always returns a cors error. The fact that i get cors errors shouldn't be a problem though because in my error logs i can see the corresponding statuscode 404 for not found and 200 for success.

This is exactly the information I need but I don't know how to access it in JS. I tried using Axios and fetch but haven't found a solution yet. Does anyone have any suggestions?

To be clear i don't have any problems finding the statuscode in any other requests, it's only handling these CORS errors giving a problem.

suggestions such as the one below don't fix my error.

fetch(`${baseUrl}api/user/login`, {
    credentials: "include", // ¹ See note below
    headers: myHeaders
})
.then(function(response) {
    console.log(response.status); // Will show you the status
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    return response.json();
})
.then(// ...
```


问:
Text changed event not firing
I am using a textbox inside an update panel and there is textchanged event for this text box. textchanged event is firing first time and showing an alert box that email id  is present. when i giving email id in text box . but after clicking ok button in alert box again i give email id in text box  this time textchanged event not firing.

HTML

```<code><dt>Email:<span style="color: #FF0000;">*</span></dt>
<dd>
<**asp:UpdatePanel ID="UpdatePanel8" runat="server">
    <ContentTemplate>
        <cc1:OboutTextBox ID="txtEmail"   class="input" runat="server"
            ontextchanged="txtEmail_TextChanged" AutoPostBack="true"></cc1:OboutTextBox>

   </ContentTemplate>
 <Triggers>
        <asp:AsyncPostBackTrigger ControlID="txtEmail" EventName="TextChanged"  />
 </Triggers>
</asp:UpdatePanel>**
</dd>
</dl>
</code>```

Code Behind:

```<code>protected void txtEmail_TextChanged(object sender, EventArgs e)
    {
        bool flag = false;
        if (txtEmail.Text.Trim() != "")
        {
            string _GlobalDB = Server.MapPath("~//DB//Global.accdb");
            flag = Utility.isEmailExist(txtEmail.Text.Trim(), _GlobalDB);
        }
        if (flag)
        {

           ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", @"javascript:alert('Email ID Exist ,Please Use another Email ID.')", true);
            txtEmail.Text = "";
            txtEmail.Focus();

        }

    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Text changed event not firing

Body:
I am using a textbox inside an update panel and there is textchanged event for this text box. textchanged event is firing first time and showing an alert box that email id  is present. when i giving email id in text box . but after clicking ok button in alert box again i give email id in text box  this time textchanged event not firing.

HTML

Email:*

<**asp:UpdatePanel ID="UpdatePanel8" runat="server">
    <ContentTemplate>
        <cc1:OboutTextBox ID="txtEmail"   class="input" runat="server"
            ontextchanged="txtEmail_TextChanged" AutoPostBack="true"></cc1:OboutTextBox>

   </ContentTemplate>
 <Triggers>
        <asp:AsyncPostBackTrigger ControlID="txtEmail" EventName="TextChanged"  />
 </Triggers>
</asp:UpdatePanel>**

Code Behind:

protected void txtEmail_TextChanged(object sender, EventArgs e)
    {
        bool flag = false;
        if (txtEmail.Text.Trim() != "")
        {
            string _GlobalDB = Server.MapPath("~//DB//Global.accdb");
            flag = Utility.isEmailExist(txtEmail.Text.Trim(), _GlobalDB);
        }
        if (flag)
        {

           ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", @"javascript:alert('Email ID Exist ,Please Use another Email ID.')", true);
            txtEmail.Text = "";
            txtEmail.Focus();

        }

    }


问:
Why does python wait to print a statement without newline until after multiprocessing pool is complete?
I have a multiprocess Pool that takes a little bit of time to complete. I would like print a message letting me know that the pool has stated, and on the same line, print "complete" when its done. Something like this "Pool has started its thing... complete."

For some reason, when I change the end= to anything other than the default \n, it will wait to print the whole message at the same time.

Code that acts weird:

```<code>print("Sanity print statement.")
print("Pool has started its thing...", end=' ')
with Pool(16) as pool:
    var = pool.map(task, args)
print("complete.")
</code>```

Output:

```<code>line 1: Sanity print statement.
# waits a few seconds
line 2: Pool has started its thing... complete.
</code>```

Code that acts as expected:

```<code>print("Sanity print statement.")
print("Pool has started its thing...", end='\n')
with Pool(16) as pool:
    var = pool.map(task, args)
print("complete.")
</code>```

Output:

```<code>line 1: Sanity print statement.
line 2: Pool has started its thing...
# waits a few seconds
line 2: Pool has starte its thing... complete.
</code>```

This was a little difficult to show the exact behavior of the output so I hope I made it clear enough.

And this is just me trying to understand. I know it can just be printed on the next line, but I need to be able to sleep at night knowing that computer's haven't started thinking for themselves.

Body:
I have a multiprocess Pool that takes a little bit of time to complete. I would like print a message letting me know that the pool has stated, and on the same line, print "complete" when its done. Something like this "Pool has started its thing... complete."

For some reason, when I change the end= to anything other than the default \n, it will wait to print the whole message at the same time.

Code that acts weird:

print("Sanity print statement.")
print("Pool has started its thing...", end=' ')
with Pool(16) as pool:
    var = pool.map(task, args)
print("complete.")

Output:

line 1: Sanity print statement.
# waits a few seconds
line 2: Pool has started its thing... complete.

Code that acts as expected:

print("Sanity print statement.")
print("Pool has started its thing...", end='\n')
with Pool(16) as pool:
    var = pool.map(task, args)
print("complete.")

Output:

line 1: Sanity print statement.
line 2: Pool has started its thing...
# waits a few seconds
line 2: Pool has starte its thing... complete.

This was a little difficult to show the exact behavior of the output so I hope I made it clear enough.

And this is just me trying to understand. I know it can just be printed on the next line, but I need to be able to sleep at night knowing that computer's haven't started thinking for themselves.


问:
How to create confusion matrix for upsampled ML model
I am using RStudio, the caret package, to create predictive models. I want to create a confusion matrix, but I do not know how to access observed values after the resampling has been performed.

I have an imbalanced dataset so I've used upsampling with the following code:

```<code>library(caret)

control <- trainControl(method = "LGOCV", number = 1000)
control$sampling = "up"

# I create my predictive model with random forest:

metric = "Accuracy"

set.seed(123)
fit.rand = train(Diet~., data = year3data, method = "ranger", metric = metric, trControl = control)
</code>```

Now I want to find weighted accuracy using a confusion matrix, but all the code I know of requires input of 'true' values and predicted values. I do not know how to access the true observation values from the upsampled dataset, and I know they won't be the same as those in the original dataset. Below is an example of the code I'd like to use:

```<code>confusionMatrix(data = fit.rand$pred, reference = fit.rand$obs, mode = "prec_recall")
</code>```

The object fit.rand does have fit.rand$pred, but it does not have fit.rand$obs. I would like to know how to access the observations (post-resampling) that were used to create fit.rand please. Thank you!

TLDR -> code and the problem below

```<code>library(caret)

control <- trainControl(method = "LGOCV", number = 1000)
control$sampling = "up"

metric = "Accuracy"

set.seed(123)
fit.rand = train(Diet~., data = year3data, method = "ranger", metric = metric, trControl = control)

confusionMatrix(data = fit.rand$pred, reference = fit.rand$obs, mode = "prec_recall")
</code>```

confusionMatrix is the part of the code that I am having a problem with because fit.rand$obs does not exist. I would like to know how to access the observation values used to create fit.rand, because the resampling process has changed them from the original values in my 'year3data' dataframe.

Body:
I am using RStudio, the caret package, to create predictive models. I want to create a confusion matrix, but I do not know how to access observed values after the resampling has been performed.

I have an imbalanced dataset so I've used upsampling with the following code:

library(caret)

control <- trainControl(method = "LGOCV", number = 1000)
control$sampling = "up"

# I create my predictive model with random forest:

metric = "Accuracy"

set.seed(123)
fit.rand = train(Diet~., data = year3data, method = "ranger", metric = metric, trControl = control)

Now I want to find weighted accuracy using a confusion matrix, but all the code I know of requires input of 'true' values and predicted values. I do not know how to access the true observation values from the upsampled dataset, and I know they won't be the same as those in the original dataset. Below is an example of the code I'd like to use:

confusionMatrix(data = fit.rand$pred, reference = fit.rand$obs, mode = "prec_recall")

The object fit.rand does have fit.rand$pred, but it does not have fit.rand$obs. I would like to know how to access the observations (post-resampling) that were used to create fit.rand please. Thank you!

TLDR -> code and the problem below

library(caret)

control <- trainControl(method = "LGOCV", number = 1000)
control$sampling = "up"

metric = "Accuracy"

set.seed(123)
fit.rand = train(Diet~., data = year3data, method = "ranger", metric = metric, trControl = control)

confusionMatrix(data = fit.rand$pred, reference = fit.rand$obs, mode = "prec_recall")

confusionMatrix is the part of the code that I am having a problem with because fit.rand$obs does not exist. I would like to know how to access the observation values used to create fit.rand, because the resampling process has changed them from the original values in my 'year3data' dataframe.


问:
Connect Direct script to "copy" file from source directory to destination directory
I am trying to write a script that takes a file from a specified location and copies it to the destination folder.

I currently have have the following with moves the file, but i need it to copy instead:

```<code>NT_JOB CCD1222
  RUN THURSDAY
  DELAYSUB 11:00
  AGENT atl_stsprd01
  USER connectd
  ARGS source-file.txt +
  W1222 +
  CD.PRDCL.LNX +
  "\\path\to\source\folder\" +
  W99999_UNIX.properties +
  /path/to/destination/folder/ +
  destination-file.txt +
  binary
  EXITCODE 0 SUCCESS
  CMDNAME \data\scripts\filetransfer.bat
  RESOURCE ADD(1, DRES)
ENDJOB
</code>```

What do i need to take the above and make it copy the file over to the destination folder instead!?

Body:
I am trying to write a script that takes a file from a specified location and copies it to the destination folder.

I currently have have the following with moves the file, but i need it to copy instead:

NT_JOB CCD1222
  RUN THURSDAY
  DELAYSUB 11:00
  AGENT atl_stsprd01
  USER connectd
  ARGS source-file.txt +
  W1222 +
  CD.PRDCL.LNX +
  "\\path\to\source\folder\" +
  W99999_UNIX.properties +
  /path/to/destination/folder/ +
  destination-file.txt +
  binary
  EXITCODE 0 SUCCESS
  CMDNAME \data\scripts\filetransfer.bat
  RESOURCE ADD(1, DRES)
ENDJOB

What do i need to take the above and make it copy the file over to the destination folder instead!?