问:
Change value in NSDictionary
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

```<code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'
</code>```

This is my sample server data :

```<code>{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}
</code>```

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

```<code>NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
</code>```

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

```<code>[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];
</code>```

I also tried this :

```<code>    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];
</code>```

Giving same error.

答:
Try this to change the value of question_ans & question_ans_comments

```<code>NSString *jsonString = @"{ \"data\": { \"My_Tool_Box\": { \"Visual Check\": [ { \"que_cat_id\": \"1\", \"question_id\": \"1\", \"question_name\": \"Power leads\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"2\", \"question_name\": \"Power\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"3\", \"question_name\": \"Rcd is operational\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"4\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"5\", \"question_name\": \"Safety guards if fitted to machine ARE OPERATIONAL AND ARE NOT DAMAGED\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"6\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"7\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ], \"Operational checks\": [ { \"que_cat_id\": \"2\", \"question_id\": \"8\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"2\", \"question_id\": \"9\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"2\", \"question_id\": \"10\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ], \"Operating instructions\": [ { \"que_cat_id\": \"3\", \"question_id\": \"11\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ] } }, \"status\": \"success\", \"message\": \"Question Listing\" }";

NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dic = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] mutableCopy];

NSMutableDictionary *oldDic = [[[[dic objectForKey:@"data"] objectForKey:@"My_Tool_Box"] objectForKey:@"Visual Check"] objectAtIndex:0];
NSLog(@"oldDic :: %@",oldDic);

[oldDic setObject:@"iOS Dev Answer" forKey:@"question_ans"];
[oldDic setObject:@"iOS Dev Comments" forKey:@"question_ans_comments"];

NSLog(@"dic :: %@",dic);
</code>```

Title: Change value in NSDictionary

Body:
I have data that comes from server and i save it in NSMutableDic but when i change value in that NSMutabelDic it gives me error that i can't change in NSDic!
This is error :

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKey:]: unrecognized selector sent to instance 0x7ae250c0'

This is my sample server data :

{
    "data": {
        "My_Tool_Box": {
            "Visual Check": [
                {
                    "que_cat_id": "1",
                    "question_id": "1",
                    "question_name": "Power leads",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "2",
                    "question_name": "Power",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "3",
                    "question_name": "Rcd is operational",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "4",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "5",
                    "question_name": "Safety guards if fitted  to machine ARE OPERATIONAL AND ARE NOT DAMAGED",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "6",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "1",
                    "question_id": "7",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operational checks": [
                {
                    "que_cat_id": "2",
                    "question_id": "8",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "9",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                },
                {
                    "que_cat_id": "2",
                    "question_id": "10",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ],
            "Operating instructions": [
                {
                    "que_cat_id": "3",
                    "question_id": "11",
                    "question_name": "ase to avoid damage",
                    "question_ans": "",
                    "question_ans_comments": "",
                    "question_options": {
                        "1": "Yes",
                        "2": "No",
                        "3": "N/A",
                        "4": "Comment"
                    }
                }
            ]
        }
    },
    "status": "success",
    "message": "Question Listing"
}

So i have to change value of question_ans & question_ans_comments so as when i change it i get error as i mention above.
This is the way i already applied:

NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:@"Don" forKey:@"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];

i don't have index in sequence like how i replace that key object!! Is there any easy way that i can apply here ?

This is the way i reset value :

[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] setObject:@"12" forKey:@"question_ans"];

I also tried this :

    NSDictionary *oldDict = (NSDictionary *)[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0];
    NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:oldDict];
    [newDict setObject:@"12" forKey:@"question_ans"];
    [[[[arrayGlobal valueForKey:[arrayAllColumn objectAtIndex:0]] objectAtIndex:0] mutableCopy] replaceObjectAtIndex:0 withObject:newDict];

Giving same error.

Body:
Try this to change the value of question_ans & question_ans_comments

NSString *jsonString = @"{ \"data\": { \"My_Tool_Box\": { \"Visual Check\": [ { \"que_cat_id\": \"1\", \"question_id\": \"1\", \"question_name\": \"Power leads\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"2\", \"question_name\": \"Power\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"3\", \"question_name\": \"Rcd is operational\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"4\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"5\", \"question_name\": \"Safety guards if fitted to machine ARE OPERATIONAL AND ARE NOT DAMAGED\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"6\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"1\", \"question_id\": \"7\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ], \"Operational checks\": [ { \"que_cat_id\": \"2\", \"question_id\": \"8\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"2\", \"question_id\": \"9\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } }, { \"que_cat_id\": \"2\", \"question_id\": \"10\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ], \"Operating instructions\": [ { \"que_cat_id\": \"3\", \"question_id\": \"11\", \"question_name\": \"ase to avoid damage\", \"question_ans\": \"\", \"question_ans_comments\": \"\", \"question_options\": { \"1\": \"Yes\", \"2\": \"No\", \"3\": \"N/A\", \"4\": \"Comment\" } } ] } }, \"status\": \"success\", \"message\": \"Question Listing\" }";

NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dic = [[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil] mutableCopy];

NSMutableDictionary *oldDic = [[[[dic objectForKey:@"data"] objectForKey:@"My_Tool_Box"] objectForKey:@"Visual Check"] objectAtIndex:0];
NSLog(@"oldDic :: %@",oldDic);

[oldDic setObject:@"iOS Dev Answer" forKey:@"question_ans"];
[oldDic setObject:@"iOS Dev Comments" forKey:@"question_ans_comments"];

NSLog(@"dic :: %@",dic);


来源: stackexchange

