问:
How to convert ASCII character to CGKeyCode?
I need a function that, given a character, returns the CGKeyCode associated with the position of that character on the current keyboard layout. E.g., given "b", it should return kVK_ANSI_B if using U.S. QWERTY, or kVK_ANSI_N if using Dvorak.

The Win32 API has the function VkKeyScan() for this purpose; X11 has the function XStringToKeySym(). Is there such a function in the CG API?

I need this in order to pass a parameter to CGEventCreateKeyboardEvent(). I've tried using CGEventKeyboardSetUnicodeString() instead, but that apparently does not support modifier flags (which I need).

I have searched extensively for this but cannot find a decent answer. Currently I am using the following code (found online), which works, but is not exactly elegant (and rather difficult to decipher how to simplify) and I would prefer not to use it in production code:

```<code>#include <stdint.h>
#include <stdio.h>
#include <ApplicationServices/ApplicationServices.h>

CGKeyCode keyCodeForCharWithLayout(const char c,
                                   const UCKeyboardLayout *uchrHeader);

CGKeyCode keyCodeForChar(const char c)
{
    CFDataRef currentLayoutData;
    TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();

    if (currentKeyboard == NULL) {
        fputs("Could not find keyboard layout\n", stderr);
        return UINT16_MAX;
    }

    currentLayoutData = TISGetInputSourceProperty(currentKeyboard,
                                                kTISPropertyUnicodeKeyLayoutData);
    CFRelease(currentKeyboard);
    if (currentLayoutData == NULL) {
        fputs("Could not find layout data\n", stderr);
        return UINT16_MAX;
    }

    return keyCodeForCharWithLayout(c,
           (const UCKeyboardLayout *)CFDataGetBytePtr(currentLayoutData));
}

/* Beware! Messy, incomprehensible code ahead!
 * TODO: XXX: FIXME! Please! */
CGKeyCode keyCodeForCharWithLayout(const char c,
                                   const UCKeyboardLayout *uchrHeader)
{
    uint8_t *uchrData = (uint8_t *)uchrHeader;
    UCKeyboardTypeHeader *uchrKeyboardList = uchrHeader->keyboardTypeList;

    /* Loop through the keyboard type list. */
    ItemCount i, j;
    for (i = 0; i < uchrHeader->keyboardTypeCount; ++i) {
        /* Get a pointer to the keyToCharTable structure. */
        UCKeyToCharTableIndex *uchrKeyIX = (UCKeyToCharTableIndex *)
        (uchrData + (uchrKeyboardList[i].keyToCharTableIndexOffset));

        /* Not sure what this is for but it appears to be a safeguard... */
        UCKeyStateRecordsIndex *stateRecordsIndex;
        if (uchrKeyboardList[i].keyStateRecordsIndexOffset != 0) {
            stateRecordsIndex = (UCKeyStateRecordsIndex *)
                (uchrData + (uchrKeyboardList[i].keyStateRecordsIndexOffset));

            if ((stateRecordsIndex->keyStateRecordsIndexFormat) !=
                kUCKeyStateRecordsIndexFormat) {
                stateRecordsIndex = NULL;
            }
        } else {
            stateRecordsIndex = NULL;
        }

        /* Make sure structure is a table that can be searched. */
        if ((uchrKeyIX->keyToCharTableIndexFormat) != kUCKeyToCharTableIndexFormat) {
            continue;
        }

        /* Check the table of each keyboard for character */
        for (j = 0; j < uchrKeyIX->keyToCharTableCount; ++j) {
            UCKeyOutput *keyToCharData =
                (UCKeyOutput *)(uchrData + (uchrKeyIX->keyToCharTableOffsets[j]));

            /* Check THIS table of the keyboard for the character. */
            UInt16 k;
            for (k = 0; k < uchrKeyIX->keyToCharTableSize; ++k) {
                /* Here's the strange safeguard again... */
                if ((keyToCharData[k] & kUCKeyOutputTestForIndexMask) ==
                    kUCKeyOutputStateIndexMask) {
                    long keyIndex = (keyToCharData[k] & kUCKeyOutputGetIndexMask);
                    if (stateRecordsIndex != NULL &&
                        keyIndex <= (stateRecordsIndex->keyStateRecordCount)) {
                        UCKeyStateRecord *stateRecord = (UCKeyStateRecord *)
                                                        (uchrData +
                        (stateRecordsIndex->keyStateRecordOffsets[keyIndex]));

                        if ((stateRecord->stateZeroCharData) == c) {
                            return (CGKeyCode)k;
                        }
                    } else if (keyToCharData[k] == c) {
                        return (CGKeyCode)k;
                    }
                } else if (((keyToCharData[k] & kUCKeyOutputTestForIndexMask)
                            != kUCKeyOutputSequenceIndexMask) &&
                           keyToCharData[k] != 0xFFFE &&
                           keyToCharData[k] != 0xFFFF &&
                           keyToCharData[k] == c) {
                    return (CGKeyCode)k;
                }
            }
        }
    }

    return UINT16_MAX;
}
</code>```

Is there a.) (preferably) a standard function I am overlooking, or b.) (almost certainly) a more elegant way write my own?

答:
For the purposes of this question there appear to be 3 types of keys that produce a CGKeyCode:

plain Unicode character, e.g. A

a modifier key, e.g. Shift

a special key, e.g. F1.

I riffed on Ted Wrigley's answer to create proper Swift initialisers for all 3 types. The example from CGEvent(keyboardEventSource:virtualKey:keyDown:) can now be written:

guard let shiftKeyCode = CGKeyCode(modifierFlag: .shift) else { fatalError() }
guard let zKeyCode = CGKeyCode(character: "z") else { fatalError() }

let event1 = CGEvent(keyboardEventSource: nil, virtualKey: shiftKeyCode, keyDown: true)
let event2 = CGEvent(keyboardEventSource: nil, virtualKey: zKeyCode, keyDown: true)
let event3 = CGEvent(keyboardEventSource: nil, virtualKey: zKeyCode, keyDown: false)
let event4 = CGEvent(keyboardEventSource: nil, virtualKey: shiftKeyCode, keyDown: false)
```
<pre class="lang-swift prettyprint-override"><code>//
//  CGKeyCodeInitializers.swift
//
//  Created by John Scott on 09/02/2022.
//

import Foundation
import AppKit

extension CGKeyCode {
    public init?(character: String) {
        if let keyCode = Initializers.shared.characterKeys[character] {
            self = keyCode
        } else {
            return nil
        }
    }

    public init?(modifierFlag: NSEvent.ModifierFlags) {
        if let keyCode = Initializers.shared.modifierFlagKeys[modifierFlag] {
            self = keyCode
        } else {
            return nil
        }
    }

    public init?(specialKey: NSEvent.SpecialKey) {
        if let keyCode = Initializers.shared.specialKeys[specialKey] {
            self = keyCode
        } else {
            return nil
        }
    }

    private struct Initializers {
        let specialKeys: [NSEvent.SpecialKey:CGKeyCode]
        let characterKeys: [String:CGKeyCode]
        let modifierFlagKeys: [NSEvent.ModifierFlags:CGKeyCode]

        static let shared = Initializers()

        init() {
            var specialKeys = [NSEvent.SpecialKey:CGKeyCode]()
            var characterKeys = [String:CGKeyCode]()
            var modifierFlagKeys = [NSEvent.ModifierFlags:CGKeyCode]()

            for keyCode in (0..<128).map({ CGKeyCode($0) }) {
                guard let cgevent = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(keyCode), keyDown: true) else { continue }
                guard let nsevent = NSEvent(cgEvent: cgevent) else { continue }

                var hasHandledKeyCode = false
                if nsevent.type == .keyDown {
                    if let specialKey = nsevent.specialKey {
                        hasHandledKeyCode = true
                        specialKeys[specialKey] = keyCode
                    } else if let characters = nsevent.charactersIgnoringModifiers, !characters.isEmpty && characters != "\u{0010}" {
                        hasHandledKeyCode = true
                        characterKeys[characters] = keyCode
                    }
                } else if nsevent.type == .flagsChanged, let modifierFlag = nsevent.modifierFlags.first(.capsLock, .shift, .control, .option, .command, .help, .function) {
                    hasHandledKeyCode = true
                    modifierFlagKeys[modifierFlag] = keyCode
                }
                if !hasHandledKeyCode {
                    #if DEBUG
                    print("Unhandled keycode \(keyCode): \(nsevent)")
                    #endif
                }
            }
            self.specialKeys = specialKeys
            self.characterKeys = characterKeys
            self.modifierFlagKeys = modifierFlagKeys
        }
    }

}

extension NSEvent.ModifierFlags: Hashable { }

extension OptionSet {
    public func first(_ options: Self.Element ...) -> Self.Element? {
        for option in options {
            if contains(option) {
                return option
            }
        }
        return nil
    }
}
</code>```

Body:
I need a function that, given a character, returns the CGKeyCode associated with the position of that character on the current keyboard layout. E.g., given "b", it should return kVK_ANSI_B if using U.S. QWERTY, or kVK_ANSI_N if using Dvorak.

The Win32 API has the function VkKeyScan() for this purpose; X11 has the function XStringToKeySym(). Is there such a function in the CG API?

