问:
NetSuite Custom Record Search Convert Results into List of .NET Objects
The only way I've been able to do it is through the reflection-based code below.  I can't believe there's not an "easier NetSuite way" to do this though?  Am I missing something basic?

After I perform a search on custom objects I get back an array of Record[], this can then be looped through and each item casted to a CustomObject.

The properties of the custom object are stored in the CustomRecord's customFieldList but the values are not immediately accessible you have to cast those the their real NetSuite type (like LongCustomFieldRef, DoubleCustomFieldRef, BooleanCustomFieldRef, StringCustomFieldRef, etc).

In order to not have to bother with this mess to get nice clean objects on my side I decided on the approach below:

Create classes with property names that match (including case) the NetSuite names and inherits from NetSuiteBase (defined below)

```<code>public class MyNetSuiteObject : NetSuiteBase //<-- Note base class
{
    public string myProperty1 { get; set; }
    public bool myProperty2 { get; set; }
    public int myProperty3 { get; set; }

    public static MyNetSuiteObject FromCustomSearchRecord(CustomRecord customRecord)
    {
        var ret = new MyNetSuiteObject();
        ret.AssignProperties(customRecord);
        return ret;
    }
}
</code>```

Create a base class which will inspect CustomRecords and apply property values to the .NET classes

```<code>public class NetSuiteBase
{

    public void AssignProperties(CustomRecord customRecord)
    {
        var classProps = this.GetType().GetProperties();
        foreach (var prop in classProps)
        {
            var propName = prop.Name;
            var propValue = prop.GetValue(this, null);

            //get the matching CustomFieldRef out of the customFieldList for the CustomRecord which matches our current property name
            var myCustomFieldRef = customRecord.customFieldList.Where(c => c.scriptId == propName).FirstOrDefault();

            if (myCustomFieldRef == null) continue;

            //we can't get the value out until we cast the CustomFieldRef to its "actual" type.
            var custType = myCustomFieldRef.GetType().Name;
            switch (custType)
            {
                case "LongCustomFieldRef":
                    TrySetProperty(prop, ((LongCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "DoubleCustomFieldRef":
                    TrySetProperty(prop, ((DoubleCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "BooleanCustomFieldRef":
                    TrySetProperty(prop, ((BooleanCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "StringCustomFieldRef":
                    TrySetProperty(prop, ((StringCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "DateCustomFieldRef":
                    TrySetProperty(prop, ((DateCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "SelectCustomFieldRef":
                    TrySetProperty(prop, ((SelectCustomFieldRef)myCustomFieldRef).value.name.ToString());
                    break;

                case "MultiSelectCustomFieldRef":
                    TrySetProperty(prop, ((MultiSelectCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;
                default:
                    Console.WriteLine("Unknown type: " + myCustomFieldRef.internalId);
                    break;
            }
        }
    }

    //Some of the NetSuite properties are represented as strings (I'm looking at you BOOLs), so we pass all the values from above
    //as strings and them process/attempt casts
    private void TrySetProperty(PropertyInfo prop, string value)
    {
        value = value.ToLower().Trim();

        if (prop.PropertyType == typeof(string))
        {
            prop.SetValue(this, value);
            return;
        }

        if (prop.PropertyType == typeof(bool))
        {
            if (value == "yes") value = "true";
            if (value == "no") value = "false";
            if (value == "1") value = "true";
            if (value == "0") value = "false";

            bool test;
            if (bool.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(int))
        {
            int test;
            if (int.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(double))
        {
            double test;
            if (double.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(decimal))
        {
            decimal test;
            if (decimal.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

    }
}
</code>```

After performing a NetSuite search on custom objects, loop through the results and use the above classes to convert NetSuite result to a .NET class

```<code>for (int i = 0, j = 0; i < records.Length; i++, j++)
{
    customRecord = (CustomRecord)records[i];

    var myNetSuiteObject = MyNetSuiteObject.FromCustomSearchRecord(customRecord);
}
</code>```

Is there some other "NetSuite way" to accomplish what I have above?

答:
No, there is no "NetSuite" way. What you've done is far above and beyond the call of duty, if you ask me, and it's amazing. The NetSuite/SuiteTalk WSDL is just HORRENDOUS, and so many bad choices were made in the design process that I'm shocked that it was released as-is to developers without any questions raised. Below is one other example.

This is from the documentation for their SuiteTalk course, which reveals that when parsing the results of an Advanced search, they contain within them SearchRowBasic objects. Well within each SearchRowBasic object there are multiple fields. To access those fields' values, you have to take the first element of a SearchColumnField array. Why would you DO this? If there will only ever be ONE value (and they state in their documentation that yes indeed there will only ever be ONE value), WHY the heck would you make the return object an array instead of just passing back to the developer the value of the primitive type itself directly??? That's just plain bad API construction right there, forcing the developers to use SearchColumnField[0].searchValue every time rather than just SearchColumnField.searchValue!

Body:
The only way I've been able to do it is through the reflection-based code below.  I can't believe there's not an "easier NetSuite way" to do this though?  Am I missing something basic?

After I perform a search on custom objects I get back an array of Record[], this can then be looped through and each item casted to a CustomObject.

The properties of the custom object are stored in the CustomRecord's customFieldList but the values are not immediately accessible you have to cast those the their real NetSuite type (like LongCustomFieldRef, DoubleCustomFieldRef, BooleanCustomFieldRef, StringCustomFieldRef, etc).

In order to not have to bother with this mess to get nice clean objects on my side I decided on the approach below:

Create classes with property names that match (including case) the NetSuite names and inherits from NetSuiteBase (defined below)

public class MyNetSuiteObject : NetSuiteBase //<-- Note base class
{
    public string myProperty1 { get; set; }
    public bool myProperty2 { get; set; }
    public int myProperty3 { get; set; }

    public static MyNetSuiteObject FromCustomSearchRecord(CustomRecord customRecord)
    {
        var ret = new MyNetSuiteObject();
        ret.AssignProperties(customRecord);
        return ret;
    }
}

Create a base class which will inspect CustomRecords and apply property values to the .NET classes

public class NetSuiteBase
{

