问:
I am unable to getStatusesByTag of the enqueueUniquePeriodicWork through WorkManager
I am using WorkManager via implementation "android.arch.work:work-runtime:1.0.1" to start a PeriodicWorkRequest to call a Rest API to pull some data at interval PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS which is 15 minutes, my code is:

```<code>    PeriodicWorkRequest.Builder builder = new
            PeriodicWorkRequest.Builder(MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
            .addTag(TAG_WORKER)
            .setInputData(createInputData(config));
    WorkManager.getInstance().enqueueUniquePeriodicWork(TAG_WORKER,
            ExistingPeriodicWorkPolicy.KEEP, builder.build());
</code>```

I want to know the status or the PeriodicWorkRequest enqueued by WorkManager by its TAG, through the code:

```<code>WorkManager.getInstance().getStatusesByTag(TAG_WORKER);
</code>```

But I am unable to resolve the method getStatusesByTag(TAG_WORKER), please help if anyone did the workaround to get the Status of Request been enqueued by TAG.

Thanks in advance!

答:
The API to get information on the WorkRequest's status changed last year with 1.0.0-alpha11. To know the status of your work you can use:

```<code>WorkManager.getInstance().getWorkInfosByTagLiveData(TAG_WORKER)
    .observe(lifecycleOwner, new Observer<WorkInfo>() {
        @Override
        public void onChanged(@Nullable WorkInfo workInfo) {
          if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
              displayMessage("Work finished!")
          }
        }
    });
</code>```

You can find more information on WorkManager's documentation page: "Work States and observing work"

Body:
I am using WorkManager via implementation "android.arch.work:work-runtime:1.0.1" to start a PeriodicWorkRequest to call a Rest API to pull some data at interval PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS which is 15 minutes, my code is:

    PeriodicWorkRequest.Builder builder = new
            PeriodicWorkRequest.Builder(MyWorker.class,
            PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS)
            .addTag(TAG_WORKER)
            .setInputData(createInputData(config));
    WorkManager.getInstance().enqueueUniquePeriodicWork(TAG_WORKER,
            ExistingPeriodicWorkPolicy.KEEP, builder.build());

I want to know the status or the PeriodicWorkRequest enqueued by WorkManager by its TAG, through the code:

WorkManager.getInstance().getStatusesByTag(TAG_WORKER);

But I am unable to resolve the method getStatusesByTag(TAG_WORKER), please help if anyone did the workaround to get the Status of Request been enqueued by TAG.

Thanks in advance!

Body:
The API to get information on the WorkRequest's status changed last year with 1.0.0-alpha11. To know the status of your work you can use:

WorkManager.getInstance().getWorkInfosByTagLiveData(TAG_WORKER)
    .observe(lifecycleOwner, new Observer<WorkInfo>() {
        @Override
        public void onChanged(@Nullable WorkInfo workInfo) {
          if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
              displayMessage("Work finished!")
          }
        }
    });

You can find more information on WorkManager's documentation page: "Work States and observing work"


来源: stackexchange

问:
Get count of array objects belonging to a partical ID in JavaScript/Node js
I have an array of arrays like this:

```<code>var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]
</code>```

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

```<code>[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]
</code>```

Note that the output is in the ascending order of the Count.

This is what I tried :

```<code>var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)
</code>```

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?

答:
Try using Array#prototype#reduce

const array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
];

const res = array.reduce((acc, curr) => {
 let foundElement = acc.find(x => x.id === curr[0]);

 if (!foundElement) {
  foundElement = {
   id: curr[0],
   count: 1
  };

  acc.push(foundElement);
 }
 else {
  foundElement.count += 1;
 }

 return acc;
}, [])
.sort((a, b) => a.count - b.count);

console.log(res);```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of arrays like this:

var array = [
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

The ID's in the above array (2,3 and 4) come dynamically from a server response.
I need to count the number of entries for a particular ID.
I'm not able to figure out how to loop over this array to get the expected output.
The expected output is:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

Note that the output is in the ascending order of the Count.

This is what I tried :

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

I believe the way I'm doing it is not the best approach if the data is dynamic.
How do I do it in a better way?


问:
VBA - Copy-Paste to another workbook
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

```<code>
Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub
</code>```

答:
Here, and only because I'm bored at work, the are thousands of posts like this:</p>

```<code>Option Explicit
Sub CopyPaste()

    Dim uploadfile As String 'not Variant, the filename will be a string
    Dim wbCopy As Workbook 'Better than uploader As Workbook you need to declare variables easy to read
    Dim wbPaste As Workbook 'same as above
    Dim LastRow As Lon 'integer doesn't work (it will be a long delimited to integer) either Byte(0-255) or Long

    Set wbPaste = ThisWorkbook 'the workbook containing the code

    uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If

    Set wbCopy = Workbooks.Open(uploadfile) 'declare your paste workbook like this

    ' Set uploader = ActiveWorkbook this way of referencing a workbook might give you errors, use the above

    With wbCopy.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        'Application.CutCopyMode = False this is useless here it's emptying the clipboard but below you copy something new
        .Range("A1:J100").Copy 'you missed the . on the beginning (when using With you need to use the dot to reference the with)
    End With

    With wbPaste.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
        .Range("A" & LastRow).PasteSpecial xlPasteValues 'when you copy/paste you just need to find the first cell on the paste range, Excel will paste the whole range
    End With

    Application.CutCopyMode = False 'now you can use this to avoid warning message on closing the copy workbook
    wbCopy.Close Savechanges:=False

End Sub
</code>```

Title: VBA - Copy-Paste to another workbook

Body:
I am trying to copy specific cells from one workbook to another at the end of the table.
I assume the problem is with using 'ActiveWorkbook' a lot.
I get the error "Object doesnt support this property or method" and it seems that macro copies cells from CurrentBook and not uploader.

How can I fix my code?

Dim uploadfile As Variant
Dim uploader As Workbook
Dim CurrentBook As Workbook
Dim lastRow As Integer

Set CurrentBook = ActiveWorkbook

uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If
Workbooks.Open uploadfile

Set uploader = ActiveWorkbook

With uploader
    Application.CutCopyMode = False
    Range("A1:J100").Copy
End With

CurrentBook.Activate
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
Range("A" & lastRow & ":J" & lastRow + 100).Select
Selection.Paste

uploader.Close

End Sub

Body:
Here, and only because I'm bored at work, the are thousands of posts like this:

Option Explicit
Sub CopyPaste()

    Dim uploadfile As String 'not Variant, the filename will be a string
    Dim wbCopy As Workbook 'Better than uploader As Workbook you need to declare variables easy to read
    Dim wbPaste As Workbook 'same as above
    Dim LastRow As Lon 'integer doesn't work (it will be a long delimited to integer) either Byte(0-255) or Long

    Set wbPaste = ThisWorkbook 'the workbook containing the code

    uploadfile = Application.GetOpenFilename()
    If uploadfile = "False" Then
        Exit Sub
    End If

    Set wbCopy = Workbooks.Open(uploadfile) 'declare your paste workbook like this

    ' Set uploader = ActiveWorkbook this way of referencing a workbook might give you errors, use the above

    With wbCopy.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        'Application.CutCopyMode = False this is useless here it's emptying the clipboard but below you copy something new
        .Range("A1:J100").Copy 'you missed the . on the beginning (when using With you need to use the dot to reference the with)
    End With

    With wbPaste.Sheets("MySheetName") 'reference always the worksheets, change MySheetName for the actual sheet name
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
        .Range("A" & LastRow).PasteSpecial xlPasteValues 'when you copy/paste you just need to find the first cell on the paste range, Excel will paste the whole range
    End With

    Application.CutCopyMode = False 'now you can use this to avoid warning message on closing the copy workbook
    wbCopy.Close Savechanges:=False

End Sub


问:
Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass
When i'm trying to run the test suite, am getting this exception. We are using maven project here and i am done with refreshing, cleaning, reinstalling testNG and then imported the maven projects but then also am getting the same exception. Please suggest any ways that am missing here.

Error console:

```<code>org.testng.TestNGException:
Cannot find class in classpath: EmpClass

at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:543)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:766)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1350)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2778)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:333)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:39)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:17)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:10)
at org.testng.xml.Parser.parse(Parser.java:168)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:311)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
</code>```

答: Make sure that your class is under src. </p>

ContentLicense: CC BY-SA 3.0

Body:
When i'm trying to run the test suite, am getting this exception. We are using maven project here and i am done with refreshing, cleaning, reinstalling testNG and then imported the maven projects but then also am getting the same exception. Please suggest any ways that am missing here.

Error console:

org.testng.TestNGException:
Cannot find class in classpath: EmpClass

at org.testng.xml.XmlClass.loadClass(XmlClass.java:81)
at org.testng.xml.XmlClass.init(XmlClass.java:73)
at org.testng.xml.XmlClass.<init>(XmlClass.java:59)
at org.testng.xml.TestNGContentHandler.startElement(TestNGContentHandler.java:543)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:766)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1350)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2778)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(SAXParserImpl.java:333)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:195)
at org.testng.xml.XMLParser.parse(XMLParser.java:39)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:17)
at org.testng.xml.SuiteXmlParser.parse(SuiteXmlParser.java:10)
at org.testng.xml.Parser.parse(Parser.java:168)
at org.testng.TestNG.initializeSuitesAndJarFile(TestNG.java:311)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:88)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

Body: Make sure that your class is under src.


问:
struts 1.2 - bean message display in lower case
I am using struts 1.2 in my project and need to iterate the list item in the JSP, get each item and convert that item in to lowercase. Please refer the code below.

```<code><logic:iterate id="cityData" name="cityList" >
<p>
    List Messages <bean:message name="cityData" property="cityName"/>