I need this in order to pass a parameter to CGEventCreateKeyboardEvent(). I've tried using CGEventKeyboardSetUnicodeString() instead, but that apparently does not support modifier flags (which I need).

I have searched extensively for this but cannot find a decent answer. Currently I am using the following code (found online), which works, but is not exactly elegant (and rather difficult to decipher how to simplify) and I would prefer not to use it in production code:

#include <stdint.h>
#include <stdio.h>
#include <ApplicationServices/ApplicationServices.h>

CGKeyCode keyCodeForCharWithLayout(const char c,
                                   const UCKeyboardLayout *uchrHeader);

CGKeyCode keyCodeForChar(const char c)
{
    CFDataRef currentLayoutData;
    TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();

    if (currentKeyboard == NULL) {
        fputs("Could not find keyboard layout\n", stderr);
        return UINT16_MAX;
    }

    currentLayoutData = TISGetInputSourceProperty(currentKeyboard,
                                                kTISPropertyUnicodeKeyLayoutData);
    CFRelease(currentKeyboard);
    if (currentLayoutData == NULL) {
        fputs("Could not find layout data\n", stderr);
        return UINT16_MAX;
    }

    return keyCodeForCharWithLayout(c,
           (const UCKeyboardLayout *)CFDataGetBytePtr(currentLayoutData));
}

/* Beware! Messy, incomprehensible code ahead!
 * TODO: XXX: FIXME! Please! */
CGKeyCode keyCodeForCharWithLayout(const char c,
                                   const UCKeyboardLayout *uchrHeader)
{
    uint8_t *uchrData = (uint8_t *)uchrHeader;
    UCKeyboardTypeHeader *uchrKeyboardList = uchrHeader->keyboardTypeList;

    /* Loop through the keyboard type list. */
    ItemCount i, j;
    for (i = 0; i < uchrHeader->keyboardTypeCount; ++i) {
        /* Get a pointer to the keyToCharTable structure. */
        UCKeyToCharTableIndex *uchrKeyIX = (UCKeyToCharTableIndex *)
        (uchrData + (uchrKeyboardList[i].keyToCharTableIndexOffset));

        /* Not sure what this is for but it appears to be a safeguard... */
        UCKeyStateRecordsIndex *stateRecordsIndex;
        if (uchrKeyboardList[i].keyStateRecordsIndexOffset != 0) {
            stateRecordsIndex = (UCKeyStateRecordsIndex *)
                (uchrData + (uchrKeyboardList[i].keyStateRecordsIndexOffset));

            if ((stateRecordsIndex->keyStateRecordsIndexFormat) !=
                kUCKeyStateRecordsIndexFormat) {
                stateRecordsIndex = NULL;
            }
        } else {
            stateRecordsIndex = NULL;
        }

        /* Make sure structure is a table that can be searched. */
        if ((uchrKeyIX->keyToCharTableIndexFormat) != kUCKeyToCharTableIndexFormat) {
            continue;
        }

        /* Check the table of each keyboard for character */
        for (j = 0; j < uchrKeyIX->keyToCharTableCount; ++j) {
            UCKeyOutput *keyToCharData =
                (UCKeyOutput *)(uchrData + (uchrKeyIX->keyToCharTableOffsets[j]));

            /* Check THIS table of the keyboard for the character. */
            UInt16 k;
            for (k = 0; k < uchrKeyIX->keyToCharTableSize; ++k) {
                /* Here's the strange safeguard again... */
                if ((keyToCharData[k] & kUCKeyOutputTestForIndexMask) ==
                    kUCKeyOutputStateIndexMask) {
                    long keyIndex = (keyToCharData[k] & kUCKeyOutputGetIndexMask);
                    if (stateRecordsIndex != NULL &&
                        keyIndex <= (stateRecordsIndex->keyStateRecordCount)) {
                        UCKeyStateRecord *stateRecord = (UCKeyStateRecord *)
                                                        (uchrData +
                        (stateRecordsIndex->keyStateRecordOffsets[keyIndex]));

                        if ((stateRecord->stateZeroCharData) == c) {
                            return (CGKeyCode)k;
                        }
                    } else if (keyToCharData[k] == c) {
                        return (CGKeyCode)k;
                    }
                } else if (((keyToCharData[k] & kUCKeyOutputTestForIndexMask)
                            != kUCKeyOutputSequenceIndexMask) &&
                           keyToCharData[k] != 0xFFFE &&
                           keyToCharData[k] != 0xFFFF &&
                           keyToCharData[k] == c) {
                    return (CGKeyCode)k;
                }
            }
        }
    }

    return UINT16_MAX;
}

Is there a.) (preferably) a standard function I am overlooking, or b.) (almost certainly) a more elegant way write my own?

Body:
For the purposes of this question there appear to be 3 types of keys that produce a CGKeyCode:

plain Unicode character, e.g. A

a modifier key, e.g. Shift

a special key, e.g. F1.

I riffed on Ted Wrigley's answer to create proper Swift initialisers for all 3 types. The example from CGEvent(keyboardEventSource:virtualKey:keyDown:) can now be written:

guard let shiftKeyCode = CGKeyCode(modifierFlag: .shift) else { fatalError() }
guard let zKeyCode = CGKeyCode(character: "z") else { fatalError() }

let event1 = CGEvent(keyboardEventSource: nil, virtualKey: shiftKeyCode, keyDown: true)
let event2 = CGEvent(keyboardEventSource: nil, virtualKey: zKeyCode, keyDown: true)
let event3 = CGEvent(keyboardEventSource: nil, virtualKey: zKeyCode, keyDown: false)
let event4 = CGEvent(keyboardEventSource: nil, virtualKey: shiftKeyCode, keyDown: false)

//
//  CGKeyCodeInitializers.swift
//
//  Created by John Scott on 09/02/2022.
//

import Foundation
import AppKit

extension CGKeyCode {
    public init?(character: String) {
        if let keyCode = Initializers.shared.characterKeys[character] {
            self = keyCode
        } else {
            return nil
        }
    }

    public init?(modifierFlag: NSEvent.ModifierFlags) {
        if let keyCode = Initializers.shared.modifierFlagKeys[modifierFlag] {
            self = keyCode
        } else {
            return nil
        }
    }

    public init?(specialKey: NSEvent.SpecialKey) {
        if let keyCode = Initializers.shared.specialKeys[specialKey] {
            self = keyCode
        } else {
            return nil
        }
    }

    private struct Initializers {
        let specialKeys: [NSEvent.SpecialKey:CGKeyCode]
        let characterKeys: [String:CGKeyCode]
        let modifierFlagKeys: [NSEvent.ModifierFlags:CGKeyCode]

        static let shared = Initializers()

        init() {
            var specialKeys = [NSEvent.SpecialKey:CGKeyCode]()
            var characterKeys = [String:CGKeyCode]()
            var modifierFlagKeys = [NSEvent.ModifierFlags:CGKeyCode]()

            for keyCode in (0..<128).map({ CGKeyCode($0) }) {
                guard let cgevent = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(keyCode), keyDown: true) else { continue }
                guard let nsevent = NSEvent(cgEvent: cgevent) else { continue }

                var hasHandledKeyCode = false
                if nsevent.type == .keyDown {
                    if let specialKey = nsevent.specialKey {
                        hasHandledKeyCode = true
                        specialKeys[specialKey] = keyCode
                    } else if let characters = nsevent.charactersIgnoringModifiers, !characters.isEmpty && characters != "\u{0010}" {
                        hasHandledKeyCode = true
                        characterKeys[characters] = keyCode
                    }
                } else if nsevent.type == .flagsChanged, let modifierFlag = nsevent.modifierFlags.first(.capsLock, .shift, .control, .option, .command, .help, .function) {
                    hasHandledKeyCode = true
                    modifierFlagKeys[modifierFlag] = keyCode
                }
                if !hasHandledKeyCode {
                    #if DEBUG
                    print("Unhandled keycode \(keyCode): \(nsevent)")
                    #endif
                }
            }
            self.specialKeys = specialKeys
            self.characterKeys = characterKeys
            self.modifierFlagKeys = modifierFlagKeys
        }
    }

}

extension NSEvent.ModifierFlags: Hashable { }

extension OptionSet {
    public func first(_ options: Self.Element ...) -> Self.Element? {
        for option in options {
            if contains(option) {
                return option
            }
        }
        return nil
    }
}


来源: stackexchange

问:
Can I get the network requests in testcafe from the beforeEach?
I saw this page from testcafe documentation, but it all points toward tests.

```<code>import { RequestLogger } from 'testcafe';
const logger = RequestLogger({ logResponseBody: true, logRequestBody: true });
const methodCallInBeforeEach = async => {console.log(logger.requests)}
</code>```

Every time my logger is empty, as if I had no requests. This works if I try to get the info from a test, but didn't manage to do it from the beforeEach. Is that even possible or am I missing something?

答:
I prepared a sample that demonstrates that the logger.requests works as expected inside the beforeEach hook:</p>
```<code>import { RequestLogger, Selector } from 'testcafe';

const headerLogger = RequestLogger(/testcafe/, {
    logRequestHeaders:  true,
    logResponseHeaders: true,
});

fixture `f`
    .page `https://testcafe.io`
    .requestHooks(headerLogger)
    .beforeEach(async t => {
        await t.click(Selector('a').withText('Docs'));

        console.log(headerLogger.requests.map(r => r.request.url));
    });