问:
About ![CDATA[, what is it?

Possible Duplicate:

  what is the meaning of CDATA

What is, and when is used the ![CDATA[ string/variable/constant? (I don't know what is it)

答:
CDATA is used in XML (and hence XHTML) to insert text which might include "special" characters (eg. < and >) which would normally break the XML parser (and to be fair, confuse a human reader, as well!).

For example, you could use it to embed a code segment inside an XML document.

ContentLicense: CC BY-SA 2.5

Title: About ![CDATA[, what is it?


问:
How do I retrieve the workerSize via Get-AzureRmAppServicePlan
When creating a new AppServicePlan via the Azure PowerShell cmdlet New-AzureRmAppServicePlan, it is expected for me to add a WorkerSize such as Small, Medium or Large. For example:

```<code>$appServicePlanSettings = @{
    Name = "testingServicePlan";
    Location = "westeurope";
    Tier = "Basic";
    ResourceGroupName = "testingResourceGroup";
    NumberofWorkers = 1;
    WorkerSize = "Medium";
}

New-AzureRmAppServicePlan @appServicePlanSettings
</code>```

However, when I retrieve this same AppServicePlan via Get-AzureRmAppServicePlan, I am unable to find this information. Instead I come across the Sku property, which contains a Size property with for example the value B2, indicating the WorkerSize was medium. Example:

```<code>> $plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $plan.Sku
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1
</code>```

Am I supposed to keep track of these conversions in for example a HashList if I want to be able to compare the equivalent values, or is there some other way for me to retrieve the 'Medium'? I might have missed something but couldn't find this information.

According to PowerShell's GetType() method, the object returned is a ServerFarmWithRichSku, with as base type Microsoft.Azure.Management.WebSites.Models.Resource, but the documentation for this object was a bit lacking for me to get any further

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.management.websites.models.resource?view=azuremgmtwebsites-1.6.0-preview

答:
I test in my lab, $plan.Sku.size is WorkerSize value. The following is the result.

```<code>SMALL
Name     : B1
Tier     : Basic
Size     : B1
Family   : B
Capacity : 1

Medium
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1

Large
Name     : B3
Tier     : Basic
Size     : B3
Family   : B
Capacity : 1
</code>```

I agree with Sridharan, but you had better use script like below:

```<code>$hash = @{}
$hash['B1'] = "Small"
$hash['B2'] = "Medium"
$hash['B3'] = "Large"
$hash['B4'] = "Extra Large"

$plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
$val=$plan.Sku.Size
echo $hash[$val]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When creating a new AppServicePlan via the Azure PowerShell cmdlet New-AzureRmAppServicePlan, it is expected for me to add a WorkerSize such as Small, Medium or Large. For example:

$appServicePlanSettings = @{
    Name = "testingServicePlan";
    Location = "westeurope";
    Tier = "Basic";
    ResourceGroupName = "testingResourceGroup";
    NumberofWorkers = 1;
    WorkerSize = "Medium";
}

New-AzureRmAppServicePlan @appServicePlanSettings

However, when I retrieve this same AppServicePlan via Get-AzureRmAppServicePlan, I am unable to find this information. Instead I come across the Sku property, which contains a Size property with for example the value B2, indicating the WorkerSize was medium. Example:

> $plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
> $plan.Sku
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1

Am I supposed to keep track of these conversions in for example a HashList if I want to be able to compare the equivalent values, or is there some other way for me to retrieve the 'Medium'? I might have missed something but couldn't find this information.

According to PowerShell's GetType() method, the object returned is a ServerFarmWithRichSku, with as base type Microsoft.Azure.Management.WebSites.Models.Resource, but the documentation for this object was a bit lacking for me to get any further

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.management.websites.models.resource?view=azuremgmtwebsites-1.6.0-preview

Body:
I test in my lab, $plan.Sku.size is WorkerSize value. The following is the result.

SMALL
Name     : B1
Tier     : Basic
Size     : B1
Family   : B
Capacity : 1

Medium
Name     : B2
Tier     : Basic
Size     : B2
Family   : B
Capacity : 1

Large
Name     : B3
Tier     : Basic
Size     : B3
Family   : B
Capacity : 1

I agree with Sridharan, but you had better use script like below:

$hash = @{}
$hash['B1'] = "Small"
$hash['B2'] = "Medium"
$hash['B3'] = "Large"
$hash['B4'] = "Extra Large"

$plan = Get-AzureRmAppServicePlan -Name "testingServicePlan" -ResourceGroupName "testingResourceGroup"
$val=$plan.Sku.Size
echo $hash[$val]


问:
Android: add DONE key to soft keyboard deprecated attribute
I am trying to add a DONE key to the soft keyboard so that it will hide when the user is done adding text to an EditText.

The thing is that, from other answers here, I saw that adding the following to the XML file will do the thing:

```<code> android:imeOptions="actionDone"
 android:singleLine="true"
</code>```

It actually WORKS fine, and the DONE key is showed....however, Android Studio is complaining, telling that android:singleLine="true" is deprecated, use maxLines = 1.

Well, if I change android:singleLine="true" with maxLines = 1 it DOES NOT WORK and the DONE key is not showed.

Am I missing something here?? (Android Studio 2.3.3 I am using)

答:
android:singleLine is <s>Deprecated</s> .You should use maxLines with inputType .

```<code>android:imeOptions="actionDone"
android:maxLines="1"
android:inputType="text"
</code>```

Body:
I am trying to add a DONE key to the soft keyboard so that it will hide when the user is done adding text to an EditText.

The thing is that, from other answers here, I saw that adding the following to the XML file will do the thing:

 android:imeOptions="actionDone"
 android:singleLine="true"

It actually WORKS fine, and the DONE key is showed....however, Android Studio is complaining, telling that android:singleLine="true" is deprecated, use maxLines = 1.

Well, if I change android:singleLine="true" with maxLines = 1 it DOES NOT WORK and the DONE key is not showed.

Am I missing something here?? (Android Studio 2.3.3 I am using)

Body:
android:singleLine is <s>Deprecated</s> .You should use maxLines with inputType .

android:imeOptions="actionDone"
android:maxLines="1"
android:inputType="text"


问:
jQuery gathering inputs without submit
I'm trying to get values from inputs without any action from user and then save it via php to txt file.

This is what I got so far:

```<code>var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {

     $('#display').append(email)

   $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({usremail:email}),
      success: function(data) {
      }
    });

}
var newemail = $("#test").val();
}, 1000);
</code>```

it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.

I have also tried to add something like "var newemail = email", but can't make it work corectly.

答:
You can do like this

```<code>$('#test').on('change',function () {
    var email= $(this).val();
    if(email != '') {

        $('#display').append(email);

        $.ajax({
            type: "POST",
            url: 'inputs-saving.php',
            data: ({usremail:email}),
            success: function(data) {
            }
        });

    }
});
</code>```

Here test is the email filed id.

I thing it will help you.

Title: jQuery gathering inputs without submit

Body:
I'm trying to get values from inputs without any action from user and then save it via php to txt file.

This is what I got so far:

var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {

     $('#display').append(email)

   $.ajax({
      type: "POST",
      url: 'inputs-saving.php',
      data: ({usremail:email}),
      success: function(data) {
      }
    });

}
var newemail = $("#test").val();
}, 1000);

it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.

I have also tried to add something like "var newemail = email", but can't make it work corectly.

Body:
You can do like this

$('#test').on('change',function () {
    var email= $(this).val();
    if(email != '') {

        $('#display').append(email);

        $.ajax({
            type: "POST",
            url: 'inputs-saving.php',
            data: ({usremail:email}),
            success: function(data) {
            }
        });

    }
});

Here test is the email filed id.

I thing it will help you.


问:
How to detect that the HTML element has text by clicking on text content area?
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

```<code><div>
some text
<span class="box"></span>
</div>

<div>
some text
</div>

<div><span class="box"></span></div>
</code>```

JS:

```<code>$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('<span>You clicked on a text</span>');
    }

});
</code>```

答:
When you bind an event handler to a node, or use event delegation, this refers to the node the event was bonded to (or delegated to in the case of on).

Click the .box inside the 1st div element, gets the div as this. Since the div element contains text, you the wrong result.

Instead you should get the event target. The target is the actual element clicked.

$(document).on('click', 'div', function(e) {

  var $target = $(e.target); // the event target

  if (!$target.text().trim().length > 0) {
    $target.text("foo");
  } else {
    $target.append('You clicked on a text');
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  background-color: green;
  height: 50px;
  width: 50px;
  display: block;
}</code>```

  some text

  some text

```

Body:
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

some text

some text

JS:

$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('You clicked on a text');
    }

});

Body:
When you bind an event handler to a node, or use event delegation, this refers to the node the event was bonded to (or delegated to in the case of on).

Click the .box inside the 1st div element, gets the div as this. Since the div element contains text, you the wrong result.

Instead you should get the event target. The target is the actual element clicked.

$(document).on('click', 'div', function(e) {

  var $target = $(e.target); // the event target

  if (!$target.text().trim().length > 0) {
    $target.text("foo");
  } else {
    $target.append('<span>You clicked on a text</span>');
  }

});

.box {
  background-color: green;
  height: 50px;
  width: 50px;
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  some text
  <span class="box"></span>
</div>

<div>
  some text
</div>

<div><span class="box"></span></div>


问:
STL container leak
I'm using a vector container to hold instances of an object which contain 3 ints and 2 std::strings, this is created on the stack and populated from a function in another class but running the app through deleaker shows that the std::strings from the object are all leaked. Here's the code:

```<code>// Populator function:
void PopulatorClass::populate(std::vector<MyClass>& list) {
    // m_MainList contains a list of pointers to the master objects
    for( std::vector<MyClass*>::iterator it = m_MainList.begin(); it != m_MainList.end(); it++ ) {
        list.push_back(**it);
    }
}

