问:
JavaScript regex look behind alternative
I am trying to match the following string into 2 groups using look behind but apparently, they are not supported in JavaScript.

Regex: ((?<=:).*(?=;))|((?<=,).*$)  Online Demo

```<code>data:image/jpeg;base64,/abcd1234...

--> group1: image/jpeg
--> group2: /abcd1234...
</code>```

Then I tried to use XRegExp library hoping it would support look behind but still no success.

```<code>var XRegExp = require("xregexp");
var base64 = "data:image/jpeg;base64,/abcd1234...";
base64 = XRegExp.matchRecursive(base64, '((?<=:).*(?=;))|((?<=,).*$)', 'g');
</code>```

But I get the following error:

```<code>node_modules/xregexp/xregexp-all.js:3376
        new RegExp(generated.pattern, generated.flags),
        ^
SyntaxError: Invalid regular expression: /((?<=:).*(?=;))|((?<=,).*$)/: Invalid group at new RegExp (native)
</code>```

Is there a way to run the regex using JavaScript's native regex parser probably by reversing the string?

答:
Be more specific:

```<code>(?=[^:;]*;)([^:;]+)|([^;,]+)$
</code>```

Live demo

Or use more JS:

var re = /:([^:;]+);|,(.*)$/g;
var str = "data:image/jpeg;base64,/abcd1234...";
var matches;
while ((matches = re.exec(str)) !== null) {
  console.log(matches[1] ? matches[1] : matches[2])
}```

Body:
I am trying to match the following string into 2 groups using look behind but apparently, they are not supported in JavaScript.

Regex: ((?<=:).*(?=;))|((?<=,).*$)  Online Demo

data:image/jpeg;base64,/abcd1234...

--> group1: image/jpeg
--> group2: /abcd1234...

Then I tried to use XRegExp library hoping it would support look behind but still no success.

var XRegExp = require("xregexp");
var base64 = "data:image/jpeg;base64,/abcd1234...";
base64 = XRegExp.matchRecursive(base64, '((?<=:).*(?=;))|((?<=,).*$)', 'g');

But I get the following error:

node_modules/xregexp/xregexp-all.js:3376
        new RegExp(generated.pattern, generated.flags),
        ^
SyntaxError: Invalid regular expression: /((?<=:).*(?=;))|((?<=,).*$)/: Invalid group at new RegExp (native)

Is there a way to run the regex using JavaScript's native regex parser probably by reversing the string?

Body:
Be more specific:

(?=[^:;]*;)([^:;]+)|([^;,]+)$

Live demo

Or use more JS:

var re = /:([^:;]+);|,(.*)$/g;
var str = "data:image/jpeg;base64,/abcd1234...";
var matches;
while ((matches = re.exec(str)) !== null) {
  console.log(matches[1] ? matches[1] : matches[2])
}


来源: stackexchange

问:
Can't load page in Spring MVC
I want to add a page in my spring MVC. I can call the index file but I can't click on the link in index.jsp to show page product.jsp. Its error message is "The requested resource is not available".

Below is my controller code:

```<code>@RequestMapping({"/", "/index"})
public String index(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "index";
}

@RequestMapping({"/product"})
public String product(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "product";
}
</code>```

this index.jsp

```<code><div class="row">
   <div class="col-sm-4 menu-img-pad">
       <ul class="multi-column-dropdown">
          <li><a href="../product.jsp">Joggers</a></li>
          <li><a href="../product.jsp">Foot Ball</a></li>
          <li><a href="../product.jsp">Cricket</a></li>
       </ul>
   </div>
</div>
</code>```

答:
Add below configuration to dispatcher-servlet.xml

```<code><bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>
</code>```

In above configuration,views is folder name where container will look for your product.jsp file

ContentLicense: CC BY-SA 4.0

Title: Can't load page in Spring MVC

Body:
I want to add a page in my spring MVC. I can call the index file but I can't click on the link in index.jsp to show page product.jsp. Its error message is "The requested resource is not available".

Below is my controller code:

@RequestMapping({"/", "/index"})
public String index(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "index";
}

@RequestMapping({"/product"})
public String product(ModelMap model, HttpSession session, Principal principal) throws Exception {
    return "product";
}

this index.jsp

Joggers

Foot Ball

Cricket

Body:
Add below configuration to dispatcher-servlet.xml

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

In above configuration,views is folder name where container will look for your product.jsp file

ContentLicense: CC BY-SA 3.0


问:
EXCEL - Multiple Arrays within COUNTIF formula
Attempting to count:

Named range "STATUS" if the value of the cells equals Reserved, Blocked, Pending OR Archive

AND

Named range "COMPANY" equals Company A, Company B OR Company C.

I'm also counting multiple other criteria, all of the which are working. When I added the array for the Company the formula is no longer counting the Status.

Here is the formula I'm using:

```<code>=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A","COMPANY B","COMPANY C"},STATUS,{"Reserved","Blocked","Pending","Archive"})))
</code>```

Any help is greatly appreciated and thank you in advance!

答:
Try this

```<code>=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A";"COMPANY B";"COMPANY C"},STATUS,{"Reserved","Blocked","Pending","Archive"})))
</code>```

or

```<code>=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A","COMPANY B","COMPANY C"},STATUS,{"Reserved";"Blocked";"Pending";"Archive"})))
</code>```

Note the ; instead of , in arrays. For details on why to use semi-colon instead of comma see this.

If you want to use your formula it should be as follows

```<code>=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY A",STATUS,{"Reserved","Blocked","Pending","Archive"}))) +
SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY B",STATUS,{"Reserved","Blocked","Pending","Archive"}))) +
SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY C",STATUS,{"Reserved","Blocked","Pending","Archive"})))
</code>```

Body:
Attempting to count:

Named range "STATUS" if the value of the cells equals Reserved, Blocked, Pending OR Archive

AND

Named range "COMPANY" equals Company A, Company B OR Company C.

I'm also counting multiple other criteria, all of the which are working. When I added the array for the Company the formula is no longer counting the Status.

Here is the formula I'm using:

=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A","COMPANY B","COMPANY C"},STATUS,{"Reserved","Blocked","Pending","Archive"})))

Any help is greatly appreciated and thank you in advance!

Body:
Try this

=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A";"COMPANY B";"COMPANY C"},STATUS,{"Reserved","Blocked","Pending","Archive"})))

or

=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,{"COMPANY A","COMPANY B","COMPANY C"},STATUS,{"Reserved";"Blocked";"Pending";"Archive"})))

Note the ; instead of , in arrays. For details on why to use semi-colon instead of comma see this.

If you want to use your formula it should be as follows

=SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY A",STATUS,{"Reserved","Blocked","Pending","Archive"}))) +
SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY B",STATUS,{"Reserved","Blocked","Pending","Archive"}))) +
SUM((COUNTIFS(DATES,">="&A19,DATES,"<"&EDATE(A19,1),AGENT,"JOHN DOE",COMPANY,"COMPANY C",STATUS,{"Reserved","Blocked","Pending","Archive"})))


问:
Using Moq : Mock object update automatically?
I am new to  MoQ framework. I am writing unit testing for controller using MoQ framework and here is my test method,

```<code>var mockedItemDetail = new ItemDetail()
        {
            Name = null
        };

        var mockObject = new Mock<IItem>();
        mockObject.Setup(x => x.GetItemDetail()).Returns(mockedItemDetail);

        var result = myController.GetDetails() as ViewResult;
</code>```

Here is my Controller Method,

```<code>public ActionResult GetDetails()
    {
        var controllerItemDetail = new ItemDetail();
        controllerItemDetail = _item.GetItemDetail();
        controllerItemDetail.Name = "Changed Name";
        return View("ViewName", controllerItemDetail);
    }
</code>```

Test runs and now I want to assert the sent mockedItemDetail and received model result controllerItemDetail.

In above case, mockedItemDetail property "Name" has null and received controllerItemDetail property Name as "Changed Name".

But whenever I debug, after calling the test method GetDetails(),

My mockedItemDetail property Name is also updated as "Changed Name" in the current scope and I don't know why? Is this is the actual behavior of MoQ?

Edited Content

Consider the same above case in below mock list, here the change in the mock object will not update in all contexts. i.e. The list count for mockedItemDetailList remains 0 and the list count of controllerItemDetail is 1 even after test method calls. Why?

Test method:

```<code>var mockedItemDetailList = new List<ItemDetail>();

    var mockObject = new Mock<IItem>();
    mockObject.Setup(x => x.GetListOfItemDetail()).Returns(mockedItemDetailList);

    var result = myController.GetDetails() as ViewResult;