test(`t`, async t => {

});

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I saw this page from testcafe documentation, but it all points toward tests.

import { RequestLogger } from 'testcafe';
const logger = RequestLogger({ logResponseBody: true, logRequestBody: true });
const methodCallInBeforeEach = async => {console.log(logger.requests)}

Every time my logger is empty, as if I had no requests. This works if I try to get the info from a test, but didn't manage to do it from the beforeEach. Is that even possible or am I missing something?

Body:
I prepared a sample that demonstrates that the logger.requests works as expected inside the beforeEach hook:

import { RequestLogger, Selector } from 'testcafe';

const headerLogger = RequestLogger(/testcafe/, {
    logRequestHeaders:  true,
    logResponseHeaders: true,
});

fixture `f`
    .page `https://testcafe.io`
    .requestHooks(headerLogger)
    .beforeEach(async t => {
        await t.click(Selector('a').withText('Docs'));

        console.log(headerLogger.requests.map(r => r.request.url));
    });

test(`t`, async t => {

});


问:
Window form does not close
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

```<code>private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}
</code>```

please write some code

答: You can close the form using Form.Close()</p>

ContentLicense: CC BY-SA 3.0

Title: Window form does not close

Body:
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}

please write some code


问:
How to get value from constant file array based on key in php?
I have one file which is constants inside this file i have one array i want to call that array key into another file,can you please help me to fix the issue..?

constants.php

```<code><?php

namespace App\Ship\Constants;

class Constants
{
    const USER_DEPT = 'MECH';
    const STAFF_DEPT = 'Batch_1';
    const USER_SECTION = 1;
    const STAFF_SECTION =50;

    const USER_TYPES = [
            self::USER_DEPT => self::USER_SECTION,
            self::STAFF_DEPT => self::STAFF_SECTION
    ];
}
</code>```

Controller.php

```<code>//$field is either USER or STAFF based on request it's coming
public function check($field){
            constants::USER_TYPES[$field.'_DEPT'];
}
</code>```

Error
undefined index USER_DEPT

答:
When you declare an array key as variable then the actual key will be the assigned by the value of that variable. in your case USER_TYPES array contain these data:

```<code>Array
(
    [MECH] => 1
    [Batch_1] => 50
)
</code>```

Thats why you getting undefined index error

if want to access array index like USER_DEPT then you have to assign your constant like this:

```<code>const USER_DEPT = 'USER_DEPT';
const STAFF_DEPT = 'STAFF_DEPT';
</code>```

Or change array key like:

```<code>const USER_TYPES = [
    'USER_DEPT' => self::USER_SECTION,
    'STAFF_DEPT' => self::STAFF_SECTION
];
</code>```

Body:
I have one file which is constants inside this file i have one array i want to call that array key into another file,can you please help me to fix the issue..?

constants.php

<?php

namespace App\Ship\Constants;

class Constants
{
    const USER_DEPT = 'MECH';
    const STAFF_DEPT = 'Batch_1';
    const USER_SECTION = 1;
    const STAFF_SECTION =50;

    const USER_TYPES = [
            self::USER_DEPT => self::USER_SECTION,
            self::STAFF_DEPT => self::STAFF_SECTION
    ];
}

Controller.php

//$field is either USER or STAFF based on request it's coming
public function check($field){
            constants::USER_TYPES[$field.'_DEPT'];
}

Error
undefined index USER_DEPT

Body:
When you declare an array key as variable then the actual key will be the assigned by the value of that variable. in your case USER_TYPES array contain these data:

Array
(
    [MECH] => 1
    [Batch_1] => 50
)

Thats why you getting undefined index error

if want to access array index like USER_DEPT then you have to assign your constant like this:

const USER_DEPT = 'USER_DEPT';
const STAFF_DEPT = 'STAFF_DEPT';

Or change array key like:

const USER_TYPES = [
    'USER_DEPT' => self::USER_SECTION,
    'STAFF_DEPT' => self::STAFF_SECTION
];


问:
calling DataGridView.EndEdit() from picturebox click event doesn't work
I'm using a DataGridView with no binding a datasource. How can I end the datagridview editing mode by clicking on a picturebox. I've tested EndEdit() in picturebox click event, but seems it doesn't work.</p>
```<code>    private void pictureBox1_Click(object sender, EventArgs e)
    {
        dgv.EndEdit();
    }
</code>```

答: Calling EndEdit() won't end the editing mode if DataGridView.EditMode is set to EditOnEnter.

Body:
I'm using a DataGridView with no binding a datasource. How can I end the datagridview editing mode by clicking on a picturebox. I've tested EndEdit() in picturebox click event, but seems it doesn't work.

    private void pictureBox1_Click(object sender, EventArgs e)
    {
        dgv.EndEdit();
    }


问:
How to replace LDAP Authentication from Azure AD B2C?
I have a requirement to replace the LDAP Authentication from a gateway microservice with Azure AD B2C, Is there any standard way or steps to replace that with newer authentication method or we need to completely do that from scratch to provide the implementation through Azure AD B2C.</p>

答:
There's a write-up here and some custom policy samples here.

The main steps are:

Migrate the users; either big bang or just in time. The main issue is that you need new passwords

Replace the LDAP API that you use to authenticate with an appropriate B2C code sample

Replace the LDAP user CRUD calls with the appropriate Graph API call


问:
How to handle multiple instances of input to one field
I want to add a line in a multiline textbox after every information that the user enters in the TextBox in Windows form. I wont be able to determine the point to draw line as I wont know how long the user will enter information. So I am thinking of adding a  string "_______" after a button click in the code. Is there a better way? </p>

答:
If you intend to use a regular multiline textbox, printing a line of '-' characters is your best bet. Of course, you could print a line of '─' characters to make the line solid. Another alternative is to use a WebBrowser control, and set its DocumentText property to the HTML you would like to display. This will allow you to append
 whenever you want a dividing line.

OwnerDisplayName: LearnOneTime

LastEditorDisplayName: Keltex

Body: If you intend to use a regular multiline textbox, printing a line of '-' characters is your best bet. Of course, you could print a line of '─' characters to make the line solid. Another alternative is to use a WebBrowser control, and set its DocumentText property to the HTML you would like to display. This will allow you to append <hr/> whenever you want a dividing line.

OwnerDisplayName: Tormod Fjeldskår

ContentLicense: CC BY-SA 2.5


问:
How to find the *smallest* number in the list that is close to a given number in Python?
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

```<code>my_list=[1,10,15,20,45,56]
my_no=9
</code>```

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!

答:
List comprehension is another elegant way to do this.</p>
```<code>my_list=[1,10,15,20,45,56]
my_no = 9
output = max([x for x in my_list if x<=my_no])
print(output) #1
</code>```

Body:
I wanted to know if there is a way to find the smallest number in the list which is closest to a given number.

Foe e.x.

my_list=[1,10,15,20,45,56]
my_no=9

Output should be equal to 1
Explanation: since 9 comes between 1 and 10 and I want the smaller number, i.e. 1.

Similarly if my_no=3, output is equal to 1

I am new to python, so any help will be much appreciated. Thanks!

Body:
List comprehension is another elegant way to do this.

my_list=[1,10,15,20,45,56]
my_no = 9
output = max([x for x in my_list if x<=my_no])
print(output) #1


问:
Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls
Recently I've realised that, some adblocker extensions (such as adBlocker plus) block some Ajax calls. I get that error on the console:

```<code>GET http://localhost/prj/conn.php?q=users/list/ net::ERR_BLOCKED_BY_CLIENT
</code>```

Why does it block some Ajax call but not the others and what causes that? Is there any workaround other than telling user to turn off adblocker?

答: If there are any ad blockers (Brave browser use default blocker), turn it off. This worked for me</p>

Body:
Recently I've realised that, some adblocker extensions (such as adBlocker plus) block some Ajax calls. I get that error on the console:

GET http://localhost/prj/conn.php?q=users/list/ net::ERR_BLOCKED_BY_CLIENT

Why does it block some Ajax call but not the others and what causes that? Is there any workaround other than telling user to turn off adblocker?


问:
How to set multiple schedule in azure timer function?
I have a working sample azure timer function, but about setting it in multiple schedule, I'm not sure if doing it correctly, because I can't test it immediately because it is scheduled hours gap.

My goal is, to display context.log every 8:00AM, and 8:00PM every day.

note: my code below actually don't work because parameter hour does not accept array (for demonstration purpose only)

Here is my code:

```<code>export const TimerTrigger1 = TypedAzFunc.createFunctionBuilder(__dirname)
  .with(
    TimerTriggerPlugin.init({
      schedule: {
        crontab: {
          second: 0,
          minute: { interval: 1 },
          hour: [{ interval: 8 }, { interval: 20 }],
          day: '*',
          month: '*',
          dayOfWeek: '*',
        },
      },
    })
  )
  .build(async (context, timer) => {
    var timeStamp = new Date().toISOString()

    if (timer.isPastDue) {
      context.log('timer has already triggered')
    }
    context.log('timer has triggered', timeStamp)
  })

export const run = TimerTrigger1.run
</code>```

答: You could solve this by having 2 timers, one for 8 am and one for 8 pm.</p>

Body:
I have a working sample azure timer function, but about setting it in multiple schedule, I'm not sure if doing it correctly, because I can't test it immediately because it is scheduled hours gap.