// Class definition
class MyClass {
private:
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Code causing the problem:
std::vector<MyClass> list;
PopulatorClass.populate(list);
</code>```

When this is run through deleaker the leaked memory is in the allocator for the std::string classes.

I'm using Visual Studio 2010 (CRT).

Is there anything special I need to do to make the strings delete properly when unwinding the stack and deleting the vector?

Thanks,
J

答: May be Memory leak with std::vector<std::string> or something like this.

Title: STL container leak

Body:
I'm using a vector container to hold instances of an object which contain 3 ints and 2 std::strings, this is created on the stack and populated from a function in another class but running the app through deleaker shows that the std::strings from the object are all leaked. Here's the code:

// Populator function:
void PopulatorClass::populate(std::vector<MyClass>& list) {
    // m_MainList contains a list of pointers to the master objects
    for( std::vector<MyClass*>::iterator it = m_MainList.begin(); it != m_MainList.end(); it++ ) {
        list.push_back(**it);
    }
}

// Class definition
class MyClass {
private:
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Code causing the problem:
std::vector<MyClass> list;
PopulatorClass.populate(list);

When this is run through deleaker the leaked memory is in the allocator for the std::string classes.

I'm using Visual Studio 2010 (CRT).

Is there anything special I need to do to make the strings delete properly when unwinding the stack and deleting the vector?

Thanks,
J


答:
The response which you get from the server is static. So its come in NSDictionary. You need to alloc your own NSMutableDictionary and you have add all value into it.

```<code>NSMutableDictionary *dicYourData = [[NSMutableDictionary alloc] initWithDictionary:PASS_YOUR_RESPONSE_DIRECTORY];
</code>```

Now you can use dicYourData anywhere and make it updatable.

Title: Change value in NSDictionary

Body:
The response which you get from the server is static. So its come in NSDictionary. You need to alloc your own NSMutableDictionary and you have add all value into it.

NSMutableDictionary *dicYourData = [[NSMutableDictionary alloc] initWithDictionary:PASS_YOUR_RESPONSE_DIRECTORY];

Now you can use dicYourData anywhere and make it updatable.


问:
app.php shown as plain text on Symfony 3
Setting up my app to EC2 instance, I have the following virtual host:

```<code><VirtualHost *:80>
   ServerName melomaniacs.com

   ## Vhost docroot
   DocumentRoot "/var/www/html/myProject/web"
   DirectoryIndex  app.php

   ## Directories, there should at least be a declaration for /var/www/html/myProject/web

<Directory "/var/www/html/myProject/web">
       Options Indexes FollowSymLinks MultiViews
         AllowOverride None
         Order allow,deny
        Allow from All
        Satisfy Any
        <IfModule mod_rewrite.c>
            Options -MultiViews
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ app.php [QSA,L]
        </IfModule>
    </Directory>

   ## Logging
   ErrorLog "/var/log/httpd/melomaniacs_error.log"
   ServerSignature Off
   CustomLog "/var/log/httpd/melomaniacs_access.log" combined

   ## Server aliases
   ServerAlias *.melomaniacs.com
   SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

   ## Custom fragment

 </VirtualHost>
</code>```

But when I'm trying to get to app.php (When I access to the IP) I'm getting its content as plain text:

```<code>loadClassCache(); $kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);
</code>```

UPDATE:
 Just Tried to add into httpd.conf the line:

LoadModule php7_module modules/libphp7.so
but it it says:

```<code>[warn] module php7_module is already loaded, skipping when restarting apache.
</code>```

I have tried many possible configurations but I can't get it, any idea what's happening?

答: install php   and enable its extension for your web server</p>

Body:
Setting up my app to EC2 instance, I have the following virtual host:

<VirtualHost *:80>
   ServerName melomaniacs.com

   ## Vhost docroot
   DocumentRoot "/var/www/html/myProject/web"
   DirectoryIndex  app.php

   ## Directories, there should at least be a declaration for /var/www/html/myProject/web

<Directory "/var/www/html/myProject/web">
       Options Indexes FollowSymLinks MultiViews
         AllowOverride None
         Order allow,deny
        Allow from All
        Satisfy Any
        <IfModule mod_rewrite.c>
            Options -MultiViews
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteRule ^(.*)$ app.php [QSA,L]
        </IfModule>
    </Directory>

   ## Logging
   ErrorLog "/var/log/httpd/melomaniacs_error.log"
   ServerSignature Off
   CustomLog "/var/log/httpd/melomaniacs_access.log" combined

   ## Server aliases
   ServerAlias *.melomaniacs.com
   SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

   ## Custom fragment

 </VirtualHost>

But when I'm trying to get to app.php (When I access to the IP) I'm getting its content as plain text:

loadClassCache(); $kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel->handle($request); $response->send(); $kernel->terminate($request, $response);

UPDATE:
 Just Tried to add into httpd.conf the line:

LoadModule php7_module modules/libphp7.so
but it it says:

[warn] module php7_module is already loaded, skipping when restarting apache.

I have tried many possible configurations but I can't get it, any idea what's happening?


问:
can not resolve symbol 'from' Error in Android Studio
can not resolve symbol 'from' in

```<code>LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
</code>```

this is my complete class:

```<code>package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}
</code>```

What can i do?
please help me
thnx

答:
try this way my friend it will help you</p>

```<code>  View view = LayoutInflater.from(context).inflate(R.layout.cust_invitation, parent, false);
  ViewHolder viewHolder = new ViewHolder(view);
  return viewHolder;
</code>```

Body:
can not resolve symbol 'from' in

LayoutInflater inflater = new LayoutInflater.from(parent.getContext());

this is my complete class:

package ir.sangram.sangram.chat;

import android.content.Context;
import android.provider.ContactsContract;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

import de.hdodenhof.circleimageview.CircleImageView;
import ir.sangram.sangram.R;

/**
 * Created by HOW on 07/04/2017.
 */
class ChatListViewHolder extends RecyclerView.ViewHolder{
    public CircleImageView profile_picture;
    public TextView user_name, last_chat, unread_messages;
    public ChatListViewHolder(View itemView) {
        super(itemView);
        profile_picture = (CircleImageView) itemView.findViewById(R.id.profile_picture);
        user_name = (TextView) itemView.findViewById(R.id.user_name);
        last_chat = (TextView) itemView.findViewById(R.id.last_chat);
        unread_messages = (TextView) itemView.findViewById(R.id.unread_messages);
    }
}
public class ChatListAdapter extends RecyclerView.Adapter<ChatListViewHolder>{
    private List<ChatListData> chat_list = new ArrayList<ChatListData>();

    public ChatListAdapter(List<ChatListData> chat_list) {
        this.chat_list = chat_list;
    }

    @Override
    public ChatListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
        //LayoutInflater inflater;// = new LayoutInflater.from(parent.getContext());
        //inflater = ( LayoutInflater )parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);//!!!!!!!!!!
        View itemView = inflater.inflate(R.layout.chat_list_row,parent,false);
        return new ChatListViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ChatListViewHolder holder, int position) {
        holder.profile_picture.setImageResource(chat_list.get(position).getProfile_picture_id());
        holder.user_name.setText(chat_list.get(position).getUser_name());
        holder.unread_messages.setText(chat_list.get(position).getUnread_messages());
        holder.last_chat.setText(chat_list.get(position).getLast_chat());
    }

    @Override
    public int getItemCount() {
        return chat_list.size();
    }
}

What can i do?
please help me
thnx

Body:
try this way my friend it will help you

  View view = LayoutInflater.from(context).inflate(R.layout.cust_invitation, parent, false);
  ViewHolder viewHolder = new ViewHolder(view);
  return viewHolder;


问:
The best way to let asp.net fire events and methods automatically -according to a schedule-
Well, I'm sure this is not the first time to see this question. and TBH you can find this question answered on many other websites and blogs -not only here-

But I never saw a complete answer for this question, I mean no one talked about the advantages and the disadvantages. no one shared a real experience.

Although Quartz.NET seems like a good solution but yet, there's no enough reviews or a good comparison between the different ways to achieve such a thing.

As far as I read about it I found this are the possible ways of doing this :

Using a:  Web Service, Windows Appliction, Console Application, Quartz.NET.

Examples of stuff I want to achieve with the scheduled or automatic methods/events are like archiving after a certain period, auto deleting/moving records in the database, setting a property of an object after a certain time, automatically run some methods according to my holiday schedule.

I hope you'd share your experience either with one of those approaches or share a new way of doing this.

答:
Check out the following question that was asking something similar:

https://stackoverflow.com/questions/3243400/how-to-do-background-processing-similar-to-that-on-stackoverflow/

I linked to a blog post by Jeff Atwood himself that had a unique approach to accomplish this:

https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

I am not endorsing this approach but it's a good alternative if you don't want to make a service or use another tool.


问:
MEMORY_BASIC_INFORMATION.AllocationBase IMAGE_DOS_HEADER validity check
I'm using VirtualQueryEx to loop through memory allocation within a process. However, for some odd reason when comparing the allocationbase to the valid IMAGE_DOS_HEADER signature / 'MZ' I get an access violation... Could someone point out what is not correct in my code? </p>

```<code>MEMORY_BASIC_INFORMATION mbi;
do
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0)
   {
      continue;
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) &&
         !(mbi.Protect & PAGE_PROTECT))
   {
      if (mbi.AllocationBase != nullptr)
      {
         bool hasValidDosHeader = *(WORD*)mbi.AllocationBase ==
         IMAGE_DOS_SIGNATURE; //THIS CAUSES AN ACCESS VIOLATION
      }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);