</code>```

Controller method:

```<code>    public ActionResult GetDetails()
{
    var controllerItemDetail = new ItemDetail();
    controllerItemDetail = _item.GetListOfItemDetail();
    controllerItemDetail.Add(new ItemDetail(){
    Name = "Changed Name"
    });
    return View("ViewName", controllerItemDetail);
}
</code>```

答:
You have a very specific object:

```<code>var mockedItemDetail = new ItemDetail()
{
    Name = null
};
</code>```

When you call mockObject.Setup(x => x.GetItemDetail()).Returns(mockedItemDetail);, you're returning the reference to mockItemDetail. Any changes on that object will update in all contexts.

A quick follow up. To have it return a blank new ItemDetail() each time, you can simply use the lambda method of Returns():

```<code>mockObject.Setup(x => x.GetItemDetail()).Returns(() => new ItemDetail()
{
    Name = null
});
</code>```

Body:
I am new to  MoQ framework. I am writing unit testing for controller using MoQ framework and here is my test method,

var mockedItemDetail = new ItemDetail()
        {
            Name = null
        };

        var mockObject = new Mock<IItem>();
        mockObject.Setup(x => x.GetItemDetail()).Returns(mockedItemDetail);

        var result = myController.GetDetails() as ViewResult;

Here is my Controller Method,

public ActionResult GetDetails()
    {
        var controllerItemDetail = new ItemDetail();
        controllerItemDetail = _item.GetItemDetail();
        controllerItemDetail.Name = "Changed Name";
        return View("ViewName", controllerItemDetail);
    }

Test runs and now I want to assert the sent mockedItemDetail and received model result controllerItemDetail.

In above case, mockedItemDetail property "Name" has null and received controllerItemDetail property Name as "Changed Name".

But whenever I debug, after calling the test method GetDetails(),

My mockedItemDetail property Name is also updated as "Changed Name" in the current scope and I don't know why? Is this is the actual behavior of MoQ?

Edited Content

Consider the same above case in below mock list, here the change in the mock object will not update in all contexts. i.e. The list count for mockedItemDetailList remains 0 and the list count of controllerItemDetail is 1 even after test method calls. Why?

Test method:

var mockedItemDetailList = new List<ItemDetail>();

    var mockObject = new Mock<IItem>();
    mockObject.Setup(x => x.GetListOfItemDetail()).Returns(mockedItemDetailList);

    var result = myController.GetDetails() as ViewResult;

Controller method:

    public ActionResult GetDetails()
{
    var controllerItemDetail = new ItemDetail();
    controllerItemDetail = _item.GetListOfItemDetail();
    controllerItemDetail.Add(new ItemDetail(){
    Name = "Changed Name"
    });
    return View("ViewName", controllerItemDetail);
}

Body:
You have a very specific object:

var mockedItemDetail = new ItemDetail()
{
    Name = null
};

When you call mockObject.Setup(x => x.GetItemDetail()).Returns(mockedItemDetail);, you're returning the reference to mockItemDetail. Any changes on that object will update in all contexts.

A quick follow up. To have it return a blank new ItemDetail() each time, you can simply use the lambda method of Returns():

mockObject.Setup(x => x.GetItemDetail()).Returns(() => new ItemDetail()
{
    Name = null
});


问:
Azure Automation script to request OMS
i wrote an Automation script in PowerShell which give me every morning a report about our azure subscriptions (Vm, Automation jobs, alerts, ...).
Now, i'm adding a new function wich works well from my computer but fails when run from Automation and i don't find how to make it works.

Works well from my computer (VS code / PS 5.1 / PS 4.0)

```<code>$omsRGname = "xxx"
$omsWorkspaceName = "xxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat
</code>```

from my local computer

```<code>Elapsed: 00:00:00.4270000 -- Status: Successful
Count: 1

Date                Computer      Threat                   ThreatStatus
----                --------      ------                   ------------
29/06/2017 12:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 11:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 10:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 09:55:38 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
</code>```

When i run my code from Automation, i get this error

```<code>ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does
not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:164 char:33
+ $OMSComputers = $Result.Value | ConvertFrom-Json
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: ({
  "Computer"...ng": {}
  }
}:JObject) [ConvertFrom-Json], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

Well, my error is here

```<code>$OMSComputers = $Result.Value | ConvertFrom-Json
</code>```

When i look into its value, i get this (just took one property from the list given by $Result.Value)

```<code>VALUEOUT:

Name                       : Computer
Type                       : Property
HasValues                  : True
First                      : {}
Last                       : {}
Count                      : 1
Parent                     : {Computer, Threat, ThreatStatus, __metadata}
Root                       : {Computer, Threat, ThreatStatus, __metadata}
Next                       : {}
Previous                   :
Path                       : Computer
LineNumber                 : 0
LinePosition               : 0
IsReadOnly                 : False
AllowNew                   : True
AllowEdit                  : True
AllowRemove                : True
SupportsChangeNotification : True
SupportsSearching          : False
SupportsSorting            : False
IsSorted                   : False
SortProperty               :
SortDirection              : Ascending
IsFixedSize                : False
SyncRoot                   : System.Object
IsSynchronized             : False
</code>```

isee this line

```<code>Keys                       : {Computer, Threat, ThreatStatus, __metadata}
</code>```

i've tried to parse it as a hashtable, but with no result.

Does anyone have any other creative ways to solve this?
Thanks

Edit:
I've only past my function here. But in the full script i'm well connected and the PS module is already there (if not the function fail telling me, the RG can not be found, but in spite of, i click and add the module from your Link).
If i look at the $result content i get the query result.

```<code>{
    "Computer": "xxx.local",
    "Threat": "Virus:ALisp/Bursted.DT",
    "ThreatStatus": "Quarantined",
    "__metadata": {
        "Type": "ProtectionStatus",
        "TimeGenerated": "2017-06-29T10:55:37.77Z",
        "highlighting": {}
    }
}
</code>```

when i ask for its type

```<code>Newtonsoft.Json.Linq.JObject
</code>```

So i import the Newtonsoft.Json module and try to convert from this kind of Json but it's failing too.

It's looks like my OMS query is working (i have a result in $Result) but when Automation try to convert with 'ConvertFrom-Json', it fails.

```<code>#debug
Write-Output "VALUEOUT:"
Write-Output "Get-variable RESULT"
Get-Variable Result -ValueOnly |format-list
$OMSComputers = $Result.Value | ConvertFrom-Json
</code>```

Output:

```<code>    VALUEOUT:
    Get-variable RESULT

    Id       : subscriptions/xxx/providers/Microsoft.Operatio
               nalInsights/workspaces/xxx/search/xxx|10.1.0.27|2017-07-05T14-33-52Z
    Metadata : Microsoft.Azure.Commands.OperationalInsights.Models.PSSearchMetadata
    Error    :
    Value    : {"Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T10:55:37.77Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T09:48:28.42Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T08:55:37.757Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T07:55:38.327Z",
                 "highlighting": {}
               }...}

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does

not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

At line:65 char:33

+ $OMSComputers = $Result.Value | ConvertFrom-Json

+                                 ~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: ({

  "Computer"...ng": {}

  }

}:JObject) [ConvertFrom-Json], ParameterBindingException

    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

I don't get why the ConvertFrom-Json fail :/

答:
I have exactly the same problem with the command:
$Result.Value | ConvertFrom-Json

This behavior is happening both in an automation runbook and executing locally

This is my workaround to extract the $result.Value from a query using a ForEach and passing the values to a hashtable:

```<code>  $dynamicQuery = "* | measure count() by Type"
$now = Get-Date
$StartDateAndTime = $now.AddHours(-24).ToString("yyyy-MM-ddTHH:mm:ss")

$EndDateAndTime = $now.ToString("yyyy-MM-ddTHH:mm:ss")

$result = Get-AzureRmOperationalInsightsSearchResults `
-ResourceGroupName $ResourceGroupName `
-WorkspaceName $WorkSpaceName `
-Query $dynamicQuery `
-Start $StartDateAndTime `
-End $EndDateAndTime

 $queryResults = new-object System.Collections.Hashtable

Foreach ($item in $result.value)
{
 $obj1 = $item["Type"].ToString()
   $obj2= $item["AggregatedValue"].ToString()
  [void]$queryResults.Add($obj1,$obj2)
}

Write-Output $queryResults
</code>```

I've added it as an issue here, as this is not how the module is documented and this is not an elegant solution:
https://github.com/Azure/azure-powershell/issues/4256

Title: Azure Automation script to request OMS

Body:
i wrote an Automation script in PowerShell which give me every morning a report about our azure subscriptions (Vm, Automation jobs, alerts, ...).
Now, i'm adding a new function wich works well from my computer but fails when run from Automation and i don't find how to make it works.

Works well from my computer (VS code / PS 5.1 / PS 4.0)

$omsRGname = "xxx"
$omsWorkspaceName = "xxx"
$omsQueryThreat = 'Type=ProtectionStatus ThreatStatusRank!=150 ThreatStatusRank!=470 | select Computer,Threat,ThreatStatus'
$ArrayThreat = New-Object System.Collections.ArrayList

function OmsRequest {
    Param(
        [parameter(Position = 0, Mandatory = $true)]
        $omsRG,
        [parameter(Position = 1, Mandatory = $true)]
        $omsWorkspace,
        [parameter(Position = 2, Mandatory = $true)]
        $omsQuery
    )
    Process {
        Import-Module AzureRm.OperationalInsights
        $error.clear()
        $Result.clear
        $script:Result = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $omsRG -WorkspaceName $omsWorkspace -Query $omsQuery
        $reqIdParts = $Result.Id.Split("/")
        $reqId = $reqIdParts[$reqIdParts.Count - 1]
        $wait = Get-Date
        while ($Result.Metadata.Status -eq "Pending" -and $error.Count -eq 0) {
            $Result = Get-AzureRmOperationalInsightsSearchResults -WorkspaceName $omsWorkspace -ResourceGroupName $omsRG -Id $reqId
            #debug
            $elapsedTime = $(get-date) - $wait
            Write-Output "Elapsed: $elapsedTime -- Status: $($Result.Metadata.Status)"
            Write-Output "Count: $($Result.Count)"
        }
    }
}