My goal is, to display context.log every 8:00AM, and 8:00PM every day.

note: my code below actually don't work because parameter hour does not accept array (for demonstration purpose only)

Here is my code:

export const TimerTrigger1 = TypedAzFunc.createFunctionBuilder(__dirname)
  .with(
    TimerTriggerPlugin.init({
      schedule: {
        crontab: {
          second: 0,
          minute: { interval: 1 },
          hour: [{ interval: 8 }, { interval: 20 }],
          day: '*',
          month: '*',
          dayOfWeek: '*',
        },
      },
    })
  )
  .build(async (context, timer) => {
    var timeStamp = new Date().toISOString()

    if (timer.isPastDue) {
      context.log('timer has already triggered')
    }
    context.log('timer has triggered', timeStamp)
  })

export const run = TimerTrigger1.run


问:
Fetch and function error on AJAX and APIs call on reactjs
I'm getting an error of items.map is not a function when fetching the file that is hosted from unsplash.

I'm not sure if the problem is from the .map or from fetching the file from source.

Below is my code and also here is the complete sandbox code https://codesandbox.io/.

```<code>import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map((item) =>
          <li key={item.results.id}>
            {item.results.description}
          </li>
        )}
      </ul>
    );
  }
}

export default MyComponent;
</code>```

答:
It seems the response JSON is an object and not an array. When you update the items state with an object it's no longer mappable.

```<code>// 20220209004834
// https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U#f3f3f3

{
  "total": 10000,
  "total_pages": 1000,
  "results": [
    {
      "id": "_LuLiJc1cdo",
      "created_at": "2016-06-06T01:08:36-04:00",
      "updated_at": "2022-02-08T13:00:46-05:00",
      "promoted_at": "2016-06-06T01:08:36-04:00",
      ...
      "description": "follow @kalenemsley on ig",
      ...
    },
    ...
  ],
  ...
}
</code>```

You probably want the results array property for your state.

```<code>useEffect(() => {
  fetch("....")
    .then((res) => res.json())
    .then(
      (result) => {
        setIsLoaded(true);
        setItems(result.results);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    );
}, []);
</code>```

Then when mapping each item you access the properties correctly

```<code><ul>
  {items.map((item) =>
    <li key={item.id}>
      {item.description}
    </li>
  )}
</ul>
</code>```

Body:
I'm getting an error of items.map is not a function when fetching the file that is hosted from unsplash.

I'm not sure if the problem is from the .map or from fetching the file from source.

Below is my code and also here is the complete sandbox code https://codesandbox.io/.

import { React, useState, useEffect } from "react";

function MyComponent() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);
  useEffect(() => {
    fetch(
      "https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U"
    )
      .then((res) => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      );
  }, []);

  if (error) {
    return
Error: {error.message}
;
  } else if (!isLoaded) {
    return
Loading...
;
  } else {
    return (

        {items.map((item) =>

            {item.results.description}

        )}

    );
  }
}

export default MyComponent;

Body:
It seems the response JSON is an object and not an array. When you update the items state with an object it's no longer mappable.

// 20220209004834
// https://api.unsplash.com/search/photos?query=nature?orientation=landscape&client_id=ddIh7_ebg4KwNHzNLf3ePCZb6yIPREJ5jxG3dYgoj6U#f3f3f3

{
  "total": 10000,
  "total_pages": 1000,
  "results": [
    {
      "id": "_LuLiJc1cdo",
      "created_at": "2016-06-06T01:08:36-04:00",
      "updated_at": "2022-02-08T13:00:46-05:00",
      "promoted_at": "2016-06-06T01:08:36-04:00",
      ...
      "description": "follow @kalenemsley on ig",
      ...
    },
    ...
  ],
  ...
}

You probably want the results array property for your state.