</p>
</logic:iterate>
</code>```

I want to display the cityName in lower case. Can anybody have any idea about this?

Thanks
AK

答:
Please try using <bean:define/> instead of <bean:message />

```<code><logic:iterate id="cityData" name="cityList" >
 <bean:define id = "name" name="cityData" property="cityName" type = "java.lang.String"/>
 <p>
  List Messages <%=name.toLowerCase())%>
 </p>
</logic:iterate>
</code>```

Body:
I am using struts 1.2 in my project and need to iterate the list item in the JSP, get each item and convert that item in to lowercase. Please refer the code below.

<logic:iterate id="cityData" name="cityList" >

    List Messages <bean:message name="cityData" property="cityName"/>

</logic:iterate>

I want to display the cityName in lower case. Can anybody have any idea about this?

Thanks
AK

Body:
Please try using <bean:define/> instead of <bean:message />

<logic:iterate id="cityData" name="cityList" >
 <bean:define id = "name" name="cityData" property="cityName" type = "java.lang.String"/>
 <p>
  List Messages <%=name.toLowerCase())%>
 </p>
</logic:iterate>


问:
JQuery - How to add a class to every last list item?
Got some code here that isn't working:

```<code>$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});
</code>```

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

```<code><ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="last">Item 3</li>
</ul>
</code>```

Hope that makes sense,
Cheers!

答:
Easy mistake to make.  Try this:

```<code>$("#sidebar ul li:last-child").addClass("last");
</code>```

Basically :last doesn't quite do what you think it does.  It only matches the very last in the document, not the last in each list. That's what :last-child is for.

OwnerDisplayName: Keith Donegan

ContentLicense: CC BY-SA 2.5

Body:
Got some code here that isn't working:

$("#sidebar ul li:last").each(function(){
      $(this).addClass("last");
});

Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.

Item 1

Item 2

Item 3

Hope that makes sense,
Cheers!

Body:
Easy mistake to make.  Try this:

$("#sidebar ul li:last-child").addClass("last");

Basically :last doesn't quite do what you think it does.  It only matches the very last in the document, not the last in each list. That's what :last-child is for.

OwnerDisplayName: cletus


问:
WorkflowInspectionServices throw me an XamlObjectWriterException in Workflow Foundation
For a simple prototype, I've to display a workflow file, and show on which step we are actually.

I found a sample here: http://msdn.microsoft.com/en-us/library/ee624139.aspx

Which does almost what I need.

In this sample, all action never wait on another action. So I created myself some very dummy Activity:

```<code>    public class WaitForNextCall :NativeActivity
{
    public const String WaitBookmark = "WaitingStep";

    #region Overrides of NativeActivity

    /// <summary>
    /// When implemented in a derived class, runs the activity’s execution logic.
    /// </summary>
    /// <param name="context">The execution context in which the activity executes.</param>
    protected override void Execute(NativeActivityContext context)
    {
        context.CreateBookmark(WaitBookmark);
    }

    protected override bool CanInduceIdle
    {
        get
        {
            return true;
        }
    }
    #endregion
}
</code>```

Which seems to work. Since there I was creating my workflow directly in-code:

```<code>            return new Sequence()
                   {
                       Activities =
                           {
                               new WaitForNextCall(){DisplayName = "Step one"},
                               new WaitForNextCall(){DisplayName = "Step Two"},
                               new WaitForNextCall(){DisplayName = "Step Three"},
                               new WaitForNextCall(){DisplayName = "Step Four"}
                           }
                   };
</code>```

The only problem with that is that I only see a "Sequence" element in the workflow designer.

So I created a xaml file which describe exactily the same thing, and I load it like this:

```<code>return ActivityXamlServices.Load("Workflows/WorkflowSample.xaml") as DynamicActivity;
</code>```

But then I got this exception:

```<code>    System.Xaml.XamlObjectWriterException occurred
  Message=Impossible de créer le type inconnu '{clr-MyTestNameSpace.UserInterface.WorkflowItems}WaitForNextCall'.
  Source=System.Xaml
  LineNumber=0
  LinePosition=0
  StackTrace:
       à System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
       à System.Xaml.XamlWriter.WriteNode(XamlReader reader)
       [...]
</code>```

I double-checked, the file is present(it appears, that there is another error message when file isn't specified correctly). But it cannot find my "WaitFornextCall" class, which is used just several lines below.

I'm a little desesperate, I'm trying to understand how works Workflow foundations, but it's a little hard for now :(

Any advice will be welcome

Edit:
I tried this to read the file, I don't have any exception in my constructor, but I don't know why, some libraries I'm using(ActiPro) seems to doesn't work anymore after the load:

```<code>        XamlReader reader = new XamlXmlReader("Workflows/WorkflowSample.xaml", new XamlXmlReaderSettings(){LocalAssembly =  System.Reflection.Assembly.GetExecutingAssembly()});

        return ActivityXamlServices.Load(reader);
</code>```

答:
"Workflows/WorkflowSample.xaml" probably was built against a prior version of your code.

Delete it, rebuild your solution, then recreate it.

Body:
For a simple prototype, I've to display a workflow file, and show on which step we are actually.

I found a sample here: http://msdn.microsoft.com/en-us/library/ee624139.aspx

Which does almost what I need.

In this sample, all action never wait on another action. So I created myself some very dummy Activity:

    public class WaitForNextCall :NativeActivity
{
    public const String WaitBookmark = "WaitingStep";

    #region Overrides of NativeActivity

    ///
    /// When implemented in a derived class, runs the activity’s execution logic.
    ///
    /// <param name="context">The execution context in which the activity executes.</param>
    protected override void Execute(NativeActivityContext context)
    {
        context.CreateBookmark(WaitBookmark);
    }

    protected override bool CanInduceIdle
    {
        get
        {
            return true;
        }
    }
    #endregion
}

Which seems to work. Since there I was creating my workflow directly in-code:

            return new Sequence()
                   {
                       Activities =
                           {
                               new WaitForNextCall(){DisplayName = "Step one"},
                               new WaitForNextCall(){DisplayName = "Step Two"},
                               new WaitForNextCall(){DisplayName = "Step Three"},
                               new WaitForNextCall(){DisplayName = "Step Four"}
                           }
                   };

The only problem with that is that I only see a "Sequence" element in the workflow designer.

So I created a xaml file which describe exactily the same thing, and I load it like this:

return ActivityXamlServices.Load("Workflows/WorkflowSample.xaml") as DynamicActivity;

But then I got this exception:

    System.Xaml.XamlObjectWriterException occurred
  Message=Impossible de créer le type inconnu '{clr-MyTestNameSpace.UserInterface.WorkflowItems}WaitForNextCall'.
  Source=System.Xaml
  LineNumber=0
  LinePosition=0
  StackTrace:
       à System.Xaml.XamlObjectWriter.WriteStartObject(XamlType xamlType)
       à System.Xaml.XamlWriter.WriteNode(XamlReader reader)
       [...]

I double-checked, the file is present(it appears, that there is another error message when file isn't specified correctly). But it cannot find my "WaitFornextCall" class, which is used just several lines below.

I'm a little desesperate, I'm trying to understand how works Workflow foundations, but it's a little hard for now :(

Any advice will be welcome

Edit:
I tried this to read the file, I don't have any exception in my constructor, but I don't know why, some libraries I'm using(ActiPro) seems to doesn't work anymore after the load:

        XamlReader reader = new XamlXmlReader("Workflows/WorkflowSample.xaml", new XamlXmlReaderSettings(){LocalAssembly =  System.Reflection.Assembly.GetExecutingAssembly()});

        return ActivityXamlServices.Load(reader);


问:
Open a image file then display it in new window
I have a button in my GUI then after selecting a image file I want it to display in new window.

Code:

```<code>import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
a = Tk()

def openimgfile():
    currdir = os.getcwd()
    name = filedialog.askopenfile(initialdir = currdir, title = "Select a Image", filetype = ( ("PNG", "*.png"), ("JPEG", "*.jpg;.*jpeg"), ("All files", "*.*") ) )

a.title("Pattern Matching")
a.minsize(200,200)
button1 = Button(text="Open file",width = 10,height =10,command=openimgfile).pack()

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

答:
For this to work you need to initialize this in command function:</p>