OmsRequest $omsRGname $omsWorkspaceName $omsQueryThreat
#debug
Write-Output "VALUEOUT:" $Result.Value
#
$OMSComputers = $Result.Value | ConvertFrom-Json
if ($OMSComputers) {
    foreach ( $ThreatDetails in $OMSComputers) {
        <#write "$(get-date($ThreatDetails.__metadata.TimeGenerated) -format G) - $($ThreatDetails.Computer) - $($ThreatDetails.Threat) - $($ThreatDetails.ThreatStatus)"#>
        $ThDetails = [PSCustomObject] @{
            Date         = (get-date($ThreatDetails.__metadata.TimeGenerated) -format G);
            Computer     = $ThreatDetails.Computer;
            Threat       = $ThreatDetails.Threat;
            ThreatStatus = $ThreatDetails.ThreatStatus;
        }
        $ArrayThreat.Add($ThDetails) |Out-Null
    }
}
else {Write-Output "OK"}

$ArrayThreat

from my local computer

Elapsed: 00:00:00.4270000 -- Status: Successful
Count: 1

Date                Computer      Threat                   ThreatStatus
----                --------      ------                   ------------
29/06/2017 12:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 11:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 10:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 09:55:38 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 08:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 07:55:37 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined
29/06/2017 06:48:28 xxx.local     Virus:ALisp/Bursted.DT   Quarantined

When i run my code from Automation, i get this error

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does
not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:164 char:33
+ $OMSComputers = $Result.Value | ConvertFrom-Json
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: ({
  "Computer"...ng": {}
  }
}:JObject) [ConvertFrom-Json], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Well, my error is here

$OMSComputers = $Result.Value | ConvertFrom-Json

When i look into its value, i get this (just took one property from the list given by $Result.Value)

VALUEOUT:

Name                       : Computer
Type                       : Property
HasValues                  : True
First                      : {}
Last                       : {}
Count                      : 1
Parent                     : {Computer, Threat, ThreatStatus, __metadata}
Root                       : {Computer, Threat, ThreatStatus, __metadata}
Next                       : {}
Previous                   :
Path                       : Computer
LineNumber                 : 0
LinePosition               : 0
IsReadOnly                 : False
AllowNew                   : True
AllowEdit                  : True
AllowRemove                : True
SupportsChangeNotification : True
SupportsSearching          : False
SupportsSorting            : False
IsSorted                   : False
SortProperty               :
SortDirection              : Ascending
IsFixedSize                : False
SyncRoot                   : System.Object
IsSynchronized             : False

isee this line

Keys                       : {Computer, Threat, ThreatStatus, __metadata}

i've tried to parse it as a hashtable, but with no result.

Does anyone have any other creative ways to solve this?
Thanks

Edit:
I've only past my function here. But in the full script i'm well connected and the PS module is already there (if not the function fail telling me, the RG can not be found, but in spite of, i click and add the module from your Link).
If i look at the $result content i get the query result.

{
    "Computer": "xxx.local",
    "Threat": "Virus:ALisp/Bursted.DT",
    "ThreatStatus": "Quarantined",
    "__metadata": {
        "Type": "ProtectionStatus",
        "TimeGenerated": "2017-06-29T10:55:37.77Z",
        "highlighting": {}
    }
}

when i ask for its type

Newtonsoft.Json.Linq.JObject

So i import the Newtonsoft.Json module and try to convert from this kind of Json but it's failing too.

It's looks like my OMS query is working (i have a result in $Result) but when Automation try to convert with 'ConvertFrom-Json', it fails.

#debug
Write-Output "VALUEOUT:"
Write-Output "Get-variable RESULT"
Get-Variable Result -ValueOnly |format-list
$OMSComputers = $Result.Value | ConvertFrom-Json

Output:

    VALUEOUT:
    Get-variable RESULT

    Id       : subscriptions/xxx/providers/Microsoft.Operatio
               nalInsights/workspaces/xxx/search/xxx|10.1.0.27|2017-07-05T14-33-52Z
    Metadata : Microsoft.Azure.Commands.OperationalInsights.Models.PSSearchMetadata
    Error    :
    Value    : {"Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T10:55:37.77Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T09:48:28.42Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T08:55:37.757Z",
                 "highlighting": {}
               }, "Computer": "xxx.local" "Threat": "Virus:ALisp/Bursted.DT" "ThreatStatus": "Quarantined"
               "__metadata": {
                 "Type": "ProtectionStatus",
                 "TimeGenerated": "2017-06-29T07:55:38.327Z",
                 "highlighting": {}
               }...}

ConvertFrom-Json : The input object cannot be bound to any parameters for the command either because the command does

not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

At line:65 char:33

+ $OMSComputers = $Result.Value | ConvertFrom-Json

+                                 ~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: ({

  "Computer"...ng": {}

  }

}:JObject) [ConvertFrom-Json], ParameterBindingException

    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

I don't get why the ConvertFrom-Json fail :/

Body:
I have exactly the same problem with the command:
$Result.Value | ConvertFrom-Json

This behavior is happening both in an automation runbook and executing locally

This is my workaround to extract the $result.Value from a query using a ForEach and passing the values to a hashtable:

  $dynamicQuery = "* | measure count() by Type"
$now = Get-Date
$StartDateAndTime = $now.AddHours(-24).ToString("yyyy-MM-ddTHH:mm:ss")

$EndDateAndTime = $now.ToString("yyyy-MM-ddTHH:mm:ss")

$result = Get-AzureRmOperationalInsightsSearchResults `
-ResourceGroupName $ResourceGroupName `
-WorkspaceName $WorkSpaceName `
-Query $dynamicQuery `
-Start $StartDateAndTime `
-End $EndDateAndTime

 $queryResults = new-object System.Collections.Hashtable

Foreach ($item in $result.value)
{
 $obj1 = $item["Type"].ToString()
   $obj2= $item["AggregatedValue"].ToString()
  [void]$queryResults.Add($obj1,$obj2)
}

Write-Output $queryResults

I've added it as an issue here, as this is not how the module is documented and this is not an elegant solution:
https://github.com/Azure/azure-powershell/issues/4256


问:
Save Canvas image to the device/gallery on android
So i am trying for a few days now to take an image from the Canvas of my application and save that to the device... i've  tried some (with no result) plugins like: Save2Canvas, Base64 To Gallery, Canvas2ImagePlugin and Cordova base64ToGallery Plugin...

I am using:
Cordova 7.0.1
Ionic 1.x

Right now the part of my Js. function to save is like this

```<code> var image = canvas
    .toDataURL("image/png");
    window.location.href=image;
</code>```

Wich kinda works on ionic 1.x via browser but not on the device...

答:
Try this using canvas2ImagePlugin(that you mentioned). This worked for me for saving my canvas content to gallery.</p>

```<code><canvas id="myCanvas"  width="165px" height="145px" ></canvas>

<script>
    //get the canvas element
    var canvas = document.querySelector('canvas');

    //save to Gallery
    window.canvas2ImagePlugin.saveImageDataToLibrary(
        function(msg){
            console.log(msg);
        },
        function(err){
            console.log(err);
        },
        document.getElementById('myCanvas')
    );

</script>
</code>```

Body:
So i am trying for a few days now to take an image from the Canvas of my application and save that to the device... i've  tried some (with no result) plugins like: Save2Canvas, Base64 To Gallery, Canvas2ImagePlugin and Cordova base64ToGallery Plugin...

I am using:
Cordova 7.0.1
Ionic 1.x

Right now the part of my Js. function to save is like this

 var image = canvas
    .toDataURL("image/png");
    window.location.href=image;

Wich kinda works on ionic 1.x via browser but not on the device...

Body:
Try this using canvas2ImagePlugin(that you mentioned). This worked for me for saving my canvas content to gallery.

<canvas id="myCanvas"  width="165px" height="145px" ></canvas>

<script>
    //get the canvas element
    var canvas = document.querySelector('canvas');

    //save to Gallery
    window.canvas2ImagePlugin.saveImageDataToLibrary(
        function(msg){
            console.log(msg);
        },
        function(err){
            console.log(err);
        },
        document.getElementById('myCanvas')
    );

</script>


问:
How to insert arrays into a main array in PHP to make it 2d array?
I have these 3 arrays:

```<code>$date = array('2017-06-10',
              '2017-06-11',
              '2017-06-12');
$time_start = array('02:00 PM',
                    '03:00 PM',
                    '04:00 PM');
$time_end = array('05:00 PM',
                  '06:00 PM',
                  '07:00 PM');
</code>```

I want to put these arrays into one array that will produce this form:

```<code>$frequency = array(array('2017-06-10','02:00 PM','05:00 PM'),
                   array('2017-06-11','03:00 PM','06:00 PM'),
                   array('2017-06-12','04:00 PM','07:00 PM'));