</code>```

<p>PS: I've also tried casting the AllocationBase to an IMAGE_DOS_HEADER* and then checking e_magic with IMAGE_DOS_SIGNATURE, which also causes an access violation... </p>

答:
VirtualQueryEx returns information about the remote memory, but does not read it for you.

You need msdn: ReadProcessMemory to actually copy the memory from the remote process to your process in order to read the memory.

```<code>MEMORY_BASIC_INFORMATION mbi;
do
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0)
   {
      break; // we can't continue in the loop, as we don't know the size.
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) &&
         !(mbi.Protect & PAGE_PROTECT))
   {
       if (mbi.AllocationBase != nullptr)
       {
          IMAGE_DOS_HEADER dosHeader;
          if (ReadProcessMemory(handle, mbi.AllocationBase, &dosHeader, mbi.RegionSize, NULL)) {

              bool hasValidDosHeader = dosHeader.e_magic == IMAGE_DOS_SIGNATURE;
          }
       }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);
</code>```

Body:
I'm using VirtualQueryEx to loop through memory allocation within a process. However, for some odd reason when comparing the allocationbase to the valid IMAGE_DOS_HEADER signature / 'MZ' I get an access violation... Could someone point out what is not correct in my code?

MEMORY_BASIC_INFORMATION mbi;
do
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0)
   {
      continue;
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) &&
         !(mbi.Protect & PAGE_PROTECT))
   {
      if (mbi.AllocationBase != nullptr)
      {
         bool hasValidDosHeader = *(WORD*)mbi.AllocationBase ==
         IMAGE_DOS_SIGNATURE; //THIS CAUSES AN ACCESS VIOLATION
      }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);

PS: I've also tried casting the AllocationBase to an IMAGE_DOS_HEADER* and then checking e_magic with IMAGE_DOS_SIGNATURE, which also causes an access violation...

Body:
VirtualQueryEx returns information about the remote memory, but does not read it for you.

You need msdn: ReadProcessMemory to actually copy the memory from the remote process to your process in order to read the memory.

MEMORY_BASIC_INFORMATION mbi;
do
{
   if (VirtualQueryEx(handle, currentAddress, &mbi, sizeof(mbi)) == 0)
   {
      break; // we can't continue in the loop, as we don't know the size.
   }

   if (mbi.State & MEM_COMMIT && !(mbi.Protect & PAGE_NOACCESS) &&
         !(mbi.Protect & PAGE_PROTECT))
   {
       if (mbi.AllocationBase != nullptr)
       {
          IMAGE_DOS_HEADER dosHeader;
          if (ReadProcessMemory(handle, mbi.AllocationBase, &dosHeader, mbi.RegionSize, NULL)) {

              bool hasValidDosHeader = dosHeader.e_magic == IMAGE_DOS_SIGNATURE;
          }
       }
   }
   currentAddress += mbi.RegionSize;
} while(currentAddress < endAddress);


问:
Best way to submit/retrieve data from external server, when you have access to external server but not the same domain server
I'm working on an SDK type thing for submitting data (including file uploads) to a service that I run.

I'm doing research, and trying to figure out the best way to submit data and get a response to an external server (my server) without being blocked by XSS restrictions.

The current setup is as so:

The customer hosts a server, and uses my server side library.
They generate a client page that loads the required JS from my server.
The client page requests data from my server (if it was not passed from the SDK on page load), and displays the information to the user.
The user then triggers an event, which submits data (potentially including file uploads) to my server (not the local server with the SDK library).
My server responds success or fail and the client JS handles it appropriately.

Some notes:
My server is a private PHP server that I have complete control over.
Although I could route all data through the customer's server (as they are using my library), it is not ideal, as it requires more set up for the customer, is slower for the end user, and handling file uploads is problematic as I want those files on my server, not theirs.
I thought perhaps the file upload inputs could be in an iframe. Will this allow uploads direct to my server?
Since the customer is using my library with an API key, I can authenticate the client's requests by passing an authentication token to the front end on page load that then gets passed to my server with whatever communication method ends up working.

I am open to changes in the architecture, but this is the ideal set up for me. I am just not sure what frontend methods are best for implementing this.

答:
JSONP would work if you only need to make GET requests, but it sounds like you need to do POSTs as well since you mention file uploads.

For your case, Cross-Origin Resource Sharing (CORS) might work. The short explanation is that a browser will send an extra header named Origin if you make a request with XMLHttpRequest to another domain. Your server needs to respond with an additional header named Access-Control-Allow-Origin with a value of * or the value the browser sent in the Origin header. There are some nuances and gotchas when using CORS, so I recommend reading the link above for a thorough explanation.

With CORS set up, you should be able to use XMLHttpRequest to upload files.


问:
What's the most efficient way to search words in this kind of file by Ruby
I have a file like:

```<code>Fruit.Store={
    #blabla
    "customer-id:12345,item:store/apple" = 10;   #blabla
    "customer-id:23456,item:store/banana" = 10;   #blabla
    "customer-id:23456,item:store/watermelon" = 10;
    #blabla
    "customer-id:67890,item:store/watermelon" = 10;
}
</code>```

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file. When "12345" and "apple" are input, the first line should be returned. What's the most efficient way to solve this problem by Ruby? Thank you!

答:
```<code>def lookup(input, id, fruit)
  IO.foreach(input).detect do |line|
    line =~ %r|^\p{Space}*customer-id:#{id},item:store/#{fruit}|
  end
end
lookup("/path/to/file", 12345, 'apple')
#⇒ "    \"customer-id:12345,item:store/apple\" = 10;   #blabla\n"
</code>```

Body:
I have a file like:

Fruit.Store={
    #blabla
    "customer-id:12345,item:store/apple" = 10;   #blabla
    "customer-id:23456,item:store/banana" = 10;   #blabla
    "customer-id:23456,item:store/watermelon" = 10;
    #blabla
    "customer-id:67890,item:store/watermelon" = 10;
}

Except the comments, each line has the same format: customer-id and item:store/ are fixed, and customer-id is a 5-digit number. There are about 1000 unique lines in the file. When "12345" and "apple" are input, the first line should be returned. What's the most efficient way to solve this problem by Ruby? Thank you!


问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答:
Because first statement is true and it return from here. After return next line code is not executed.

function deepEqual(a, b) {
  if (a === b) {
    //return true;
  }

  if (a == null || typeof a != "object" ||
    b == null || typeof b != "object") {
    return false;
  }
}
var c = null;
console.log(deepEqual(c, c));```

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true