```<code>from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()

def open_img_file():
    filename = filedialog.askopenfilename(initialdir=os.getcwd(
    ), title="Select file", filetypes=(("png images", ".png"), ("all files", "*.*")))
    if not filename:
        return
    # setup new window
    new_window = Toplevel(window)
    # get image
    image = ImageTk.PhotoImage(Image.open(filename))
    # load image
    panel = Label(new_window, image=image)
    panel.image = image
    panel.pack()

window.title("Pattern Matching")
window.minsize(200, 200)
button = Button(text="Open file", width=10, height=10,
                command=open_img_file)
button.pack()

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

Body:
I have a button in my GUI then after selecting a image file I want it to display in new window.

Code:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import os
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
a = Tk()

def openimgfile():
    currdir = os.getcwd()
    name = filedialog.askopenfile(initialdir = currdir, title = "Select a Image", filetype = ( ("PNG", "*.png"), ("JPEG", "*.jpg;.*jpeg"), ("All files", "*.*") ) )

a.title("Pattern Matching")
a.minsize(200,200)
button1 = Button(text="Open file",width = 10,height =10,command=openimgfile).pack()

a.mainloop()

Body:
For this to work you need to initialize this in command function:

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk
import os

window = Tk()

def open_img_file():
    filename = filedialog.askopenfilename(initialdir=os.getcwd(
    ), title="Select file", filetypes=(("png images", ".png"), ("all files", "*.*")))
    if not filename:
        return
    # setup new window
    new_window = Toplevel(window)
    # get image
    image = ImageTk.PhotoImage(Image.open(filename))
    # load image
    panel = Label(new_window, image=image)
    panel.image = image
    panel.pack()

window.title("Pattern Matching")
window.minsize(200, 200)
button = Button(text="Open file", width=10, height=10,
                command=open_img_file)
button.pack()

window.mainloop()


问:
flask-restplus nested namespace with blueprint and namespace
I made api server with flask-restplus.

While working with it, I noticed that it maybe have to versioning for scaling up.

So refer the docs, I found Namespace and Blueprint is usuable.

First, file structure like this.

```<code>/app
  - /main
    - __init__.py
    - /controller
      - /v1/
        - article_controller.py
  - __init__.py
</code>```

[/main/v1/__init__.py]

```<code>from flask_restplus import Namespace, Api
from flask import Blueprint

from .article_controller import api as article_ns

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='Appeal API',
          version='1.0',
          description='Appeal API',
          )

api.add_namespace(article_ns, path='/articles')
</code>```

I import article_controller.py and add it via add_namespace().

[/main/__init__.py]

```<code>from flask_restplus import Api
from flask import Blueprint

from app.main.controller.v1 import api as api_v1

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='Appeal API v1',
          version='1.0',
          description='Appeal API v1',
          #   prefix='/api'
          )

# Version1
api.add_namespace(api_v1, path='/v1/')
</code>```

Import v1 and add it to namespace.

But when I access to /v1/articles, Not found errors has occured.

I can't catch where is the wrong code.

Any solution here?

Thanks.

答:
Where did you create your flask app?

in your app (the root of your project), you should have something like

app.py

that's where you define your flask app and register blueprints in it

like...

```<code>from flask import Flask
from main import blueprint as api1

app = Flask(__name__)
app.register_blueprint(api1)
app.run(debug=True)
</code>```

look at this example in docs

Body:
I made api server with flask-restplus.

While working with it, I noticed that it maybe have to versioning for scaling up.

So refer the docs, I found Namespace and Blueprint is usuable.

First, file structure like this.

/app
  - /main
    - __init__.py
    - /controller
      - /v1/
        - article_controller.py
  - __init__.py

[/main/v1/__init__.py]

from flask_restplus import Namespace, Api
from flask import Blueprint

from .article_controller import api as article_ns

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='Appeal API',
          version='1.0',
          description='Appeal API',
          )

api.add_namespace(article_ns, path='/articles')

I import article_controller.py and add it via add_namespace().

[/main/__init__.py]

from flask_restplus import Api
from flask import Blueprint

from app.main.controller.v1 import api as api_v1

blueprint = Blueprint('api', __name__)

api = Api(blueprint,
          title='Appeal API v1',
          version='1.0',
          description='Appeal API v1',
          #   prefix='/api'
          )

# Version1
api.add_namespace(api_v1, path='/v1/')

Import v1 and add it to namespace.

But when I access to /v1/articles, Not found errors has occured.

I can't catch where is the wrong code.

Any solution here?

Thanks.

Body:
Where did you create your flask app?

in your app (the root of your project), you should have something like

app.py

that's where you define your flask app and register blueprints in it

like...

from flask import Flask
from main import blueprint as api1

app = Flask(__name__)
app.register_blueprint(api1)
app.run(debug=True)

look at this example in docs


问:
How to create Regular expression to extract a value from the string response?
How to find the regular expression to extract the Value Tag from the following response?</p>

```<code><CustomFieldList>
    <CustomField>
        <Name>OFFER_META_DATA</Name>
        <Value>
            SE7gOMOEOfvKjka8b+8k4SqccKEAB8ZjUqDl0Mv7OZeKEITd0l2rAFAL1XAxgzE8+lLt6XaR9IYDY0MmUaRfGXkiE/SOmYzMB+DccN2V1cOfsBav1BNaUsubTKW79qtXwwNcg4saeZZSqaiAVDJIFFUZq+u0UhqE6aZ2EbdwELyHZPP9HfHSRHCV9ihjlHvGHKRYdL2j4PvE5O5eg3ajmSTmI5aRAG42+epkCroTRDglUmCnHMTlA3VvSvtBV/fq9lI54JqqkSDj+83tKhclvZWPw08zu6drpp6PeZwmG1UwlmokLAwI0QCxYjnJEYwt7Ikt1sm8JqWzUPoVGHJoyw==%~~`%~~~~~~~%^**(%$#%ZWZby8uQ7CCjcQDbU7exlCDAXUeQ47bkD2kcxkobEQ9y1IBlPDpk7JEquCdxOnkKCRi9y8AswLegW98YyC+OAUoMCvN5XWYMJOmGK2gkj+5xzUbGZy9GS7ov4DQ+rPaHqvomADIKxXNw52ZSda/cwvfcUETGxi6yDcEgdIXj4abWQTNUGoSE34oHPNZ0CamHd1ZCZr36DqrIRXO595aTTAQX2E/ZUvoXnxT79ezoCOkt/xGOAEGKUjCUYYGnOAmHARf5t4aqK9Z+JhB8wVtT9KaD7xunGePjINmQrEYDeosEGrFyQ0OQWfwDyjQmA+GFbFRoabZgg3tkjCNCWEXI6Q==
        </Value>
    </CustomField>
</CustomFieldList>
</code>```

答:
Use CSS selector as shown below:-

Hope this helps.

Body:
How to find the regular expression to extract the Value Tag from the following response?

<CustomFieldList>
    <CustomField>
        <Name>OFFER_META_DATA</Name>
        <Value>
            SE7gOMOEOfvKjka8b+8k4SqccKEAB8ZjUqDl0Mv7OZeKEITd0l2rAFAL1XAxgzE8+lLt6XaR9IYDY0MmUaRfGXkiE/SOmYzMB+DccN2V1cOfsBav1BNaUsubTKW79qtXwwNcg4saeZZSqaiAVDJIFFUZq+u0UhqE6aZ2EbdwELyHZPP9HfHSRHCV9ihjlHvGHKRYdL2j4PvE5O5eg3ajmSTmI5aRAG42+epkCroTRDglUmCnHMTlA3VvSvtBV/fq9lI54JqqkSDj+83tKhclvZWPw08zu6drpp6PeZwmG1UwlmokLAwI0QCxYjnJEYwt7Ikt1sm8JqWzUPoVGHJoyw==%~~`%~~~~~~~%^**(%$#%ZWZby8uQ7CCjcQDbU7exlCDAXUeQ47bkD2kcxkobEQ9y1IBlPDpk7JEquCdxOnkKCRi9y8AswLegW98YyC+OAUoMCvN5XWYMJOmGK2gkj+5xzUbGZy9GS7ov4DQ+rPaHqvomADIKxXNw52ZSda/cwvfcUETGxi6yDcEgdIXj4abWQTNUGoSE34oHPNZ0CamHd1ZCZr36DqrIRXO595aTTAQX2E/ZUvoXnxT79ezoCOkt/xGOAEGKUjCUYYGnOAmHARf5t4aqK9Z+JhB8wVtT9KaD7xunGePjINmQrEYDeosEGrFyQ0OQWfwDyjQmA+GFbFRoabZgg3tkjCNCWEXI6Q==
        </Value>
    </CustomField>
</CustomFieldList>


问:
How do I base conditional formatting on validation results in Excel?
I want to change the formatting of a cell if the cell is not valid. In this case, "valid" means that the cell has failed the data validation rules.

I'm asking this question because I couldn't find the answer on SO. I eventually solved it. I'll post my answer and see if people want to comment or provide a better answer!

答:
If you are referencing a list in another workbook, then it is simpler to recreate the data validation rule as a conditional formatting rule.

If your conditional formatting starts at Cell A1 on Sheet1, and the list is contained from A1:A10 on Sheet2, then your conditional formatting rule would be:

```<code>=AND($A1<>0,COUNTIF(Sheet2!$A$1:$A$10,$A1)<1)
</code>```

This would highlight the cell if its value does not appear in the source list, and is not blank.

Clearly, for non-list based data validation, you can come up with an equivalent formula in the same manner.

You could make things more robust by setting up a named range for the list which both the data validation and conditional formatting refer to, such that if the list range grows, you only need to edit it in one place (the Name Manager), and it will update both Data Validation and Conditional Formatting ranges.

Body:
If you are referencing a list in another workbook, then it is simpler to recreate the data validation rule as a conditional formatting rule.

If your conditional formatting starts at Cell A1 on Sheet1, and the list is contained from A1:A10 on Sheet2, then your conditional formatting rule would be:

=AND($A1<>0,COUNTIF(Sheet2!$A$1:$A$10,$A1)<1)

This would highlight the cell if its value does not appear in the source list, and is not blank.

Clearly, for non-list based data validation, you can come up with an equivalent formula in the same manner.

You could make things more robust by setting up a named range for the list which both the data validation and conditional formatting refer to, such that if the list range grows, you only need to edit it in one place (the Name Manager), and it will update both Data Validation and Conditional Formatting ranges.


问:
javascript compare array of objects by key
I want to match id and parentId if match then add in child

ex

let menuItems = [
  {
        "id": "menu-0",
        "title": "Home",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-1",
        "title": "About",
        "parentId": null,
        "childCount": 2
    },
     {
        "id": "menu-3",
        "title": "About Sub1",
        "parentId": "menu-1",
        "childCount": 2
    },
     {
        "id": "menu-5",
        "title": "About Sub2",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-4",
        "title": "About Sub1 sub1",
        "parentId": "menu-3",
        "childCount": 0
    },
     {
        "id": "menu-6",
        "title": "Contact",
        "parentId": null,
        "childCount": 2
    }
]```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
 <li>About
     <ul>
         <li>
            About Sub1
         </li>
    </ul>
 </li>
 <li>
            Contact
 </li>