</code>```

I tried array_combine and array_merge but they showed different results as what I wanted to produce. Please help.

答:
Or you could do:

```<code>$frequency=array_map(null,$date, $time_start, $time_end);
</code>```

see here: http://php.net/manual/de/function.array-map.php

and for a short demo, here: http://rextester.com/VJRCA63297

Body:
I have these 3 arrays:

$date = array('2017-06-10',
              '2017-06-11',
              '2017-06-12');
$time_start = array('02:00 PM',
                    '03:00 PM',
                    '04:00 PM');
$time_end = array('05:00 PM',
                  '06:00 PM',
                  '07:00 PM');

I want to put these arrays into one array that will produce this form:

$frequency = array(array('2017-06-10','02:00 PM','05:00 PM'),
                   array('2017-06-11','03:00 PM','06:00 PM'),
                   array('2017-06-12','04:00 PM','07:00 PM'));

I tried array_combine and array_merge but they showed different results as what I wanted to produce. Please help.

Body:
Or you could do:

$frequency=array_map(null,$date, $time_start, $time_end);

see here: http://php.net/manual/de/function.array-map.php

and for a short demo, here: http://rextester.com/VJRCA63297


问:
Is it possible to extract scss with a specific variable into css using gulp?
I'm using gulp to compile sass into css. Right now I have color variable defined in sass.
In _varibales.scss.

```<code>  $color: #009999;
</code>```

In app.scss I have used this variable in multiple places.

```<code>    .button{
      color:$color
    }
    .background{
       background :$color
       padding:10px
    }
    .element{
       margin:0 auto
    }
</code>```

So is there a way to extract classes or id's having this variable and generate a new file called color.css using gulp?

答:
I have come up with this solution using line-reader:

```<code>var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var fs = require('fs');

// read a file line-by-line
var lineReader = require('line-reader');

gulp.task('default', function () {

  var myVar;
  var re;
  var s = "";  // will build up temp file with this variable

  fs.readFile('variabales.scss', 'utf8', function (err, contents) {

     // e.g., assumes a single line format like   $color: #009999;
     // myVar will = $color
    myVar = contents.split(/:/)[0].trim();

     // want to include lines that have a {, } or @ symbol on them
     // as well as the $___ sass variable
    re = new RegExp('(\\' + myVar + ')|{|}|@');
  });

  var readStream = fs.createReadStream('app.scss');
  lineReader.eachLine(readStream, function(line, last) {

    if (line.match( re )) {
      s += line + "\n";
    }

    if (last) {

      fs.writeFileSync('temp.scss', s);

      gulp.src("temp.scss")
        // gulp-sass gets rid of the empty ruleset automatically!
        .pipe(sass().on('error', sass.logError))
        .pipe(rename('app.css'))
        .pipe(gulp.dest('./'));

      return false; // stop reading
    }
  })
});
</code>```

Your app.scssfile should have an import statement at the very top like:

```<code>@import "variabales.scss";

.button{
    color : $color;
}

.background{
    background : $color;
    padding : 10px;
}

.element{
    margin : 0 auto;
}
</code>```

So Sass can retrieve the variable from variabales.scss.

No doubt this could be improved by writing to a buffer instead of to a temp file or directly to a stream.

If you wanted your final app.css file to have more sass variables in it than just one, you could generalize this by modifying the regexp to match on "$" instead of the specific "$color".

```<code>  re = new RegExp('[\\${}@]');
</code>```

And then you could rid of the fs. readFile call.

Here is the resulting app.css file:

```<code>.button {
  color: #009999; }

.background {
  background: #009999; }
</code>```

Body:
I'm using gulp to compile sass into css. Right now I have color variable defined in sass.
In _varibales.scss.

  $color: #009999;

In app.scss I have used this variable in multiple places.

    .button{
      color:$color
    }
    .background{
       background :$color
       padding:10px
    }
    .element{
       margin:0 auto
    }

So is there a way to extract classes or id's having this variable and generate a new file called color.css using gulp?

Body:
I have come up with this solution using line-reader:

var gulp = require("gulp");
var sass = require("gulp-sass");
var rename = require("gulp-rename");
var fs = require('fs');

// read a file line-by-line
var lineReader = require('line-reader');

gulp.task('default', function () {

  var myVar;
  var re;
  var s = "";  // will build up temp file with this variable

  fs.readFile('variabales.scss', 'utf8', function (err, contents) {

     // e.g., assumes a single line format like   $color: #009999;
     // myVar will = $color
    myVar = contents.split(/:/)[0].trim();

     // want to include lines that have a {, } or @ symbol on them
     // as well as the $___ sass variable
    re = new RegExp('(\\' + myVar + ')|{|}|@');
  });

  var readStream = fs.createReadStream('app.scss');
  lineReader.eachLine(readStream, function(line, last) {

    if (line.match( re )) {
      s += line + "\n";
    }

    if (last) {

      fs.writeFileSync('temp.scss', s);

      gulp.src("temp.scss")
        // gulp-sass gets rid of the empty ruleset automatically!
        .pipe(sass().on('error', sass.logError))
        .pipe(rename('app.css'))
        .pipe(gulp.dest('./'));

      return false; // stop reading
    }
  })
});

Your app.scssfile should have an import statement at the very top like:

@import "variabales.scss";

.button{
    color : $color;
}

.background{
    background : $color;
    padding : 10px;
}

.element{
    margin : 0 auto;
}

So Sass can retrieve the variable from variabales.scss.

No doubt this could be improved by writing to a buffer instead of to a temp file or directly to a stream.

If you wanted your final app.css file to have more sass variables in it than just one, you could generalize this by modifying the regexp to match on "$" instead of the specific "$color".

  re = new RegExp('[\\${}@]');

And then you could rid of the fs. readFile call.

Here is the resulting app.css file:

.button {
  color: #009999; }

.background {
  background: #009999; }


问:
Logout from the application Android
I have tried to logout from my app when the user clicks on Logout.It is working fine in case the user after login without closing the app if he doed logout .Then it is working properly.Back button will be ineffective in case to show again the login page after doing login
But when the user after login closes the application and then he does logout the login page is not showing it is showing a blank page to me

Code

```<code>public class AppState {
    private static AppState singleInstance;

    private boolean isLoggingOut;

    private AppState() {
    }

    public static AppState getSingleInstance() {
        if (singleInstance == null) {
            singleInstance = new AppState();
        }
        return singleInstance;
    }

    public boolean isLoggingOut() {
        return isLoggingOut;
    }

    public void setLoggingOut(boolean isLoggingOut) {
        this.isLoggingOut = isLoggingOut;
    }
}
</code>```

OnClick of logout

```<code>logout.setOnClickListener(new OnClickListener() {
    @Override
            public void onClick(View arg0) {
                SharedPreferences myPrefs = getSharedPreferences("MY",
                        MODE_PRIVATE);
                SharedPreferences.Editor editor = myPrefs.edit();
                editor.clear();
                editor.commit();
                AppState.getSingleInstance().setLoggingOut(true);
                Log.d(TAG, "Now log out and start the activity login");
                Intent intent = new Intent(HomePage.this,
                        LoginPage.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            }
        });
</code>```

IN the LoginActivity

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MAIN_ACTIVITY_REQUEST_CODE) {

            if (!AppState.getSingleInstance().isLoggingOut()) {
                finish();
            } else {
                AppState.getSingleInstance().setLoggingOut(false);
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }
</code>```

Please suggest me what i have done wrong in this

After Your Suggestions  of Vivek Bhusal i tried to use sharedpref

HomePage logout Clicked

```<code>logout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                SharedPreferences myPrefs = getSharedPreferences("Activity",
                        MODE_PRIVATE);
                SharedPreferences.Editor editor = myPrefs.edit();
                editor.clear();
                editor.commit();
                //AppState.getSingleInstance().setLoggingOut(true);
                setLoginState(true);
                Log.d(TAG, "Now log out and start the activity login");
                Intent intent = new Intent(HomePage.this,
                        LoginPage.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            }
        });

private void setLoginState(boolean status) {
        SharedPreferences sp = getSharedPreferences("LoginState",
                MODE_PRIVATE);
            SharedPreferences.Editor ed = sp.edit();
            ed.putBoolean("setLoggingOut", status);
            ed.commit();
    }
</code>```

On the Login Page

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        SharedPreferences sp = getSharedPreferences("LoginState",
                MODE_PRIVATE);
        boolean stateValue  = sp.getBoolean("setLoggingOut", false);
        if (requestCode == MAIN_ACTIVITY_REQUEST_CODE) {

            if (!stateValue) {
                finish();
            } else {
                //AppState.getSingleInstance().setLoggingOut(false);
                updateLoginState(false);
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
</code>```

Still the same issue showing a blank screen when i again restart the app and then do the logout.

答:
case R.id.drawer_item_logout: //name of logout button

```<code>                    AlertDialog.Builder builder=new AlertDialog.Builder(Home.this); //Home is name of the activity
                    builder.setMessage("Do you want to exit?");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            finish();
                            Intent i=new Intent();
                            i.putExtra("finish", true);
                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
                           //startActivity(i);
                            finish();

                        }
                    });

                    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

                        AlertDialog alert=builder.create();
                    alert.show();

                    break;
</code>```

Title: Logout from the application Android

Body:
I have tried to logout from my app when the user clicks on Logout.It is working fine in case the user after login without closing the app if he doed logout .Then it is working properly.Back button will be ineffective in case to show again the login page after doing login
But when the user after login closes the application and then he does logout the login page is not showing it is showing a blank page to me

Code

public class AppState {
    private static AppState singleInstance;

    private boolean isLoggingOut;

    private AppState() {
    }

    public static AppState getSingleInstance() {
        if (singleInstance == null) {
            singleInstance = new AppState();
        }
        return singleInstance;
    }

    public boolean isLoggingOut() {
        return isLoggingOut;
    }

    public void setLoggingOut(boolean isLoggingOut) {
        this.isLoggingOut = isLoggingOut;
    }
}

OnClick of logout

logout.setOnClickListener(new OnClickListener() {
    @Override
            public void onClick(View arg0) {
                SharedPreferences myPrefs = getSharedPreferences("MY",
                        MODE_PRIVATE);
                SharedPreferences.Editor editor = myPrefs.edit();
                editor.clear();
                editor.commit();
                AppState.getSingleInstance().setLoggingOut(true);
                Log.d(TAG, "Now log out and start the activity login");
                Intent intent = new Intent(HomePage.this,
                        LoginPage.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            }
        });

IN the LoginActivity

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MAIN_ACTIVITY_REQUEST_CODE) {

            if (!AppState.getSingleInstance().isLoggingOut()) {
                finish();
            } else {
                AppState.getSingleInstance().setLoggingOut(false);
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

Please suggest me what i have done wrong in this

After Your Suggestions  of Vivek Bhusal i tried to use sharedpref

HomePage logout Clicked

logout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                SharedPreferences myPrefs = getSharedPreferences("Activity",
                        MODE_PRIVATE);
                SharedPreferences.Editor editor = myPrefs.edit();
                editor.clear();
                editor.commit();
                //AppState.getSingleInstance().setLoggingOut(true);
                setLoginState(true);
                Log.d(TAG, "Now log out and start the activity login");
                Intent intent = new Intent(HomePage.this,
                        LoginPage.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            }
        });

private void setLoginState(boolean status) {
        SharedPreferences sp = getSharedPreferences("LoginState",
                MODE_PRIVATE);
            SharedPreferences.Editor ed = sp.edit();
            ed.putBoolean("setLoggingOut", status);
            ed.commit();
    }

On the Login Page

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        SharedPreferences sp = getSharedPreferences("LoginState",
                MODE_PRIVATE);
        boolean stateValue  = sp.getBoolean("setLoggingOut", false);
        if (requestCode == MAIN_ACTIVITY_REQUEST_CODE) {

            if (!stateValue) {
                finish();
            } else {
                //AppState.getSingleInstance().setLoggingOut(false);
                updateLoginState(false);
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

Still the same issue showing a blank screen when i again restart the app and then do the logout.

Body:
case R.id.drawer_item_logout: //name of logout button

                    AlertDialog.Builder builder=new AlertDialog.Builder(Home.this); //Home is name of the activity
                    builder.setMessage("Do you want to exit?");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            finish();
                            Intent i=new Intent();
                            i.putExtra("finish", true);
                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // To clean up all activities
                           //startActivity(i);
                            finish();

                        }
                    });

                    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

                        AlertDialog alert=builder.create();
                    alert.show();

                    break;


问:
Android: Keep asynctask even after app is killed
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

```<code>    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}
</code>```

答: You can Keep asynctask even after app is killed but when your doInBackground work finished and onPostExecute method work on that time you need to require available object of context otherwise app will crashed.

Body:
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}


问:
file handling in python
Thanks in advance. I have written a program which works for small files. But that doesn't work for files of 1 GB. Please tell me is there is any way to handle big file. Here is the code.</p>

```<code>fh=open('reg.fa','r')
c=fh.readlines()
fh.close()
s=''
for i in range(0,(len(c))):
    s=s+c[i]
    lines=s.split('\n')
    for line in s:
            s=s.replace('\n','')
s=s.replace('\n','')
print s
</code>```

答:
```<code>import sys
import os
</code>```

Use wb+ mode if file is not created, this will create file and also write data!

```<code>f = open('f_name.txt','wb+')
while 1:
    part = f.read(1024)
    if not part:
        break
    part = part.replace('\n', '')
    sys.stdout.write(part)
 f.close()
</code>```

OwnerDisplayName: ram

ContentLicense: CC BY-SA 2.5

Title: file handling in python

Body:
Thanks in advance. I have written a program which works for small files. But that doesn't work for files of 1 GB. Please tell me is there is any way to handle big file. Here is the code.

fh=open('reg.fa','r')
c=fh.readlines()
fh.close()
s=''
for i in range(0,(len(c))):
    s=s+c[i]
    lines=s.split('\n')
    for line in s:
            s=s.replace('\n','')
s=s.replace('\n','')
print s

Body:
import sys
import os

Use wb+ mode if file is not created, this will create file and also write data!

f = open('f_name.txt','wb+')
while 1:
    part = f.read(1024)
    if not part:
        break
    part = part.replace('\n', '')
    sys.stdout.write(part)
 f.close()


问:
Sticky Sidebar with JavaScript - Sticky only until specifed element
I want to create a sticky sidebar. But the sticky sidebar should only be stick until the ending of the sidebar has reached a specifed element.

Here is the webpage I want to get worked with the sidebar:
https://digital-hacks.de/vpn-verbindung-einrichten/

You can see the code in the head section or here.

```<code><script>
    var sidebar = $('#sidebar-content'),
        nav = $('.sidebar-content'),
        startPosition = sidebar .offset().top,
        stopPosition = $('#abspann').offset().top - nav.outerHeight();

    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop()

        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        }
    });