问:
how to check if any subarray doesn't contain an item from other subarray? Ruby
I have an array

```<code>animals = [
  [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
   {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
   {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
   {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"}]
]
</code>```

Every animal (Alex, Alf and Sonia) is described by colour, health and age (vname values), but Alf does not have his hash with age in third subarray and Sonia does not have her hashes with health (second subarray) and age (third subarray). I want to check if any subarray does not have "vname" pair for some dog and if doesn't to add hash like this

```<code>{"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"}
</code>```

to get an array

```<code>animals = [
 [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
  {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
  {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "health", "value" => "unknown"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"},
  {"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "age", "value" => "unknown"}]
]
</code>```

Can You help me with this?

答:
Umm. Set the names in an Array. Loop through your animals array and for each of the array inside, check if has hash for all animal names. Add the default hash for those that are missing.

```<code>    animal_names = ["Alex", "Alf", "Sonia"]

    animals.each do |animals_by_vname|
      vname         = animals_by_vname.first["vname"]
      names_present = animals_by_vname.map {|i| i["name"]}
      names_missing = animal_names - names_present

      names_missing.each do |name|
        animals_by_vname << {
          "name"   => name,
          "spices" => "dog",
          "vname"  => vname,
          "value"  => "unknown"
        }
      end
    end

    puts animals # should be you wanted it.
</code>```

That solves your problem.

However, I honestly believe, the data structure needs to be optimised. Maybe have a hash of arrays with animal names as keys. Like:

```<code>    {
      "Alex": { health: "good" }
      "Alf": { age: 10, health: "good" }
    }
</code>```

Body:
I have an array