    public void AssignProperties(CustomRecord customRecord)
    {
        var classProps = this.GetType().GetProperties();
        foreach (var prop in classProps)
        {
            var propName = prop.Name;
            var propValue = prop.GetValue(this, null);

            //get the matching CustomFieldRef out of the customFieldList for the CustomRecord which matches our current property name
            var myCustomFieldRef = customRecord.customFieldList.Where(c => c.scriptId == propName).FirstOrDefault();

            if (myCustomFieldRef == null) continue;

            //we can't get the value out until we cast the CustomFieldRef to its "actual" type.
            var custType = myCustomFieldRef.GetType().Name;
            switch (custType)
            {
                case "LongCustomFieldRef":
                    TrySetProperty(prop, ((LongCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "DoubleCustomFieldRef":
                    TrySetProperty(prop, ((DoubleCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "BooleanCustomFieldRef":
                    TrySetProperty(prop, ((BooleanCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "StringCustomFieldRef":
                    TrySetProperty(prop, ((StringCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "DateCustomFieldRef":
                    TrySetProperty(prop, ((DateCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;

                case "SelectCustomFieldRef":
                    TrySetProperty(prop, ((SelectCustomFieldRef)myCustomFieldRef).value.name.ToString());
                    break;

                case "MultiSelectCustomFieldRef":
                    TrySetProperty(prop, ((MultiSelectCustomFieldRef)myCustomFieldRef).value.ToString());
                    break;
                default:
                    Console.WriteLine("Unknown type: " + myCustomFieldRef.internalId);
                    break;
            }
        }
    }

    //Some of the NetSuite properties are represented as strings (I'm looking at you BOOLs), so we pass all the values from above
    //as strings and them process/attempt casts
    private void TrySetProperty(PropertyInfo prop, string value)
    {
        value = value.ToLower().Trim();

        if (prop.PropertyType == typeof(string))
        {
            prop.SetValue(this, value);
            return;
        }

        if (prop.PropertyType == typeof(bool))
        {
            if (value == "yes") value = "true";
            if (value == "no") value = "false";
            if (value == "1") value = "true";
            if (value == "0") value = "false";

            bool test;
            if (bool.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(int))
        {
            int test;
            if (int.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(double))
        {
            double test;
            if (double.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

        if (prop.PropertyType == typeof(decimal))
        {
            decimal test;
            if (decimal.TryParse(value, out test))
            {
                prop.SetValue(this, test);
                return;
            }
        }

    }
}

After performing a NetSuite search on custom objects, loop through the results and use the above classes to convert NetSuite result to a .NET class

for (int i = 0, j = 0; i < records.Length; i++, j++)
{
    customRecord = (CustomRecord)records[i];

    var myNetSuiteObject = MyNetSuiteObject.FromCustomSearchRecord(customRecord);
}

Is there some other "NetSuite way" to accomplish what I have above?


来源: stackexchange

问:
How to programmatically add a css rule to an element
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit() before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.

Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.

Here's the two rules I have that I want to add to my host element depending on some condition:

```<code>custom-component + custom-component > .vertical-component {
    margin-top: 1rem;
}
</code>```

and

```<code>custom-component + custom-component > .horizontal-component {
    margin-left: 1rem;
}
</code>```

In my component code, I have something like this:

```<code>export class CustomComponent {
    public constructor(private host: ElementRef, private renderer: Renderer2) {

    }

    public applyStylesToHost(): void {
        if (this.variant == TYPE.VERTICAL) {
            // Set the rule with the margin-top
        } else {
            // Set the rule with the margin-left
        }
    }
}
</code>```

I was looking for a method like this.renderer.setRule(), but there is no such thing. How can I programmatically add a specific rule to my host element?

The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule(), but when I tried to do it, the method addRule didn't exist on the sheet element.

答:
If you want to go this way, you should use probably method:

```<code>renderer.setStyle(...)
</code>```

or

```<code>renderer.addClass(...)
renderer.removeClass(...)
</code>```

I suggest to read documentation for Renderer2

ContentLicense: CC BY-SA 4.0

Body:
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit() before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.

Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.

Here's the two rules I have that I want to add to my host element depending on some condition:

custom-component + custom-component > .vertical-component {
    margin-top: 1rem;
}

and

custom-component + custom-component > .horizontal-component {
    margin-left: 1rem;
}

In my component code, I have something like this:

export class CustomComponent {
    public constructor(private host: ElementRef, private renderer: Renderer2) {

    }

    public applyStylesToHost(): void {
        if (this.variant == TYPE.VERTICAL) {
            // Set the rule with the margin-top
        } else {
            // Set the rule with the margin-left
        }
    }
}

I was looking for a method like this.renderer.setRule(), but there is no such thing. How can I programmatically add a specific rule to my host element?

The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule(), but when I tried to do it, the method addRule didn't exist on the sheet element.

Body:
If you want to go this way, you should use probably method:

renderer.setStyle(...)

or

renderer.addClass(...)
renderer.removeClass(...)

I suggest to read documentation for Renderer2


问:
how to get transaction id and name in bluesnap payment gateway
I am using bluesnap payment gateway in PHP. And it is working properly. But in return I am not getting transaction id and customer name is not showing in sandbox account also.

Below is my transaction page at which blusnap code will be run and return desired output.

```<code>require_once('New_folder/vendor/autoload.php');

$environment = 'sandbox'; // or 'production'
$keys = \tdanielcox\Bluesnap\Bluesnap::init($environment, 'API_111111111111111111111', 'password11');

$response = \tdanielcox\Bluesnap\CardTransaction::create([
    'creditCard' => [
        'firstName' => 'Jane',
        'lastName' => 'Shopper',
        'cardNumber' => '3566000020000410',
        'expirationMonth' => '02',
        'expirationYear' => '2023',
        'securityCode' => '123'
    ],
    'amount' => 10.00,
    'currency' => 'USD',
    'recurringTransaction' => 'ECOMMERCE',
    'cardTransactionType' => 'AUTH_CAPTURE',
]);

if ($response->failed())
{
    $error = $response->data;
    $transaction = $response->data;
echo"```";
print_r($transaction);
echo"```";

    // handle error
}

$transaction = $response->data;
echo"```";
print_r($transaction);
echo"```";
//$transaction;
</code>```

My success response is: In this return transaction id is not showing. And also not getting customer name in bluesnap sandbox panel.

```<code>tdanielcox\Bluesnap\Models\CardTransaction Object
(
[children:protected] => Array
    (
        [transactionMetaData] => item
        [creditCard] => item
        [vendorInfo] => item
    )

[cardTransactionType] => AUTH_CAPTURE
[amount] => 10
[recurringTransaction] => ECOMMERCE
[merchantTransactionId] =>
[softDescriptor] => BLS*onboardingDefault
[vaultedShopperId] => 27595185
[currency] => USD
[transactionMetaData] =>
[creditCard] => tdanielcox\Bluesnap\Models\CreditCard Object
    (
        [cardNumber] =>
        [encryptedCardNumber] =>
        [cardLastFourDigits] => 0410
        [cardType] => JCB
        [expirationMonth] =>
        [expirationYear] =>
        [securityCode] =>
        [encryptedSecurityCode] =>
        [children:protected] => Array
            (
            )

        [cardSubType] => CREDIT
        [cardCategory] => STANDARD
        [binCategory] => CONSUMER
        [cardRegulated] => N
        [issuingCountryCode] => us
    )

[transactionFraudInfo] =>
[id] => 1031167745
[usdAmount] => 10
[transactionApprovalDate] => 05/29/2020
[transactionApprovalTime] => 00:07:12
[cardHolderInfo] => Array
    (
    )

[processingInfo] => Array
    (
        [processingStatus] => success
        [cvvResponseCode] => ND
        [authorizationCode] => 654321
        [avsResponseCodeZip] => U
        [avsResponseCodeAddress] => U
        [avsResponseCodeName] => U
    )

[fraudResultInfo] => Array
    (
    )

)
</code>```

答:
The shopper name is in an incorrect position in your request. Try this instead:

```<code>create([
'cardHolderInfo' => [
        'firstName' => 'Jane',
        'lastName' => 'Shopper'
    ],
    'creditCard' => [
        'cardNumber' => '3566000020000410',
        'expirationMonth' => '02',
        'expirationYear' => '2023',
        'securityCode' => '123'
    ],
    'amount' => 10.00,
    'currency' => 'USD',
    'recurringTransaction' => 'ECOMMERCE',
    'cardTransactionType' => 'AUTH_CAPTURE',
]);
</code>```

Source: https://developers.bluesnap.com/v8976-JSON/docs/auth-capture

transactionId is always returned in the response, make sure there's nothing wrong with the php code or model that is displaying it..

Body:
I am using bluesnap payment gateway in PHP. And it is working properly. But in return I am not getting transaction id and customer name is not showing in sandbox account also.

Below is my transaction page at which blusnap code will be run and return desired output.

require_once('New_folder/vendor/autoload.php');

$environment = 'sandbox'; // or 'production'
$keys = \tdanielcox\Bluesnap\Bluesnap::init($environment, 'API_111111111111111111111', 'password11');

$response = \tdanielcox\Bluesnap\CardTransaction::create([
    'creditCard' => [
        'firstName' => 'Jane',
        'lastName' => 'Shopper',
        'cardNumber' => '3566000020000410',
        'expirationMonth' => '02',
        'expirationYear' => '2023',
        'securityCode' => '123'
    ],
    'amount' => 10.00,
    'currency' => 'USD',
    'recurringTransaction' => 'ECOMMERCE',
    'cardTransactionType' => 'AUTH_CAPTURE',
]);

if ($response->failed())
{
    $error = $response->data;
    $transaction = $response->data;
echo"
";
print_r($transaction);
echo"
";

    // handle error
}

$transaction = $response->data;
echo"
";
print_r($transaction);
echo"
";
//$transaction;

My success response is: In this return transaction id is not showing. And also not getting customer name in bluesnap sandbox panel.

tdanielcox\Bluesnap\Models\CardTransaction Object
(
[children:protected] => Array
    (
        [transactionMetaData] => item
        [creditCard] => item
        [vendorInfo] => item
    )

[cardTransactionType] => AUTH_CAPTURE
[amount] => 10
[recurringTransaction] => ECOMMERCE
[merchantTransactionId] =>
[softDescriptor] => BLS*onboardingDefault
[vaultedShopperId] => 27595185
[currency] => USD
[transactionMetaData] =>
[creditCard] => tdanielcox\Bluesnap\Models\CreditCard Object
    (
        [cardNumber] =>
        [encryptedCardNumber] =>
        [cardLastFourDigits] => 0410
        [cardType] => JCB
        [expirationMonth] =>
        [expirationYear] =>
        [securityCode] =>
        [encryptedSecurityCode] =>
        [children:protected] => Array
            (
            )

        [cardSubType] => CREDIT
        [cardCategory] => STANDARD
        [binCategory] => CONSUMER
        [cardRegulated] => N
        [issuingCountryCode] => us
    )

[transactionFraudInfo] =>
[id] => 1031167745
[usdAmount] => 10
[transactionApprovalDate] => 05/29/2020
[transactionApprovalTime] => 00:07:12
[cardHolderInfo] => Array
    (
    )

[processingInfo] => Array
    (
        [processingStatus] => success
        [cvvResponseCode] => ND
        [authorizationCode] => 654321
        [avsResponseCodeZip] => U
        [avsResponseCodeAddress] => U
        [avsResponseCodeName] => U
    )

[fraudResultInfo] => Array
    (
    )

)

Body:
The shopper name is in an incorrect position in your request. Try this instead:

create([
'cardHolderInfo' => [
        'firstName' => 'Jane',
        'lastName' => 'Shopper'
    ],
    'creditCard' => [
        'cardNumber' => '3566000020000410',
        'expirationMonth' => '02',
        'expirationYear' => '2023',
        'securityCode' => '123'
    ],
    'amount' => 10.00,
    'currency' => 'USD',
    'recurringTransaction' => 'ECOMMERCE',
    'cardTransactionType' => 'AUTH_CAPTURE',
]);

Source: https://developers.bluesnap.com/v8976-JSON/docs/auth-capture

transactionId is always returned in the response, make sure there's nothing wrong with the php code or model that is displaying it..


问:
curl_init causes error on specific web pages
If a server has the function "curl_init" disabled, would that cause an error number 7 and the error message: "couldn't connect to host" or is there another reason why I am getting this error?

And if it is a security issue is there a way around this since I do not have control over the security of these websites?

```<code>    <?php

$url = $_POST["url"];
$url = $url.'/';
echo "<br> <b>URL: </b>".$url;

function get_web_page($url)
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        //CURLOPT_PROXY         => "localhost:80",
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;

$html= get_web_page($url);

echo '<br> <b>Error Number: </b>'.$html['errno'];
echo '<br> <b>Error Message: </b>'.$html['errmsg'];

?>
</code>```

I hope this is enough code to work off of.

This is the site im working on. At the bottom you should be able to enter any URL.  If you put www.csun.edu it gets that error. But if you put library.csun.edu it does not.

http://www.csun.edu/~ppm90976/profilepoojamanjrekar.html

答:
Could you please give your code? I will try to answer your question, but based on your question, I'm not sure if I can.

curl_init() is a native function since PHP4. Unless I'm mistaken, it can't be disabled. On top of that, if it were to be disabled, it wouldn't present a 'couldn't connect to host' (errno:7) error.

So what I think you meant to ask is what would happen 'if the remote server doesn't have it enabled'. This question is actually moot, since what curl does is basically 'fetch' a page, when visiting another site/ page under specific conditions. As long as a web page is viewable under the conditions you set (using the curl_setopt() function), it will work.

Now, what I recall is that the error number 7 could happen if the page you requested has a redirect and your curl options specify that it should not follow redirections. To check if this is the cause of your issue, set this option before you execute the url:

```<code>curl_setopt('CURLOPT_FOLLOWLOCATION', true);
</code>```

Let me know if that helped.

ContentLicense: CC BY-SA 3.0

Body:
If a server has the function "curl_init" disabled, would that cause an error number 7 and the error message: "couldn't connect to host" or is there another reason why I am getting this error?

And if it is a security issue is there a way around this since I do not have control over the security of these websites?

    <?php

$url = $_POST["url"];
$url = $url.'/';
echo "
 URL: ".$url;

function get_web_page($url)
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        //CURLOPT_PROXY         => "localhost:80",
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;

$html= get_web_page($url);

echo '
 Error Number: '.$html['errno'];
echo '
 Error Message: '.$html['errmsg'];

?>

I hope this is enough code to work off of.

This is the site im working on. At the bottom you should be able to enter any URL.  If you put www.csun.edu it gets that error. But if you put library.csun.edu it does not.

http://www.csun.edu/~ppm90976/profilepoojamanjrekar.html

Body:
Could you please give your code? I will try to answer your question, but based on your question, I'm not sure if I can.

curl_init() is a native function since PHP4. Unless I'm mistaken, it can't be disabled. On top of that, if it were to be disabled, it wouldn't present a 'couldn't connect to host' (errno:7) error.

So what I think you meant to ask is what would happen 'if the remote server doesn't have it enabled'. This question is actually moot, since what curl does is basically 'fetch' a page, when visiting another site/ page under specific conditions. As long as a web page is viewable under the conditions you set (using the curl_setopt() function), it will work.

Now, what I recall is that the error number 7 could happen if the page you requested has a redirect and your curl options specify that it should not follow redirections. To check if this is the cause of your issue, set this option before you execute the url:

curl_setopt('CURLOPT_FOLLOWLOCATION', true);

Let me know if that helped.


问:
array_walk not working as expected when modifying the values
I am trying to add a new value to the array (I know it is possible with array_map() but I would like to test it with the array_walk()).

This is the code:

$array = [
    [
        'id'   => 1,
        'name' => 'Jesus',
    ],
    [
        'id'   => 2,
        'name' => 'David',
    ],
];
```

<p>And I want this output:</p>

<pre class="lang-php prettyprint-override"><code>$array = [
    [
        'id'     => 1,
        'name'   => 'Jesus',
        'locked' => 0,
    ],
    [
        'id'     => 2,
        'name'   => 'David',
        'locked' => 0,
    ],
];
</code>```

I tried with the following code:

array_walk($array, static function(array $item): array {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
    return $item;
});

// Also I tried the same code but not returning the array, I mean:

array_walk($array, static function(array $item): void {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
});

```

<p>Is it possible what I want with an <code>array_walk()</code>?</p>

<hr>

<p>That would be the solution with an <code>array_map()</code>.</p>

<pre class="lang-php prettyprint-override"><code>$arrayMapped = array_map(static function(array $item): array {
    return $item += ['locked' => 0];
}, $array);

var_dump($arrayMapped);
</code>```

Cheers!

答:
Arrays are passed by value. You need to define the argument by reference using &

array_walk($array, function(array &$item): void {
    $item['locked'] = 0;
});
```

Body:
I am trying to add a new value to the array (I know it is possible with array_map() but I would like to test it with the array_walk()).

This is the code:

$array = [
    [
        'id'   => 1,
        'name' => 'Jesus',
    ],
    [
        'id'   => 2,
        'name' => 'David',
    ],
];

And I want this output:

$array = [
    [
        'id'     => 1,
        'name'   => 'Jesus',
        'locked' => 0,
    ],
    [
        'id'     => 2,
        'name'   => 'David',
        'locked' => 0,
    ],
];

I tried with the following code:

array_walk($array, static function(array $item): array {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
    return $item;
});

// Also I tried the same code but not returning the array, I mean:

array_walk($array, static function(array $item): void {
    $item += ['locked' => 0];
    //var_dump($item); // Here the array has the three values.
});

Is it possible what I want with an array_walk()?

That would be the solution with an array_map().

$arrayMapped = array_map(static function(array $item): array {
    return $item += ['locked' => 0];
}, $array);

var_dump($arrayMapped);

Cheers!


问:
Is there a way to keep two notebooks with different tab style in tkinter using python?
In case of label or button, I know how it's done.

```<code>style=ttk.Style()
style.configure('One.TLabel', font=('Arial', 32))
style.configure('Two.TLabel', font=('Arial', 18))

h1=Label(root, text='Heading', style='One.TLabel')
h2=Label(root, text='Sub-heading', style='Two.TLabel')

h1.pack()
h2.pack()
</code>```

This works.

But in case of a notebook tab, say I wanna change tab padding and font. Same this method doesn't work.

```<code>style=ttk.Style()
style.configure('One.TNotebook.Tab', font=('Arial', 14), padding=20)
style.configure('Two.TNotebook.Tab', font=('Arial', 12), padding=10)

# adding book1 tabs
book1=Notebook(root, style='One.TNotebook')
# adding book2 tabs
book2=Notebook(root, style='Two.TNotebook')

book1.pack()
book2.pack()
</code>```

How do we do it? Is there a work-around?

答:
You can use ttk.Style(), for the notebooks as follows, to define two different styles for two different notebooks that cohabit in the same window:

```<code>import tkinter as tk
from tkinter import ttk

root = tk.Tk()

style = ttk.Style()
style.configure('One.TNotebook.Tab', font=('Arial', 24), padding=40)

book1 = ttk.Notebook(root, style='One.TNotebook')
book1.pack()
frame1 = ttk.Frame(book1, width=400, height=200, relief=tk.SUNKEN)
frame2 = ttk.Frame(book1, width =400, height=200, relief=tk.SUNKEN)
book1.add(frame1, text = 'One')
book1.add(frame2, text = 'Two')

style.configure('Two.TNotebook.Tab', font=('Arial', 12), padding=10)

book2 = ttk.Notebook(root, style='Two.TNotebook')
book2.pack()
frame3 = ttk.Frame(book2, width=400, height=200, relief=tk.FLAT)
frame4 = ttk.Frame(book2, width =400, height=200, relief=tk.FLAT)
book2.add(frame3, text='Three')
book2.add(frame4, text='Four')

root.mainloop()
</code>```

Body:
In case of label or button, I know how it's done.

style=ttk.Style()
style.configure('One.TLabel', font=('Arial', 32))
style.configure('Two.TLabel', font=('Arial', 18))

h1=Label(root, text='Heading', style='One.TLabel')
h2=Label(root, text='Sub-heading', style='Two.TLabel')

h1.pack()
h2.pack()

This works.

But in case of a notebook tab, say I wanna change tab padding and font. Same this method doesn't work.

style=ttk.Style()
style.configure('One.TNotebook.Tab', font=('Arial', 14), padding=20)
style.configure('Two.TNotebook.Tab', font=('Arial', 12), padding=10)

# adding book1 tabs
book1=Notebook(root, style='One.TNotebook')
# adding book2 tabs
book2=Notebook(root, style='Two.TNotebook')

book1.pack()
book2.pack()

How do we do it? Is there a work-around?

Body:
You can use ttk.Style(), for the notebooks as follows, to define two different styles for two different notebooks that cohabit in the same window:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

style = ttk.Style()
style.configure('One.TNotebook.Tab', font=('Arial', 24), padding=40)

book1 = ttk.Notebook(root, style='One.TNotebook')
book1.pack()
frame1 = ttk.Frame(book1, width=400, height=200, relief=tk.SUNKEN)
frame2 = ttk.Frame(book1, width =400, height=200, relief=tk.SUNKEN)
book1.add(frame1, text = 'One')
book1.add(frame2, text = 'Two')

style.configure('Two.TNotebook.Tab', font=('Arial', 12), padding=10)

book2 = ttk.Notebook(root, style='Two.TNotebook')
book2.pack()
frame3 = ttk.Frame(book2, width=400, height=200, relief=tk.FLAT)
frame4 = ttk.Frame(book2, width =400, height=200, relief=tk.FLAT)
book2.add(frame3, text='Three')
book2.add(frame4, text='Four')

root.mainloop()


问:
The method run(Class<MyNewAppApplication>, String[]) is undefined for the type String
I imported my project that was working normally before and after I changed my OS [ same OS ] when I imported this project as existing maven project in STS , it says The method run(Class<MyNewAppApplication>, String[]) is undefined for the type String and shows nothing else.
Other file is working and it show this error and I literally have no idea of what is happening.

```<code> @SpringBootApplication
public class MyNewAppApplication {

    private static final String SpringApplication = null;

    public static void main(String[] args) {
      SpringApplication.run(MyNewAppApplication.class, args);

    }
}
</code>```

it shows error at run() method.

答:
You have defined a static field SpringApplication

```<code> private static final String SpringApplication = null;
</code>```

Remove that line because this hides the SpringApplication class

Body:
I imported my project that was working normally before and after I changed my OS [ same OS ] when I imported this project as existing maven project in STS , it says The method run(Class<MyNewAppApplication>, String[]) is undefined for the type String and shows nothing else.
Other file is working and it show this error and I literally have no idea of what is happening.

 @SpringBootApplication
public class MyNewAppApplication {

    private static final String SpringApplication = null;

    public static void main(String[] args) {
      SpringApplication.run(MyNewAppApplication.class, args);

    }
}

it shows error at run() method.

Body:
You have defined a static field SpringApplication

 private static final String SpringApplication = null;

Remove that line because this hides the SpringApplication class


问:
Jquery, search and show a hidden div
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

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

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

 ```

im pretty new to this community. thanks for any help!

答:
I made two changes:

in the css for setup initially state

```<code>.foodcard{display: none}
</code>```

and in JS, add a condition for text empty

```<code> grcsearch.trim().length === 0
</code>```

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1 || grcsearch.trim().length === 0)
    {
       $this.closest('.foodcard').fadeOut();}
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

.foodcard{display: none}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

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

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

 ```

Title: Jquery, search and show a hidden div

Body:
Im working on a grocery list where you can search and add groceries to your list. My grocery items are populated from a MySQL table and the text is added to a div called "foodcard". My Jquery script almost works exactly how i want it, except that all 150+ cards are visible and only when you start typing in the input box do the cards get hidden and fade in the related search term. Im having trouble figuring out how to hide the cards on page load and show only the search term. ill give you all my code, but please tell me if i need to include anymore

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1)
    $this.closest('.foodcard').fadeOut();
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });

.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>

    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <link rel="stylesheet" href="css/mdb.min.css">

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

 Grocery List

Search and add groceries we need to get on our next trip out!

                <input type="text" id="grcsearch" class="form-control form-control-lg">
                Search for Groceries

              Apples

              Banana's

              Oranges

              Butter

              Milk

              Bread

              Ramen

              Chicken

              Ground Beef

              Cheese

im pretty new to this community. thanks for any help!

Body:
I made two changes:

in the css for setup initially state

.foodcard{display: none}

and in JS, add a condition for text empty

 grcsearch.trim().length === 0

$(document).ready(function(){

  $('#grcsearch').on('keyup', function () {
    var grcsearch = $('#grcsearch').val().toLowerCase();

   $('.foodcard').each(function(){
    var $this = $(this);

    if($this.text().toLowerCase().indexOf(grcsearch) === -1 || grcsearch.trim().length === 0)
    {
       $this.closest('.foodcard').fadeOut();}
    else $this.closest('.foodcard').fadeIn();

   })

   });
  });

.wrapper {
    text-align: center;

}

.grocerylistcard {
    width: 85%;
    height: 90%;
    border-radius:15px;
    padding-bottom: 20px;
    padding-top: 20px;
    padding-left: 30px;
    padding-right: 30px;
    border-width: 2px;
    border: solid 2px;
    border-color: rgb(199, 185, 201);
    background-color: #D5CAD6;
    margin: auto;
    display: inline-block;
    box-shadow: 5px 5px 3px grey;
}

.pccontainer1 {
   display: flex;
   flex-direction: row;
   }

   .foodcard {
    width: 15%;
    background-color: rgb(236, 231, 203);
    margin: 10px;
    margin-right: 10px !important;
    margin-left: 10px !important;

    border-radius: 10px;
    display: inline-table;

}

.foodcard{display: none}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta http-equiv="Expires" content="-1">

    <title>J & K Life Assist</title>
    <!-- MDB icon -->
    <link rel="icon" href="img/mdb-favicon.ico" type="image/x-icon">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css">
    <!-- Google Fonts Roboto -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Material Design Bootstrap -->
    <link rel="stylesheet" href="css/mdb.min.css">
    <!-- Your custom styles (optional) -->
    <link rel="stylesheet" href="/css/style.css">
    <!-- custom font awesome kit-->

      <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>

<div class="wrapper">
        <div class="grocerylistcard">
            <h3 id="bptitle"> Grocery List </h3>
            <p>Search and add groceries we need to get on our next trip out!</p>
            <hr class="my-4">

            <div class="md-form form-lg" id="grocerysearchwrap">
                <input type="text" id="grcsearch" class="form-control form-control-lg">
                <label for="grocerysearch">Search for Groceries</label>

            </div>

            <!-- Central Modal Small -->
            <br />

<!-- this is where my PHP sript loads the SQL table items, but heres some hand typed cards for your reference -->
<div class="pccontainer1">

            <div class="foodcard">

              Apples
            </div>
            <div class="foodcard">

              Banana's
            </div>
            <div class="foodcard">

              Oranges
            </div>
            <div class="foodcard">

              Butter
            </div>
            <div class="foodcard">

              Milk
            </div>

           </div> <!--pc container-->

           <div class="pccontainer1">

            <div class="foodcard">

              Bread
            </div>
            <div class="foodcard">

              Ramen
            </div>
            <div class="foodcard">

              Chicken
            </div>
            <div class="foodcard">

              Ground Beef
            </div>
            <div class="foodcard">

              Cheese
            </div>

           </div> <!--pc container-->
<!-- grocery items above -->
        </div>
        <!--grocery card ends here-->
    </div> <!-- customcard wrapper-->


问:
Spring Boot not loading @ConfigurationProperties
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

```<code>suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

</code>```

Here is the code of the bean:--

```<code>package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

</code>```

My main SpringBootApplication:----

```<code>package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

</code>```

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner

答:
You should have the @Configuration on the SuppourtedFiles class and also the @EnableConfigurationProperties on the FirstBoot1Application class and add the org.springframework.boot:spring-boot-configuration-processor dependency.

```<code>package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {
    //You should not create the extensions object just declare it
    private List<String> extensions;

    public List<String>getExtensions() {
        return extensions;
    }
    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }
}
</code>```

```<code>package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}
</code>```

And also in the properties you do not need double quotes. You can just have,

```<code>suppourted.extensions[0]=jpg
suppourted.extensions[1]=pdf
suppourted.extensions[2]=png
</code>```

Body:
I am developing a Spring boot application where I am trying to configure custom properties for a bean which gives the suppourted extensions for my file .
When I run the application it runs sucessfully with 0 errors but the extensions are not loaded from the application.properties file.

Here is my code in application.properties :-----

suppourted.extensions[0]="jpg"
suppourted.extensions[1]="pdf"
suppourted.extensions[2]="png"

Here is the code of the bean:--

package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {

    private List<String> extensions=new ArrayList<>();

    public List<String>getExtensions() {
        return extensions;
    }

    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }

    @Override
    public String toString() {
        return "SuppourtedFiles [extensions=" + extensions.size() + "]";
    }

}

My main SpringBootApplication:----

package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

I do not understand where the problem is occuring. Kindly help me.

Update:--

I want to send that object to my jsp page for displaying it using model not just create that bean in CommandLineRunner

Body:
You should have the @Configuration on the SuppourtedFiles class and also the @EnableConfigurationProperties on the FirstBoot1Application class and add the org.springframework.boot:spring-boot-configuration-processor dependency.

package com.MyBoot.FirstBoot;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "suppourted")
public class SuppourtedFiles {
    //You should not create the extensions object just declare it
    private List<String> extensions;

    public List<String>getExtensions() {
        return extensions;
    }
    public void setExtensions(List<String>extensions) {
        this.extensions = extensions;
    }
}

package com.MyBoot.FirstBoot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableConfigurationProperties
public class FirstBoot1Application {

    public static void main(String[] args) {
        SpringApplication.run(FirstBoot1Application.class, args);
    }

}

And also in the properties you do not need double quotes. You can just have,

suppourted.extensions[0]=jpg
suppourted.extensions[1]=pdf
suppourted.extensions[2]=png


问:
const char* vs char* (C++)
For the following program:

```<code>int DivZero(int, int, int);

int main()
{
    try {
        cout << DivZero(1,0,2) << endl;
    }
    catch(char* e)
    {
        cout << "Exception is thrown!" << endl;
        cout << e << endl;
        return 1;
    }
    return 0;
}

int DivZero(int a, int b, int c)
{
    if( a <= 0 || b <= 0 || c <= 0)
        throw "All parameters must be greater than 0.";
    return b/c + a;
}
</code>```

Using char* e will give

terminate called after throwing an
  instance of 'char const*'

According to C++ Exception Handling , the solution is to use const char* instead.

Further reading from function (const char *) vs. function (char *) said that

The type of "String" is char*', not
  const char*'

(this is a C discussion I think...)

Additional reading on Stack Overflow char* vs const char* as a parameter tells me the difference. But none of them address my questions:

It seems like both char* and string* have limit on the numbers of characters. Am I correct?

How does adding the keyword const to char* eliminates that limit? I thought the only purpose of const is to set a flag that said "unmodifiable". I understand that const char* e means " the pointer which points to unmodifiable char type".

The solution to that error is to use const char* e.

Even const string* e doesn't work. (just for the sake of testing...)

Can anyone explain, please? Thank you!

By the way, I am on Ubuntu, compiled by GCC, on Eclipse.

答:
Why are you throwing and catching strings anyway?

You should throw and catch exceptions, e.g. std::runtime_error

The answer to your question is that whenever you insert a string in quotes in the code it returns a null terminated const char*

The reason your code doesn't work as above is because it's the wrong type, so that catch, isn't catching what you're throwing. You're throwing a const char*.

There is no limit to the number of characters in a char array beyond the size of your stack/heap. If you're referring to the example you posted, that person had created a fixed size array, so they were limited.

Title: const char* vs char* (C++)

Body:
For the following program:

int DivZero(int, int, int);

int main()
{
    try {
        cout << DivZero(1,0,2) << endl;
    }
    catch(char* e)
    {
        cout << "Exception is thrown!" << endl;
        cout << e << endl;
        return 1;
    }
    return 0;
}

int DivZero(int a, int b, int c)
{
    if( a <= 0 || b <= 0 || c <= 0)
        throw "All parameters must be greater than 0.";
    return b/c + a;
}

Using char* e will give

terminate called after throwing an
  instance of 'char const*'

According to C++ Exception Handling , the solution is to use const char* instead.

Further reading from function (const char *) vs. function (char *) said that

The type of "String" is char*', not
  const char*'

(this is a C discussion I think...)

Additional reading on Stack Overflow char* vs const char* as a parameter tells me the difference. But none of them address my questions:

It seems like both char* and string* have limit on the numbers of characters. Am I correct?

How does adding the keyword const to char* eliminates that limit? I thought the only purpose of const is to set a flag that said "unmodifiable". I understand that const char* e means " the pointer which points to unmodifiable char type".

The solution to that error is to use const char* e.

Even const string* e doesn't work. (just for the sake of testing...)

Can anyone explain, please? Thank you!

By the way, I am on Ubuntu, compiled by GCC, on Eclipse.


问:
Firebase Web sign in, check for custom value
i have a sign in function for my website:

```<code>function signIn(){

        var email = document.getElementById("txtEmail");
    var password = document.getElementById("txtPassword");

        const promise = auth.signInWithEmailAndPassword(email.value, password.value);
        promise.catch(e => console.log(e.message));
        promise.then(() => {
            window.location.replace("main.html");
        });
    }
</code>```

Now when somebody creates an account i'm setting a custom value which is a boolean:

```<code>isArtist = false;
</code>```

Now what I want is while trying to signup, check if isArtist is false or not. How to do this?

EDIT:

my signup function:

```<code>  function signUp(){

    var userArtistName = document.getElementById("userArtistName").value;
    var userEmail = document.getElementById("userEmail").value;
    var userPassword = document.getElementById("userPassword").value;

        firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
            var user = firebase.auth().currentUser;
            var uid;
            if (user != null) {
                uid = user.uid;
            }
            var firebaseRef = firebase.database().ref();
            var userData = {
                userArtistName: userArtistName,
                userEmail: userEmail,
                userIsArtist: true,
                userId: uid,
            }
            firebaseRef.child('users/' + uid).set(userData);
            console.log('User successfully created!');
           // code for replace user
        }).catch((error) => {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
        });
    }
</code>```

And this is my firebase structure:

答:
I want to allow users to login only if userIsArtist = true.

You cannot prevent a user to login based on a specific value, but you can prevent him to fetch your database. For that you need to write a Security Rule that allows/denies access based on this data.

Something along the following lines:

```<code>".read": "auth.uid != null && root.child('users/' + auth.uid + '/userIsArtist').val() === true"
</code>```

In parallel, in your front-end, after login, you can logout the user and redirect the user to the login page in case he/she is not allowed.

Something like the following, where after signing in we fetch the Realtime Database based on the user uid:

```<code>auth.signInWithEmailAndPassword(email.value, password.value)
.then(userCredential => {
   const userId = userCredential.user.uid;

   return firebase.database().ref('/users/' + userId).once('value')
})
.then(snapshot => {
  var userIsArtist = snapshot.val().userIsArtist;
  if (!userIsArtist) {
     //Redirect to login or other action or message
  }
});
</code>```

However, in this specific case (Role based access right), the recommended approach is to use Custom Claims. See the following documentation items:

https://firebase.google.com/docs/auth/admin/custom-claims

https://firebase.google.com/docs/database/security/user-security#section-custom

Note that you can access the Custom Claim from your front-end and, similarly to the solution above, you can redirect the user which does not have the userIsArtist Custom Claim.

Also note that using the Custom Claim in a Security Rule is different than the Realtime Database example above. See the doc (link in the second bullet point above).

Finally, note that one advantage of using a Custom Claim over the above solution, is that you can use it in the Security Rules of other Firebase services, e.g. Cloud storage.

Body:
i have a sign in function for my website:

function signIn(){

        var email = document.getElementById("txtEmail");
    var password = document.getElementById("txtPassword");

        const promise = auth.signInWithEmailAndPassword(email.value, password.value);
        promise.catch(e => console.log(e.message));
        promise.then(() => {
            window.location.replace("main.html");
        });
    }

Now when somebody creates an account i'm setting a custom value which is a boolean:

isArtist = false;

Now what I want is while trying to signup, check if isArtist is false or not. How to do this?

EDIT:

my signup function:

  function signUp(){

    var userArtistName = document.getElementById("userArtistName").value;
    var userEmail = document.getElementById("userEmail").value;
    var userPassword = document.getElementById("userPassword").value;

        firebase.auth().createUserWithEmailAndPassword(userEmail, userPassword).then((success) => {
            var user = firebase.auth().currentUser;
            var uid;
            if (user != null) {
                uid = user.uid;
            }
            var firebaseRef = firebase.database().ref();
            var userData = {
                userArtistName: userArtistName,
                userEmail: userEmail,
                userIsArtist: true,
                userId: uid,
            }
            firebaseRef.child('users/' + uid).set(userData);
            console.log('User successfully created!');
           // code for replace user
        }).catch((error) => {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
        });
    }

And this is my firebase structure:

Body:
I want to allow users to login only if userIsArtist = true.

You cannot prevent a user to login based on a specific value, but you can prevent him to fetch your database. For that you need to write a Security Rule that allows/denies access based on this data.

Something along the following lines:

".read": "auth.uid != null && root.child('users/' + auth.uid + '/userIsArtist').val() === true"

In parallel, in your front-end, after login, you can logout the user and redirect the user to the login page in case he/she is not allowed.

Something like the following, where after signing in we fetch the Realtime Database based on the user uid:

auth.signInWithEmailAndPassword(email.value, password.value)
.then(userCredential => {
   const userId = userCredential.user.uid;

   return firebase.database().ref('/users/' + userId).once('value')
})
.then(snapshot => {
  var userIsArtist = snapshot.val().userIsArtist;
  if (!userIsArtist) {
     //Redirect to login or other action or message
  }
});

However, in this specific case (Role based access right), the recommended approach is to use Custom Claims. See the following documentation items:

https://firebase.google.com/docs/auth/admin/custom-claims

https://firebase.google.com/docs/database/security/user-security#section-custom

Note that you can access the Custom Claim from your front-end and, similarly to the solution above, you can redirect the user which does not have the userIsArtist Custom Claim.

Also note that using the Custom Claim in a Security Rule is different than the Realtime Database example above. See the doc (link in the second bullet point above).

Finally, note that one advantage of using a Custom Claim over the above solution, is that you can use it in the Security Rules of other Firebase services, e.g. Cloud storage.


问:
Get data from Active Directory using react and ASP.NET Core
Can someone share code to retrieve user details along with thumbnail image to be displayed on the basis of an input of a SamAccountName?

This has to be accomplished using ASP.NET Core and react. I am pretty new to these technologies, please help.

My trials as below

Controller code:

```<code>public Image ourTeam()
    {
        var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();

        Image image = GetImage(userDetails.CN); //I get image data
        //context.Response.ContentType = "image/jpeg";

        var stream = new System.IO.MemoryStream();

        if (image != null)
            image.Save(stream, ImageFormat.Jpeg);

        return image;
    }
</code>```

Component code:

```<code>import * as React from 'react';

import { RouteComponentProps } from 'react-router';

interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}

export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

    fetch('api/Home/ourTeam')
        .then(response => response.json() as Promise<ImageData[]>)
        .then(data => {
            this.setState({ imageList: data, loading: false });
        });
}

    public render() {

    let contents = this.state.loading
        ? <p><em>Loading...</em></p>
        : this.renderImageTable(this.state.imageList);
    return <div>
        <h1>Team</h1>

        {contents}
    </div>;
}

private renderImageTable(imageList: ImageData[]) {
    return <div className='table'>{
        imageList.map(x =>
            <img src={x.byteData} alt={x.CN} />)
    }</div>;

}
}

export class ImageData {
CN: string = "";
byteData: string = "";
}
</code>```

PFB the code on how I am authenticating and then retrieving image:

```<code>private Image GetImage(string cn)
    {
        string LDAP_PATH = "LDAP://" + "SOMEPATH.com";
        string user = "USERID";
        string password = "PASSWORD";
                    using (DirectoryEntry entry = new DirectoryEntry(LDAP_PATH, user, password))
        {
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.PropertiesToLoad.Add("sAMAccountName");
                search.PropertiesToLoad.Add("distinguishedName");
                search.Filter = "(&(objectClass=user)(sAMAccountName=" + cn + "))";
                SearchResult result = search.FindOne();
                if (result == null)
                {
                    search.Filter = "(&(objectClass=user)(cn=" + cn + "))";
                    result = search.FindOne();
                }

                if (result != null)
                {
                    DirectoryEntry entryUser = result.GetDirectoryEntry();
                    string propertyName = "thumbnailPhoto";
                    if (entryUser.Properties.Contains(propertyName))
                    {
                        byte[] img = entryUser.Properties[propertyName].Value as byte[];
                        MemoryStream memStream = new MemoryStream(img);
                        return Image.FromStream(memStream);
                    }
                }
            }
        }

        // User not authenticated
        return null;
    }
</code>```

答:
I assume you want to return the image as if you were just downloading a file.

First, return a byte[] from GetImage. You don't gain anything here by converting it to an Image object. If you needed to edit the image in code, then it would make sense. But since you're not, it doesn't matter.

So change this:

```<code>byte[] img = entryUser.Properties[propertyName].Value as byte[];
MemoryStream memStream = new MemoryStream(img);
return Image.FromStream(memStream);
</code>```

To this:

```<code>return entryUser.Properties[propertyName].Value as byte[];
</code>```

Then in your controller, return a FileContentResult, like this:

```<code>public ActionResult ourTeam()
{
    var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();

    byte[] image = GetImage(userDetails.CN);

    return File(image, "image/jpeg");
}
</code>```

Body:
Can someone share code to retrieve user details along with thumbnail image to be displayed on the basis of an input of a SamAccountName?

This has to be accomplished using ASP.NET Core and react. I am pretty new to these technologies, please help.

My trials as below

Controller code:

public Image ourTeam()
    {
        var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();

        Image image = GetImage(userDetails.CN); //I get image data
        //context.Response.ContentType = "image/jpeg";

        var stream = new System.IO.MemoryStream();

        if (image != null)
            image.Save(stream, ImageFormat.Jpeg);

        return image;
    }

Component code:

import * as React from 'react';

import { RouteComponentProps } from 'react-router';

interface FetchImageDataState {
imageList: ImageData[];
loading: boolean;
}

export class OurTeam extends React.Component<RouteComponentProps<{}>, FetchImageDataState> {
constructor() {
    super();
    this.state = { imageList: [], loading: true }; //initialize to default

    fetch('api/Home/ourTeam')
        .then(response => response.json() as Promise<ImageData[]>)
        .then(data => {
            this.setState({ imageList: data, loading: false });
        });
}

    public render() {

    let contents = this.state.loading
        ?
Loading...

        : this.renderImageTable(this.state.imageList);
    return

Team

        {contents}

;
}

private renderImageTable(imageList: ImageData[]) {
    return
{
        imageList.map(x =>
            )
    }
;

}
}

export class ImageData {
CN: string = "";
byteData: string = "";
}

PFB the code on how I am authenticating and then retrieving image:

private Image GetImage(string cn)
    {
        string LDAP_PATH = "LDAP://" + "SOMEPATH.com";
        string user = "USERID";
        string password = "PASSWORD";
                    using (DirectoryEntry entry = new DirectoryEntry(LDAP_PATH, user, password))
        {
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.PropertiesToLoad.Add("sAMAccountName");
                search.PropertiesToLoad.Add("distinguishedName");
                search.Filter = "(&(objectClass=user)(sAMAccountName=" + cn + "))";
                SearchResult result = search.FindOne();
                if (result == null)
                {
                    search.Filter = "(&(objectClass=user)(cn=" + cn + "))";
                    result = search.FindOne();
                }

                if (result != null)
                {
                    DirectoryEntry entryUser = result.GetDirectoryEntry();
                    string propertyName = "thumbnailPhoto";
                    if (entryUser.Properties.Contains(propertyName))
                    {
                        byte[] img = entryUser.Properties[propertyName].Value as byte[];
                        MemoryStream memStream = new MemoryStream(img);
                        return Image.FromStream(memStream);
                    }
                }
            }
        }

        // User not authenticated
        return null;
    }

Body:
I assume you want to return the image as if you were just downloading a file.

First, return a byte[] from GetImage. You don't gain anything here by converting it to an Image object. If you needed to edit the image in code, then it would make sense. But since you're not, it doesn't matter.

So change this:

byte[] img = entryUser.Properties[propertyName].Value as byte[];
MemoryStream memStream = new MemoryStream(img);
return Image.FromStream(memStream);

To this:

return entryUser.Properties[propertyName].Value as byte[];

Then in your controller, return a FileContentResult, like this:

public ActionResult ourTeam()
{
    var userDetails = db.users.Where(x=>x.saMAccountName == "someUsername").FirstOrDefault();

    byte[] image = GetImage(userDetails.CN);

    return File(image, "image/jpeg");
}


问:
Change the table letter color according to the condition in javascript
I have table with my office shift rota. where it have letters like as shown below but its with out any color.
I want to update the colors as below according to letter dynamically
Ex: AW => yellow, W => red , T => Green, etc ..

Apologies, not able to copy the code from office machine, provided sample table data.

```<code><table>
<tbody>
<tr><td class="t-Report-cell"  headers="EMPLOYEE">Rahul</td><td class="t-Report-cell"  headers="D1">M</td><td class="t-Report-cell"  headers="D2">M</td><td class="t-Report-cell"  headers="D3">M</td><td class="t-Report-cell"  headers="D4">M</td><td class="t-Report-cell"  headers="D5">M</td><td class="t-Report-cell"  headers="D6">O</td><td class="t-Report-cell"  headers="D7">O</td><td class="t-Report-cell"  headers="D8">M</td><td class="t-Report-cell"  headers="D9">M</td><td class="t-Report-cell"  headers="D10">M</td><td class="t-Report-cell"  headers="D11">M</td><td class="t-Report-cell"  headers="D12">M</td><td class="t-Report-cell"  headers="D13">M</td><td class="t-Report-cell"  headers="D14">M</td><td class="t-Report-cell"  headers="D15">M</td><td class="t-Report-cell"  headers="D16">M</td><td class="t-Report-cell"  headers="D17">M</td><td class="t-Report-cell"  headers="D18">M</td><td class="t-Report-cell"  headers="D19">M</td><td class="t-Report-cell"  headers="D20">M</td><td class="t-Report-cell"  headers="D21">M</td><td class="t-Report-cell"  headers="D22">M</td><td class="t-Report-cell"  headers="D23">M</td><td class="t-Report-cell"  headers="D24">M</td><td class="t-Report-cell"  headers="D25">M</td><td class="t-Report-cell"  headers="D26">M</td><td class="t-Report-cell"  headers="D27">M</td><td class="t-Report-cell"  headers="D28">M</td><td class="t-Report-cell"  headers="D29">M</td><td class="t-Report-cell"  headers="D30">M</td><td class="t-Report-cell"  headers="D31"></td></tr>
<tr><td class="t-Report-cell"  headers="EMPLOYEE">Srinivas</td><td class="t-Report-cell"  headers="D1">A</td><td class="t-Report-cell"  headers="D2">A</td><td class="t-Report-cell"  headers="D3">A</td><td class="t-Report-cell"  headers="D4">A</td><td class="t-Report-cell"  headers="D5">A</td><td class="t-Report-cell"  headers="D6">A</td><td class="t-Report-cell"  headers="D7">W</td><td class="t-Report-cell"  headers="D8">W</td><td class="t-Report-cell"  headers="D9">A</td><td class="t-Report-cell"  headers="D10">A</td><td class="t-Report-cell"  headers="D11">A</td><td class="t-Report-cell"  headers="D12">A</td><td class="t-Report-cell"  headers="D13">A</td><td class="t-Report-cell"  headers="D14">W</td><td class="t-Report-cell"  headers="D15">W</td><td class="t-Report-cell"  headers="D16">A</td><td class="t-Report-cell"  headers="D17">A</td><td class="t-Report-cell"  headers="D18">A</td><td class="t-Report-cell"  headers="D19">A</td><td class="t-Report-cell"  headers="D20">A</td><td class="t-Report-cell"  headers="D21">W</td><td class="t-Report-cell"  headers="D22">W</td><td class="t-Report-cell"  headers="D23">A</td><td class="t-Report-cell"  headers="D24">A</td><td class="t-Report-cell"  headers="D25">X</td><td class="t-Report-cell"  headers="D26">A</td><td class="t-Report-cell"  headers="D27">A</td><td class="t-Report-cell"  headers="D28">W</td><td class="t-Report-cell"  headers="D29">W</td><td class="t-Report-cell"  headers="D30">A</td><td class="t-Report-cell"  headers="D31"></td></tr>
<tr><td class="t-Report-cell"  headers="EMPLOYEE">Rajesh</td><td class="t-Report-cell"  headers="D1">M</td><td class="t-Report-cell"  headers="D2">M</td><td class="t-Report-cell"  headers="D3">M</td><td class="t-Report-cell"  headers="D4">M</td><td class="t-Report-cell"  headers="D5">M</td><td class="t-Report-cell"  headers="D6">O</td><td class="t-Report-cell"  headers="D7">W</td><td class="t-Report-cell"  headers="D8">W</td><td class="t-Report-cell"  headers="D9">M</td><td class="t-Report-cell"  headers="D10">M</td><td class="t-Report-cell"  headers="D11">M</td><td class="t-Report-cell"  headers="D12">M</td><td class="t-Report-cell"  headers="D13">M</td><td class="t-Report-cell"  headers="D14">W</td><td class="t-Report-cell"  headers="D15">W</td><td class="t-Report-cell"  headers="D16">M</td><td class="t-Report-cell"  headers="D17">M</td><td class="t-Report-cell"  headers="D18">M</td><td class="t-Report-cell"  headers="D19">M</td><td class="t-Report-cell"  headers="D20">M</td><td class="t-Report-cell"  headers="D21">W</td><td class="t-Report-cell"  headers="D22">W</td><td class="t-Report-cell"  headers="D23">M</td><td class="t-Report-cell"  headers="D24">M</td><td class="t-Report-cell"  headers="D25">M</td><td class="t-Report-cell"  headers="D26">M</td><td class="t-Report-cell"  headers="D27">M</td><td class="t-Report-cell"  headers="D28">W</td><td class="t-Report-cell"  headers="D29">W</td><td class="t-Report-cell"  headers="D30">M</td><td class="t-Report-cell"  headers="D31"></td></tr>
      </tbody>
</table>
</code>```

Please suggest.

答:
An idea could be to add a data attribute while dynamically creating the  elements and apply styles depending on it

```<code><td data-text="aw">
  AW
</td>
</code>```

```<code>td[data-text="aw"] {
  background-color: yellow
}
</code>```

Body:
I have table with my office shift rota. where it have letters like as shown below but its with out any color.
I want to update the colors as below according to letter dynamically
Ex: AW => yellow, W => red , T => Green, etc ..

Apologies, not able to copy the code from office machine, provided sample table data.

Rahul	M	M	M	M	M	O	O	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M	M

Srinivas	A	A	A	A	A	A	W	W	A	A	A	A	A	W	W	A	A	A	A	A	W	W	A	A	X	A	A	W	W	A

Rajesh	M	M	M	M	M	O	W	W	M	M	M	M	M	W	W	M	M	M	M	M	W	W	M	M	M	M	M	W	W	M

Please suggest.

Body:
An idea could be to add a data attribute while dynamically creating the  elements and apply styles depending on it

<td data-text="aw">
  AW
</td>

td[data-text="aw"] {
  background-color: yellow
}


问:
Is there a way to determine the indices where a python string differs from another string?
I've searched far and wide and can't seem to find any prebuilt library that can do this:

Given 2 strings in python where one is the original string and the other has certain words replaced with place holders, I would like to identify the indices of the words in the original string that have been replaced with placeholders.

Example:

```<code>original = "This is the original string"

processed = "This is [placeholder] string"

indices = [8, 20]
</code>```

The first index is the start of the substring that has been replaced, and the second index is the end of this substring.

Any help would be much appreciated.

答:
That might not be the prettiest Python code I've written, but this would work:

```<code>first = [index for index,
        (a, b) in enumerate(zip(list(original),
        list(processed))) if a != b ][0]

second = [len(original) - index for index,
         (a, b) in enumerate(zip(list(original[::-1]),
         list(processed[::-1]))) if a != b ][0]

difference = [first, second]
</code>```

It returns the first index where there is a discordance. And also the same backwards.

```<code>Out[76]: [8, 20]
</code>```

In more detail:

Comparing every letter, it returns the first index where first != second

Comparing every letter starting from the end, it returns len(first) - first difference

It creates a list of these two indices

Body:
I've searched far and wide and can't seem to find any prebuilt library that can do this:

Given 2 strings in python where one is the original string and the other has certain words replaced with place holders, I would like to identify the indices of the words in the original string that have been replaced with placeholders.

Example:

original = "This is the original string"

processed = "This is [placeholder] string"

indices = [8, 20]

The first index is the start of the substring that has been replaced, and the second index is the end of this substring.

Any help would be much appreciated.

Body:
That might not be the prettiest Python code I've written, but this would work:

first = [index for index,
        (a, b) in enumerate(zip(list(original),
        list(processed))) if a != b ][0]

second = [len(original) - index for index,
         (a, b) in enumerate(zip(list(original[::-1]),
         list(processed[::-1]))) if a != b ][0]

difference = [first, second]

It returns the first index where there is a discordance. And also the same backwards.

Out[76]: [8, 20]

In more detail:

Comparing every letter, it returns the first index where first != second

Comparing every letter starting from the end, it returns len(first) - first difference

It creates a list of these two indices


问:
How to have a cornerradius on Flex 4 TextInput component
How do I get corner radius on my TextInput component in Flex 4. </p>

```<code><s:TextInput prompt="username" width="150" maxChars="100" id="txt_username"
    color="#000000"/>
</code>```

答:
Create a custom skin (possibly by copying spark TextInputSkin) and add a border graphic with rounded corners, like this:

```<code><!-- border -->
<s:Rect id="border" left="0" right="0" top="0" bottom="0"
        radiusX="10" radiusY="10">

    <s:stroke>
        <s:SolidColorStroke id="borderStroke" weight="1" />
    </s:stroke>
</s:Rect>
</code>```

If you want more special rounded corners you can also use these attributes:

```<code>topLeftRadiusX="4" topLeftRadiusY="8"
bottomLeftRadiusX="2" bottomRightRadiusY="10"
</code>```

The default TextInputSkin does not allow for rounded corners, so there is no style that you could set on your TextInput to do it. So, no, there's no other way than creating a custom skin class.

Body:
How do I get corner radius on my TextInput component in Flex 4.

<s:TextInput prompt="username" width="150" maxChars="100" id="txt_username"
    color="#000000"/>

Body:
Create a custom skin (possibly by copying spark TextInputSkin) and add a border graphic with rounded corners, like this:

<!-- border -->
<s:Rect id="border" left="0" right="0" top="0" bottom="0"
        radiusX="10" radiusY="10">

    <s:stroke>
        <s:SolidColorStroke id="borderStroke" weight="1" />
    </s:stroke>
</s:Rect>

If you want more special rounded corners you can also use these attributes:

topLeftRadiusX="4" topLeftRadiusY="8"
bottomLeftRadiusX="2" bottomRightRadiusY="10"

The default TextInputSkin does not allow for rounded corners, so there is no style that you could set on your TextInput to do it. So, no, there's no other way than creating a custom skin class.


问:
Why is a named function passed as 1st parameter to useEffect not a necessary dependency?
[Solved] I believe the 2 effects below should have the same effect.
But why does the eslint rule not complain in the second case?

It should be mandatory dependency in both case as doSomething can change and change the effect.

```<code>  const doSomething = useCallback(() => {
    void someProp;
  }, [someProp]);

useEffect(()=> doSomething(), [doSomething]); // eslint(react-hooks/exhaustive-deps) complains if I remove the dependency
useEffect(doSomething, []); // no complaint here, why?
</code>```

Edit:
It was actually fixed a while back (even before I wrote that question).
https://github.com/facebook/react/pull/18435

答:
useEffect should not return a value, except a clean up function.

e.g:

useEffect(() => {
  return () => {}
}, [])
```

And you're using doSomething, which was specified outside the hook, inside the useEffect hook.

Body:
[Solved] I believe the 2 effects below should have the same effect.
But why does the eslint rule not complain in the second case?

It should be mandatory dependency in both case as doSomething can change and change the effect.

  const doSomething = useCallback(() => {
    void someProp;
  }, [someProp]);

useEffect(()=> doSomething(), [doSomething]); // eslint(react-hooks/exhaustive-deps) complains if I remove the dependency
useEffect(doSomething, []); // no complaint here, why?

Edit:
It was actually fixed a while back (even before I wrote that question).
https://github.com/facebook/react/pull/18435

Body:
useEffect should not return a value, except a clean up function.

e.g:

useEffect(() => {
  return () => {}
}, [])

And you're using doSomething, which was specified outside the hook, inside the useEffect hook.


答: Could you just add them as

Title: How to programmatically add a css rule to an element

Body:
I am using Angular 6 and Typescript. Here's my issue. I need to add a specific CSS rule to the host of a component that I am writing. I cannot apply that rule systematically, I need to have some logic in ngOnInit() before adding my rule. I know this sounds like bad practice, but there are no workarounds and this is the only way I can solve the problem I am facing. I can easily add classes on new styles to my host, but I cannot seem to find a way to add a rule.

Some people have been marking my question as a duplicate. Please read my question carefully. I am not trying to add a class, I am trying to a add a RULE. This is very different and there are no results for such question.

Here's the two rules I have that I want to add to my host element depending on some condition:

custom-component + custom-component > .vertical-component {
    margin-top: 1rem;
}

and

custom-component + custom-component > .horizontal-component {
    margin-left: 1rem;
}

In my component code, I have something like this:

export class CustomComponent {
    public constructor(private host: ElementRef, private renderer: Renderer2) {

    }

    public applyStylesToHost(): void {
        if (this.variant == TYPE.VERTICAL) {
            // Set the rule with the margin-top
        } else {
            // Set the rule with the margin-left
        }
    }
}

I was looking for a method like this.renderer.setRule(), but there is no such thing. How can I programmatically add a specific rule to my host element?

The closest thing I found is this link. The author suggest doing document.createElement("style").sheet.addRule(), but when I tried to do it, the method addRule didn't exist on the sheet element.

Body:
Could you just add them as <style> tag to the whole document?

var st = document.createElement('style');
st.appendChild(document.createTextNode(`
    custom-component + custom-component > .vertical-component {
        margin-top: 1rem;
    }
`));
document.head.appendChild(st);


问:
why this svg does not fill the screen?
why this svg does not fill the screen?

i just open "and_gate.svg" (svg below) with last version of firefox/chrome. it doesn't fill height of the screen. (I wrote height because this svg's width:26 height:32.)

 <svg viewBox="0 0 26 32" xmlns="http://www.w3.org/2000/svg">
   <path d="M 0 19 A 13 13 0 0 1 26 19 v 19 h -26 v -19 Z" fill="#000" />
 </svg>```
</div>
</div>
</p>

<p>however if a svg that width:26 height:32 fills entire height of the screen. (svg below)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <svg viewBox="0 0 26 32" xmlns="http://www.w3.org/2000/svg">
   <rect x="0" y="0" width="26" height="32" fill="#000" />
 </svg></code>```

答:
If you combine the two it is clear your path leaves white.. ehm green space

The A(rc) goes from y=19 to y=13 , not to y=0 (top)

<svg viewBox="0 0 26 32" xmlns="http://www.w3.org/2000/svg">
  <rect x="0" y="0" width="26" height="32" fill="green" />
  <path d="M 0 19 A 13 13 0 0 1 26 19 v 19 h -26 v -19 Z" fill="#000" />
</svg>```

Title: why this svg does not fill the screen?

Body:
why this svg does not fill the screen?

i just open "and_gate.svg" (svg below) with last version of firefox/chrome. it doesn't fill height of the screen. (I wrote height because this svg's width:26 height:32.)

 <svg viewBox="0 0 26 32" xmlns="http://www.w3.org/2000/svg">
   <path d="M 0 19 A 13 13 0 0 1 26 19 v 19 h -26 v -19 Z" fill="#000" />
 </svg>

however if a svg that width:26 height:32 fills entire height of the screen. (svg below)

 <svg viewBox="0 0 26 32" xmlns="http://www.w3.org/2000/svg">
   <rect x="0" y="0" width="26" height="32" fill="#000" />
 </svg>


问:
How do I find the most popular IDs ordered by row count in MongoDB?
I have a polling application, where, when a user votes, entries such as these are created into the votes collection:

```<code>{"vote": "apples", "voter_id": 54729, "poll_id": 1}
{"vote": "oranges", "voter_id": 48201, "poll_id": 1}
{"vote": "apples", "voter_id": 22810, "poll_id": 1}
{"vote": "oranges", "voter_id": 55901, "poll_id": 1}
{"vote": "oranges", "voter_id": 54321, "poll_id": 1}
</code>```

I am trying to figure out the query which would allow me to find the most popular votes for a given poll_id. For the example data above, I want a result like:

```<code>{"vote": "oranges", "count": 3}
{"vote": "apples", "count": 2}
</code>```

What query should I use to obtain this?

答:
You can use the aggregation pipeline:

```<code>db.collection.aggregate([{$match:{poll_id:1}},{$group:{_id: { vote: "$vote" },count:{$sum:1}}},{$project:{vote:"$_id.vote",count:1,_id:0}},{$sort:{count:-1}}])
</code>```

Output:

```<code>{ "count" : 2, "vote" : "apples" }
{ "count" : 3, "vote" : "oranges" }
</code>```

And you can sort by count and then return the top K:

```<code>db.collection.aggregate([{$match:{poll_id:1}},{$group:{_id: { vote: "$vote" },count:{$sum:1}}},{$project:{vote:"$_id.vote",count:1,_id:0}},{$sort:{count:-1}},{$limit:1}])
</code>```

Output:

```<code>{ "count" : 3, "vote" : "oranges" }
</code>```

Try it out:
https://mongoplayground.net/p/Mp_c7SAxmYY

Body:
I have a polling application, where, when a user votes, entries such as these are created into the votes collection:

{"vote": "apples", "voter_id": 54729, "poll_id": 1}
{"vote": "oranges", "voter_id": 48201, "poll_id": 1}
{"vote": "apples", "voter_id": 22810, "poll_id": 1}
{"vote": "oranges", "voter_id": 55901, "poll_id": 1}
{"vote": "oranges", "voter_id": 54321, "poll_id": 1}

I am trying to figure out the query which would allow me to find the most popular votes for a given poll_id. For the example data above, I want a result like:

{"vote": "oranges", "count": 3}
{"vote": "apples", "count": 2}

What query should I use to obtain this?

Body:
You can use the aggregation pipeline:

db.collection.aggregate([{$match:{poll_id:1}},{$group:{_id: { vote: "$vote" },count:{$sum:1}}},{$project:{vote:"$_id.vote",count:1,_id:0}},{$sort:{count:-1}}])

Output:

{ "count" : 2, "vote" : "apples" }
{ "count" : 3, "vote" : "oranges" }

And you can sort by count and then return the top K:

db.collection.aggregate([{$match:{poll_id:1}},{$group:{_id: { vote: "$vote" },count:{$sum:1}}},{$project:{vote:"$_id.vote",count:1,_id:0}},{$sort:{count:-1}},{$limit:1}])

Output:

{ "count" : 3, "vote" : "oranges" }

Try it out:
https://mongoplayground.net/p/Mp_c7SAxmYY


问:
Mouse listener throws no errors but doesn't fire (java)
I am following code I found on geeksforgeeks but the mouse listener isn't firing. I suspect that somehow the implementation of runnable is locking access to my board object, but I'm not sure. I'm in a similar boat to the OP of this post.

```<code>public class Game extends Canvas implements MouseListener {

    JFrame jf = new JFrame();

    Game() {
        jf.getContentPane().add(this, BorderLayout.CENTER);
        jf.setSize(new Dimension(500,500+30));
        jf.setVisible(true);
        jf.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e){
        System.out.println("Hello World!");
    }

    public void mousePressed(MouseEvent e){}

    public void mouseReleased(MouseEvent e){}

    public void mouseEntered(MouseEvent e){}

    public void mouseExited(MouseEvent e){}

    public static void main(String[] args){
        Game game = new Game();
    }
}
</code>```

I suspect but doubt that the mouse listener may not be functioning properly due to it being created in a non-static method, but I doubt that that is the problem. I've tried moving the declaration to the beginning of the constructor, but that didn't help.

答: The problem was with using Canvas instead of JPanel as the superclass. When I switched, the mouse listener started firing.</p>

Body:
I am following code I found on geeksforgeeks but the mouse listener isn't firing. I suspect that somehow the implementation of runnable is locking access to my board object, but I'm not sure. I'm in a similar boat to the OP of this post.

public class Game extends Canvas implements MouseListener {

    JFrame jf = new JFrame();

    Game() {
        jf.getContentPane().add(this, BorderLayout.CENTER);
        jf.setSize(new Dimension(500,500+30));
        jf.setVisible(true);
        jf.addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e){
        System.out.println("Hello World!");
    }

    public void mousePressed(MouseEvent e){}

    public void mouseReleased(MouseEvent e){}

    public void mouseEntered(MouseEvent e){}

    public void mouseExited(MouseEvent e){}

    public static void main(String[] args){
        Game game = new Game();
    }
}

I suspect but doubt that the mouse listener may not be functioning properly due to it being created in a non-static method, but I doubt that that is the problem. I've tried moving the declaration to the beginning of the constructor, but that didn't help.


问:
how to use highcharts-angular callback function to get chart object
I have used https://github.com/highcharts/highcharts-angular this official wrapper and try to call the callback function to get the chart object. Unfortunately, though I tried various methods that did not give any proper results as I expect. Also, there aren't many documents that describe the callback function. Can someone let me know how to use the callback function?   </p>

答:
The callback didn't work for me either.
I was inspecting the code source and I saw the @Output event emitter called chartInstance...
It is also documented:

component output chartInstance - emitted after chart is created (see demo app and logChartInstance function)

So I've used as a normal output event binding:

```<code><highcharts-chart
 [Highcharts]="Highcharts"
 [options]="chartOptions"
 ...
 (chartInstance)="onChartInstance($event)"
 ...
></highcharts-chart>
</code>```

And voilà... I think that is not a definitive solution but as a temporary workaround it works pretty well for me.

Body:
The callback didn't work for me either.
I was inspecting the code source and I saw the @Output event emitter called chartInstance...
It is also documented:

component output chartInstance - emitted after chart is created (see demo app and logChartInstance function)

So I've used as a normal output event binding:

<highcharts-chart
 [Highcharts]="Highcharts"
 [options]="chartOptions"
 ...
 (chartInstance)="onChartInstance($event)"
 ...
></highcharts-chart>

And voilà... I think that is not a definitive solution but as a temporary workaround it works pretty well for me.