</script>
</code>```

I want that the sidebar gets attached to the screen if the user scrolls down and it should end if the ending of the sidebar has reached the element #abspann.

But I get a error in my code:
Uncaught TypeError: $ is not a function at (index):415

How can I get this working?

I found the sourcecode here.

Greetings

答:
I think this will work.

```<code><script>
    var nav = $('.sidebar-content'),
        startPosition = nav.offset().top,
        stopPosition = $('#abspann').offset().top - $(window).height();

    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop()

        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        }
    });
</script>
</code>```

Style sticky class as you desire position: fixed and other tweaks you need to do. it's woking on your website. I tried using the console.

Body:
I want to create a sticky sidebar. But the sticky sidebar should only be stick until the ending of the sidebar has reached a specifed element.

Here is the webpage I want to get worked with the sidebar:
https://digital-hacks.de/vpn-verbindung-einrichten/

You can see the code in the head section or here.

I want that the sidebar gets attached to the screen if the user scrolls down and it should end if the ending of the sidebar has reached the element #abspann.

But I get a error in my code:
Uncaught TypeError: $ is not a function at (index):415

How can I get this working?

I found the sourcecode here.

Greetings

Body:
I think this will work.

<script>
    var nav = $('.sidebar-content'),
        startPosition = nav.offset().top,
        stopPosition = $('#abspann').offset().top - $(window).height();

    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop()

        if (y > startPosition) {
            nav.addClass('sticky');
            if (y > stopPosition) {
                nav.css('top', stopPosition - y);
            } else {
                nav.css('top', 0);
            }
        } else {
            nav.removeClass('sticky');
        }
    });
</script>

Style sticky class as you desire position: fixed and other tweaks you need to do. it's woking on your website. I tried using the console.


问:
C++ Issues deducing template parameters
I have a template class, ComponentCache, that is essentially a wrapper around a std::vector, except that it only provides random access to the data.

```<code>template<class T>
class ComponentCache
{
public:
  ComponentCache()
  {
    m_Components.reserve(1024);
  }

  ~ComponentCache()
  { }

  //Get a component stored at some index.
  //If the index is greater than the size of the index,
  //resize it to the size of the index + 128
  T& GetComponent(const std::uint32_t& index)
  {
    if(index >= m_Components.size())
    {
      std::uint32_t newSize = index + 128;
      m_Components.resize(newSize);
    }

    return m_Components.at(index);
  }
private:
  std::vector<T> m_Components;
};
</code>```

I have another template class, ComponentStorage, that is essentially a wrapper around an std::tuple>.

```<code>template<class... T>
class ComponentStorage
{
public:
  ComponentStorage()
  { }
  ~ComponentStorage()
  { }

  //Gets a component at some index from the tuple of components
  template<class Component>
  Component& GetComponent(const aecs::Entity& index)
  {
   return std::get<aecs::Component::ComponentCache<Component>>
     (m_ComponentLines).GetComponent(index);
  }

private:
  std::tuple<aecs::Component::ComponentCache<T>...> m_ComponentLines;
};
</code>```

Finally, I have another template class, World, that acts as a place to keep a memory pool and the ComponentStorage class logically near eachother.

```<code>template<class... Components>
class World
{
  struct EntityMetadata
  {
    std::bitset<sizeof...(Components)> ComponentBitset;
    bool IsActive = false;
  };
public:
  World(std::size_t size = 128)
  {
    m_EntityMetadata.resize(size);
  }
  ~World()
  { }