</ul></code>```

```<code>data[i].id == data[i].parentId
</code>```

but return false

答:
```<code>enter code here{ for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data.length; j++) {
                if(data[i].id == data[j].parentId){
                    console.log(data[i]);
                }
        }
    }

output
{id: "menu-1", title: "About", parentId: null, childCount: 2}
 {id: "menu-1", title: "About", parentId: null, childCount: 2}
 {id: "menu-3", title: "About Sub1", parentId: "menu-1", childCount: 2}
</code>```

<p>}</p>

Body:
I want to match id and parentId if match then add in child

ex

let menuItems = [
  {
        "id": "menu-0",
        "title": "Home",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-1",
        "title": "About",
        "parentId": null,
        "childCount": 2
    },
     {
        "id": "menu-3",
        "title": "About Sub1",
        "parentId": "menu-1",
        "childCount": 2
    },
     {
        "id": "menu-5",
        "title": "About Sub2",
        "parentId": "menu-1",
        "childCount": 0
    },
     {
        "id": "menu-4",
        "title": "About Sub1 sub1",
        "parentId": "menu-3",
        "childCount": 0
    },
     {
        "id": "menu-6",
        "title": "Contact",
        "parentId": null,
        "childCount": 2
    }
]

About

            About Sub1

            Contact

data[i].id == data[i].parentId

but return false

Body:
enter code here{ for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data.length; j++) {
                if(data[i].id == data[j].parentId){
                    console.log(data[i]);
                }
        }
    }

output
{id: "menu-1", title: "About", parentId: null, childCount: 2}
 {id: "menu-1", title: "About", parentId: null, childCount: 2}
 {id: "menu-3", title: "About Sub1", parentId: "menu-1", childCount: 2}

}


问:
How do I find out how many records of 1 model have associated objects of an association?
I have two models - Property & Photos.

```<code>class Property < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

class Photo < ActiveRecord::Base
  belongs_to :property
end
</code>```

All I want to do is create a scope that returns only the Properties that actually have photos (i.e. photos.count > 0).

I have tried a million iterations of queries, and they don't work for one reason or another.

See some examples of what I have tried and the results:

```<code>[32] pry(main)> Property.includes(:photos).where('photos.count > 0').count
   (4.1ms)  SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