animals = [
  [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
   {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
   {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
   {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"}]
]

Every animal (Alex, Alf and Sonia) is described by colour, health and age (vname values), but Alf does not have his hash with age in third subarray and Sonia does not have her hashes with health (second subarray) and age (third subarray). I want to check if any subarray does not have "vname" pair for some dog and if doesn't to add hash like this

{"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"}

to get an array

animals = [
 [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
  {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
  {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "health", "value" => "unknown"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"},
  {"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "age", "value" => "unknown"}]
]

Can You help me with this?

Body:
Umm. Set the names in an Array. Loop through your animals array and for each of the array inside, check if has hash for all animal names. Add the default hash for those that are missing.

    animal_names = ["Alex", "Alf", "Sonia"]

    animals.each do |animals_by_vname|
      vname         = animals_by_vname.first["vname"]
      names_present = animals_by_vname.map {|i| i["name"]}
      names_missing = animal_names - names_present

      names_missing.each do |name|
        animals_by_vname << {
          "name"   => name,
          "spices" => "dog",
          "vname"  => vname,
          "value"  => "unknown"
        }
      end
    end

    puts animals # should be you wanted it.

That solves your problem.

However, I honestly believe, the data structure needs to be optimised. Maybe have a hash of arrays with animal names as keys. Like:

    {
      "Alex": { health: "good" }
      "Alf": { age: 10, health: "good" }
    }


问:
How do I get value after selected from dropdown menu with Python?
I want the last value from this dropdown menu.

```<code><select id="VersionValue">
  <option value="0">Select Version</option>
  <option value="1110.0">1110.0</option>
  <option value="1111.0">1111.0</option>
  <option value="1112.0">1112.0</option>
  <option value="1113.0">1113.0</option>
  <option value="1114.0">1114.0</option>
</select>
</code>```

My code in python to get last dropdown menu

```<code>    select = Select(driver.find_element_by_id("VersionValue"))
    selectLen = len(select.options)
    select.select_by_index(selectLen - 1)
</code>```

How do I get value after selected from dropdown menu with Python?
I use selenium library for python.

答:
You have first_selected_option, use it after selecting the value

```<code>option = select.first_selected_option
</code>```

This will return the webelement of the option. To get the value use

```<code>option.text
</code>```

Or

```<code>option.get_attribute("value")
</code>```

Body:
I want the last value from this dropdown menu.

<select id="VersionValue">
  <option value="0">Select Version</option>
  <option value="1110.0">1110.0</option>
  <option value="1111.0">1111.0</option>
  <option value="1112.0">1112.0</option>
  <option value="1113.0">1113.0</option>
  <option value="1114.0">1114.0</option>
</select>

My code in python to get last dropdown menu

    select = Select(driver.find_element_by_id("VersionValue"))
    selectLen = len(select.options)
    select.select_by_index(selectLen - 1)

How do I get value after selected from dropdown menu with Python?
I use selenium library for python.

Body:
You have first_selected_option, use it after selecting the value

option = select.first_selected_option

This will return the webelement of the option. To get the value use

option.text

Or

option.get_attribute("value")


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
Yes.

From "The Pragmatic Programmer" p.292:

By setting a reference to NULL you reduce the number of pointers to the object by one ... (which will allow the garbage collector to remove it)

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

OwnerDisplayName: James Brooks


问:
jquery - Why do these appended divs ignore their css?
I'm appending some div's with jquery.
And gave them size and color with css.
However they don't seem to pick up on the css?
And how can put some of the divs inside others

Here is my code
http://jsfiddle.net/Eqxzz/

答: You have no CSS applying to #drag1, or #drag2, etc. I think you have classes and IDs mixed up here. Try using a class on your elements and apply the style through that class.</p>


问:
PHP Extract HTML content by HTML parse get null object
I am trying to extract content from a local HTML file. And I use the HTML parse method, however get nothing.

PHP code is as below:

```<code>$doc = new \DOMDocument();
$doc->loadHTML("assets.html");
$tables = $doc->getElementsByTagName('table');
foreach($tables as $table) {
   $content = $doc->saveHTML($table);
 }
echo $content;
</code>```

Debug step by step,$doc->loadHTML("assets.html") return true,and got DOMNodeList::__set_state(array(
)) for $tables .

The part of assets.html is as below:

                                    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
                                            新增

                                        </button>

增加资产

增加明细

                                    <button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
                                    <button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
                                    <button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>

                                          序号
                                          资产类别
                                          资产名称
                                          型号
                                          单位
                                          数量

```

答:
Found some mistake in your code.

1 : You can not use loadHTML method for load html.

2 : In your HTML file some tags are not properly closing.

Check below code,

PHP

```<code><?php
    $dom = new DomDocument();
    $dom->loadHTML(file_get_contents('assets.html'));
    $tables = $dom->documentElement->getElementsByTagName('table');
    foreach($tables as $table) {
        $content = $dom->saveHTML($table);
    }
    echo $content;
?>
</code>```

HTML

```<code><div class="btn-group">
    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
            新增
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu " role="menu">
        <li><a href="#" id="newassets">增加资产</a></li>
        <li><a href="#" id="newdetail">增加明细</a></li>
    </ul>
</div>
<button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
<button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
<button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>
<div class="dataTable_hr_info">
    <table class="table table-striped table-bordered table-hover" action="" id="assetsInfo">
        <thead>
            <tr>
                <th data-field="state" data-checkbox="true"></th>
                <th data-field="pr" >1</th>
                <th data-field="category">2</th>
                <th data-field="name" >3</th>
                <th data-field="model">4</th>
                <th data-field="unit">5</th>
                <th data-field="count">6</th>
            </tr>
        </thead>
    </table>
</div>
</code>```

Body:
I am trying to extract content from a local HTML file. And I use the HTML parse method, however get nothing.

PHP code is as below:

$doc = new \DOMDocument();
$doc->loadHTML("assets.html");
$tables = $doc->getElementsByTagName('table');
foreach($tables as $table) {
   $content = $doc->saveHTML($table);
 }
echo $content;

Debug step by step,$doc->loadHTML("assets.html") return true,and got DOMNodeList::__set_state(array(
)) for $tables .

The part of assets.html is as below:

                                    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
                                            新增

                                        </button>

增加资产

增加明细

                                    <button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
                                    <button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
                                    <button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>

                                          序号
                                          资产类别
                                          资产名称
                                          型号
                                          单位
                                          数量

Body:
Found some mistake in your code.

1 : You can not use loadHTML method for load html.

2 : In your HTML file some tags are not properly closing.

Check below code,

PHP

<?php
    $dom = new DomDocument();
    $dom->loadHTML(file_get_contents('assets.html'));
    $tables = $dom->documentElement->getElementsByTagName('table');
    foreach($tables as $table) {
        $content = $dom->saveHTML($table);
    }
    echo $content;
?>

HTML

<div class="btn-group">
    <button type="button" class="btn btn-info dropdown-toggle" id="manage" data-toggle="dropdown">
            新增
    <span class="caret"></span>
    </button>
    <ul class="dropdown-menu " role="menu">
        <li><a href="#" id="newassets">增加资产</a></li>
        <li><a href="#" id="newdetail">增加明细</a></li>
    </ul>
</div>
<button type="button" class="btn btn-danger" id="deleteassets" value="" >删除</button>
<button type="button" class="btn btn-success" id="modifyassets" value="" >修改</button>
<button type="button" class="btn btn-warning" id="lend-lease" value="" >领用</button>
<div class="dataTable_hr_info">
    <table class="table table-striped table-bordered table-hover" action="" id="assetsInfo">
        <thead>
            <tr>
                <th data-field="state" data-checkbox="true"></th>
                <th data-field="pr" >1</th>
                <th data-field="category">2</th>
                <th data-field="name" >3</th>
                <th data-field="model">4</th>
                <th data-field="unit">5</th>
                <th data-field="count">6</th>
            </tr>
        </thead>
    </table>
</div>


答:
You're calling LayoutInflater.from as if you were calling a constructor:

```<code>LayoutInflater inflater = new LayoutInflater.from(parent.getContext());
</code>```

That's a mixture of constructor-call syntax (new) and method call syntax (.from). It would work if LayoutInflater.from were a static nested class, but it's not... it's just at static method. So you want:

```<code>LayoutInflater inflater = LayoutInflater.from(parent.getContext());
</code>```

Title: can not resolve symbol 'from' Error in Android Studio

Body:
You're calling LayoutInflater.from as if you were calling a constructor:

LayoutInflater inflater = new LayoutInflater.from(parent.getContext());

That's a mixture of constructor-call syntax (new) and method call syntax (.from). It would work if LayoutInflater.from were a static nested class, but it's not... it's just at static method. So you want:

LayoutInflater inflater = LayoutInflater.from(parent.getContext());


问:
Error : JAVA_HOME is pointing to invalid version of java while Installing Maximo Anywhere 7.6.2 on MAC OSX
I am trying to install Maximo Anywhere 7.6.2 on MAC OSX by referring to documentation on ibm site below :

Maximo_Anywhere_7_6_1_Installation_Start_to_Finish.pdf

On my mac I have  jdk1.8.0_131.jdk  which is set as  export  JAVA_HOME  as well as in ~/.bash_profile.

But  IBM installation manager has taken  jre version
as  " Java SE 1.7.0_111". I verified it in /Applications/IBM/InstallationManager/eclipse/jre_7.0.90060.20161108_1344

So when I try to Install IBM Anywhere component using IBM installation manager
i get the error

I referred to this IBM support link but it is not working.

Please Help

答:
I have just struggled with identical problem. In case of MacOS installation simple export JAVA_HOME=... may not be sufficient due to default sudo security restrictions (at least this was the case on my MacOS 10.12).
By default sudo environment inherits only subset of current process environment variables. There is no JAVA_HOME among them so when you start Installation Manager it will fail at one of the first prerequisites checks with following error:

```<code>The JAVA_HOME environment variable is pointing to an invalid version of Java. Install Oracle JDK and update the JAVA_HOME environment variable to contain the path of the JDK installation directory.
The JAVA_HOME environment variable is pointing to a directory that does not contain a java that was vended by Oracle Corporation or SunMicrosystems Inc.
Update JAVA_HOME so that java.vendor is set to either Oracle Corporation or Sun Microsystems Inc.
</code>```

Solution to this problem is to edit sodoers file (sudo visudo) and add one more line to Defaults section. In my case it was:

```<code>##
## Defaults specification
##

Defaults    env_reset
Defaults    env_keep += "BLOCKSIZE"
Defaults    env_keep += "COLORFGBG COLORTERM"
[...]
# Newly added line
Defaults    env_keep += "JAVA_HOME"
</code>```

Once this was done installation went smoothly.

Body:
I have just struggled with identical problem. In case of MacOS installation simple export JAVA_HOME=... may not be sufficient due to default sudo security restrictions (at least this was the case on my MacOS 10.12).
By default sudo environment inherits only subset of current process environment variables. There is no JAVA_HOME among them so when you start Installation Manager it will fail at one of the first prerequisites checks with following error:

The JAVA_HOME environment variable is pointing to an invalid version of Java. Install Oracle JDK and update the JAVA_HOME environment variable to contain the path of the JDK installation directory.
The JAVA_HOME environment variable is pointing to a directory that does not contain a java that was vended by Oracle Corporation or SunMicrosystems Inc.
Update JAVA_HOME so that java.vendor is set to either Oracle Corporation or Sun Microsystems Inc.

Solution to this problem is to edit sodoers file (sudo visudo) and add one more line to Defaults section. In my case it was:

##
## Defaults specification
##

Defaults    env_reset
Defaults    env_keep += "BLOCKSIZE"
Defaults    env_keep += "COLORFGBG COLORTERM"
[...]
# Newly added line
Defaults    env_keep += "JAVA_HOME"

Once this was done installation went smoothly.


问:
Apply css style to all components in Angular 2 app
I have very basic, and reusable css rules, such as:

```<code>.ng-invalid {
    border-left: 5px solid #a94442;
}

.ng-valid {
    border-left: 5px solid #42A948;
}
</code>```

I'd like to re-use these for all of my components. If I place this in my root AppComponent, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent.

I must be missing something very obvious here.

答:
You can write your CSS inside src/styles.css

or you can create your new CSS file and specify inside .angular-cli.json file

```<code>"apps": [
  "styles": ["styles.scss"]
]
</code>```

Body:
I have very basic, and reusable css rules, such as:

.ng-invalid {
    border-left: 5px solid #a94442;
}

.ng-valid {
    border-left: 5px solid #42A948;
}

I'd like to re-use these for all of my components. If I place this in my root AppComponent, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent.

I must be missing something very obvious here.

Body:
You can write your CSS inside src/styles.css

or you can create your new CSS file and specify inside .angular-cli.json file

"apps": [
  "styles": ["styles.scss"]
]


问:
How Spring Cloud Config Server PUSH plain text files to Config Client Application?
What I have implemented so far are:

Spring Cloud Config Server with "native" repo.

spring.profiles.active: native

spring.cloud.config.server.native.searchLocations: file:/path/to/config-repo

Config Server is pushing notification to Config Client App through RabbitMQ, as http://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_push_notifications_and_spring_cloud_bus

Config Client App has @RefreshScope annotated on Service bean.

So /config-repo has 3 files - application.yaml, client.yaml and client.json
All yaml properties changes will be auto reloaded by Config Client App for sure. However, client.json didn't.

Based on https://github.com/spring-cloud/spring-cloud-config/issues/147, I can fetch the file on Config Client App through REST api call to Config Server, with /{appname}/{profile}/{label}/client.json

Question are:

1) Is Config Server monitoring this plain text file changes by "native"?

2) how can Config Client App auto reload this client.json once it's updated? (I can have schedule task to call Config server, but this isn't ideal.)

答:
the Config client:
restTemplate.getForObject("http://localhost:8080/application/default/master/testing-dev.json",String.class);

can get the .json suffix file content ,but i think it don't get the file content ,have other way to get the file content


问:
centering text positioning using flexbox
Trying to do a simple website recreation using flexbox. Here is the final goal (for this step):

Pretty simple. But I am struggling with aligning the text. I am able to get the header to center just fine. It's mainly the paragraph underneath that I am having trouble centering. Is there a way to center that paragraph vertically and horizontally to its outer container? New to flexbox and would like any tips! Here is a link to my codepen and relevant code: https://codepen.io/gkunthara/pen/qjympg

HTML

```<code> <div class = "content-container">
<h1 class = "main-header"> Connect with Subscribers Effortlessly </h1>
 <p class = "sub-header"> Email Marketing Platform for Bloggers &
Authors. </p>
 </div>
</code>```

CSS

```<code> .content-container  .main-header{

  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height:75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;

}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
  margin-top: 150px;
}
</code>```

答:
If you remove the margin-top in your .content-container .sub-header rule and add flex-direction: column; align-items: center; to your .content-container the text will center properly

Updated codepen

Stack snippet

* {
  box-sizing: border-box;
}

.header-container {
  display: flex;
  width: 100%;
  height: 100px;
  align-items: center;
  justify-content: space-between;
  padding-left: 50px;
  padding-right: 75px;
}

.header-container .logo {
  width: 250px;
}

.header-container .logo .sb {
  max-width: 100%;
}

.header-container .nav-bar-container {
  display: flex;
}

.nav-link {
  text-decoration: none;
  color: #4B4B4B;
  font-weight: bold;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  padding: 15px;
}

.content-container {
  width: 100%;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-style: solid;
  margin-top: 15px;
}

.content-container .main-header {
  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height: 75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;
}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
}

/* Resize window to see its effect */

@media( max-width: 700px) {
  .header-container {
    flex-direction: column;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header-container">
   <img class="sb" src="logo.png" alt="logo">
  <nav class="nav-bar-container">
     Tour
     Pricing
     Medium
     Sign Up
     Login
  </nav>
</div>

<div class="content-container">
  <h1 class="main-header"> Connect with Subscribers Effortlessly </h1>
  <p class="sub-header"> Email Marketing Platform for Bloggers & Authors. </p>
</div></code>```

If you intended to center the .content-container .sub-header w/o take the .content-container  .main-header into account, you need to position the .content-container  .main-header absolute

With this, it will work with or w/o the flex-direction: column;, which I added in the first solution.

Note though, that on less wider screen you need to adjust both, or else they will overlap

Updated codepen

Added these properties to your .content-container  .main-header

```<code>position: absolute;
top: 0;
left: 0;
right: 0;
text-align: center;
</code>```

Body:
Trying to do a simple website recreation using flexbox. Here is the final goal (for this step):

Pretty simple. But I am struggling with aligning the text. I am able to get the header to center just fine. It's mainly the paragraph underneath that I am having trouble centering. Is there a way to center that paragraph vertically and horizontally to its outer container? New to flexbox and would like any tips! Here is a link to my codepen and relevant code: https://codepen.io/gkunthara/pen/qjympg

HTML

 Connect with Subscribers Effortlessly

 Email Marketing Platform for Bloggers &
Authors.

CSS

 .content-container  .main-header{

  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height:75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;

}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
  margin-top: 150px;
}

Body:
If you remove the margin-top in your .content-container .sub-header rule and add flex-direction: column; align-items: center; to your .content-container the text will center properly

Updated codepen

Stack snippet

* {
  box-sizing: border-box;
}

.header-container {
  display: flex;
  width: 100%;
  height: 100px;
  align-items: center;
  justify-content: space-between;
  padding-left: 50px;
  padding-right: 75px;
}

.header-container .logo {
  width: 250px;
}

.header-container .logo .sb {
  max-width: 100%;
}

.header-container .nav-bar-container {
  display: flex;
}

.nav-link {
  text-decoration: none;
  color: #4B4B4B;
  font-weight: bold;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  padding: 15px;
}

.content-container {
  width: 100%;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-style: solid;
  margin-top: 15px;
}

.content-container .main-header {
  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height: 75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;
}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
}

/* Resize window to see its effect */

@media( max-width: 700px) {
  .header-container {
    flex-direction: column;
  }
}

<div class="header-container">
  <a class="logo"> <img class="sb" src="logo.png" alt="logo"> </a>
  <nav class="nav-bar-container">
    <a class="nav-link" href="#"> Tour </a>
    <a class="nav-link" href="#"> Pricing </a>
    <a class="nav-link" href="#"> Medium </a>
    <a class="nav-link" href="#"> Sign Up </a>
    <a class="nav-link" href="#"> Login </a>
  </nav>
</div>

<div class="content-container">
  <h1 class="main-header"> Connect with Subscribers Effortlessly </h1>
  <p class="sub-header"> Email Marketing Platform for Bloggers & Authors. </p>
</div>

If you intended to center the .content-container .sub-header w/o take the .content-container  .main-header into account, you need to position the .content-container  .main-header absolute

With this, it will work with or w/o the flex-direction: column;, which I added in the first solution.

Note though, that on less wider screen you need to adjust both, or else they will overlap

Updated codepen

Added these properties to your .content-container  .main-header

position: absolute;
top: 0;
left: 0;
right: 0;
text-align: center;


问:
Mysql error 1045 - access denied for 'db_user'@'@localhost' (with two at symbols @)
I installed WAMP (last version: 3.0.6) on a new PC. I extracted a database from my old PC and imported it through phpMyAdmin. I created a user ('db_user'@'%') with all the rights to access this database (every rights on everything, indeed).

When I connect to phpMyAdmin with this user it works but when I try to connect through a web-interface using PHP, I get the following error message:

1045 - access denied for 'db_user'@'@localhost')

My connector PHP file looks like this:

```<code>define("HOST", "localhost");
define("USER", "db_user");
define("PASSWORD", "a_password");
define("DATABASE", "my_test_db");
define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$mysqli->set_charset("utf8");
</code>```

The same thing was working on my old computer.
What can I do?

答:
```<code>define("HOST", "localhost");
define("USER", "db_user");
define("PASSWORD", "a_password");
define("DATABASE", "my_test_db");
define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");

mysqli_report(MYSQLI_REPORT_STRICT);

try {
     $mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
     $mysqli->set_charset("utf8");
} catch (Exception $e ) {
     echo "Service unavailable";
     echo "message: " . $e->message;   // not in live code obviously...
     exit;
}
</code>```

Body:
I installed WAMP (last version: 3.0.6) on a new PC. I extracted a database from my old PC and imported it through phpMyAdmin. I created a user ('db_user'@'%') with all the rights to access this database (every rights on everything, indeed).

When I connect to phpMyAdmin with this user it works but when I try to connect through a web-interface using PHP, I get the following error message:

1045 - access denied for 'db_user'@'@localhost')

My connector PHP file looks like this:

define("HOST", "localhost");
define("USER", "db_user");
define("PASSWORD", "a_password");
define("DATABASE", "my_test_db");
define("CAN_REGISTER", "any");
define("DEFAULT_ROLE", "member");

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$mysqli->set_charset("utf8");

The same thing was working on my old computer.
What can I do?


问:
Running PostgreSQL commands from anywhere on the terminal
First off, let me say that I'm new to both using Mac and PostgreSQL. I just installed Postgres using their installer and it was installed in /Library/Postgres/... when I tried running createdb from the terminal it returned an error createdb: command not found. I ended up using /library/postgresql/9.6/bin/createdb before I coud get it to work.
Here's my question, how do I set it so that I don't have to type in the full path again to use the createdb command.
I'd love a detailed explanation.
Thanks

答:
First you need to execute the psql command to get into the postgresql interacive shell.

In your terminal:

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

Postgresql interactive shell should start. In this shell

```<code>> createdb yourdatabasename;
</code>```

Btw: If psql is not found you will probably need to add it to your path and restart your terminal, something like this with the path matching your machine:

```<code>export PATH=/Library/PostgreSQL/9.5/bin:$PATH
</code>```

Body:
First you need to execute the psql command to get into the postgresql interacive shell.

In your terminal:

psql

Postgresql interactive shell should start. In this shell

> createdb yourdatabasename;

Btw: If psql is not found you will probably need to add it to your path and restart your terminal, something like this with the path matching your machine:

export PATH=/Library/PostgreSQL/9.5/bin:$PATH


问:
What is the reason of UnknownHostException in android application?
I am facing a strange problem.

I am trying to access a server from Samsung Galaxy Nexus. Things work fine most of the times, however I have observed that sometimes, the application running on the mobile is not able to connect to the server, below is the exception trace.

When this scenario occurs, the application is not able to reach the server consistently. Once when this issue was reproduced, I tried opening the URL in the browser on the phone, and the URL opened. However, in the application, we were still facing issues. I force stopped the application and started again, still the same issue. Ultimately, I had to reset my wifi and post that, everything worked fine.

Please note that the actual URL mentioned here has been hidden for confidentiality issues.

Any comments please?

Regards,

----- logs start

WARNING: (2160,e,ProtocolObjectHTTP)http EX:ConnectExceptionfailed to

connect to abc-def.csrlbs.com/50.19.101.191 (port 80): connect failed:
  ETIMEDOUT (Connection timed out)  java.net.ConnectException: failed to
  connect to abc-def.csrlbs.com/50.19.101.191 (port 80): connect failed:
  ETIMEDOUT (Connection timed out)  at
  libcore.io.IoBridge.connect(IoBridge.java:114)    at
  java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)    at
  java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)    at
  java.net.Socket.connect(Socket.java:842)  at
  libcore.net.http.HttpConnection.(HttpConnection.java:76)    at
  libcore.net.http.HttpConnection.(HttpConnection.java:50)    at
  libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
    at
  libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    at
  libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)     at
  libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)    at
  libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)  at
  libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
    at
  libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
    at com.sirf.pal.android.ProtocolObjectHTTP.a(SourceFile:138)    at
  com.sirf.pal.android.e.a(SourceFile:265)  at
  com.sirf.pal.android.ProtocolObjectHTTP.run(SourceFile:524)   at
  java.lang.Thread.run(Thread.java:856) Caused by:
  libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed
  out)  at libcore.io.Posix.connect(Native Method)  at
  libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)     at
  libcore.io.IoBridge.connectErrno(IoBridge.java:127)   at
  libcore.io.IoBridge.connect(IoBridge.java:112)    ... 18 more