  /*Entity Management*/
  const aecs::Entity& CreateEntity()
  {
    auto entity = m_EntityPool.Create();
    if(entity != 0xFFFFFFFF)
    {
      auto entityIndex = aecs::GetIndexFromEntity(entity);
      m_EntityMetadata.at(entityIndex).IsActive = true;
    }
    return std::move(entity);
  }
  void DestroyEntity(const aecs::Entity& entity)
  {
    if(entity == 0xFFFFFFFF)
    {
      return;
    }
    auto entityIndex = aecs::GetIndexFromEntity(entity);
    m_EntityMetadata.at(entityIndex).IsActive = false;
    m_EntityPool.Destroy(entity);
  }
  const std::vector<aecs::Entity>& GetActiveEntities()
  {
    return m_EntityPool.GetActiveEntities();
  }
  const bool IsEntityActive(const aecs::Entity& entity)
  {
    auto entityIndex = aecs::GetIndexFromEntity(entity);
    return m_EntityMetadata.at(entityIndex).IsActive;
  }

  /*Component Management*/
  template<class Component>
    Component& GetComponentFromEntity(const aecs::Entity &entity)
  {
    const std::uint32_t index = aecs::GetIndexFromEntity(entity);
    return m_ComponentStorage.GetComponent<Component>(index);
  }
  template<class Component>
    void AddComponentToEntity(const aecs::Entity& entity)
  {
    //TODO: Implement

    auto entityIndex = aecs::GetIndexFromEntity(entity);

    m_EntityMetadata.at(entityIndex).ComponentBitset.set(
      aecs::mpl::IndexOf<Component, std::tuple<Components...>>::value);
  }
  template<class Component>
    void RemoveComponentFromEntity(const aecs::Entity& entity)
  {
    //TODO: Implement
    auto componentIndex = aecs::mpl::IndexOf<Component,
      std::tuple<Components...>>::value;
    auto entityIndex = aecs::GetIndexFromEntity(entity);

    m_EntityMetadata.at(entityIndex).ComponentBitset.reset(componentIndex);

  }
  template<class Component>
    const bool EntityHasComponent(const aecs::Entity& entity)
  {
    auto componentIndex = aecs::mpl::IndexOf<Component,
      std::tuple<Components...>>::value;
    auto entityIndex = aecs::GetIndexFromEntity(entity);

    std::bitset<sizeof...(Components)> tempBitset;
    tempBitset.set(componentIndex);

    return (m_EntityMetadata.at(entityIndex).ComponentBitset & tempBitset) ==
                                                           tempBitset;
  }

private:
  aecs::EntityPool m_EntityPool;
  aecs::ComponentStorage<Components...> m_ComponentStorage;

  std::vector<EntityMetadata> m_EntityMetadata;
};
</code>```

Throwing it all together, it should work something like this:

```<code>struct Position
{
  float x;
  float y;
};

struct Velocity
{
  float x;
  float y;
};

int main() {

  aecs::World<Position, Velocity> w;

  const auto e = w.CreateEntity();
  Velocity& v1 = w.GetComponentFromEntity<Velocity>(e);
  return 0;
}
</code>```

However, I get the following compilation error regarding GetComponentFromEntity:

```<code>error: expected primary-expression before '>' token
     return m_ComponentStorage.GetComponent<Component>(index);
</code>```

If I switch it up so that it should automatically deduce the type of Component, I instead get the following errors:

```<code>E:\CLion\AECS\aecs/World/World.h: In instantiation of 'Component& aecs::World<Components>::GetComponentFromEntity(const Entity&) [with Component = Velocity; Components = {Position, Velocity}; aecs::Entity = unsigned int]':
E:\CLion\AECS\main.cpp:26:54:   required from here
E:\CLion\AECS\aecs/World/World.h:69:49: error: no matching function for call to 'aecs::ComponentStorage<Position, Velocity>::GetComponent(const uint32_t&)'
     return m_ComponentStorage.GetComponent(index);
                                                 ^
In file included from E:\CLion\AECS\aecs/World/World.h:9:0,
                 from E:\CLion\AECS\main.cpp:2:
e:\clion\aecs\aecs\componentstorage\componentstorage.h:27:14: note: candidate: template<class Component> Component& aecs::ComponentStorage<T>::GetComponent(const Entity&) [with Component = Component; T = {Position, Velocity}]
   Component& GetComponent(const aecs::Entity& index)
              ^
e:\clion\aecs\aecs\componentstorage\componentstorage.h:27:14: note:   template argument deduction/substitution failed:
In file included from E:\CLion\AECS\main.cpp:2:0:
E:\CLion\AECS\aecs/World/World.h:69:49: note:   couldn't deduce template parameter 'Component'
     return m_ComponentStorage.GetComponent(index);
</code>```

It seems like the compiler should have no problem deducing the type of Component at compile-time, because Component is what's being returned.
I feel like I am making some obvious mistake, but everything looks correct to me. Am I forgetting something important regarding templates?

答:
Put yourself into the shoes of the compiler when it's parsing the line:

```<code>return m_ComponentStorage.GetComponent<Component>(index);
</code>```

The type of m_ComponentStorage depends on Components..., which is unknown when parsing the code. How can you possibly tell what GetComponent is supposed to be?

It could be a template member function, but it could also be a simple member variable. For sanity's sake, compilers are instructed to assume they are dealing with a member variable in that scenario.

You can tell the compiler what it's dealing with using

```<code>    return m_ComponentStorage.template GetComponent<Component>(index);
</code>```

Title: C++ Issues deducing template parameters

Body:
I have a template class, ComponentCache, that is essentially a wrapper around a std::vector, except that it only provides random access to the data.

template<class T>
class ComponentCache
{
public:
  ComponentCache()
  {
    m_Components.reserve(1024);
  }

  ~ComponentCache()
  { }

  //Get a component stored at some index.
  //If the index is greater than the size of the index,
  //resize it to the size of the index + 128
  T& GetComponent(const std::uint32_t& index)
  {
    if(index >= m_Components.size())
    {
      std::uint32_t newSize = index + 128;
      m_Components.resize(newSize);
    }

    return m_Components.at(index);
  }
private:
  std::vector<T> m_Components;
};

I have another template class, ComponentStorage, that is essentially a wrapper around an std::tuple>.

template<class... T>
class ComponentStorage
{
public:
  ComponentStorage()
  { }
  ~ComponentStorage()
  { }

  //Gets a component at some index from the tuple of components
  template<class Component>
  Component& GetComponent(const aecs::Entity& index)
  {
   return std::get<aecs::Component::ComponentCache<Component>>
     (m_ComponentLines).GetComponent(index);
  }

private:
  std::tuple<aecs::Component::ComponentCache<T>...> m_ComponentLines;
};

Finally, I have another template class, World, that acts as a place to keep a memory pool and the ComponentStorage class logically near eachother.

template<class... Components>
class World
{
  struct EntityMetadata
  {
    std::bitset<sizeof...(Components)> ComponentBitset;
    bool IsActive = false;
  };
public:
  World(std::size_t size = 128)
  {
    m_EntityMetadata.resize(size);
  }
  ~World()
  { }

  /*Entity Management*/
  const aecs::Entity& CreateEntity()
  {
    auto entity = m_EntityPool.Create();
    if(entity != 0xFFFFFFFF)
    {
      auto entityIndex = aecs::GetIndexFromEntity(entity);
      m_EntityMetadata.at(entityIndex).IsActive = true;
    }
    return std::move(entity);
  }
  void DestroyEntity(const aecs::Entity& entity)
  {
    if(entity == 0xFFFFFFFF)
    {
      return;
    }
    auto entityIndex = aecs::GetIndexFromEntity(entity);
    m_EntityMetadata.at(entityIndex).IsActive = false;
    m_EntityPool.Destroy(entity);
  }
  const std::vector<aecs::Entity>& GetActiveEntities()
  {
    return m_EntityPool.GetActiveEntities();
  }
  const bool IsEntityActive(const aecs::Entity& entity)
  {
    auto entityIndex = aecs::GetIndexFromEntity(entity);
    return m_EntityMetadata.at(entityIndex).IsActive;
  }

  /*Component Management*/
  template<class Component>
    Component& GetComponentFromEntity(const aecs::Entity &entity)
  {
    const std::uint32_t index = aecs::GetIndexFromEntity(entity);
    return m_ComponentStorage.GetComponent<Component>(index);
  }
  template<class Component>
    void AddComponentToEntity(const aecs::Entity& entity)
  {
    //TODO: Implement

    auto entityIndex = aecs::GetIndexFromEntity(entity);

    m_EntityMetadata.at(entityIndex).ComponentBitset.set(
      aecs::mpl::IndexOf<Component, std::tuple<Components...>>::value);
  }
  template<class Component>
    void RemoveComponentFromEntity(const aecs::Entity& entity)
  {
    //TODO: Implement
    auto componentIndex = aecs::mpl::IndexOf<Component,
      std::tuple<Components...>>::value;
    auto entityIndex = aecs::GetIndexFromEntity(entity);

    m_EntityMetadata.at(entityIndex).ComponentBitset.reset(componentIndex);

  }
  template<class Component>
    const bool EntityHasComponent(const aecs::Entity& entity)
  {
    auto componentIndex = aecs::mpl::IndexOf<Component,
      std::tuple<Components...>>::value;
    auto entityIndex = aecs::GetIndexFromEntity(entity);

    std::bitset<sizeof...(Components)> tempBitset;
    tempBitset.set(componentIndex);

    return (m_EntityMetadata.at(entityIndex).ComponentBitset & tempBitset) ==
                                                           tempBitset;
  }

private:
  aecs::EntityPool m_EntityPool;
  aecs::ComponentStorage<Components...> m_ComponentStorage;

  std::vector<EntityMetadata> m_EntityMetadata;
};

Throwing it all together, it should work something like this:

struct Position
{
  float x;
  float y;
};

struct Velocity
{
  float x;
  float y;
};

int main() {

  aecs::World<Position, Velocity> w;

  const auto e = w.CreateEntity();
  Velocity& v1 = w.GetComponentFromEntity<Velocity>(e);
  return 0;
}

However, I get the following compilation error regarding GetComponentFromEntity:

error: expected primary-expression before '>' token
     return m_ComponentStorage.GetComponent<Component>(index);

If I switch it up so that it should automatically deduce the type of Component, I instead get the following errors:

E:\CLion\AECS\aecs/World/World.h: In instantiation of 'Component& aecs::World<Components>::GetComponentFromEntity(const Entity&) [with Component = Velocity; Components = {Position, Velocity}; aecs::Entity = unsigned int]':
E:\CLion\AECS\main.cpp:26:54:   required from here
E:\CLion\AECS\aecs/World/World.h:69:49: error: no matching function for call to 'aecs::ComponentStorage<Position, Velocity>::GetComponent(const uint32_t&)'
     return m_ComponentStorage.GetComponent(index);
                                                 ^
In file included from E:\CLion\AECS\aecs/World/World.h:9:0,
                 from E:\CLion\AECS\main.cpp:2:
e:\clion\aecs\aecs\componentstorage\componentstorage.h:27:14: note: candidate: template<class Component> Component& aecs::ComponentStorage<T>::GetComponent(const Entity&) [with Component = Component; T = {Position, Velocity}]
   Component& GetComponent(const aecs::Entity& index)
              ^
e:\clion\aecs\aecs\componentstorage\componentstorage.h:27:14: note:   template argument deduction/substitution failed:
In file included from E:\CLion\AECS\main.cpp:2:0:
E:\CLion\AECS\aecs/World/World.h:69:49: note:   couldn't deduce template parameter 'Component'
     return m_ComponentStorage.GetComponent(index);

It seems like the compiler should have no problem deducing the type of Component at compile-time, because Component is what's being returned.
I feel like I am making some obvious mistake, but everything looks correct to me. Am I forgetting something important regarding templates?

Body:
Put yourself into the shoes of the compiler when it's parsing the line:

return m_ComponentStorage.GetComponent<Component>(index);

The type of m_ComponentStorage depends on Components..., which is unknown when parsing the code. How can you possibly tell what GetComponent is supposed to be?

It could be a template member function, but it could also be a simple member variable. For sanity's sake, compilers are instructed to assume they are dealing with a member variable in that scenario.

You can tell the compiler what it's dealing with using

    return m_ComponentStorage.template GetComponent<Component>(index);


问:
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?
I post file and parameter by curl command to t.php:

t.php:

```<code><?php