[33] pry(main)> Property.joins(:photos).where('photos.count > 0').count
   (11.1ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^

[38] pry(main)> Property.joins(:photos).count("properties.id").count
   (158.2ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `count' for 72604:Fixnum
from (pry):38:in `__pry__'

[39] pry(main)> Property.joins(:photos).count("properties.id")
   (50.6ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
=> 72604

[40] pry(main)> Photo.joins(:properties).count("photos.id")
ActiveRecord::ConfigurationError: Association named 'properties' was not found on Photo; perhaps you misspelled it?
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/associations/join_dependency.rb:112:in `build'

[41] pry(main)> Photo.joins(:property).count("photos.id")
   (65.0ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[42] pry(main)> Photo.joins(:property).count("photos.id")
   (60.5ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[43] pry(main)> Property.joins(:photos).count("properties.id").distinct
   (46.4ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `distinct' for 72604:Fixnum
from (pry):43:in `__pry__'

[44] pry(main)> Property.joins(:photos).distinct.count("properties.id")
=> 0
</code>```

This should be simple, but for some reason it's much more difficult than I expected.

Thoughts?

答:
In order to get only the Properties that actually have photos (i.e. photos.count > 0), you need to perform inner join of two tables.

In rails 5, you can do it by below command

```<code>Property.joins(:photos)
</code>```

This will be transformed to SQL as

```<code>SELECT  "properties".* FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
</code>```

If you want to add more conditions on your queries, you can add Where clause

```<code>Property.joins(:photos).where(properties: {id: [1, 2]})
</code>```

Body:
I have two models - Property & Photos.

class Property < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

class Photo < ActiveRecord::Base
  belongs_to :property
end

All I want to do is create a scope that returns only the Properties that actually have photos (i.e. photos.count > 0).

I have tried a million iterations of queries, and they don't work for one reason or another.

See some examples of what I have tried and the results:

[32] pry(main)> Property.includes(:photos).where('photos.count > 0').count
   (4.1ms)  SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
[33] pry(main)> Property.joins(:photos).where('photos.count > 0').count
   (11.1ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^

[38] pry(main)> Property.joins(:photos).count("properties.id").count
   (158.2ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `count' for 72604:Fixnum
from (pry):38:in `__pry__'

[39] pry(main)> Property.joins(:photos).count("properties.id")
   (50.6ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
=> 72604

[40] pry(main)> Photo.joins(:properties).count("photos.id")
ActiveRecord::ConfigurationError: Association named 'properties' was not found on Photo; perhaps you misspelled it?
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/associations/join_dependency.rb:112:in `build'

[41] pry(main)> Photo.joins(:property).count("photos.id")
   (65.0ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[42] pry(main)> Photo.joins(:property).count("photos.id")
   (60.5ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604

[43] pry(main)> Property.joins(:photos).count("properties.id").distinct
   (46.4ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `distinct' for 72604:Fixnum
from (pry):43:in `__pry__'

[44] pry(main)> Property.joins(:photos).distinct.count("properties.id")
=> 0

This should be simple, but for some reason it's much more difficult than I expected.

Thoughts?

Body:
In order to get only the Properties that actually have photos (i.e. photos.count > 0), you need to perform inner join of two tables.

In rails 5, you can do it by below command

Property.joins(:photos)

This will be transformed to SQL as

SELECT  "properties".* FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"

If you want to add more conditions on your queries, you can add Where clause

Property.joins(:photos).where(properties: {id: [1, 2]})


问:
Trying to get the cpu usage of a specified process on different servers
Basically I'm trying to write a script which will retrieve the cpu usage of a process(multiple processes specified in a XML file) from different servers inside a network.

I'm trying to use Invoke-Command to run the script, add the resulting table to collectionVariable and finally convert the result to Html.

Table format

```<code>$Format = @"
<style>
TABLE {width:90%;margin-left:5%; border-width: 1px; border-style: solid;
border-color: black; border-collapse: collapse;}
TH {border-width: 1px; padding: 3px; border-style: solid; border-color:
black; background-color: #6495ED;}
TD {border-width: 1px; padding: 3px; border-style: solid; border-color:
black;}
</style>
"@
</code>```

Function to parse the xml file with the credentials

```<code>function parseXmlCredential {
[xml]$xml1 = get-content xmlCredentials\*.xml

$servers = $xml1.Configuration.servers;
$names = $xml1.Configuration.name;
$username = $xml1.Configuration.username;
$password = $xml1.Configuration.password;

$server = $servers -split ','
$name = $names -split ','

return $server, $name, $username, $password
}

$server, $name, $username, $password = parseXmlCredential;
</code>```

Properties of the item to be selected

```<code> $properties = @(
 @{Name = 'Server';  Expression = { $server}},
 @{Name = "Process Name";Expression ={$_.Name}},
 @{Name = "Process Id";Expression = {$_.Id}},
 @{Name = 'CPUPercent(%)';Expression = {
      $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
      [Math]::Round( ($_.CPU * 100 / $TotalSec), 2)}},
 @{Name ="Memory (MB)";Expression = {[Math]::Round(($_.privatememorysize / 1mb),2)}}
 )
</code>```

Inside it I will store the resulting tables for each process

```<code>$collectionVariable = New-Object System.Collections.ArrayList
</code>```

Accessing all servers

```<code>foreach($j in $server)
 {
 $server = $j
</code>```

For each server I retrieve data for all the required processes

```<code>foreach($i in $name)
 {
 $rezultat = Invoke-Command -ComputerName $j -ScriptBlock {

 $table = Get-Process |
 Where-Object {$_.Name -like $i+'*' } |
 Where-Object {$_.Name -notmatch "^(idle|_total|system)$"} |
 Select-Object  $properties |
 Sort-Object -Property *CPUPercent* -Descending |
 ConvertTo-Html -As TABLE -Fragment |
 Out-String

 $collectionVariable.Add($table) | Out-Nul
   } -ArgumentList $i,(,$properties),(,$collectionVariable)
  }
 }
</code>```

Convert the result to Html

```<code>ConvertTo-Html -Head $Format -PostContent $collectionVariable |
 Out-File //the out file
</code>```

As a result I should have a html page with tables for each process, but I get the following error.

```<code>You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2309

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2309

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2256

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2256

ConvertTo-Html : Cannot validate argument on parameter 'PostContent'. The
argument is null, empty, or an element of the argument collection
contains a null value. Supply a collection that does not contain any null
values and then try the command again.
At C:\Users\lucianp\Downloads\processes_details_powershell\script.ps1:72
char:43
+ ConvertTo-Html -Head $Header -PostContent $collectionVariable |
+                                           ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [ConvertTo-Html],
ParameterBindingValidationException    +FullyQualifiedErrorIdParameterArgumentValidationError,Microsoft.PowerShell.Commands.ConvertToHtmlCommand
</code>```

答:
I found the answer:
The problem was with the collectionVariable, I was trying to add the result inside the Invoke-Command.Instead, I should add $rezultat outside the invoke-command, right afer it.</p>

Body:
Basically I'm trying to write a script which will retrieve the cpu usage of a process(multiple processes specified in a XML file) from different servers inside a network.

I'm trying to use Invoke-Command to run the script, add the resulting table to collectionVariable and finally convert the result to Html.

Table format

$Format = @"

"@

Function to parse the xml file with the credentials

function parseXmlCredential {
[xml]$xml1 = get-content xmlCredentials\*.xml

$servers = $xml1.Configuration.servers;
$names = $xml1.Configuration.name;
$username = $xml1.Configuration.username;
$password = $xml1.Configuration.password;

$server = $servers -split ','
$name = $names -split ','

return $server, $name, $username, $password
}

$server, $name, $username, $password = parseXmlCredential;

Properties of the item to be selected

 $properties = @(
 @{Name = 'Server';  Expression = { $server}},
 @{Name = "Process Name";Expression ={$_.Name}},
 @{Name = "Process Id";Expression = {$_.Id}},
 @{Name = 'CPUPercent(%)';Expression = {
      $TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
      [Math]::Round( ($_.CPU * 100 / $TotalSec), 2)}},
 @{Name ="Memory (MB)";Expression = {[Math]::Round(($_.privatememorysize / 1mb),2)}}
 )

Inside it I will store the resulting tables for each process

$collectionVariable = New-Object System.Collections.ArrayList

Accessing all servers

foreach($j in $server)
 {
 $server = $j

For each server I retrieve data for all the required processes

foreach($i in $name)
 {
 $rezultat = Invoke-Command -ComputerName $j -ScriptBlock {

 $table = Get-Process |
 Where-Object {$_.Name -like $i+'*' } |
 Where-Object {$_.Name -notmatch "^(idle|_total|system)$"} |
 Select-Object  $properties |
 Sort-Object -Property *CPUPercent* -Descending |
 ConvertTo-Html -As TABLE -Fragment |
 Out-String

 $collectionVariable.Add($table) | Out-Nul
   } -ArgumentList $i,(,$properties),(,$collectionVariable)
  }
 }

Convert the result to Html

ConvertTo-Html -Head $Format -PostContent $collectionVariable |
 Out-File //the out file

As a result I should have a html page with tables for each process, but I get the following error.

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2309

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2309

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2256

You cannot call a method on a null-valued expression.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
+ PSComputerName        : osvm2256

ConvertTo-Html : Cannot validate argument on parameter 'PostContent'. The
argument is null, empty, or an element of the argument collection
contains a null value. Supply a collection that does not contain any null
values and then try the command again.
At C:\Users\lucianp\Downloads\processes_details_powershell\script.ps1:72
char:43
+ ConvertTo-Html -Head $Header -PostContent $collectionVariable |
+                                           ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [ConvertTo-Html],
ParameterBindingValidationException    +FullyQualifiedErrorIdParameterArgumentValidationError,Microsoft.PowerShell.Commands.ConvertToHtmlCommand


问:
How do I configure a Bitnami Lightsail LAMP server to host a second web site?
I have an AWS Lightsail Bitnami LAMP instance hosting a single web site.  I want to create a site for a second domain on the same server but haven't yet found success.

I copied and modified a httpd-vhosts.conf file and placed it in /opt/bitnami/apache2/conf.  I added an include statement to the end of /opt/bitnami/apache2/conf/bitnami/bitnami.conf pointing to the new httpd-vhosts.conf file. When attempting to access either the new or old site the browser response is "Forbidden You don't have permission to access / on this server".

There are two code blocks in /opt/bitnami/apache2/conf/httpd-vhosts.conf. This is one of them.  The second block is identical with "site1" changed to "site2".

```<code><VirtualHost *:80>
    ServerAdmin me@site1.com
    DocumentRoot "/opt/bitnami/apache2/site1.com/htdocs"
        <Directory />
                Options -Indexes
                AllowOverride All
        </Directory>
        <Directory /opt/bitnami/apache2/site1.com/htdocs>
                Options -Indexes
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
    ServerName site1.com
    ServerAlias www.site1.com
    ErrorLog "logs/site1.com-error_log"
    CustomLog "logs/site1.com-access_log" common
</VirtualHost>
</code>```

It appears that the new httpd-vhosts.conf file is being read because the new error and access logs are created.  The error log states "client denied by server configuration:".  The directory associated with this error in the error log is ...site1.com/htdocs as defined in the httpd-vhosts.conf file.

答:
Bitnami Engineer here.

Let's try these changes to fix the errors you are running into:

Remove the following block

```<code>        <Directory />
                Options -Indexes
                AllowOverride All
        </Directory>
</code>```

You only need the one that sets the configuration for the folder where you have your app's files.

You will need to substitute these lines because they are not supported in the new Apache's version

```<code>Order allow,deny
allow from all
</code>```

is deprecated. You need to use Require all granted when using Apache 2.4

https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require

Set the permissions of your app's folder properly

```<code>sudo chown -R bitnami:daemon /opt/bitnami/apache2/site1.com/htdocs
sudo chmod -R g+w /opt/bitnami/apache2/site1.com/htdocs
</code>```

Body:
I have an AWS Lightsail Bitnami LAMP instance hosting a single web site.  I want to create a site for a second domain on the same server but haven't yet found success.

I copied and modified a httpd-vhosts.conf file and placed it in /opt/bitnami/apache2/conf.  I added an include statement to the end of /opt/bitnami/apache2/conf/bitnami/bitnami.conf pointing to the new httpd-vhosts.conf file. When attempting to access either the new or old site the browser response is "Forbidden You don't have permission to access / on this server".

There are two code blocks in /opt/bitnami/apache2/conf/httpd-vhosts.conf. This is one of them.  The second block is identical with "site1" changed to "site2".

<VirtualHost *:80>
    ServerAdmin me@site1.com
    DocumentRoot "/opt/bitnami/apache2/site1.com/htdocs"
        <Directory />
                Options -Indexes
                AllowOverride All
        </Directory>
        <Directory /opt/bitnami/apache2/site1.com/htdocs>
                Options -Indexes
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>
    ServerName site1.com
    ServerAlias www.site1.com
    ErrorLog "logs/site1.com-error_log"
    CustomLog "logs/site1.com-access_log" common
</VirtualHost>

It appears that the new httpd-vhosts.conf file is being read because the new error and access logs are created.  The error log states "client denied by server configuration:".  The directory associated with this error in the error log is ...site1.com/htdocs as defined in the httpd-vhosts.conf file.

Body:
Bitnami Engineer here.

Let's try these changes to fix the errors you are running into:

Remove the following block

        <Directory />
                Options -Indexes
                AllowOverride All
        </Directory>

You only need the one that sets the configuration for the folder where you have your app's files.

You will need to substitute these lines because they are not supported in the new Apache's version

Order allow,deny
allow from all

is deprecated. You need to use Require all granted when using Apache 2.4

https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require

Set the permissions of your app's folder properly

sudo chown -R bitnami:daemon /opt/bitnami/apache2/site1.com/htdocs
sudo chmod -R g+w /opt/bitnami/apache2/site1.com/htdocs


问:
Azure function sendgrid email not being received
I have an Azure Function that serves as a contact form for a website, my function seems to work returning 200 OK, but I am not receiving the email.

It uses the Azure sendgrid binding, send grid shows no activity and the target mailbox does not receive anything.

Assuming all my API keys are correct here is the function bellow

```<code>module.exports = async function (context, req) {
    if (req.body.email) {
        var message = {
            from: {
                email: req.body.email
            },
            subject: "Contact form submission from: " + req.body.name,
            content: [{
                type: 'text/plain',
                value: req.body.message
            }]
        };

        context.done(null, message);

        return {
            res: {
                status: 200
            },
            message: message
        };
    } else {
        return {
            res: {
                status: 400
            }
        };
    }
};
</code>```

my function.json

```<code>{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "message",
      "type": "sendGrid",
      "direction": "out",
      "apiKey" : "ASSUME_THIS_IS_CORRECT",
      "to": "$SomeoneTo@somewhere.tld",
      "from": "$someoneFrom@somewhere.tld",
      "subject": "Someone Mailed Ya!"
  }
  ]
}
</code>```

my host.json

```<code>{
  "version": "2.0",
  "extensions": {
      "sendGrid": {
          "from": "Full Name <$SomeoneFrom@somwhere.tld>"
      }
  }
}
</code>```

I gave the api key full access key so not too sure what's up with this?

答:
Here is the same code i have tried:

```<code>module.exports = function (context, order) {
    context.log(order);
    var message = {
         "personalizations": [ { "to": [ { "email": "testto@gmail.com" } ] } ],
        from: { email: "testfrom@gmail.com" },
        subject: "Azure news",
        content: [{
            type: 'text/plain',
            value: order
        }]
    };

    context.done(null, {message});
};
</code>```

and the binding was:

```<code>{
  "bindings": [
    {
      "type": "queueTrigger",
      "name": "order",
      "direction": "in",
      "queueName": "samples-orders"
    },
    {
      "type": "sendGrid",
      "name": "message",
      "direction": "out",
      "apiKey": "mysendgridkey",
      "from": "testfrom@gmail.com",
      "to": "testto@gmail.com"
    }
  ],
  "disabled": false
}
</code>```

in the Gmail, i allowed access to less secure apps

and it worked. Try and see if it works.

Body:
I have an Azure Function that serves as a contact form for a website, my function seems to work returning 200 OK, but I am not receiving the email.

It uses the Azure sendgrid binding, send grid shows no activity and the target mailbox does not receive anything.

Assuming all my API keys are correct here is the function bellow

module.exports = async function (context, req) {
    if (req.body.email) {
        var message = {
            from: {
                email: req.body.email
            },
            subject: "Contact form submission from: " + req.body.name,
            content: [{
                type: 'text/plain',
                value: req.body.message
            }]
        };

        context.done(null, message);

        return {
            res: {
                status: 200
            },
            message: message
        };
    } else {
        return {
            res: {
                status: 400
            }
        };
    }
};

my function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "name": "message",
      "type": "sendGrid",
      "direction": "out",
      "apiKey" : "ASSUME_THIS_IS_CORRECT",
      "to": "$SomeoneTo@somewhere.tld",
      "from": "$someoneFrom@somewhere.tld",
      "subject": "Someone Mailed Ya!"
  }
  ]
}

my host.json

{
  "version": "2.0",
  "extensions": {
      "sendGrid": {
          "from": "Full Name <$SomeoneFrom@somwhere.tld>"
      }
  }
}

I gave the api key full access key so not too sure what's up with this?

Body:
Here is the same code i have tried:

module.exports = function (context, order) {
    context.log(order);
    var message = {
         "personalizations": [ { "to": [ { "email": "testto@gmail.com" } ] } ],
        from: { email: "testfrom@gmail.com" },
        subject: "Azure news",
        content: [{
            type: 'text/plain',
            value: order
        }]
    };

    context.done(null, {message});
};

and the binding was:

{
  "bindings": [
    {
      "type": "queueTrigger",
      "name": "order",
      "direction": "in",
      "queueName": "samples-orders"
    },
    {
      "type": "sendGrid",
      "name": "message",
      "direction": "out",
      "apiKey": "mysendgridkey",
      "from": "testfrom@gmail.com",
      "to": "testto@gmail.com"
    }
  ],
  "disabled": false
}

in the Gmail, i allowed access to less secure apps

and it worked. Try and see if it works.


问:
How can "go to sleep" time for heroku dynos be set to a value other than 30 minutes?
I have a heroku app operated by free dynos. This app is called -- let us say -- 5 times a day by users at random times. It serves a request in 3-4 milliseconds. At every request a dyno is awakened and having served the request this dyno listens for 30 minutes needlessly. Is there any possibility to set the default 30 minute "go to sleep" time to e.g. 15 seconds or something like that?

I checked https://devcenter.heroku.com/articles/free-dyno-hours, it does not say anything on this.

答: To my knowledge it is not possible to change the default 30 minutes before going to sleep. Also it seems to be generally not possible to force a app to go to sleep. (As discussed in this post). To be 100% sure, you could ask Heroku support. Hope my answer helped. </p>


问:
Add related ForeignKey fields with serializer in Django REST Framework
I'm using Django 2.2 and Django REST Framework

I have three models like

```<code>class Plan(models.Model):
    name = models.CharField(_('Plan Name'), max_length=100)
    default = models.NullBooleanField(default=None, unique=True)
    created = models.DateTimeField(_('created'), db_index=True)
    quotas = models.ManyToManyField('Quota', through='PlanQuota')

class Quota(models.Model):
    codename = models.CharField(max_length=50, unique=True)
    name = models.CharFieldmax_length=100)
    unit = models.CharField(max_length=100, blank=True)

class PlanQuota(models.Model):
    plan = models.ForeignKey('Plan', on_delete=models.CASCADE)
    quota = models.ForeignKey('Quota', on_delete=models.CASCADE)
    value = models.IntegerField(default=1, null=True, blank=True)
</code>```

I have to get all quota and their value from PlanQuota in the plan serializer while getting a list of plans.

I have the following serializer

```<code>class PlanQuotaSerialier(serializers.ModelSerializer):
    class Meta:
        model = PlanQuota
        depth = 1
        fields = ['quota', 'value']

class PlanListSerializer(serializers.ModelSerializer):
    plan_quota = PlanQuotaSerialier(read_only=True, many=True)

    class Meta:
        model = Plan
        depth = 1
        fields = ['name', 'default', 'created', 'plan_quota']
</code>```

But there is no plan_quota in the response.

How can I add all Quota and their value for each plan in a single query (SQL JOIN)?

Edit 2:

Adding source to the serializer field worked

```<code>plan_quota = PlanQuotaSerialier(source='planquota_set', many=True)
</code>```

And the result is like

```<code>"results": [
        {
            "name": "Test Plan 1",
            "default": true,
            "plan_quotas": [
                {
                    "quota": {
                        "id": 1,
                        "order": 0,
                        "codename": "TEST",
                        "name": "Test Domain",
                        "unit": "count",
                        "description": "",
                        "is_boolean": false,
                        "url": ""
                    },
                    "value": 10
                },
             ]
       }
]
</code>```

Can I club all fields from quota with value field in the plan_quotas list?

答:
This is how I got it solved.

For the first query, added source

plan_quota = PlanQuotaSerialier(source='planquota_set', many=True)

For removing quota key, added to_presentation() in the PlanQuotaSerializer

```<code>def to_representation(self, instance):

    representation = super().to_representation(instance)
    if 'quota' in representation:
        representation['quota']['quota_id'] = representation['quota'].pop('id')
        representation.update(representation.pop('quota'))

    return representation
</code>```

Body:
I'm using Django 2.2 and Django REST Framework

I have three models like

class Plan(models.Model):
    name = models.CharField(_('Plan Name'), max_length=100)
    default = models.NullBooleanField(default=None, unique=True)
    created = models.DateTimeField(_('created'), db_index=True)
    quotas = models.ManyToManyField('Quota', through='PlanQuota')

class Quota(models.Model):
    codename = models.CharField(max_length=50, unique=True)
    name = models.CharFieldmax_length=100)
    unit = models.CharField(max_length=100, blank=True)

class PlanQuota(models.Model):
    plan = models.ForeignKey('Plan', on_delete=models.CASCADE)
    quota = models.ForeignKey('Quota', on_delete=models.CASCADE)
    value = models.IntegerField(default=1, null=True, blank=True)

I have to get all quota and their value from PlanQuota in the plan serializer while getting a list of plans.

I have the following serializer

class PlanQuotaSerialier(serializers.ModelSerializer):
    class Meta:
        model = PlanQuota
        depth = 1
        fields = ['quota', 'value']

class PlanListSerializer(serializers.ModelSerializer):
    plan_quota = PlanQuotaSerialier(read_only=True, many=True)

    class Meta:
        model = Plan
        depth = 1
        fields = ['name', 'default', 'created', 'plan_quota']

But there is no plan_quota in the response.

How can I add all Quota and their value for each plan in a single query (SQL JOIN)?

Edit 2:

Adding source to the serializer field worked

plan_quota = PlanQuotaSerialier(source='planquota_set', many=True)

And the result is like

"results": [
        {
            "name": "Test Plan 1",
            "default": true,
            "plan_quotas": [
                {
                    "quota": {
                        "id": 1,
                        "order": 0,
                        "codename": "TEST",
                        "name": "Test Domain",
                        "unit": "count",
                        "description": "",
                        "is_boolean": false,
                        "url": ""
                    },
                    "value": 10
                },
             ]
       }
]

Can I club all fields from quota with value field in the plan_quotas list?

Body:
This is how I got it solved.

For the first query, added source

plan_quota = PlanQuotaSerialier(source='planquota_set', many=True)

For removing quota key, added to_presentation() in the PlanQuotaSerializer

def to_representation(self, instance):

    representation = super().to_representation(instance)
    if 'quota' in representation:
        representation['quota']['quota_id'] = representation['quota'].pop('id')
        representation.update(representation.pop('quota'))

    return representation


问:
Why SonarScanner ignores sonar.sources value (You must define the following mandatory properties)?
I would like you to help me with a problem that I have when executing: 'build now', because when I execute it the console output shows a series of failures

One of the failures was and still is, the properties of the file, I have already configured them and it is still giving faults, I have also saved them in the project directory, but nothing keeps failing.

these are the properties which i have in my project

```<code>sonar.projectKey=sistema_integracion
sonar.projectName=sistema_integracion
sonar.projectVersion=1.0
sonar.projectDescription=proyecto_asir
sonar.source=C:\Program Files (x86)\Jenkins\workspace\proyecto_integracion\spring_boot\src\main\java\hello
sonar.language=java
sonar.java.binaries=.
sonar.sourceEncoding=UTF-8
sonar.scm.disabled=True
</code>```

-And these are the flaws , I would appreciate all the help possible.
Thank you so much.

ERROR: Error during SonarQube Scanner execution

ERROR: You must define the following mandatory properties for 'sistema_integracion': sonar.sources

ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.

WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succeeded?

ERROR: SonarQube scanner exited with non-zero code: 1

Finished: FAILURE

答:
Here is your problem:

```<code>ERROR: You must define the following mandatory properties for 'sistema_integracion': sonar.sources
</code>```

You defined an absolute path:

```<code>sonar.source=C:\Program Files (x86)\Jenkins\workspace\proyecto_integracion\spring_boot\src\main\java\hello
</code>```

The path must be relative. If this is your file structure:

```<code>sonar-project.properties
src
  \-main
       \-java
</code>```

Then you should set:

```<code>sonar.sources=src/main/java
</code>```

Body:
I would like you to help me with a problem that I have when executing: 'build now', because when I execute it the console output shows a series of failures

One of the failures was and still is, the properties of the file, I have already configured them and it is still giving faults, I have also saved them in the project directory, but nothing keeps failing.

these are the properties which i have in my project

sonar.projectKey=sistema_integracion
sonar.projectName=sistema_integracion
sonar.projectVersion=1.0
sonar.projectDescription=proyecto_asir
sonar.source=C:\Program Files (x86)\Jenkins\workspace\proyecto_integracion\spring_boot\src\main\java\hello
sonar.language=java
sonar.java.binaries=.
sonar.sourceEncoding=UTF-8
sonar.scm.disabled=True

-And these are the flaws , I would appreciate all the help possible.
Thank you so much.

ERROR: Error during SonarQube Scanner execution

ERROR: You must define the following mandatory properties for 'sistema_integracion': sonar.sources

ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.

WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succeeded?

ERROR: SonarQube scanner exited with non-zero code: 1

Finished: FAILURE

Body:
Here is your problem:

ERROR: You must define the following mandatory properties for 'sistema_integracion': sonar.sources

You defined an absolute path:

sonar.source=C:\Program Files (x86)\Jenkins\workspace\proyecto_integracion\spring_boot\src\main\java\hello

The path must be relative. If this is your file structure:

sonar-project.properties
src
  \-main
       \-java

Then you should set:

sonar.sources=src/main/java


问:
Handling Large Datasets with With X axis Charts
I am using FLOTR API to display charts

I have some large sets of data for Six Months . For example

```<code>var jsonData = [August 19, 2004',August 20, 2004',August 21, 2004',August 22, 2004',.........,January 1 , 2005] ;
</code>```

Like this for 6 Months .

But inside X axis I need to display only the Months date values .

```<code>Flotr.draw(
xaxis:{
tickFormatter: function(n)
{
return ;
},
}
</code>```

Please tell me , what will be the best solution for this ??

答:
In your xaxis object, you need to use the ticks property to specify the ticks you want.

It would look something like this:

```<code>xaxis: {
  ...
  ticks: [[<timestamp>,'August, 2004'],[<timestamp>,'September, 2004'],...,[<timestamp>,'January, 2005]],
  ...
}
</code>```

You'll have to create the timestamps the same way you've created them for your data, but that's about it.

Body:
I am using FLOTR API to display charts

I have some large sets of data for Six Months . For example

var jsonData = [August 19, 2004',August 20, 2004',August 21, 2004',August 22, 2004',.........,January 1 , 2005] ;

Like this for 6 Months .

But inside X axis I need to display only the Months date values .

Flotr.draw(
xaxis:{
tickFormatter: function(n)
{
return ;
},
}

Please tell me , what will be the best solution for this ??

Body:
In your xaxis object, you need to use the ticks property to specify the ticks you want.

It would look something like this:

xaxis: {
  ...
  ticks: [[<timestamp>,'August, 2004'],[<timestamp>,'September, 2004'],...,[<timestamp>,'January, 2005]],
  ...
}

You'll have to create the timestamps the same way you've created them for your data, but that's about it.


问:
How to position multiple buttons on the same line separately in react-native?
I want to create two buttons in same line separately.I used flex=2 but it's not working.How can i fix that?</p>

```<code><View style={{ flex: 2,flexDirection: "row" ,marginLeft:20}}>
    <BtnDft h={40} w={100} name={ "Update"} />
    <BtnDft h={40} w={100} name={ "Log out"} />
</View>
</code>```

答:
Remove flex: 2

```<code>{ flexDirection: "row" ,marginLeft: 20, justifyContent: 'space-evenly' }
</code>```

change the position of the buttons using justifyContent, Available options are flex-start, center, flex-end, space-around, space-between and space-evenly.

Body:
I want to create two buttons in same line separately.I used flex=2 but it's not working.How can i fix that?

<View style={{ flex: 2,flexDirection: "row" ,marginLeft:20}}>
    <BtnDft h={40} w={100} name={ "Update"} />
    <BtnDft h={40} w={100} name={ "Log out"} />
</View>

Body:
Remove flex: 2

{ flexDirection: "row" ,marginLeft: 20, justifyContent: 'space-evenly' }

change the position of the buttons using justifyContent, Available options are flex-start, center, flex-end, space-around, space-between and space-evenly.


问:
Passing an auto_ptr to a function effectively makes it a sink. Why?
I'm reading some notes about shared pointers.
They say the first attempt by STL with the auto_ptr had the following major drawbacks:

They can't be used in STL containers

Copying the auto_ptr transfers ownership

Passing an auto_ptr to a function effectively makes it a sink

I understand the first two, but am unsure what the last one means.

Could someone please explain this.

Thanks.

答:
A data sink is something that sucks up your data, taking ownership of it.

The terminology originates in the notion of "pipelines", where some particular entity in a chain of entities takes its data from a "source", then pushes its result to a "sink". The next entity in the chain does the same thing, and so forth. At each stage, the entity can no longer do anything with the data that it's passed on.

By analogy (and example), consider taking data from std::cin (a stream acting as a source), doing some calculations then pushing the result to std::cout (a stream acting as a sink). Once you're done, you're done; the results are out in the ether and you can't get them back.

That's what auto_ptr does: it gives away ownership of your data, whether you wanted it to or not.


问:
Replacing a 'NULL' value in a CSV file with the date of today - Python
I am currently working on a Python project, that imports a data text file (CSV in my case) and then outputs the employees who have worked the most time together in a common project. First, this is the code and the data file:

```<code>from collections import defaultdict
from itertools import combinations
from datetime import datetime
import csv

d = defaultdict(list)

with open("data.csv") as f:
    next(f) # skip header
    r = csv.reader(f)
    # unpack use height as key and  append name age and position
    for EmpID, ProjectID, FromDate, ToDate in r:
        d[int(ProjectID)].append((EmpID, FromDate, ToDate))

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('Employees with EmpID:', ref[0][0], 'and', ref[1][0],
                      'worked together on a common project (Project ID:', job, ') for a total of', dd, 'days')
</code>```

And this is the data file, I am importing:

```<code>EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09
</code>```

Now, I have a task that if there is a value 'NULL' in the 'DateTo' column, I have to make it equal today. I am thinking that there should be an automatic python function that gives the current date, and then do an if statement inside the CSV code block to replace 'NULL' with today's date (but it is only open in read mode as far as I know?). I would very much appreciate it if anyone can give me any tips! Thanks.

EDIT:
PANDAS PREVIOUS ATTEMPT FOR SOLUTION: (50% done)

```<code># Load the Pandas libraries with alias 'pd'
import pandas as pd
import datetime as dt
import numpy as np
# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)
</code>```

Body:
I am currently working on a Python project, that imports a data text file (CSV in my case) and then outputs the employees who have worked the most time together in a common project. First, this is the code and the data file:

from collections import defaultdict
from itertools import combinations
from datetime import datetime
import csv

d = defaultdict(list)

with open("data.csv") as f:
    next(f) # skip header
    r = csv.reader(f)
    # unpack use height as key and  append name age and position
    for EmpID, ProjectID, FromDate, ToDate in r:
        d[int(ProjectID)].append((EmpID, FromDate, ToDate))

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('Employees with EmpID:', ref[0][0], 'and', ref[1][0],
                      'worked together on a common project (Project ID:', job, ') for a total of', dd, 'days')

And this is the data file, I am importing:

EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09

Now, I have a task that if there is a value 'NULL' in the 'DateTo' column, I have to make it equal today. I am thinking that there should be an automatic python function that gives the current date, and then do an if statement inside the CSV code block to replace 'NULL' with today's date (but it is only open in read mode as far as I know?). I would very much appreciate it if anyone can give me any tips! Thanks.

EDIT:
PANDAS PREVIOUS ATTEMPT FOR SOLUTION: (50% done)

# Load the Pandas libraries with alias 'pd'
import pandas as pd
import datetime as dt
import numpy as np
# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)

Body:
use fillna

import pandas as pd
from io import StringIO
from datetime import datetime

document = '''
EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,NULL
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09'''

# df = pd.read_csv('data.csv')

df = pd.read_csv(StringIO(document))
df['DateTo'] = df['DateTo'].fillna(datetime.today().strftime('%Y-%m-%d'))
print(df)

   EmpID  ProjectID    DateFrom      DateTo
0      1        100  2014-11-01  2015-05-01
1      2        101  2013-12-06  2014-10-06
2      3        102  2015-06-04  2017-09-04
3      5        103  2014-10-01  2015-12-01
4      2        100  2013-03-07  2019-05-30
5      2        103  2015-07-09  2019-01-19
6      4        102  2013-11-13  2014-03-13
7      4        103  2016-02-14  2017-03-15
8      5        104  2014-03-15  2015-11-09


问:
How to position icon position in materialbutton
I am using Materialbutton from the support library. I want the icon to be to the right of the text?  Ican't seem to find how to do it.
Any help is appreciated</p>

答:
A layout only approach to do this would be:

If you are using the support library

```<code>implementation 'com.android.support:design:28.0.0'
</code>```

you can try

```<code><android.support.v7.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableRight="@android:drawable/ic_menu_camera"
    android:text="Camera" />
</code>```

If you are using the newer material ui library

```<code>implementation 'com.google.android.material:material:1.0.0'
</code>```

you can try

```<code><androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableRight="@android:drawable/ic_menu_camera"
    android:text="Camera" />
</code>```

Body:
A layout only approach to do this would be:

If you are using the support library

implementation 'com.android.support:design:28.0.0'

you can try

<android.support.v7.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableRight="@android:drawable/ic_menu_camera"
    android:text="Camera" />

If you are using the newer material ui library

implementation 'com.google.android.material:material:1.0.0'

you can try

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableRight="@android:drawable/ic_menu_camera"
    android:text="Camera" />


问:
Building multiple go plugins under a directory in one shot
I have a list of plugins under a subdir. I want to build all of them with a single command. There is an example dir layout.

```<code>plugins/cat/cat.go
plugins/dog/dog.go
plugins/cow/cow.go
</code>```

I build them right now like:

```<code>go build -i -buildmode=plugin -o build/cat.so plugins/cat/cat.go
go build -i -buildmode=plugin -o build/dog.so plugins/dog/dog.go
go build -i -buildmode=plugin -o build/cow.so plugins/cow/cow.go
</code>```

There is an other command (because it's in a Makefile), which help me to get closer:

```<code># Ex.: make bin-so TARGET=cat
bin-so: builddir
    go build -i -buildmode=plugin -o build/$(TARGET).so plugins/$(TARGET)/$(TARGET).go
</code>```

I want to create a single line which builds these plugins. I found out how I can list the folder names, but I have to use it somehow in the command above.

```<code>find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")'
</code>```

So it will list the name of the folders, these are good to me, but I have to redirect it to the plugin builder command.

I want to have something similar (just an example):

```<code>find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")' | go build -i -buildmode=plugin -o build/$1).so plugins/$1/$1.go
</code>```

答:
You can just do this in one find command with the -execdir option that allows you run commands directly on the basename of the files

```<code>find ./plugins -mindepth 1 -maxdepth 1 -type d -execdir bash -c '
    for arg; do
        name="${arg##*./}"
        go build -i -buildmode=plugin -o build/"${name}".so plugins/"${name}"/"${name}".go
    done' _ {} +
</code>```

This is much better than using multiple pipelines after find to achieve the same result. Imagine the part within the sh -c '..' as a separate script and you are passing the arguments to the script with the names returned ./cow.go etc.

The advantage of -execdir here is you don't need to worry about the immediate paths before the directory names. You get the final base-name of the directories found.

See Understanding the -exec option of find on Unix.SE to learn more about each of the options used.

Body:
I have a list of plugins under a subdir. I want to build all of them with a single command. There is an example dir layout.

plugins/cat/cat.go
plugins/dog/dog.go
plugins/cow/cow.go

I build them right now like:

go build -i -buildmode=plugin -o build/cat.so plugins/cat/cat.go
go build -i -buildmode=plugin -o build/dog.so plugins/dog/dog.go
go build -i -buildmode=plugin -o build/cow.so plugins/cow/cow.go

There is an other command (because it's in a Makefile), which help me to get closer:

# Ex.: make bin-so TARGET=cat
bin-so: builddir
    go build -i -buildmode=plugin -o build/$(TARGET).so plugins/$(TARGET)/$(TARGET).go

I want to create a single line which builds these plugins. I found out how I can list the folder names, but I have to use it somehow in the command above.

find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")'

So it will list the name of the folders, these are good to me, but I have to redirect it to the plugin builder command.

I want to have something similar (just an example):

find ./plugins -mindepth 1 -maxdepth 1 -type d | awk 'sub(/^.*\//, "")' | go build -i -buildmode=plugin -o build/$1).so plugins/$1/$1.go

Body:
You can just do this in one find command with the -execdir option that allows you run commands directly on the basename of the files

find ./plugins -mindepth 1 -maxdepth 1 -type d -execdir bash -c '
    for arg; do
        name="${arg##*./}"
        go build -i -buildmode=plugin -o build/"${name}".so plugins/"${name}"/"${name}".go
    done' _ {} +

This is much better than using multiple pipelines after find to achieve the same result. Imagine the part within the sh -c '..' as a separate script and you are passing the arguments to the script with the names returned ./cow.go etc.

The advantage of -execdir here is you don't need to worry about the immediate paths before the directory names. You get the final base-name of the directories found.

See Understanding the -exec option of find on Unix.SE to learn more about each of the options used.


问:
How to mock a dictionary in Python
Let's say I have a function like this:

```<code>def do_something(dict_obj):
   # access to the dict_obj then do some stuff
   eg.
   if dict_obj['doors']:
      do_something_with_doors()
   map_car_make(dict_obj['make'])
   ...

   if dict_obj['is_active']:
        do_something_else()
</code>```

I want to mock the dict_obj to have is_active element and don't care the rest, how do I do that?

答:
How to mock a dictionary in Python is a good/direct question someone else can search, so:

I suggest MagicMock instead of Mock

Overload the __getitem__

from unittest.mock import MagicMock

m = MagicMock()
d = {'key_1': 'value'}
m.__getitem__.side_effect = d.__getitem__

# dict behaviour
m['key_1'] # => 'value'
m['key_2'] # => raise KeyError

# mock behaviour
m.foo(42)
m.foo.assert_called_once_with(43) # => raise AssertionError
```
<p>Related Questions:</p>
<ul>
<li>How to let MagicMock behave like a dict?</li>
<li>Understanding __getitem__ method</li>
</ul>
<p>=== EDIT ===</p>
<p>As a function for direct copy/pasting</p>
<pre class="lang-py prettyprint-override"><code>def mock_dict(d):
  m = MagicMock()
  m.__getitem__.side_effect = d.__getitem__
  return m
</code>```

Title: How to mock a dictionary in Python

Body:
Let's say I have a function like this:

def do_something(dict_obj):
   # access to the dict_obj then do some stuff
   eg.
   if dict_obj['doors']:
      do_something_with_doors()
   map_car_make(dict_obj['make'])
   ...

   if dict_obj['is_active']:
        do_something_else()

I want to mock the dict_obj to have is_active element and don't care the rest, how do I do that?

Body:
How to mock a dictionary in Python is a good/direct question someone else can search, so:

I suggest MagicMock instead of Mock

Overload the __getitem__

from unittest.mock import MagicMock

m = MagicMock()
d = {'key_1': 'value'}
m.__getitem__.side_effect = d.__getitem__

# dict behaviour
m['key_1'] # => 'value'
m['key_2'] # => raise KeyError

# mock behaviour
m.foo(42)
m.foo.assert_called_once_with(43) # => raise AssertionError

Related Questions:

How to let MagicMock behave like a dict?

Understanding __getitem__ method

=== EDIT ===

As a function for direct copy/pasting

def mock_dict(d):
  m = MagicMock()
  m.__getitem__.side_effect = d.__getitem__
  return m