useEffect(() => {
  fetch("....")
    .then((res) => res.json())
    .then(
      (result) => {
        setIsLoaded(true);
        setItems(result.results);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    );
}, []);

Then when mapping each item you access the properties correctly

<ul>
  {items.map((item) =>
    <li key={item.id}>
      {item.description}
    </li>
  )}
</ul>


问:
Writing to CSV file with numpy arrays without brackets
I'm attempting to map out coordinates for a circle and export those values to excel to then plot the values. My output CSV file returns the correct values but with brackets around the values ex x,y, [0.],[9.]. I would like to learn how to remove those brackets with my current code attempt if possible.

```<code>import numpy as np
from itertools import zip_longest

r = 9
h = 1
k = 1

# r = int(input('Radius'))
# h = int(input('h'))
# k = int(input('k'))

deg = np.arange(0, 361, 1)[:, np.newaxis]
theta = (np.pi * deg * 2)/360

x = (r * np.sin(theta) + h)
y = (r * np.cos(theta) + k)
d = x, y

Points = zip_longest(*d, fillvalue = '')
with open('test.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(('x','y','r','h','k'))
    wr.writerows(Points)
myfile.close()
</code>```

答:
x and y are arrays with shape (361,1). When you iterate over such an array (as zip_longest will do), you get a stream of arrays of shape (1,) which is where your surplus brackets come from.

One solution would be to make your arrays (361,) instead (i.e, one-dimensional). Then iterating would give scalars.

Another solution would be to use np.hstack([x,y]) instead of zip, and tossing the entire resulting (361,2) array to writerows.

(Off topic: You do not need myfile.close(); the with ... construct takes care of that for you — that's what it's for!)

Body:
I'm attempting to map out coordinates for a circle and export those values to excel to then plot the values. My output CSV file returns the correct values but with brackets around the values ex x,y, [0.],[9.]. I would like to learn how to remove those brackets with my current code attempt if possible.

import numpy as np
from itertools import zip_longest

r = 9
h = 1
k = 1

# r = int(input('Radius'))
# h = int(input('h'))
# k = int(input('k'))

deg = np.arange(0, 361, 1)[:, np.newaxis]
theta = (np.pi * deg * 2)/360

x = (r * np.sin(theta) + h)
y = (r * np.cos(theta) + k)
d = x, y

Points = zip_longest(*d, fillvalue = '')
with open('test.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
    wr = csv.writer(myfile)
    wr.writerow(('x','y','r','h','k'))
    wr.writerows(Points)
myfile.close()


问:
How do I reduce the nex lines of Ruby code?
```<code>    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end
</code>```

So I want to reduce this case when is there another way of implementing this?

答:
How about:</p>
```<code>CASES = [@meals_controller, @customers_controller].product([:add, :list, :edit, :delete])

def route_action(action)
  if action > 0
    selected = CASES[action-1] # something like [:@meals_controller, :add]
    if selected
      selected.first.send(*selected.last)
    else
      puts "action number too large"
    end
  elsif action == 0
    stop
  else # Do we have to catch this?
    puts "action number negative" # programming error?
  end
end

</code>```

Body:
    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end

So I want to reduce this case when is there another way of implementing this?

Body:
How about:

CASES = [@meals_controller, @customers_controller].product([:add, :list, :edit, :delete])

def route_action(action)
  if action > 0
    selected = CASES[action-1] # something like [:@meals_controller, :add]
    if selected
      selected.first.send(*selected.last)
    else
      puts "action number too large"
    end
  elsif action == 0
    stop
  else # Do we have to catch this?
    puts "action number negative" # programming error?
  end
end


问:
What does :-> mean in a haskell type specification
I've seen this in a few places:

```<code>data T = T a :-> b
</code>```

Notably in quickcheck we have

```<code>data Fun a b = Fun (a :-> b, b) (a -> b)
</code>```

What is the :-> and how does it differ from ->?

答:
Operators beginning with a colon is a constructor or type name. In this case it is a type name for a data type specific to quickcheck, but in general the symbol :-> could be used for any constructor or type name as you like (it's not part of the language proper).

The definition of :-> in quickcheck:

```<code>-- the type of possibly partial concrete functions
data a :-> c where
  Pair  :: (a :-> (b :-> c)) -> ((a,b) :-> c)
  (:+:) :: (a :-> c) -> (b :-> c) -> (Either a b :-> c)
  Unit  :: c -> (() :-> c)
  Nil   :: a :-> c
  Table :: Eq a => [(a,c)] -> (a :-> c)
  Map   :: (a -> b) -> (b -> a) -> (b :-> c) -> (a :-> c)
</code>```

Body:
I've seen this in a few places:

data T = T a :-> b

Notably in quickcheck we have

data Fun a b = Fun (a :-> b, b) (a -> b)

What is the :-> and how does it differ from ->?

Body:
Operators beginning with a colon is a constructor or type name. In this case it is a type name for a data type specific to quickcheck, but in general the symbol :-> could be used for any constructor or type name as you like (it's not part of the language proper).

The definition of :-> in quickcheck:

-- the type of possibly partial concrete functions
data a :-> c where
  Pair  :: (a :-> (b :-> c)) -> ((a,b) :-> c)
  (:+:) :: (a :-> c) -> (b :-> c) -> (Either a b :-> c)
  Unit  :: c -> (() :-> c)
  Nil   :: a :-> c
  Table :: Eq a => [(a,c)] -> (a :-> c)
  Map   :: (a -> b) -> (b -> a) -> (b :-> c) -> (a :-> c)


问:
Backing property vs. getter for returning a less specific type
This is a follow up question to my previous question I have a hard time understanding the purpose of a "backing property"

I understand that sometimes, we want to to have a private mutable list inside a class, and expose an immutable list to outside classes. Like this:

```<code>class Demo {
    private val _myList: MutableList<String> = mutableListOf()
    val myList: List<String> get() = _myList
}

fun main() {
    val list = Demo().myList
}
</code>```

In this case, list is an immutable list, as desired.

But what about this code:

```<code>class Demo {
    private val myList: MutableList<String> = mutableListOf()

    fun getList(): List<String> = myList.toList()
}

fun main() {
    val list = Demo().getList()
}
</code>```

In this case, we don't have an extra property, and list is also an immutable list. This is kind of the Java way of doing this.

What's the real difference between the two?

答:
The problem would be in the Java-style getList() method. You're calling the extension function toList() every time the method is called. The code for that method:

```<code>public fun <T> Iterable<T>.toList(): List<T> {
    if (this is Collection) {
        return when (size) {
            0 -> emptyList()
            1 -> listOf(if (this is List) get(0) else iterator().next())
            else -> this.toMutableList()
        }
    }
    return this.toMutableList().optimizeReadOnlyList()
}
</code>```

I don't know how efficient these underlying calls are, but this seems like a lot of unnecessary function calls and conversions inside a getter method.

Body:
This is a follow up question to my previous question I have a hard time understanding the purpose of a "backing property"

I understand that sometimes, we want to to have a private mutable list inside a class, and expose an immutable list to outside classes. Like this:

class Demo {
    private val _myList: MutableList<String> = mutableListOf()
    val myList: List<String> get() = _myList
}

fun main() {
    val list = Demo().myList
}

In this case, list is an immutable list, as desired.

But what about this code:

class Demo {
    private val myList: MutableList<String> = mutableListOf()

    fun getList(): List<String> = myList.toList()
}

fun main() {
    val list = Demo().getList()
}

In this case, we don't have an extra property, and list is also an immutable list. This is kind of the Java way of doing this.

What's the real difference between the two?

Body:
The problem would be in the Java-style getList() method. You're calling the extension function toList() every time the method is called. The code for that method:

public fun <T> Iterable<T>.toList(): List<T> {
    if (this is Collection) {
        return when (size) {
            0 -> emptyList()
            1 -> listOf(if (this is List) get(0) else iterator().next())
            else -> this.toMutableList()
        }
    }
    return this.toMutableList().optimizeReadOnlyList()
}

I don't know how efficient these underlying calls are, but this seems like a lot of unnecessary function calls and conversions inside a getter method.


问:
Bold & Non-Bold Text In A Single UILabel?
How would it be possible to include both bold and non-bold text in a uiLabel?

I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?

Apple achieves this in several of their apps;
Examples Screenshot:

Thanks!
- Dom

答: AttributeString has constructors that take mark down strings, doing it this way can mean your attribute string has no other attributes, so if you are using xibs, you can have the text without the bold, set to all the other attributes you want, then in code enumerate through the attribute ranges of your mark down string and apply them to the attributed string you get from you xib file, and then reapply it to your attributed attributeString of the particular field.</p>


问:
Ignoring case sensitivity when filtering with boto3
I'm trying to filter the list of EC2 instances that I get in my script. I want my search to be based on tags, as we tag instances based on their purpose (service machines, personal gateways, etc).

I use this:

client = boto3.client('ec2', region_name='eu-west-1')

results = (
   client.get_paginator('describe_instances')
   .paginate(
       Filters=[
           {'Name': 'tag:Service', 'Values': ['gw']}
           ]
           )
   .build_full_result()
)
counter=0

for result in results['Reservations']:
    counter+=1
    print(counter, result['Instances'][0]['InstanceId'])
```
<p>The above works fine, but I'm not getting the correct amount of instances according to my counter.</p>
<p>I went and double checked it: in my EC2 console I get 361 instances based on that same tag:
<img src="https://i.stack.imgur.com/do4Ka.png" alt="enter image description here" /></p>
<p>When I run the above code, I get 335 instances (according to the counter I placed).</p>
<p>Then when I change the filter to use <code>GW</code> instead of <code>gw</code>, I get a 26 instances only, which add up to 361 (335 + 26).</p>
<p>I tried fixing it by simply adding another filter, like so:</p>
<pre class="lang-py prettyprint-override"><code>results = (
   client.get_paginator('describe_instances')
   .paginate(
       Filters=[
           {'Name': 'tag:Service', 'Values': ['gw']},
           {'Name': 'tag:Service', 'Values': ['GW']}
           ]
           )
   .build_full_result()
)
</code>```

This variation doesn't return anything, so I guess I can't use the same key with "different" values?

I tried stuff like {'Name': 'tag:Service', 'Values': ['gw'|'GW'] but | is not supported.

I would like to avoid searching for these tags inside a loop. I think utilizing the built-in filter inside of my paginator would be cleaner and simpler.

I'm not sure what other options I have. Why would the EC2 console be case insensitive, but the filter is not?

Edit:

turns out I wasn't paying enough attention to the docs, I just needed: {'Name': 'tag:Service', 'Values': ['gw', 'GW']}

答:
From docs:

If you specify multiple values for a filter, the values are joined with an OR , and the request returns all results that match any of the specified values.

So it should be:

```<code>{'Name': 'tag:Service', 'Values': ['gw','GW']}
</code>```

Body:
I'm trying to filter the list of EC2 instances that I get in my script. I want my search to be based on tags, as we tag instances based on their purpose (service machines, personal gateways, etc).

I use this:

client = boto3.client('ec2', region_name='eu-west-1')

results = (
   client.get_paginator('describe_instances')
   .paginate(
       Filters=[
           {'Name': 'tag:Service', 'Values': ['gw']}
           ]
           )
   .build_full_result()
)
counter=0

for result in results['Reservations']:
    counter+=1
    print(counter, result['Instances'][0]['InstanceId'])

The above works fine, but I'm not getting the correct amount of instances according to my counter.

I went and double checked it: in my EC2 console I get 361 instances based on that same tag:

When I run the above code, I get 335 instances (according to the counter I placed).

Then when I change the filter to use GW instead of gw, I get a 26 instances only, which add up to 361 (335 + 26).

I tried fixing it by simply adding another filter, like so:

results = (
   client.get_paginator('describe_instances')
   .paginate(
       Filters=[
           {'Name': 'tag:Service', 'Values': ['gw']},
           {'Name': 'tag:Service', 'Values': ['GW']}
           ]
           )
   .build_full_result()
)

This variation doesn't return anything, so I guess I can't use the same key with "different" values?

I tried stuff like {'Name': 'tag:Service', 'Values': ['gw'|'GW'] but | is not supported.

I would like to avoid searching for these tags inside a loop. I think utilizing the built-in filter inside of my paginator would be cleaner and simpler.

I'm not sure what other options I have. Why would the EC2 console be case insensitive, but the filter is not?

Edit:

turns out I wasn't paying enough attention to the docs, I just needed: {'Name': 'tag:Service', 'Values': ['gw', 'GW']}

Body:
From docs:

If you specify multiple values for a filter, the values are joined with an OR , and the request returns all results that match any of the specified values.

So it should be:

{'Name': 'tag:Service', 'Values': ['gw','GW']}


问:
How to implement labelImg function on the web browser
i am using labelImg tool for a graphical image annotation.
But for our education site, we would like to add this function of a graphical image annotation like labelImg into our web service.
https://github.com/tzutalin/labelImg

So Can we make labelling tool for data preparation for training on our website as one of function of data training?

Anyone have any idea concerned with this?

Ryan.

答:
Labelimg is a desktop app that uses Qt for its UI. There exists solutions to run Qt in a Browser. See for example the solutions for Running Qt over the Web.

Otherwise I would recommend to explore other web-based tools for image annotation, e.g., the Computer Vision Annotation Tool (CVAT).

I hope you succeed in your endeavor.

To previous flags/deletion of my answer: As per Stackoverflow's code of conduct I did "make sure my answer provides at least a viable alternative. The answer can be “don’t do that”, but it should also include “try this instead”. Any answer that gets the asker going in the right direction is helpful". Please comment with further explanation why this is not a valid answer. Many thanks and all the best.


问:
Creating a new collection from results of a mongodb query
I'm trying to create a new collection using the results of a mongodb query. For example,

db.coll.find({name:'abcd'})
```

will return a subset of the collection. Now, I want to insert this result into a new collection. How can I do this?

答:
Just a note:
If you want include only particular fields from output - you can use project keyword, as:

```<code>db.coll.aggregate([
    {$match: {name: 'abcd'}},
    { $project: {'name': 1}}
    {$out: 'newcoll'}
])
</code>```

Body:
I'm trying to create a new collection using the results of a mongodb query. For example,

db.coll.find({name:'abcd'})

will return a subset of the collection. Now, I want to insert this result into a new collection. How can I do this?

Body:
Just a note:
If you want include only particular fields from output - you can use project keyword, as:

db.coll.aggregate([
    {$match: {name: 'abcd'}},
    { $project: {'name': 1}}
    {$out: 'newcoll'}
])


问:
How to do a function call in HTML with vueJS
For my dev lessons, I need to create a social network for a company.

One of the functionalities is to display the comment number linked to a publication (a bit like on Facebook).

To get the comments, I am using vueX to get all data from one source. So, to display the comment count number, here is my idea : for each publication contained in an array, I get all publication comments in another array. So, if I do a {{comments.length}}, for example, this should display "3 comments"

So I wrote the following code :

```<code>  <div v-if="publications.length > 0">
    <AddPostForm />
    <section
      v-for="post in publications"
      :key="post.postId"
      class="publications"
    >
      <div v-bind:data-id="post.postId" class="publications__card">
        <div class="publications__author" :data-user-id="post.userId">
          <img :src="post.avatarUrl" alt="Photo de profil" />
          <span
            class="publications__author-profile"
            @click="goToProfile(post.userId)"
          >
            {{ post.firstName }} {{ post.lastName }}
          </span>
        </div>

        <div
          class="publications__content"
          v-if="post.postContent !== null && post.postContent !== ''"
        >
          <p>{{ post.postContent }}</p>
        </div>

        <div
          class="publications__content"
          v-else-if="
            post.postContent === null ||
            (post.postContent === '' &&
              (post.imageUrl !== null || post.imageUrl !== ''))
          "
        >
          <img :src="post.imageUrl" alt="Image de publication" />
        </div>

        <div
          class="publications__content"
          v-else-if="
            (post.postContent !== null || post.postContent !== '') &&
            (post.imageUrl !== null || post.imageUrl !== '')
          "
        >
          <p>{{ post.postContent }}</p>
          <img :src="post.imageUrl" alt="Image de publication" />
        </div>

        <div class="publications__date-time">
          <p>Publié le {{ post.post_date }}</p>
        </div>

        <div class="publications__delete" v-if="user.admin === 1">
          <p class="publications__delete-txt" @click="deletePost(post.postId)">
            Supprimer
          </p>
        </div>
        <div
          class="publications__like-comment-count"
          v-if="post.comment_count > 0"
        >
          <div
            class="publications__comment-count"
            @click="goToComments(post.userId, post.postId)"
            v-if="comments.length === 1"
          >
            {{ comments.length }} commentaire
          </div>

          <div
            class="publications__comment-count"
            @click="goToComments(post.userId, post.postId)"
            v-else
          >
            {{ comments.length }} commentaires
          </div>
        </div>

        <div class="publications__like-comment">
          <div class="like-comment__like">
            <FaSolidHeart />
            <span class="icon__legend"> J'aime</span>
          </div>

          <div class="like-comment__comment" @click="comment = true">
            <FaSolidComment />
            <span
              class="icon__legend"
              @click="goToComments(post.userId, post.postId)"
              > Commenter</span
            >
          </div>
        </div>
      </div>
    </section>
  </div>
  <div v-else-if="publications.length === 0">
    <p>Aucune publication pour le moment</p>
  </div>
</template>

<script>
import axios from 'axios';
import { mapState } from 'vuex';

import FaSolidHeart from './Heart.vue';
import FaSolidComment from './CommentIcon.vue';
import AddPostForm from './AddPost.vue';

const userSessionData = JSON.parse(localStorage.getItem('userSession'));
const sessionToken = userSessionData.token;
if (sessionToken) {
  axios.defaults.headers.common['Authorization'] = 'Bearer ' + sessionToken;
}

export default {
  name: 'Wall',
  components: {
    FaSolidHeart,
    FaSolidComment,
    AddPostForm
  },
  data() {
    return {
      comment: false,
      user: []
    };
  },
  beforeMount() {
    this.getResult();
    this.getSession();
  },
  methods: {
    getResult: function () {
      this.$store.dispatch('setPublications');
    },
    goToProfile: function (userId) {
      this.$router.push(`/profile/${userId}`);
    },
    goToComments: function (userId, postId) {
      this.$router.push(`/comments/${userId}/${postId}`);
    },
    getSession: function () {
      if (localStorage.userSession) {
        this.user = JSON.parse(localStorage.userSession);
      }
    },
    deletePost: function (postId) {
      axios
        .delete(`http://localhost:3000/api/publications/${postId}`)
        .then(() => this.$router.go())
        .catch((error) => console.log(error));
    },
    getComments: function (postId) {
      // this.$store.dispatch('getPublicationComments', postId);
      console.log(postId);
    }
  },
  computed: {
    ...mapState(['publications', 'comments'])
  }
};
</script>

<style scoped>
.publications {
  width: 30%;
  margin: 10px auto;
}

.publications__card {
  width: 99%;
  padding: 10px;
  padding-left: 15px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background-color: rgba(138, 185, 241, 0.4);
}

.publications__card .publications__author:hover {
  cursor: pointer;
}

.publications__card .publications__date-time {
  margin-top: -20px;
  font-size: 0.8rem;
  color: grey;
}

.publications__card .publications__delete .publications__delete-txt {
  margin-top: -5px;
  font-size: 0.85rem;
}

.publications__card .publications__like-comment-count {
  width: 92%;
  height: fit-content;
  margin: auto 0;
  padding: 5px;
  border-top: 1px solid white;
}

.publications__card .publications__comment-count {
  margin-right: 15px;
  text-align: right;
}

.publications__card .publications__like-comment {
  width: 95%;
  height: fit-content;
  margin: auto 0;
  padding-top: 10px;
  display: flex;
  justify-content: space-around;
  border-top: 1px solid white;
}

.publications__card .like-comment__like:hover,
.publications__card .like-comment__comment:hover,
.publications__card .publications__comment-count:hover,
.publications__card .publications__delete .publications__delete-txt:hover {
  cursor: pointer;
  color: #4b77be;
}

.publications__card .publications__add-comment {
  width: 95%;
  padding-top: 5px;
  border-top: 1px solid white;
}

.publications__card .publications__add-comment .add-comment__field {
  width: 98%;
  height: 25px;
  margin-top: 5px;
  padding-top: 0px;
  padding: 13px;
  border-radius: 50px;
  resize: none;
  font-family: 'poppins';
  outline: none;
}
</style>
</code>```

My question is how may I call the getComments function from the HTML so that I can display comment count number properly ?

Thank you so much for your help :)

答: You can simply do {{ getComments() }} in your markup.

Body:
For my dev lessons, I need to create a social network for a company.

One of the functionalities is to display the comment number linked to a publication (a bit like on Facebook).

To get the comments, I am using vueX to get all data from one source. So, to display the comment count number, here is my idea : for each publication contained in an array, I get all publication comments in another array. So, if I do a {{comments.length}}, for example, this should display "3 comments"

So I wrote the following code :

 0">
    <AddPostForm />

            {{ post.firstName }} {{ post.lastName }}

{{ post.postContent }}

{{ post.postContent }}

Publié le {{ post.post_date }}

            Supprimer

 0"
        >

            {{ comments.length }} commentaire

            {{ comments.length }} commentaires

            <FaSolidHeart />
             J'aime

            <FaSolidComment />
             Commenter

Aucune publication pour le moment

</template>

My question is how may I call the getComments function from the HTML so that I can display comment count number properly ?

Thank you so much for your help :)


问:
exclude specific text-based values from comma separated value count and give output excluding those
I want to count the ; separated values in a dataframe

solution for that can be something like this

```<code>count=[]
for row in gdf.itertuples():
    newstr = row.info.split(";")
    n = len(newstr)
    count.append(n)

gdf["count"] = count
</code>```

However here is an issue i dont want to count those ; seperated values if they are a specific symbol, in my case its either #, ##, ### or ####
so lets say for image below for id:2 i want the count to be two and for id:6 i want the count to be one and so on

failed attempts so far

i tried stripping them before doing the count, i replaced using
.replace method and # symbols were removed but the separators still
stayed and made it more messier

tried len-1 didnt worked

i tried adding another for loop and if statement which i thought would work

but no

```<code>count=[]
for row in gdf.itertuples():
        newstr = row.info.split(";")
        for i in newstr:
            if (i !='#'):
                n = len(newstr)
        count.append(n)
</code>```

thanks for the help

答:
You can exclude the unwanted ## with a regex, then count the ; and add 1:

```<code>df = pd.DataFrame({'info': ['1;2;3', '##;2;3', '1;##;3', '1;2;##']})

df['count'] = df['info'].str.replace('#+;|;#+', '', regex=True).str.count(';').add(1)
</code>```

output:

```<code>     info  count
0   1;2;3      3
1  ##;2;3      2
2  1;##;3      2
3  1;2;##      2
</code>```

regex:

```<code>#+;   # match one or more literal # followed by ;
|     # OR
;#+   # match one or more literal # preceded by ;
</code>```

Body:
I want to count the ; separated values in a dataframe

solution for that can be something like this

count=[]
for row in gdf.itertuples():
    newstr = row.info.split(";")
    n = len(newstr)
    count.append(n)

gdf["count"] = count

However here is an issue i dont want to count those ; seperated values if they are a specific symbol, in my case its either #, ##, ### or ####
so lets say for image below for id:2 i want the count to be two and for id:6 i want the count to be one and so on

failed attempts so far

i tried stripping them before doing the count, i replaced using
.replace method and # symbols were removed but the separators still
stayed and made it more messier

tried len-1 didnt worked

i tried adding another for loop and if statement which i thought would work

but no

count=[]
for row in gdf.itertuples():
        newstr = row.info.split(";")
        for i in newstr:
            if (i !='#'):
                n = len(newstr)
        count.append(n)

thanks for the help

Body:
You can exclude the unwanted ## with a regex, then count the ; and add 1:

df = pd.DataFrame({'info': ['1;2;3', '##;2;3', '1;##;3', '1;2;##']})

df['count'] = df['info'].str.replace('#+;|;#+', '', regex=True).str.count(';').add(1)

output:

     info  count
0   1;2;3      3
1  ##;2;3      2
2  1;##;3      2
3  1;2;##      2

regex:

#+;   # match one or more literal # followed by ;
|     # OR
;#+   # match one or more literal # preceded by ;


问:
Scrapy CrawlSpider Rule 'Allow' is resulting in a "Documentation not found" error
i'm trying to scrape data off all the fights in UFC stats such as this page UFCStats

However, when using  'allow' and 'callback', pycharm is throwing me a "Documentation not found" error. Screenshot here 2.

```<code>from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

# http://ufcstats.com/statistics/events/completed
# http://ufcstats.com/event-details/335ad945324c3a2e
# http://ufcstats.com/fight-details/e786542667fdecf0

class UFCSpider(CrawlSpider):
        name = 'UFC'
        allowed_domains = ['ufcstats.com']
        start_urls = [
            'http://ufcstats.com/'
        ]
        rules = [
            Rule(LinkExtractor(allow='fight-details'), callback= 'parse_item')
        ]
</code>```

Could anyone help me solve this issue?

答:
Define the rules as below. callback is an argument of Rule class, not LinkExtractor.

```<code> rules = [
        Rule(LinkExtractor(allow=('fight-details', )), callback='parse_item'),
    ]
</code>```

Body:
i'm trying to scrape data off all the fights in UFC stats such as this page UFCStats

However, when using  'allow' and 'callback', pycharm is throwing me a "Documentation not found" error. Screenshot here 2.

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

# http://ufcstats.com/statistics/events/completed
# http://ufcstats.com/event-details/335ad945324c3a2e
# http://ufcstats.com/fight-details/e786542667fdecf0

class UFCSpider(CrawlSpider):
        name = 'UFC'
        allowed_domains = ['ufcstats.com']
        start_urls = [
            'http://ufcstats.com/'
        ]
        rules = [
            Rule(LinkExtractor(allow='fight-details'), callback= 'parse_item')
        ]

Could anyone help me solve this issue?

Body:
Define the rules as below. callback is an argument of Rule class, not LinkExtractor.

 rules = [
        Rule(LinkExtractor(allow=('fight-details', )), callback='parse_item'),
    ]


问:
mPDF 5.7.1 - image displays as a broken [x]
I have a small issue with mPDF (version 5.7.1).

This code should generate PDF with image file:

```<code> $mpdf = new mPDF();
 $html = '<img src="https://www.google.pl/images/srpr/logo11w.png"/>';
 $mpdf->WriteHTML($html);
 $mpdf->debug = true;
 $output = $mpdf->Output();
 exit();
</code>```

Well there is no image but an [x] instead.

I've googled enough to get to the conclusion that it has to be done this way but I also tried realpath to the file. Still nothing.

The only thing I haven't tried is  and copying the image into the folder because I don't know into which folder I should copy file logo11w.png.

Any suggestions?

答:
.htaccess with password also can blocks access

An exception can be added:

```<code>AuthType Basic
AuthUserFile "/home/domain.pl/public_html/.htpasswd"
require valid-user
AuthName "set password"
Order allow,deny
# payu
Allow from 185.68.14.10
Allow from 185.68.14.11
Allow from 185.68.14.12
Allow from 185.68.14.26
Allow from 185.68.14.27
Allow from 185.68.14.28
# serwer localhost
Allow from 185.185.185.185
satisfy any
</code>```

Body:
I have a small issue with mPDF (version 5.7.1).

This code should generate PDF with image file:

 $mpdf = new mPDF();
 $html = '';
 $mpdf->WriteHTML($html);
 $mpdf->debug = true;
 $output = $mpdf->Output();
 exit();

Well there is no image but an [x] instead.

I've googled enough to get to the conclusion that it has to be done this way but I also tried realpath to the file. Still nothing.

The only thing I haven't tried is  and copying the image into the folder because I don't know into which folder I should copy file logo11w.png.

Any suggestions?

Body:
.htaccess with password also can blocks access

An exception can be added:

AuthType Basic
AuthUserFile "/home/domain.pl/public_html/.htpasswd"
require valid-user
AuthName "set password"
Order allow,deny
# payu
Allow from 185.68.14.10
Allow from 185.68.14.11
Allow from 185.68.14.12
Allow from 185.68.14.26
Allow from 185.68.14.27
Allow from 185.68.14.28
# serwer localhost
Allow from 185.185.185.185
satisfy any


问:
Using BIM 360 Field API to download a checklist as a PDF file
I need to download a checklist as a PDF file by using the APIs of BIM 360 Field. Is this possible? I'm trying to use the command POST /api/binary_data without any success. Do I need, instead, to create the PDF myself after using the GET /fieldapi/checklists/v1/:id ?</p>

答:
AFAIK, you need to make the GET request to /fieldapi/checklists/v1/:id, then create the pdf yourself.

Also note that to retrieve custom fields from a checklist, you need to change at least one of the fields from the default values.

Or if you have the time you can play with Microsoft Power Automate, to download the report on a schedule.


问:
my python code comes up with errors if I define the variable people and if i don't define the variable people
```<code>import random
people=0
def intake (testage):
    if testage <= 18:
        print("Person accepted!")
        people=people+1
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")
</code>```

on line 2 the variable people comes up with errors if I define it or if I don't define it

答:
You're assigning to the variable people from inside the function intake. This makes the function intake's version of people different from the one that's defined outside the function.

To use the same people inside intake, you need to declare people as global.

```<code>import random
people=0
def intake (testage):
    global people # declare people as global
    if testage <= 18:
        print("Person accepted!")
        people=people+1 # now, people is the same one as above
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")
</code>```

Body:
import random
people=0
def intake (testage):
    if testage <= 18:
        print("Person accepted!")
        people=people+1
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")

on line 2 the variable people comes up with errors if I define it or if I don't define it

Body:
You're assigning to the variable people from inside the function intake. This makes the function intake's version of people different from the one that's defined outside the function.

To use the same people inside intake, you need to declare people as global.

import random
people=0
def intake (testage):
    global people # declare people as global
    if testage <= 18:
        print("Person accepted!")
        people=people+1 # now, people is the same one as above
    else:
        print("Person Denied!")
while people <= 150:
    age=random.randint(0,81)
    intake(age)
print("At capacity!")


问:
Create an array of object properties for each item that has the same key
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

```<code>[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]
</code>```

becomes

```<code>[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]
</code>```

any ideas?

答:
You can use reduce like this:

const data = [
  { category: 'furniture' },
  { category: 'mirrors' },
  { availability: 'in_stock' }
];

const result = data.reduce(
  (a, x) => {
    const key = Object.keys(x)[0]; // find the key of the current object
    if (!a.tmp[key]) { // if the current key doesn't exist in the lookup object (tmp) yet ...
      a.tmp[key] = []; // create an empty array in the lookup object for the current key
      a.result.push({ [key]: a.tmp[key] }); // push the current object to the result
    }
    a.tmp[key].push(x[key]); // push the current value to the array
    return a;
  },
  { result: [], tmp: {} },
).result;

console.log(result);```

I'm sure there are easier ways to achieve this, but that's the best I can come up with right now.

Body:
I'm merging two objects together to create a filter object. However I want to group the merged objects property values where the keys are the same.

So...

[{category: 'furniture'}, {category: 'mirrors'}, {availability: 'in_stock'}]

becomes

[{category: ['furniture', 'mirrors']}, {availability: 'in_stock'}]

any ideas?

Body:
You can use reduce like this:

const data = [
  { category: 'furniture' },
  { category: 'mirrors' },
  { availability: 'in_stock' }
];

const result = data.reduce(
  (a, x) => {
    const key = Object.keys(x)[0]; // find the key of the current object
    if (!a.tmp[key]) { // if the current key doesn't exist in the lookup object (tmp) yet ...
      a.tmp[key] = []; // create an empty array in the lookup object for the current key
      a.result.push({ [key]: a.tmp[key] }); // push the current object to the result
    }
    a.tmp[key].push(x[key]); // push the current value to the array
    return a;
  },
  { result: [], tmp: {} },
).result;

console.log(result);

I'm sure there are easier ways to achieve this, but that's the best I can come up with right now.


问:
visualize dependence on global variables using vim, ctags potentially
I'd like to highlight variables in my (Maple-code, but doesn't matter much) code which are global for routines.

e.g. I have

```<code>global_var1:=1;
global_var2:=2;

...

some_proc:=proc()
  local local_var1, global_var2;
  local_var1:=1;
  local_var2:=local_var1*global_var1+global_var2;
end proc;
</code>```

I want to highlight global_var1 inside of some_proc() in this example. Obviously the naming is not so trivial in general as in the example.

Can I use ctags to do this?

答:
It depends on ctags. With some languages it is unable to extract local variables (viml), with other languages, it doesn't detect all local variables (C++). Hence, the first thing you'll have to do is to see what ctags can do for your language (Maple).

The other difficulty is to restrict the highlighting to one specific function, and to stay synchronized every time newlines are inserted to the edited file. I know no easy way to do this -- may be with a vim syntax region that starts at local.*{global-name} and ends at end proc to neutralize the highlighting of all global variables?

One task that'll be much more easier would be to highlight variable masking, i.e. highlight global_var2 at the point in the function where it is declared local. Alas, it's not what you're looking for.

Body:
I'd like to highlight variables in my (Maple-code, but doesn't matter much) code which are global for routines.

e.g. I have

global_var1:=1;
global_var2:=2;

...

some_proc:=proc()
  local local_var1, global_var2;
  local_var1:=1;
  local_var2:=local_var1*global_var1+global_var2;
end proc;

I want to highlight global_var1 inside of some_proc() in this example. Obviously the naming is not so trivial in general as in the example.

Can I use ctags to do this?


问:
I'm using a Django REST backend with React Frontend on an AWS EC2 instance, but mobile browser get requests are not working
As stated in my description, I'm running a Django REST backend with React Frontend on an AWS EC2 instance, making use of Docker images, and Nginx.

When using the app on a desktop browser, everything works perfectly, but as soon as I start using a mobile browser(Tried Chrome, Safari and Firefox on multiple devices) most if my GET requests don't work:

Any ideas on how to solve this?

答: Turns out I had some trailing / missing in my GET request's URLs. With Django sometimes it works, and sometimes it doesn't if you forget a / at the end of your URL.


问:
VueJS - SSR - Wait for async data in created() hook before render
I have a VueJS microfrontend that is SSR thanks to a Ara Framework cluster.
In order to make it fully autonomous I would like it to fetch data in the created() hook before the render occurs so that I have a fully complete DOM rendered in SSR.

Logging showed the problem is created() does not wait for my axios data call to end wheter I use async/await, then() or a classic Promise. Then it either fails on DOM or renders a empty dom if I add a v-if="data"

The idea would be to have a functionnal asyncData() like in Nuxt without to have using the whole framework as I have Ara Framework already applying SSR to my Vue app.

```<code> created() {
return new Promise(resolve => {
  console.log('created')
  const { interfaceIn, InterfaceEnum } = this.interfaceService
  console.log('1')

  if (this.hydratation) {
    this.article = interfaceIn(InterfaceEnum.ARTICLE, this.hydratation)
  } else {
    console.log('1,5')
    this.utils.api
      .mainGet(
        axios,
        this.$utils.api.getHostByContext('ctx1', 'ctx2'),
        `/news/${this.slug}`,
        'Article'
      )
      .then(data => {
        console.log('2')

        this.article = interfaceIn(InterfaceEnum.ARTICLE, data.article)
        console.log('3')
        resolve()
      })
    console.log('4')

    // this.article = interfaceIn(InterfaceEnum.ARTICLE, article)
    console.log(this.article.id)
  }
})
// this.loading = false
// this.loading = true
</code>```

}

console output on SSR http call

HTTP call used with ara Framework

Minimal repro is quite complex to provide as it requires the microfrontend + working ara framework cluster for SSR

Thanks

答: Answer was to use the serverPrefetch() lifeCycle hook designed for this.</p>

Body:
I have a VueJS microfrontend that is SSR thanks to a Ara Framework cluster.
In order to make it fully autonomous I would like it to fetch data in the created() hook before the render occurs so that I have a fully complete DOM rendered in SSR.

Logging showed the problem is created() does not wait for my axios data call to end wheter I use async/await, then() or a classic Promise. Then it either fails on DOM or renders a empty dom if I add a v-if="data"

The idea would be to have a functionnal asyncData() like in Nuxt without to have using the whole framework as I have Ara Framework already applying SSR to my Vue app.

 created() {
return new Promise(resolve => {
  console.log('created')
  const { interfaceIn, InterfaceEnum } = this.interfaceService
  console.log('1')

  if (this.hydratation) {
    this.article = interfaceIn(InterfaceEnum.ARTICLE, this.hydratation)
  } else {
    console.log('1,5')
    this.utils.api
      .mainGet(
        axios,
        this.$utils.api.getHostByContext('ctx1', 'ctx2'),
        `/news/${this.slug}`,
        'Article'
      )
      .then(data => {
        console.log('2')

        this.article = interfaceIn(InterfaceEnum.ARTICLE, data.article)
        console.log('3')
        resolve()
      })
    console.log('4')

    // this.article = interfaceIn(InterfaceEnum.ARTICLE, article)
    console.log(this.article.id)
  }
})
// this.loading = false
// this.loading = true

}

console output on SSR http call

HTTP call used with ara Framework

Minimal repro is quite complex to provide as it requires the microfrontend + working ara framework cluster for SSR

Thanks


问:
Not able to execute sample code provided in Hugging faces Models card
When i am trying sample code from Hugging face i get below error.
the code can be found from https://huggingface.co/facebook/tts_transformer-en-ljspeech

Code:

```<code>from fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hub
from fairseq.models.text_to_speech.hub_interface import TTSHubInterface
import IPython.display as ipd

models, cfg, task = load_model_ensemble_and_task_from_hf_hub(
    "facebook/fastspeech2-en-ljspeech",
    arg_overrides={"vocoder": "hifigan", "fp16": False}
)
model = models[0]
TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
generator = task.build_generator(model, cfg)

text = "Hello, this is a test run."

sample = TTSHubInterface.get_model_input(task, text)
wav, rate = TTSHubInterface.get_prediction(task, model, generator, sample)

ipd.Audio(wav, rate=rate)
</code>```

Error:

```<code>TypeError                                 Traceback (most recent call last)
Input In [1], in <module>
     10 model = models[0]
     11 TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
---> 12 generator = task.build_generator(model, cfg)
     14 text = "Hello, this is a test run."
     16 sample = TTSHubInterface.get_model_input(task, text)

File ~/office/virtual_environments/eye_for_bliend/Images/fairseq/fairseq/tasks/text_to_speech.py:151, in TextToSpeechTask.build_generator(self, models, cfg, vocoder, **unused)
    149 if vocoder is None:
    150     vocoder = self.build_default_vocoder()
--> 151 model = models[0]
    152 if getattr(model, "NON_AUTOREGRESSIVE", False):
    153     return NonAutoregressiveSpeechGenerator(model, vocoder, self.data_cfg)

TypeError: 'TTSTransformerModel' object is not subscriptable
</code>```

答:
What worked for me was to put the model in a list where you build the generator on line 12.</p>
```<code>generator = task.build_generator([model], cfg)
</code>```

Body:
When i am trying sample code from Hugging face i get below error.
the code can be found from https://huggingface.co/facebook/tts_transformer-en-ljspeech

Code:

from fairseq.checkpoint_utils import load_model_ensemble_and_task_from_hf_hub
from fairseq.models.text_to_speech.hub_interface import TTSHubInterface
import IPython.display as ipd

models, cfg, task = load_model_ensemble_and_task_from_hf_hub(
    "facebook/fastspeech2-en-ljspeech",
    arg_overrides={"vocoder": "hifigan", "fp16": False}
)
model = models[0]
TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
generator = task.build_generator(model, cfg)

text = "Hello, this is a test run."

sample = TTSHubInterface.get_model_input(task, text)
wav, rate = TTSHubInterface.get_prediction(task, model, generator, sample)

ipd.Audio(wav, rate=rate)

Error:

TypeError                                 Traceback (most recent call last)
Input In [1], in <module>
     10 model = models[0]
     11 TTSHubInterface.update_cfg_with_data_cfg(cfg, task.data_cfg)
---> 12 generator = task.build_generator(model, cfg)
     14 text = "Hello, this is a test run."
     16 sample = TTSHubInterface.get_model_input(task, text)

File ~/office/virtual_environments/eye_for_bliend/Images/fairseq/fairseq/tasks/text_to_speech.py:151, in TextToSpeechTask.build_generator(self, models, cfg, vocoder, **unused)
    149 if vocoder is None:
    150     vocoder = self.build_default_vocoder()
--> 151 model = models[0]
    152 if getattr(model, "NON_AUTOREGRESSIVE", False):
    153     return NonAutoregressiveSpeechGenerator(model, vocoder, self.data_cfg)

TypeError: 'TTSTransformerModel' object is not subscriptable

Body:
What worked for me was to put the model in a list where you build the generator on line 12.

generator = task.build_generator([model], cfg)


问:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource

Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

```<code>$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some <a   href=\"/social/suggestions\">suggestions</a>";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages
</code>```

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

答:
mysql_query($sqlx) return false instead of result. It means any error occured. Try to check is $sqlx correct query and check mysql_error() to get what error is occured. To check was here any error or not you can use

```<code>if(!$resultx){
     print 'error:'.mysql_error();
}
else{
    //use result
}
</code>```

Body:
Possible Duplicate:

  Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result

I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.

The code basically prints messages from a db
Here is the code:

$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some suggestions";
}
$row=mysql_fetch_array($results);

$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages

$username is got further up the file.

Here is the error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34

Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.

One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)

Any idea??

Have I done the mysql_fetch_array wrong when getting $row??
thanks

Body:
mysql_query($sqlx) return false instead of result. It means any error occured. Try to check is $sqlx correct query and check mysql_error() to get what error is occured. To check was here any error or not you can use

if(!$resultx){
     print 'error:'.mysql_error();
}
else{
    //use result
}