print_r( $_FILES );
print_r( $_POST );
?>
</code>```

it's need the same names for file and parameter "name":

```<code>curl http://localhost/t.php -X POST -F "name=@D:\file.zip" -F "name=test"
</code>```

result is:

```<code>Array
(
    [name] => Array
        (
            [name] => file.zip
            [type] => application/octet-stream
            [tmp_name] => D:\www\tmp\php653B.tmp
            [error] => 0
            [size] => 150
        )

)
Array
(
    [name] => test
)
</code>```

it is ok!

But,
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?

```<code>//
$data = [
    'name' => curl_file_create('D:\file.zip'),
    //'name' => 'test', // <--- ?????????????
];

$curl = curl_init('http://localhost/t.php');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data );
$out = curl_exec($curl);
curl_close($curl);
</code>```

Help me, please

答:
```<code>$boundary = '---'.time().'---' ;
$header = 'Content-Type: multipart/form-data; boundary='.$boundary;

$filename = 'D:\file.zip';
$file_contents = file_get_contents($filename);
$content =  "--". $boundary . "\r\n".
            "Content-Disposition: form-data; name=\"name\"; filename=\"".basename($filename)."\"\r\n".
            "Content-Type: application/zip\r\n\r\n".
            $file_contents."\r\n";
$content .= "--". $boundary. "\r\n".
            "Content-Disposition: form-data; name=\"name\"\r\n\r\n".
            "test\r\n";
$content .= "--" . $boundary . "--\r\n";
$context = stream_context_create(array(
    'http' => array(
          'method' => 'POST',
          'header' => $header,
          'content' => $content,
    )
));
$result = file_get_contents('http://localhost/t.php', false, $context);
</code>```

Body:
I post file and parameter by curl command to t.php:

t.php:

<?php

print_r( $_FILES );
print_r( $_POST );
?>

it's need the same names for file and parameter "name":

curl http://localhost/t.php -X POST -F "name=@D:\file.zip" -F "name=test"

result is:

Array
(
    [name] => Array
        (
            [name] => file.zip
            [type] => application/octet-stream
            [tmp_name] => D:\www\tmp\php653B.tmp
            [error] => 0
            [size] => 150
        )

)
Array
(
    [name] => test
)

it is ok!

But,
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?

//
$data = [
    'name' => curl_file_create('D:\file.zip'),
    //'name' => 'test', // <--- ?????????????
];

$curl = curl_init('http://localhost/t.php');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data );
$out = curl_exec($curl);
curl_close($curl);

Help me, please


问:
Salesforce: is it possible to develop a web application on top of Salesforce
Let me start with a bit of background: I'm helping a non-profit organization that would like to have a browser-based application that is backed by Salesforce, but has very specific requirements.

I see Salesforce has a REST API that we can call, so we can develop a standalone application to serve the web pages they want and use the REST API to call Salesforce when needed.

I'm wondering if there is a way to host a web application directly on Salesforce; this way we don't have to have a separate application server. Any recommendations or pointers to documentation/open source products is greatly appreciated.

答: Yes, you can create services that will allow your app to hit Salesforce</p>


问:
Add html code before checkout header title on WooCommerce
I need a function to add a HTML code before checkout header title on WooCommerce. I would like to add a process bar.

Thanks

答:
The Checkout title is located in the header.php of your theme. So there is no any WooCommerce hooks for that.

So you can accomplish that editing the header.php file of your active child theme (or active theme) using the dedicated WooCommerce conditional tag is_checkout():

```<code><?php if( is_checkout() ): ?>
    <!-- HERE GOES YOUR HTML CODE DISPLAYED ONLY IN CHECKOUT HEADER -->
<?php endif; ?>
</code>```

ADDITIONAL UPDATE:

For checkout only and not order recieved (thank you):

```<code><?php if( is_checkout() && ! WC()->cart->is_empty() ): ?>
    <!-- HERE GOES YOUR HTML CODE DISPLAYED ONLY IN CHECKOUT HEADER -->
<?php endif; ?>
</code>```

Body:
The Checkout title is located in the header.php of your theme. So there is no any WooCommerce hooks for that.

So you can accomplish that editing the header.php file of your active child theme (or active theme) using the dedicated WooCommerce conditional tag is_checkout():

<?php if( is_checkout() ): ?>
    <!-- HERE GOES YOUR HTML CODE DISPLAYED ONLY IN CHECKOUT HEADER -->
<?php endif; ?>

ADDITIONAL UPDATE:

For checkout only and not order recieved (thank you):

<?php if( is_checkout() && ! WC()->cart->is_empty() ): ?>
    <!-- HERE GOES YOUR HTML CODE DISPLAYED ONLY IN CHECKOUT HEADER -->
<?php endif; ?>


问:
Flex App Embedded in Rails App w/Authentication
We have a Rails 3 app using session-based authentication (modified acts_as_authenticated), and a Flex app that needs to be embedded in an html.erb template. The Flex app needs to access routes that have a before_filter set to check if the user is logged in.  When interacting with the HTML site, this causes the user to be redirected to a login page, then sets a Rails session property (tied to a cookie) to record that the user is logged in when making future requests.

The Flex app needs to access XML that's generated by Rails (behind the before_filter) and I don't want to force the user to log in twice -- what should I be passing as a flash parameter to the Flex app so that it can present as "already logged in" if that session exists (ie, the user has logged in via the HTML interface)?  I haven't dealt with this kind of problem before so I'm not sure if I'm even asking the right question. Any advice appreciated!

答:
Integrating flash into your authenticated service can be tricky. You can't rely on normal http sessions or cookies to manage authentication for you.  What is generally regarded best practice is to generate a unique token for each logged in user to pass on every request to the server to prove that they are in fact a logged in user. for example:

They log in through an html form.

When you serve up a swf that is going to access authenticated content you give it a flashvar of token=49r03f0239fhduffnkdjfgnas or something like that.

This token is generated server-side and stored somewhere to be checked on requests.

On every request to the server you pass this token and check it's validity.

If it's good you perform the action and return the data.

If it's bad you prompt the user.

notes:

tokens should be long and unguessable like a session variable.

each time they log in you need to generate a new token.

each time they log out you need to destroy the token.


问:
Creating thread of object in different class
I am trying to learn threading here. I have this demo class which prints the nth fibonacci number. No I am trying to create a thread for this demo object in another class threadtest1 and execute it. but I keep getting the following error

```<code>Starting thread :Thread[Fibonacci thread,5,main]
Exception in thread "main" java.lang.NullPointerException
    at threadtest1.startThread(threadtest1.java:21)
    at threadtest1.main(threadtest1.java:27)