Nov 28, 2012 12:00:50 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed1
  Nov 28, 2012 12:00:50 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:51 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed2
  Nov 28, 2012 12:00:51 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:52 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed3
  Nov 28, 2012 12:00:52 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:52 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:54 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed1
  Nov 28, 2012 12:00:54 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:55 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed2
  Nov 28, 2012 12:00:55 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:56 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed3
  Nov 28, 2012 12:00:56 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:56 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

Nov 28, 2012 12:00:57 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostException wait completed1
  Nov 28, 2012 12:00:57 PM com.sirf.pal.android.d a WARNING:
  (2160,e,ProtocolObjectHTTP)http UnknownHostExceptionUnable to resolve
  host "abc-def.csrlbs.com": No address associated with hostname

----- logs end

答:
(1) Please check that you have added the following android permissions

```<code><uses-permission android:name="android.permission.INTERNET" />
</manifest>
</code>```

(2) There is a known issue in android if underscores are used in your domain. Verify that your domain does not use underscores.Having a underscore in a domain is invalid and will throw an unknown host exception.

(3) Check your internet connection is ON and can access the domain name from your device.

Body:
(1) Please check that you have added the following android permissions

<uses-permission android:name="android.permission.INTERNET" />
</manifest>

(2) There is a known issue in android if underscores are used in your domain. Verify that your domain does not use underscores.Having a underscore in a domain is invalid and will throw an unknown host exception.