</code>```

Can anyone help?

DEMO

```<code>class demo implements Runnable
{
private int limit;
public demo(int l)
{
    limit = l;
}
public demo()
{
    limit = 10;
}
public void startDemo(Thread t)
{
    t.start();
}
public void run()
{
    int c = 1;
    if(limit>2)
    {
        int i,a = 1,b = 1;
        for(i = 3;i<=limit;i++)
        {
            c = a+b;
            a = b;
            b = c;
        }
    }
    System.out.println("Fibonacci number["+limit+"] = "+c);
}
}
</code>```

THREADTEST1

```<code>class threadtest1
{
private Thread t;
private demo d;
private int l;
public threadtest1(int l)
{
    this.l = l;
    demo d = new demo(l);
}
public threadtest1(int l1, int l2)
{
    this.l = (int)Math.max(l1,l2);
    demo d = new demo(l);
}

public void startThread()
{
    t = new Thread(d,"Fibonacci thread");
    System.out.println("Starting thread :" +t);
    d.startDemo(t);
}

public static void main(String args[])
{
    threadtest1 t1 = new threadtest1(5);
    t1.startThread();
}
}
</code>```

答:
change

```<code>demo d = new demo(l);
</code>```

to

```<code>d = new demo(l);
</code>```

as you should be initializing the field, not creating a local variable

doing so will prevent

```<code>d.startDemo(t);
</code>```

d from being uninitialized

Body:
I am trying to learn threading here. I have this demo class which prints the nth fibonacci number. No I am trying to create a thread for this demo object in another class threadtest1 and execute it. but I keep getting the following error

Starting thread :Thread[Fibonacci thread,5,main]
Exception in thread "main" java.lang.NullPointerException
    at threadtest1.startThread(threadtest1.java:21)
    at threadtest1.main(threadtest1.java:27)

Can anyone help?

DEMO

class demo implements Runnable
{
private int limit;
public demo(int l)
{
    limit = l;
}
public demo()
{
    limit = 10;
}
public void startDemo(Thread t)
{
    t.start();
}
public void run()
{
    int c = 1;
    if(limit>2)
    {
        int i,a = 1,b = 1;
        for(i = 3;i<=limit;i++)
        {
            c = a+b;
            a = b;
            b = c;
        }
    }
    System.out.println("Fibonacci number["+limit+"] = "+c);
}
}

THREADTEST1

class threadtest1
{
private Thread t;
private demo d;
private int l;
public threadtest1(int l)
{
    this.l = l;
    demo d = new demo(l);
}
public threadtest1(int l1, int l2)
{
    this.l = (int)Math.max(l1,l2);
    demo d = new demo(l);
}

public void startThread()
{
    t = new Thread(d,"Fibonacci thread");
    System.out.println("Starting thread :" +t);
    d.startDemo(t);
}

public static void main(String args[])
{
    threadtest1 t1 = new threadtest1(5);
    t1.startThread();
}
}

Body:
change

demo d = new demo(l);

to

d = new demo(l);

as you should be initializing the field, not creating a local variable

doing so will prevent

d.startDemo(t);

d from being uninitialized


问:
Show current class belongs to which module in IntelliJ IDEA
I have opened multiple modules inside the same IntelliJ window. While I'm navigating through the classes, I want to know particular class belongs to which module.

Currently I'm placing the mouse cursor on the class name tab. Then it shows a path to the class as a tool-tip, then I figure out that class is coming from which module.

Is there any other way I can quickly view the module name, a class is belongs to?

答: Module name is displaying in the Title Bar of the IntelliJ window


问:
HTML 5 drag-drop into wysiwyg editor in Firefox
I have a wysiwyg editor using the HTML 5 drag-drop api to allow the user to place widgets within the page they are editing. When the OnDrop event fires, I prevent the default event, and insert some html within the editor that represents the widget they inserted. I use execCommand("inserthtml", false, html) for this in Firefox.

This works fine in IE, but in Firefox the html is not placed in the location where it was dropped. It always gets placed in the location where the previous selection was, which leads me to believe that cancelling the OnDrop event to override the default drop also cancels the selection change.

Any ideas on how to solve this?

Thanks!

答:
Try this

```<code>$('.textarea').wysihtml5({
    events: {
        "load": function() {
        var vm=this;
           $($('.wysihtml5-sandbox').contents().find('body')).on("dragleave", function(event) {
              event.preventDefault();
              event.stopPropagation();
          });

          $($('.wysihtml5-sandbox').contents().find('body')).on("drop", function(event) {
              event.preventDefault();
              event.stopPropagation();
              debugger;
               var dt = event.originalEvent.dataTransfer;
                        var files = dt.files;

              var reader = new FileReader();
              reader.onload = function (e) {
                  var data = this.result;
                  debugger;
                  vm.composer.commands.exec('insertImage',e.target.result);
              }
              reader.readAsDataURL( files[0] );
          });
                $($('.wysihtml5-sandbox').contents().find('body')).on("dragover", function(event) {
      console.log('graddddd');
                  event.preventDefault();
                  event.stopPropagation();
                  $(this).addClass('dragging');
              });
        }
    }
});
</code>```

https://jsfiddle.net/surajmahajan007/2yu456nw/

Body:
Try this

$('.textarea').wysihtml5({
    events: {
        "load": function() {
        var vm=this;
           $($('.wysihtml5-sandbox').contents().find('body')).on("dragleave", function(event) {
              event.preventDefault();
              event.stopPropagation();
          });

          $($('.wysihtml5-sandbox').contents().find('body')).on("drop", function(event) {
              event.preventDefault();
              event.stopPropagation();
              debugger;
               var dt = event.originalEvent.dataTransfer;
                        var files = dt.files;

              var reader = new FileReader();
              reader.onload = function (e) {
                  var data = this.result;
                  debugger;
                  vm.composer.commands.exec('insertImage',e.target.result);
              }
              reader.readAsDataURL( files[0] );
          });
                $($('.wysihtml5-sandbox').contents().find('body')).on("dragover", function(event) {
      console.log('graddddd');
                  event.preventDefault();
                  event.stopPropagation();
                  $(this).addClass('dragging');
              });
        }
    }
});

https://jsfiddle.net/surajmahajan007/2yu456nw/


问:
Openbravo foreign key not found issue while doing update.database
Issue while doing a update.database in openbravo

[java] ALTER TABLE AD_FIELD
     [java]     ADD CONSTRAINT AD_COLUMN_FIELD FOREIGN KEY (AD_COLUMN_ID) REFERENCES AD_COLUMN (AD_COLUMN_ID)

[java] 250661 ERROR - Not all the commands in the final update step were executed correctly. This likely means at least one foreign key was not activated successfully. Please review which one, and fix the missing references, or recover the backup of your sources.
     [java] java.lang.Exception: There were serious problems while updating the database. Please review and fix them before continuing with the application rebuild
     [java]     at org.openbravo.ddlutils.task.AlterDatabaseDataAll.doExecute(AlterDatabaseDataAll.java:227)
     [java]     at org.openbravo.ddlutils.task.BaseDatabaseTask.execute(BaseDatabaseTask.java:86)
     [java]     at org.openbravo.ddlutils.task.AlterDatabaseJava.main(AlterDatabaseJava.java:38)`

答:
Please execute the below query in your database

```<code>select AD_FIELD_ID  from AD_FIELD where AD_COLUMN_ID not in (select  AD_COLUMN_ID from AD_COLUMN);
</code>```

The output columns are missing foreign key AD_COLUMN_ID in the AD_FIELD table.

Go to modulepath/src-db/database/sourcedata/AD_FIELD.xml

search for individual AD_FIELD_ID from above query output and delete from the AD_FIELD.xml file and do update.database again.

Body:
Please execute the below query in your database

select AD_FIELD_ID  from AD_FIELD where AD_COLUMN_ID not in (select  AD_COLUMN_ID from AD_COLUMN);

The output columns are missing foreign key AD_COLUMN_ID in the AD_FIELD table.

Go to modulepath/src-db/database/sourcedata/AD_FIELD.xml

search for individual AD_FIELD_ID from above query output and delete from the AD_FIELD.xml file and do update.database again.