(3) Check your internet connection is ON and can access the domain name from your device.


问:
How to do math operation on imported csv data?
I have read in a csv file ('Air.csv') and have performed some operations to get rid of the header (not important). Then, I used dB_a.append(row[1]) to put this column of the csv data into an array which I could later plot.

This data is dB data, and I want to convert this to power using the simple equation P = 10^(dB/10) for every value. I am new to Python, so I don't quite understand how operations within arrays, lists, etc. works. I think there is something I need to do to iterate over that full data set, which was my attempt at a for loop, but I am still receiving errors. Any suggestions?

Thank you!

```<code>frequency_a=[]
dB_a=[]

a = csv.reader(open('Air.csv'))

for row in itertools.islice(a, 18, 219):
       frequency_a.append(row[0])
       dB_a.append(row[1])
       #print(frequency_a)
       print(dB_a)

for item in dB_a:
    power_a = 10**(dB_a/10)
    print(power_a)
</code>```

答:
In your for loop, item is the iterator, so you need to use that. So instead of:

```<code>power_a = 10**(dB_a/10)
</code>```

use:

```<code>power_a = 10**(item/10)
</code>```

A nicer way to create a new list with that data could be:

```<code>power_a = [10**(db/10) for db in dB_a]
</code>```

EDIT: The other issue as pointed out in the comment, is that the values are strings. The .csv file is essentially a text file, so a collection of string, rather than integers. What you can do is convert them to numeric values using int(db) or float(db), depending whether you have whole or floating point numbers.

EDIT2: As pointed out by @J. Meijers, I was using multiplication instead of exponentiation - this has been fixed in the answer.

Body:
I have read in a csv file ('Air.csv') and have performed some operations to get rid of the header (not important). Then, I used dB_a.append(row[1]) to put this column of the csv data into an array which I could later plot.

This data is dB data, and I want to convert this to power using the simple equation P = 10^(dB/10) for every value. I am new to Python, so I don't quite understand how operations within arrays, lists, etc. works. I think there is something I need to do to iterate over that full data set, which was my attempt at a for loop, but I am still receiving errors. Any suggestions?

Thank you!

frequency_a=[]
dB_a=[]

a = csv.reader(open('Air.csv'))

for row in itertools.islice(a, 18, 219):
       frequency_a.append(row[0])
       dB_a.append(row[1])
       #print(frequency_a)
       print(dB_a)

for item in dB_a:
    power_a = 10**(dB_a/10)
    print(power_a)

Body:
In your for loop, item is the iterator, so you need to use that. So instead of:

power_a = 10**(dB_a/10)

use:

power_a = 10**(item/10)

A nicer way to create a new list with that data could be:

power_a = [10**(db/10) for db in dB_a]

EDIT: The other issue as pointed out in the comment, is that the values are strings. The .csv file is essentially a text file, so a collection of string, rather than integers. What you can do is convert them to numeric values using int(db) or float(db), depending whether you have whole or floating point numbers.

EDIT2: As pointed out by @J. Meijers, I was using multiplication instead of exponentiation - this has been fixed in the answer.