问:
FULL OUTER JOIN throwing error "wrap select in parentheses"
I am having trouble with a part of my SQL call, I receive this error

 Error: Syntax error: Each subquery argument for table-valued function calls must be enclosed in parentheses. To fix this, replace SELECT... with (SELECT...) at [32:5]

This is at the SELECT after the FULL OUTER JOIN EACH, I'd argue that I have done that, I do not know what is wrong here so any suggestions would be much appriciated.

I am trying to create a funnel that more acurately sorts previous customers from new. There are in total 3 levels in the funnel, for "simplicity" I'll only show two.

```<code>SELECT
 COUNT(s0.firstHit) AS pageId1,
 SUM(s0.exit) AS pageId2,
 COUNT(s1.firstHit) AS pageId3,
 SUM(s1.exit) AS pageId4
FROM(
  SELECT
    s0.fullVisitorId,
    s0.visitId,
    s0.firstHit,
    s0.exit,
    s1.firstHit,
    s1.exit
  FROM (
    SELECT
      fullvisitorid,
      visitid,
      (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstHit,
      (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS exitFlag
    FROM
      `<ID>.ga_sessions_2017*`
    WHERE
      _TABLE_SUFFIX BETWEEN '0601' AND '0602'
      AND 1 = 1
      AND EXISTS(SELECT 1 FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId'))
  AND EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE (SELECT COUNT(value) FROM UNNEST(hits.customDimensions) custd WHERE index=20) > 0)
  AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s0
  FULL OUTER JOIN EACH(
  SELECT
    fullVisitorId,
    visitId,
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s1
ON
  s0.fullVisitorId = s1.fullVisitorId
  AND s0.visitId = s1.visitId ) s01
</code>```

答:
You can find ways to write this query and not having the JOIN operations going on.

For instance:

```<code>SELECT
  fullvisitorid,
  visitid,
  (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstFunnelHit,
  (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstExitFunnelFlag,
  (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE (REGEXP_CONTAINS(page.pagePath, r'pageId')) OR ((select count(1) from unnest(hits) h, unnest(h.customDimensions) custd where custd.index = 20) > 0)) secondFunnelHit,
  (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId') OR ((select count(1) from unnest(hits) h, unnest(h.customDimensions) custd where custd.index = 20) > 0)) AS secondFunnelExitFlag
FROM `dataset.ga_sessions_2017*`
WHERE 1 = 1
  AND _TABLE_SUFFIX BETWEEN '0601' AND '0602'
  AND totals.visits = 1
</code>```

Notice that in just one SELECT you can bring information regarding all visitors who have been in page "pageId" and also visitors who have been in this page and fired the customDimension on index=20.

For each step in your funnel analyzes you can bring new columns as results, such as the firstFunnelHit and secondFunnelHit.

By avoiding expensive JOINs you can query up to teras of data and still have results in seconds.

Body:
I am having trouble with a part of my SQL call, I receive this error

 Error: Syntax error: Each subquery argument for table-valued function calls must be enclosed in parentheses. To fix this, replace SELECT... with (SELECT...) at [32:5]

This is at the SELECT after the FULL OUTER JOIN EACH, I'd argue that I have done that, I do not know what is wrong here so any suggestions would be much appriciated.

I am trying to create a funnel that more acurately sorts previous customers from new. There are in total 3 levels in the funnel, for "simplicity" I'll only show two.

SELECT
 COUNT(s0.firstHit) AS pageId1,
 SUM(s0.exit) AS pageId2,
 COUNT(s1.firstHit) AS pageId3,
 SUM(s1.exit) AS pageId4
FROM(
  SELECT
    s0.fullVisitorId,
    s0.visitId,
    s0.firstHit,
    s0.exit,
    s1.firstHit,
    s1.exit
  FROM (
    SELECT
      fullvisitorid,
      visitid,
      (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstHit,
      (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS exitFlag
    FROM
      `<ID>.ga_sessions_2017*`
    WHERE
      _TABLE_SUFFIX BETWEEN '0601' AND '0602'
      AND 1 = 1
      AND EXISTS(SELECT 1 FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId'))
  AND EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE (SELECT COUNT(value) FROM UNNEST(hits.customDimensions) custd WHERE index=20) > 0)
  AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s0
  FULL OUTER JOIN EACH(
  SELECT
    fullVisitorId,
    visitId,
    (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS firstHit,
    (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, 'pageId')) AS exitFlag
  FROM
    `<ID>.ga_sessions_2017*`
  WHERE
    _TABLE_SUFFIX BETWEEN '0601' AND '0602'
    AND totals.visits = 1
  GROUP BY
    fullVisitorId,
    visitId) AS s1
ON
  s0.fullVisitorId = s1.fullVisitorId
  AND s0.visitId = s1.visitId ) s01

Body:
You can find ways to write this query and not having the JOIN operations going on.

For instance:

SELECT
  fullvisitorid,
  visitid,
  (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstFunnelHit,
  (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId')) AS firstExitFunnelFlag,
  (SELECT MIN(hitNumber) FROM UNNEST(hits) WHERE (REGEXP_CONTAINS(page.pagePath, r'pageId')) OR ((select count(1) from unnest(hits) h, unnest(h.customDimensions) custd where custd.index = 20) > 0)) secondFunnelHit,
  (SELECT MAX(IF(isExit, 1, 0)) FROM UNNEST(hits) WHERE REGEXP_CONTAINS(page.pagePath, r'pageId') OR ((select count(1) from unnest(hits) h, unnest(h.customDimensions) custd where custd.index = 20) > 0)) AS secondFunnelExitFlag
FROM `dataset.ga_sessions_2017*`
WHERE 1 = 1
  AND _TABLE_SUFFIX BETWEEN '0601' AND '0602'
  AND totals.visits = 1

Notice that in just one SELECT you can bring information regarding all visitors who have been in page "pageId" and also visitors who have been in this page and fired the customDimension on index=20.

For each step in your funnel analyzes you can bring new columns as results, such as the firstFunnelHit and secondFunnelHit.

By avoiding expensive JOINs you can query up to teras of data and still have results in seconds.


来源: stackexchange

问:
VBA to delete rows based on cell value
I am trying to do the following :

VBA to lookup a value from a particular cell

Match these values in a particular column in specified sheets

Delete all rows from the sheet if the value do not match

I have tried the following - the code doesn't seem to function

```<code>Sub Delete()
    Dim List As Variant
    Dim LR As Long
    Dim r As Long
    List = Worksheets("Sheet1").Cells(28, "C").Value
    LR = Range("E" & Rows.Count).End(xlUp).Row
    For r = LR To 1 Step -1
        If IsError(Application.Match(Range("E" & r).Value, List, False)) Then
            Worksheets("Sheet2").Range("A1:AA36429").Rows(r).Delete
        End If
    Next r
End Sub
</code>```

答:
I think you have a few ways of going about this, but the quickest way I know of is to use MATCH to compare values in a range to values in an array. Please note that this has a limit to 4000 or so values to compare before it fails. For your purposes, I think the following will work:

```<code>Sub test1()
    Dim x As Long
    Dim array1() As Variant
    Dim array2() As Variant

    array1 = Array("ABC", "XYX")
    array2 = Range("A1:A2")

    If IsNumeric(Application.Match(Range("A1").Value, array1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, array2, 0)) Then
        x = IsNumeric(Application.Match(Range("A1").Value, array2, 0))
    End If

    'If x is not found in these arrays, x will be 0.
    MsgBox x
End Sub
</code>```

Another similar way is the following:

```<code>Sub test2()
    Dim array1() As Variant
    Dim FilterArray() As String
    Dim x As Variant

    x = Range("A1").Value
    array1 = Array("ABC", "RANDOM", "VBA")

    FilterArray = Filter(SourceArray:=array1, _
                          Match:=strText, _
                          Include:=True, _
                          Compare:=vbTextCompare)

    If UBound(FindOutArray) = -1 Then
        MsgBox "No, Array doesn't contain this item - " & x
    Else
        MsgBox "Yes, Array contains this item - " & x
    End If

End Sub
</code>```

So if we were to incorporate that all together (and I tested this btw):

```<code>Sub Delete()

Dim i As Integer
Dim LR As Long
Dim List() As Variant
Dim x As Long

LR = Range("E" & Rows.count).End(xlUp).Row
List = Worksheets("Sheet1").Range("A1:A2").Value

For i = 1 To LR
    If IsNumeric(Application.Match(Cells(i, "E").Value, List, 0)) Then
        Worksheets("Sheet1").Cells(i, "E").Value = ""
    End If
Next i

Worksheets("Sheet1").Columns("E").SpecialCells(xlCellTypeBlanks).Cells.Delete

End Sub
</code>```

This will set the cells that have values that are found in the array to blanks. Once the loop is finished, then the blank cells are deleted. If you want to shift the entire rows up, then use this as the last line instead:

```<code>Worksheets("Sheet1").Columns("E").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
</code>```

ContentLicense: CC BY-SA 3.0

Title: VBA to delete rows based on cell value

Body:
I am trying to do the following :

VBA to lookup a value from a particular cell

Match these values in a particular column in specified sheets

Delete all rows from the sheet if the value do not match

I have tried the following - the code doesn't seem to function

Sub Delete()
    Dim List As Variant
    Dim LR As Long
    Dim r As Long
    List = Worksheets("Sheet1").Cells(28, "C").Value
    LR = Range("E" & Rows.Count).End(xlUp).Row
    For r = LR To 1 Step -1
        If IsError(Application.Match(Range("E" & r).Value, List, False)) Then
            Worksheets("Sheet2").Range("A1:AA36429").Rows(r).Delete
        End If
    Next r
End Sub

Body:
I think you have a few ways of going about this, but the quickest way I know of is to use MATCH to compare values in a range to values in an array. Please note that this has a limit to 4000 or so values to compare before it fails. For your purposes, I think the following will work:

Sub test1()
    Dim x As Long
    Dim array1() As Variant
    Dim array2() As Variant

    array1 = Array("ABC", "XYX")
    array2 = Range("A1:A2")

    If IsNumeric(Application.Match(Range("A1").Value, array1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, array2, 0)) Then
        x = IsNumeric(Application.Match(Range("A1").Value, array2, 0))
    End If

    'If x is not found in these arrays, x will be 0.
    MsgBox x
End Sub

Another similar way is the following:

Sub test2()
    Dim array1() As Variant
    Dim FilterArray() As String
    Dim x As Variant

    x = Range("A1").Value
    array1 = Array("ABC", "RANDOM", "VBA")

    FilterArray = Filter(SourceArray:=array1, _
                          Match:=strText, _
                          Include:=True, _
                          Compare:=vbTextCompare)

    If UBound(FindOutArray) = -1 Then
        MsgBox "No, Array doesn't contain this item - " & x
    Else
        MsgBox "Yes, Array contains this item - " & x
    End If

End Sub

So if we were to incorporate that all together (and I tested this btw):

Sub Delete()

Dim i As Integer
Dim LR As Long
Dim List() As Variant
Dim x As Long

LR = Range("E" & Rows.count).End(xlUp).Row
List = Worksheets("Sheet1").Range("A1:A2").Value

For i = 1 To LR
    If IsNumeric(Application.Match(Cells(i, "E").Value, List, 0)) Then
        Worksheets("Sheet1").Cells(i, "E").Value = ""
    End If
Next i

Worksheets("Sheet1").Columns("E").SpecialCells(xlCellTypeBlanks).Cells.Delete

End Sub

This will set the cells that have values that are found in the array to blanks. Once the loop is finished, then the blank cells are deleted. If you want to shift the entire rows up, then use this as the last line instead:

Worksheets("Sheet1").Columns("E").SpecialCells(xlCellTypeBlanks).EntireRow.Delete


问:
UIAlertController in static method giving error: extra argument animated in cell
I wish to create a static method which I can place in a utility class which would launch a UIAlertController. However, I am getting the following error:

"extra argument animated in cell"

```<code>static func simpleAlertBox1(msg : String) -> Void{
    let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
    let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(defaultAction)
    present(alertController, animated: true, completion: nil)// error is being generated here
}
</code>```

I tried this but it still gave me the same error:

```<code>presentViewController(alertController, animated: true, completion: nil)
</code>```

but if I were to remove the static, then it works fine.

答:
self is an instance of UIViewController , If you want to call this function in a static way just add an other param viewcontroller in which you want to present it. very important, you need to show your alertView after viewDidload.

here an example code:

```<code>   class ViewController: UIViewController {

      override func viewDidLoad() {
         super.viewDidLoad()
      }

     override func viewDidAppear(_ animated: Bool) {
         ViewController.simpleAlertBox1(msg: "test", viewController: self)
      }

     static func simpleAlertBox1(msg : String , viewController : UIViewController) -> Void{

       let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
       let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
       alertController.addAction(defaultAction)
       viewController.present(alertController, animated: true, completion: nil)// error is being generated here

     }
 }
</code>```

Body:
I wish to create a static method which I can place in a utility class which would launch a UIAlertController. However, I am getting the following error:

"extra argument animated in cell"

static func simpleAlertBox1(msg : String) -> Void{
    let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
    let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(defaultAction)
    present(alertController, animated: true, completion: nil)// error is being generated here
}

I tried this but it still gave me the same error:

presentViewController(alertController, animated: true, completion: nil)

but if I were to remove the static, then it works fine.

Body:
self is an instance of UIViewController , If you want to call this function in a static way just add an other param viewcontroller in which you want to present it. very important, you need to show your alertView after viewDidload.

here an example code:

   class ViewController: UIViewController {

      override func viewDidLoad() {
         super.viewDidLoad()
      }

     override func viewDidAppear(_ animated: Bool) {
         ViewController.simpleAlertBox1(msg: "test", viewController: self)
      }

     static func simpleAlertBox1(msg : String , viewController : UIViewController) -> Void{

       let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
       let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
       alertController.addAction(defaultAction)
       viewController.present(alertController, animated: true, completion: nil)// error is being generated here

     }
 }


问:
Retrieve data from web service with ws addressing
I have a web service on a client site from which I need to report.

Locally, I mimicked the service using the provided wsdls and have been able to report on these. However, now pointing at the client site I am unable to access the data as the service requires ws addressing headers to be included.

The webservice is expecting the below:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:add="http://www.w3.org/2005/08/addressing" xmlns:ns="CustomerNamespace" xmlns:sch="Schema.xsd">
   <soapenv:Header>
      <add:From>
         <add:Address>Something</add:Address>
         <add:ReferenceParameters>
            <ns:TransactionGroupID>SomeOtherThing</ns:TransactionGroupID>
            <ns:SenderID>911</ns:SenderID>
         </add:ReferenceParameters>
      </add:From>
      <add:Action>Request</add:Action>
      <add:MessageID>TestGUID</add:MessageID>
   </soapenv:Header>
   <soapenv:Body>
      <sch:Request>
         <sch:SearchCustomerSystem>SystemXYZ</sch:SearchCustomerSystem>
          <sch:ServiceID>999999999999</sch:ServiceID>
      </sch:Request>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

At present, I ccan get SSRS to produce the below:

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>
</code>```

Other than creating a custom data extension (which I would rather avoid), is there a way of getting the ws addressing headers into the request?

答:
For this example I will be using C#

Using the expected envelope in your example the following classes were derived.

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
public partial class Envelope {
    /// <remarks/>
    public EnvelopeHeader Header { get; set; }
    /// <remarks/>
    public EnvelopeBody Body { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeHeader {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public From From { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public string Action { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public string MessageID { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2005/08/addressing")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2005/08/addressing", IsNullable = false)]
public partial class From {
    /// <remarks/>
    public string Address { get; set; }
    /// <remarks/>
    public FromReferenceParameters ReferenceParameters { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2005/08/addressing")]
public partial class FromReferenceParameters {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "CustomerNamespace")]
    public string TransactionGroupID { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "CustomerNamespace")]
    public ushort SenderID { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "Schema.xsd")]
    public Request Request { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "Schema.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "Schema.xsd", IsNullable = false)]
public partial class Request {
    /// <remarks/>
    public string SearchCustomerSystem { get; set; }
    /// <remarks/>
    public ulong ServiceID { get; set; }
}
```

<p>Using the above classes, the following Unit Test will be used to demonstrate </p>

<blockquote>
  <p>a way of getting the ws addressing headers into the request</p>
</blockquote>

<pre class="lang-cs prettyprint-override"><code>[TestClass]
public class MyTestClass {
    [TestMethod]
    public void _ws_addressing_headers_into_the_request() {

        var xmlWithBodyOnly = GetEnvelopFromSSRS();
        var header = BuildHeader();
        var result = AppendHeader(xmlWithBodyOnly, header);

    }

    private static EnvelopeHeader BuildHeader() {
        var header = new EnvelopeHeader {
            From = new From {
                Address = "Someting",
                ReferenceParameters = new FromReferenceParameters {
                    SenderID = 911,
                    TransactionGroupID = "SomeOtherThing"
                }
            },
            Action = "Request",
            MessageID = "SomeGuid"
        };
        return header;
    }

    private static string GetEnvelopFromSSRS() {
        var xmlWithBodyOnly = @"
<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <Request xmlns='Schema.xsd'>
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>";
        return xmlWithBodyOnly;
    }

    private string AppendHeader(string xml, EnvelopeHeader header) {
        var result = string.Empty;
        // convert string to stream
        var data = Encoding.UTF8.GetBytes(xml);
        using (var inStream = new MemoryStream(data)) {
            // Create an instance of the XmlSerializer specifying type and namespace.
            var serializer = new XmlSerializer(typeof(Envelope));
            //Deseiralize XML to something we can work with
            var envelope = (Envelope)serializer.Deserialize(inStream);
            if (envelope != null) {
                //Append the header
                envelope.Header = header;
                //Serialize the envelope back to XML
                using (var outStream = new MemoryStream()) {
                    serializer.Serialize(outStream, envelope);
                    result = Encoding.UTF8.GetString(outStream.ToArray());
                }
            }
        }
        return result;
    }
}
</code>```

Explanation.

 var xmlWithBodyOnly = GetEnvelopFromSSRS();
```

<p>mimics getting what you have been able to produce via SSRS based on the example provided in your original question.</p>

<pre class="lang-cs prettyprint-override"><code> var header = BuildHeader();
</code>```

Using the derived classes you can easily create and populate the necessary properties for your header as you see fit

private static EnvelopeHeader BuildHeader() {
    var header = new EnvelopeHeader {
        From = new From {
            Address = "Someting",
            ReferenceParameters = new FromReferenceParameters {
                SenderID = 911,
                TransactionGroupID = "SomeOtherThing"
            }
        },
        Action = "Request",
        MessageID = "SomeGuid"
    };
    return header;
}
```

<p>Now for the meat of the matter.</p>

<pre class="lang-cs prettyprint-override"><code>var result = AppendHeader(xmlWithBodyOnly, header);
</code>```

Once you have the envelope and the header you are now ready to append the ws addressing header to the request

private string AppendHeader(string xml, EnvelopeHeader header) {
    var result = string.Empty;
    // convert string to stream
    var data = Encoding.UTF8.GetBytes(xml);
    using (var inStream = new MemoryStream(data)) {
        // Create an instance of the XmlSerializer specifying type and namespace.
        var serializer = new XmlSerializer(typeof(Envelope));
        //Deseiralize XML to something we can work with
        var envelope = (Envelope)serializer.Deserialize(inStream);
        if (envelope != null) {
            //Append the header
            envelope.Header = header;
            //Serialize the envelope back to XML
            using (var outStream = new MemoryStream()) {
                serializer.Serialize(outStream, envelope);
                result = Encoding.UTF8.GetString(outStream.ToArray());
            }
        }
    }
    return result;
}
```

<p>The comments in the code explain what was done.</p>

<p>For the above example, given the following envelope</p>

<pre class="lang-xml prettyprint-override"><code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>
</code>```

When used in the above code produces the following output.

<?xml version="1.0"?>
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/soap/envelope/">

    <From xmlns="http://www.w3.org/2005/08/addressing">
      <Address>Someting</Address>
      <ReferenceParameters>
        <TransactionGroupID xmlns="CustomerNamespace">SomeOtherThing</TransactionGroupID>
        <SenderID xmlns="CustomerNamespace">911</SenderID>
      </ReferenceParameters>
    </From>
    <Action xmlns="http://www.w3.org/2005/08/addressing">Request</Action>
    <MessageID xmlns="http://www.w3.org/2005/08/addressing">SomeGuid</MessageID>

    <Request xmlns="Schema.xsd">
      <ServiceID>999999999999</ServiceID>
    </Request>

</Envelope>
```

This output can now be used to make your request to the web service as desired. The models can also be modified as needed based on what is required for the web service request.

Body:
I have a web service on a client site from which I need to report.

Locally, I mimicked the service using the provided wsdls and have been able to report on these. However, now pointing at the client site I am unable to access the data as the service requires ws addressing headers to be included.

The webservice is expecting the below:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:add="http://www.w3.org/2005/08/addressing" xmlns:ns="CustomerNamespace" xmlns:sch="Schema.xsd">
   <soapenv:Header>
      <add:From>
         <add:Address>Something</add:Address>
         <add:ReferenceParameters>
            <ns:TransactionGroupID>SomeOtherThing</ns:TransactionGroupID>
            <ns:SenderID>911</ns:SenderID>
         </add:ReferenceParameters>
      </add:From>
      <add:Action>Request</add:Action>
      <add:MessageID>TestGUID</add:MessageID>
   </soapenv:Header>
   <soapenv:Body>
      <sch:Request>
         <sch:SearchCustomerSystem>SystemXYZ</sch:SearchCustomerSystem>
          <sch:ServiceID>999999999999</sch:ServiceID>
      </sch:Request>
   </soapenv:Body>
</soapenv:Envelope>

At present, I ccan get SSRS to produce the below:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>

Other than creating a custom data extension (which I would rather avoid), is there a way of getting the ws addressing headers into the request?

Body:
For this example I will be using C#

Using the expected envelope in your example the following classes were derived.

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
public partial class Envelope {
    /// <remarks/>
    public EnvelopeHeader Header { get; set; }
    /// <remarks/>
    public EnvelopeBody Body { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeHeader {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public From From { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public string Action { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2005/08/addressing")]
    public string MessageID { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2005/08/addressing")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2005/08/addressing", IsNullable = false)]
public partial class From {
    /// <remarks/>
    public string Address { get; set; }
    /// <remarks/>
    public FromReferenceParameters ReferenceParameters { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2005/08/addressing")]
public partial class FromReferenceParameters {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "CustomerNamespace")]
    public string TransactionGroupID { get; set; }
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "CustomerNamespace")]
    public ushort SenderID { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody {
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "Schema.xsd")]
    public Request Request { get; set; }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "Schema.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "Schema.xsd", IsNullable = false)]
public partial class Request {
    /// <remarks/>
    public string SearchCustomerSystem { get; set; }
    /// <remarks/>
    public ulong ServiceID { get; set; }
}

Using the above classes, the following Unit Test will be used to demonstrate

a way of getting the ws addressing headers into the request

[TestClass]
public class MyTestClass {
    [TestMethod]
    public void _ws_addressing_headers_into_the_request() {

        var xmlWithBodyOnly = GetEnvelopFromSSRS();
        var header = BuildHeader();
        var result = AppendHeader(xmlWithBodyOnly, header);

    }

    private static EnvelopeHeader BuildHeader() {
        var header = new EnvelopeHeader {
            From = new From {
                Address = "Someting",
                ReferenceParameters = new FromReferenceParameters {
                    SenderID = 911,
                    TransactionGroupID = "SomeOtherThing"
                }
            },
            Action = "Request",
            MessageID = "SomeGuid"
        };
        return header;
    }

    private static string GetEnvelopFromSSRS() {
        var xmlWithBodyOnly = @"
<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
  <soap:Body>
    <Request xmlns='Schema.xsd'>
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>";
        return xmlWithBodyOnly;
    }

    private string AppendHeader(string xml, EnvelopeHeader header) {
        var result = string.Empty;
        // convert string to stream
        var data = Encoding.UTF8.GetBytes(xml);
        using (var inStream = new MemoryStream(data)) {
            // Create an instance of the XmlSerializer specifying type and namespace.
            var serializer = new XmlSerializer(typeof(Envelope));
            //Deseiralize XML to something we can work with
            var envelope = (Envelope)serializer.Deserialize(inStream);
            if (envelope != null) {
                //Append the header
                envelope.Header = header;
                //Serialize the envelope back to XML
                using (var outStream = new MemoryStream()) {
                    serializer.Serialize(outStream, envelope);
                    result = Encoding.UTF8.GetString(outStream.ToArray());
                }
            }
        }
        return result;
    }
}

Explanation.

 var xmlWithBodyOnly = GetEnvelopFromSSRS();

mimics getting what you have been able to produce via SSRS based on the example provided in your original question.

 var header = BuildHeader();

Using the derived classes you can easily create and populate the necessary properties for your header as you see fit

private static EnvelopeHeader BuildHeader() {
    var header = new EnvelopeHeader {
        From = new From {
            Address = "Someting",
            ReferenceParameters = new FromReferenceParameters {
                SenderID = 911,
                TransactionGroupID = "SomeOtherThing"
            }
        },
        Action = "Request",
        MessageID = "SomeGuid"
    };
    return header;
}

Now for the meat of the matter.

var result = AppendHeader(xmlWithBodyOnly, header);

Once you have the envelope and the header you are now ready to append the ws addressing header to the request

private string AppendHeader(string xml, EnvelopeHeader header) {
    var result = string.Empty;
    // convert string to stream
    var data = Encoding.UTF8.GetBytes(xml);
    using (var inStream = new MemoryStream(data)) {
        // Create an instance of the XmlSerializer specifying type and namespace.
        var serializer = new XmlSerializer(typeof(Envelope));
        //Deseiralize XML to something we can work with
        var envelope = (Envelope)serializer.Deserialize(inStream);
        if (envelope != null) {
            //Append the header
            envelope.Header = header;
            //Serialize the envelope back to XML
            using (var outStream = new MemoryStream()) {
                serializer.Serialize(outStream, envelope);
                result = Encoding.UTF8.GetString(outStream.ToArray());
            }
        }
    }
    return result;
}

The comments in the code explain what was done.

For the above example, given the following envelope

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>
          999999999999
        </ServiceID>
    </Request>
  </soap:Body>
</soap:Envelope>

When used in the above code produces the following output.

<?xml version="1.0"?>
<Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/soap/envelope/">
  <Header>
    <From xmlns="http://www.w3.org/2005/08/addressing">
      <Address>Someting</Address>
      <ReferenceParameters>
        <TransactionGroupID xmlns="CustomerNamespace">SomeOtherThing</TransactionGroupID>
        <SenderID xmlns="CustomerNamespace">911</SenderID>
      </ReferenceParameters>
    </From>
    <Action xmlns="http://www.w3.org/2005/08/addressing">Request</Action>
    <MessageID xmlns="http://www.w3.org/2005/08/addressing">SomeGuid</MessageID>
  </Header>
  <Body>
    <Request xmlns="Schema.xsd">
      <ServiceID>999999999999</ServiceID>
    </Request>
  </Body>
</Envelope>

This output can now be used to make your request to the web service as desired. The models can also be modified as needed based on what is required for the web service request.


问:
oracle sql: how do i sum different data points in a select statment?
i'm trying to return a sum which is the total of multiple rows of data that are returned. i'm trying to return data that shows an employee, account, and department. i want the sum of salary paid by those three data points. i also want a sum just by employee to show how their salary was distributed. an example is below. any help would be appreciated.

example

答:
This will return the sum of each employee's salary</p>

```<code>SELECT employee, SUM(salary)
FROM Table
GROUP BY employee
</code>```

Body:
This will return the sum of each employee's salary

SELECT employee, SUM(salary)
FROM Table
GROUP BY employee


问:
Git Remote: Error: fatal: protocol error: bad line length character: Unab
I set up a git server and want now to push initially my repo from the client.
I used git push origin master and get this error message:

```<code>fatal: protocol error: bad line length character: Unab
</code>```

I don't know what's wrong. I don't know what "Unab" is. I tried to resize the shell but it is still "Unab".
I cannot find a solution for this error message.

I setup the server with "authorized_keys" and SSH. (I can connect to it, using SSH.)

It seems to be a git problem?

BTW: The server is set up in a Windows 7 VM

答:
Late answer here, but hope it will help someone. If its a protocol error, it has to do something with your local git not able to communicate to the remote git. This can happen if you cloned the repo via ssh and sometime later, you lost the keys to the repo or your ssh agent cannot find those keys anymore.

Solution

Generate a new key and add it your git repo or configure your ssh agent to load the keys if you still have the keys with you & not with someone else ;)

Another quick fix is to go to your .git directory and edit the config file's [remote "origin"] url from git to http so that ssh keys are not needed to push and it will revert to asking your username and password.

```<code>[remote "origin"]
url = git@gitlab.*****.com:****/****.git
fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

Change to

```<code>    [remote "origin"]
    url = http://gitlab.*****.com/****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*
</code>```

Body:
I set up a git server and want now to push initially my repo from the client.
I used git push origin master and get this error message:

fatal: protocol error: bad line length character: Unab

I don't know what's wrong. I don't know what "Unab" is. I tried to resize the shell but it is still "Unab".
I cannot find a solution for this error message.

I setup the server with "authorized_keys" and SSH. (I can connect to it, using SSH.)

It seems to be a git problem?

BTW: The server is set up in a Windows 7 VM

Body:
Late answer here, but hope it will help someone. If its a protocol error, it has to do something with your local git not able to communicate to the remote git. This can happen if you cloned the repo via ssh and sometime later, you lost the keys to the repo or your ssh agent cannot find those keys anymore.

Solution

Generate a new key and add it your git repo or configure your ssh agent to load the keys if you still have the keys with you & not with someone else ;)

Another quick fix is to go to your .git directory and edit the config file's [remote "origin"] url from git to http so that ssh keys are not needed to push and it will revert to asking your username and password.

[remote "origin"]
url = git@gitlab.*****.com:****/****.git
fetch = +refs/heads/*:refs/remotes/origin/*

Change to

    [remote "origin"]
    url = http://gitlab.*****.com/****/****.git
    fetch = +refs/heads/*:refs/remotes/origin/*


问:
SSIS problems with MySQL Connector/ODBC 5.3.8
I am having a problem with a SSIS project that downloads data from a MySQL database and insert it in a SQL Server 2014 Database.

So I have two versions of the same project, one for SQL Server 2016 and another one for SQL Server 2014. They have the same scripts and data flows, but for some reason, only the one made for SQL Server 2016 works. The issues resides in the ODBC Driver connector. I can preview data in both project, but for the SQL Server 2014 version, it simply won't load it. So I get 0 rows every time I run it. Sadly, I need the 2014 version for our SQL Server, since when I deploy the project with 2016 as target version, it fails.

This pretty much sum up the whole problem and I have try quite a few things. Including, changing the ODBC connector's version. It all seems it has something to do with Visual Studio, when the target version is change from 2016 to 2014. Still, I can't find a solution to this issue.

I am using a query to source data, but I also tried with the table name, but still didn't work. I am not using any function. I am running directly from Visual Studio in debug mode.

Has anyone gone through the same error? I can't find anything related.

Please, let me know if you need anything else to understand the issue.

答:
Ok I had similar issue but it was in Source query where one of function was not behaving same between 2016 and 2014 version.

When you say 0 rows, does package failed or successful ?

Are you using a query to source data ? If yes, does it have any functions used ?

Are you running from BIDS or SQL Agent ? If Sql Agent, Check if agent job configured to run in same 32bit or 63 bit version ?


问:
What does "unhashable type: 'list'" error mean?
```<code>//database Postgresql

logging_level_ENUM = ['critical', 'error', 'warning', 'info', 'debug']

loglevel = db.Column(postgresql.ENUM(logging_level_ENUM,
                     name='log_level_to_ENUM'),
                     default=logging_level_ENUM[3])
//python module

if i in logging_level_ENUM:
    print i
</code>```

This gives me an error "unhashable type: 'list'". What does that mean and how can I fix that?

答:
Python lists are not hashable because they are mutable.  You need to use a hashable collection instead, like a tuple.

logging_level_ENUM = ('critical', 'error', 'warning', 'info', 'debug')

Body:
//database Postgresql

logging_level_ENUM = ['critical', 'error', 'warning', 'info', 'debug']

loglevel = db.Column(postgresql.ENUM(logging_level_ENUM,
                     name='log_level_to_ENUM'),
                     default=logging_level_ENUM[3])
//python module

if i in logging_level_ENUM:
    print i

This gives me an error "unhashable type: 'list'". What does that mean and how can I fix that?


问:
Create a link for all mobile devices that opens google maps by default
Create a link for all mobile devices that opens google maps with business location?

Google MAP - This link goes to the location and redirect to the mobile google app, but no mark for the business address.

Google MAP - This link goes to the location, but not redirecting to google app, instead mobile wants you to choose what to use.

I need a link that redirect to google app and mark the google Business address.

答:
In May 2017 Google launched the Google Maps URLs. This API allows to create universal cross-platform URLs that you can use on web, Android or iOS.

For example you can open native maps app on Android passing the following URLs into intents

https://www.google.com/maps/search/?api=1&query=centurylink+field

https://www.google.com/maps/search/?api=1&query=47.5951518,-122.3316393&query_place_id=ChIJKxjxuaNqkFQR3CK6O1HNNqY

For further details, please refer to the documentation:

https://developers.google.com/maps/documentation/urls/guide


问:
SqlBulkCopy is slow, doesn't utilize full network speed
for that past couple of weeks I have been creating generic script that is able to copy databases. The goal is to be able to specify any database on some server and copy it to some other location, and it should only copy the specified content. The exact content to be copied over is specified in a configuration file. This script is going to be used on some 10 different databases and run weekly. And in the end we are copying only about 3%-20% of databases which are as large as 500GB. I have been using the SMO assemblies to achieve this. This is my first time working with SMO and it took a while to create generic way to copy the schema objects, filegroups ...etc. (Actually helped find some bad stored procs).

Overall I have a working script which is lacking on performance (and at times times out) and was hoping you guys would be able to help. When executing the WriteToServer command to copy large amount of data (> 6GB) it reaches my timeout period of 1hr. Here is the core code for copying table data. The script is written in PowerShell.

```<code>$query = ("SELECT * FROM $selectedTable " + $global:selectiveTables.Get_Item($selectedTable)).Trim()
Write-LogOutput "Copying $selectedTable : '$query'"
$cmd = New-Object Data.SqlClient.SqlCommand -argumentList $query, $source
$cmd.CommandTimeout = 120;
$bulkData = ([Data.SqlClient.SqlBulkCopy]$destination)
$bulkData.DestinationTableName = $selectedTable;
$bulkData.BulkCopyTimeout = $global:tableCopyDataTimeout # = 3600
$reader = $cmd.ExecuteReader();
$bulkData.WriteToServer($reader); # Takes forever here on large tables
</code>```

The source and target databases are located on different servers so I kept track of the network speed as well. The network utilization never went over 1% which was quite surprising to me. But when I just transfer some large files between the servers, the network utilization spikes up to 10%. I have tried setting the $bulkData.BatchSize to 5000 but nothing really changed. Increasing the BulkCopyTimeout to an even greater amount would only solve the timeout. I really would like to know why the network is not being used fully.

Anyone else had this problem? Any suggestions on networking or bulk copy will be appreciated. And please let me know if you need more information.

Thanks.

UPDATE

I have tweaked several options that increase the performance of SqlBulkCopy, such as setting the transaction logging to simple and providing a table lock to SqlBulkCopy instead of the default row lock. Also some tables are better optimized for certain batch sizes. Overall, the duration of the copy was decreased by some 15%. And what we will do is execute the copy of each database simultaneously on different servers. But I am still having a timeout issue when copying one of the databases.

When copying one of the larger databases, there is a table for which I consistently get the following exception:

```<code>System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
</code>```

It is thrown about 16 minutes after it starts copying the table which is no where near my BulkCopyTimeout. Even though I get the exception that table is fully copied in the end. Also, if I truncate that table and restart my process for that table only, the tables is copied over without any issues. But going through the process of copying that entire database fails always for that one table.

I have tried executing the entire process and reseting the connection before copying that faulty table, but it still errored out. My SqlBulkCopy and Reader are closed after each table. Any suggestions as to what else could be causing the script to fail at the point each time?

```<code>CREATE TABLE [dbo].[badTable](
[someGUID] [uniqueidentifier] NOT NULL,
[xxx] [uniqueidentifier] NULL,
[xxx] [int] NULL,
[xxx] [tinyint] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NULL,
[xxx] [uniqueidentifier] NOT NULL,
[xxx] [uniqueidentifier] NULL,
CONSTRAINT [PK_badTable] PRIMARY KEY NONCLUSTERED
(
[someGUID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
</code>```

No indexes exist for this table on the target DB.

答:
SqlBulk Copy is by far the fastest way of copying data into SQL tables.

You should be getting speeds in excess of 10,000 rows per second.

In order to test the bulk copy functionality, try DBSourceTools. ( http://dbsourcetools.codeplex.com )

This utility is designed to script Databases to disk, and then re-create them on a target server.

When copying data, DBSourceTools will first export all data to a local .xml file, and then do a Bulk Copy to the target database.

This will help to further identify where your bottleneck is, by breaking the process up into two passes : one for reading and one for writing.

ContentLicense: CC BY-SA 2.5

Body:
for that past couple of weeks I have been creating generic script that is able to copy databases. The goal is to be able to specify any database on some server and copy it to some other location, and it should only copy the specified content. The exact content to be copied over is specified in a configuration file. This script is going to be used on some 10 different databases and run weekly. And in the end we are copying only about 3%-20% of databases which are as large as 500GB. I have been using the SMO assemblies to achieve this. This is my first time working with SMO and it took a while to create generic way to copy the schema objects, filegroups ...etc. (Actually helped find some bad stored procs).

Overall I have a working script which is lacking on performance (and at times times out) and was hoping you guys would be able to help. When executing the WriteToServer command to copy large amount of data (> 6GB) it reaches my timeout period of 1hr. Here is the core code for copying table data. The script is written in PowerShell.

$query = ("SELECT * FROM $selectedTable " + $global:selectiveTables.Get_Item($selectedTable)).Trim()
Write-LogOutput "Copying $selectedTable : '$query'"
$cmd = New-Object Data.SqlClient.SqlCommand -argumentList $query, $source
$cmd.CommandTimeout = 120;
$bulkData = ([Data.SqlClient.SqlBulkCopy]$destination)
$bulkData.DestinationTableName = $selectedTable;
$bulkData.BulkCopyTimeout = $global:tableCopyDataTimeout # = 3600
$reader = $cmd.ExecuteReader();
$bulkData.WriteToServer($reader); # Takes forever here on large tables

The source and target databases are located on different servers so I kept track of the network speed as well. The network utilization never went over 1% which was quite surprising to me. But when I just transfer some large files between the servers, the network utilization spikes up to 10%. I have tried setting the $bulkData.BatchSize to 5000 but nothing really changed. Increasing the BulkCopyTimeout to an even greater amount would only solve the timeout. I really would like to know why the network is not being used fully.

Anyone else had this problem? Any suggestions on networking or bulk copy will be appreciated. And please let me know if you need more information.

Thanks.

UPDATE

I have tweaked several options that increase the performance of SqlBulkCopy, such as setting the transaction logging to simple and providing a table lock to SqlBulkCopy instead of the default row lock. Also some tables are better optimized for certain batch sizes. Overall, the duration of the copy was decreased by some 15%. And what we will do is execute the copy of each database simultaneously on different servers. But I am still having a timeout issue when copying one of the databases.

When copying one of the larger databases, there is a table for which I consistently get the following exception:

System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

It is thrown about 16 minutes after it starts copying the table which is no where near my BulkCopyTimeout. Even though I get the exception that table is fully copied in the end. Also, if I truncate that table and restart my process for that table only, the tables is copied over without any issues. But going through the process of copying that entire database fails always for that one table.

I have tried executing the entire process and reseting the connection before copying that faulty table, but it still errored out. My SqlBulkCopy and Reader are closed after each table. Any suggestions as to what else could be causing the script to fail at the point each time?

CREATE TABLE [dbo].[badTable](
[someGUID] [uniqueidentifier] NOT NULL,
[xxx] [uniqueidentifier] NULL,
[xxx] [int] NULL,
[xxx] [tinyint] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NOT NULL,
[xxx] [datetime] NULL,
[xxx] [uniqueidentifier] NOT NULL,
[xxx] [uniqueidentifier] NULL,
CONSTRAINT [PK_badTable] PRIMARY KEY NONCLUSTERED
(
[someGUID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

No indexes exist for this table on the target DB.


问:
unexpected result in parsing nested json in qt (array does not exist)
I am new in qt and I also searched in stack overflow but I can't get my answer so this not a duplicated post because all similar post have array [] but in this code i have not any array
I want to parse this complex JSON file:

```<code>{
    "query": {

        "lang": "en-US",
        "results": {
            "channel": {
                "units": {
                    "distance": "mi",
                    "pressure": "in"
                },
                "ttl": "60",
                "location": {
                    "city": "city",
                    "country": "not important",
                    "region": " kkk"
                },
                "wind": {
                    "chill": "99",
                    "direction": "180",
                    "speed": "14"
                }
            }
       ...(more code)
</code>```

i want to get chill data but out put is " " , please help me to print chill data in qt

its a part of my code:

```<code>QNetworkAccessManager manager;

QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));

event.exec();
json = response->readAll();

QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());

QJsonObject jsonObj = doc.object();

foreach (const QJsonValue &value, jsonObj) {

      QJsonObject jsonobj = value.toObject();

      qDebug() <<  jsonobj["chill"].toString();
}
</code>```

output of qDebug()<<doc.object();  is

```<code>D/libuntitled7.so(13258): : ** QJsonObject({"query":{"count":1,"created":"2017-07-06T21:21:16Z","lang":"en-US","results":{"channel":{"astronomy":{"sunrise":"5:48 am","sunset":"8:15 pm"},"atmosphere":{"humidity":"16","pressure":"875.0","rising":"0","visibility":"16.1"},"description":"Yahoo! Weather","image":{"height":"18","link":"http://weather.yahoo.com","title":"Yahoo! Weather","url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif","width":"142"},"item":{"condition":{"code":"31","date":"Fri, 07 Jul 2017 12:30 AM IRDT","temp":"85","text":"Clear"},"description":"<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/31.gif\"/>\n<BR/>\n<b>Forecast:</b>\n<BR /> Fri - Sunny. High: 97Low: 78\n<BR /> Sat - Sunny. High: 100Low: 79\n<BR /> Sun - Sunny. High: 101Low: 81\n<BR /> Mon - Sunny. High: 100Low: 81\n<BR /> Tue - Mostly
D/libuntitled7.so(13258): ..\untitled7\dialog2.cpp:84 (void Dialog2::on_pushButton_clicked()):
</code>```

and next out put is 86

答:
As I comment @MohammedB.B. a way is to manually search through the keys, another way is to create a function that searches through the keys, in this case I present the second form:

```<code>QJsonObject findObject(QString key, QJsonObject object){
    if(object.isEmpty())
        return QJsonObject();
    if(object.keys().contains(key)){
        return object;
    }
    else{
        for(const QString& _key: object.keys()){
            if(object[_key].isObject()){
                const QJsonObject& result = findObject(key, object[_key].toObject());
                if(!result.isEmpty()){
                    return result;
                }
            }
        }
    }

    return QJsonObject();
}

QJsonValue findValuebyKey(QString key, QJsonDocument doc){
    QJsonObject obj_key = findObject(key, doc.object());
    return obj_key[key];
}
</code>```

Example:

```<code>QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
qDebug()<<findValuebyKey("chill", doc).toString();
</code>```

Output:

```<code>"99"
</code>```

Note:If you generate problems the "for" enable c ++ 11, you can do this by adding CONFIG += c++11 to your .pro

Body:
I am new in qt and I also searched in stack overflow but I can't get my answer so this not a duplicated post because all similar post have array [] but in this code i have not any array
I want to parse this complex JSON file:

{
    "query": {

        "lang": "en-US",
        "results": {
            "channel": {
                "units": {
                    "distance": "mi",
                    "pressure": "in"
                },
                "ttl": "60",
                "location": {
                    "city": "city",
                    "country": "not important",
                    "region": " kkk"
                },
                "wind": {
                    "chill": "99",
                    "direction": "180",
                    "speed": "14"
                }
            }
       ...(more code)

i want to get chill data but out put is " " , please help me to print chill data in qt

its a part of my code:

QNetworkAccessManager manager;

QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));

event.exec();
json = response->readAll();

QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());

QJsonObject jsonObj = doc.object();

foreach (const QJsonValue &value, jsonObj) {

      QJsonObject jsonobj = value.toObject();

      qDebug() <<  jsonobj["chill"].toString();
}

output of qDebug()<<doc.object();  is

D/libuntitled7.so(13258): : ** QJsonObject({"query":{"count":1,"created":"2017-07-06T21:21:16Z","lang":"en-US","results":{"channel":{"astronomy":{"sunrise":"5:48 am","sunset":"8:15 pm"},"atmosphere":{"humidity":"16","pressure":"875.0","rising":"0","visibility":"16.1"},"description":"Yahoo! Weather","image":{"height":"18","link":"http://weather.yahoo.com","title":"Yahoo! Weather","url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif","width":"142"},"item":{"condition":{"code":"31","date":"Fri, 07 Jul 2017 12:30 AM IRDT","temp":"85","text":"Clear"},"description":"<![CDATA[\n
\nForecast:\n
 Fri - Sunny. High: 97Low: 78\n
 Sat - Sunny. High: 100Low: 79\n
 Sun - Sunny. High: 101Low: 81\n
 Mon - Sunny. High: 100Low: 81\n
 Tue - Mostly
D/libuntitled7.so(13258): ..\untitled7\dialog2.cpp:84 (void Dialog2::on_pushButton_clicked()):

and next out put is 86

Body:
As I comment @MohammedB.B. a way is to manually search through the keys, another way is to create a function that searches through the keys, in this case I present the second form:

QJsonObject findObject(QString key, QJsonObject object){
    if(object.isEmpty())
        return QJsonObject();
    if(object.keys().contains(key)){
        return object;
    }
    else{
        for(const QString& _key: object.keys()){
            if(object[_key].isObject()){
                const QJsonObject& result = findObject(key, object[_key].toObject());
                if(!result.isEmpty()){
                    return result;
                }
            }
        }
    }

    return QJsonObject();
}

QJsonValue findValuebyKey(QString key, QJsonDocument doc){
    QJsonObject obj_key = findObject(key, doc.object());
    return obj_key[key];
}

Example:

QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
qDebug()<<findValuebyKey("chill", doc).toString();

Output:

"99"

Note:If you generate problems the "for" enable c ++ 11, you can do this by adding CONFIG += c++11 to your .pro


问:
Remove duplicate values from JS array
I have a very simple JavaScript array that may or may not contain duplicates.

```<code>var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
</code>```

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

答:
Although ES6 Solution is the best, I'm baffled as to how nobody has shown the following solution:

```<code>function removeDuplicates(arr){
    o={}
    arr.forEach(function(e){
        o[e]=true
    })
    return Object.keys(o)
}
</code>```

The thing to remember here is that objects MUST have unique keys. We are exploiting this to remove all the duplicates. I would have thought this would be the fastest solution (before ES6).

Bear in mind though that this also sorts the array.

ContentLicense: CC BY-SA 4.0

Title: Remove duplicate values from JS array

Body:
I have a very simple JavaScript array that may or may not contain duplicates.

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Body:
Although ES6 Solution is the best, I'm baffled as to how nobody has shown the following solution:

function removeDuplicates(arr){
    o={}
    arr.forEach(function(e){
        o[e]=true
    })
    return Object.keys(o)
}

The thing to remember here is that objects MUST have unique keys. We are exploiting this to remove all the duplicates. I would have thought this would be the fastest solution (before ES6).

Bear in mind though that this also sorts the array.


问:
Python Import error for f2py modules compiled with OpenMP
I'm currently experiencing an issue in wrapping some Fortran subroutines for use in a python3 script. This issue has only come up since I have attempted to use OpenMP in the subroutines.

For example, if I compile a module 'test.pyd' using f2py -c -m --fcompiler=gfortran --compiler=mingw32 --f90flags='-fopenmp' test test.f90 -lgomp, in which 'test.f90' is a Fortran subroutine which contains a parallelized loop, upon attempting to import this module into my script, I encounter ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed..

Removing the -fopenmp flag in compiling, or the !$omp comments in the Fortran subroutine remove this error.

Changing the subroutine to a roughly equivalent Fortran program, the program compiles to a .exe and runs correctly in parallel.

I'm on a Windows 10 platform, with an AMD64 processor, using GNU Fortran and C compilers from TDM-GCC

答:
I just tried your build command, and it looks prefectly fine. I am myself able to run a parallel subroutine from a python module compiled just the way you are doing.

How are you executing the python code that is using your module? I think the problem is that you don't have the openmp dll (which is named libgomp-1.dll) in your path

I would advise you to run (from a bash shell) :

where libgomp-1.dll

If the command can't find it, then you should probably add the path to your openmp dll (which is usually "C:\tools\mingw64\bin\") to your PATH.

In order to do this, you can use:

```<code>export PATH=$PATH:C:\tools\mingw64\bin\ && python script_using_module.py
</code>```

There is a good chance the way you are executing your python code doesn't account properly for the path, since you can run the parallel executable without a problem.

Body:
I just tried your build command, and it looks prefectly fine. I am myself able to run a parallel subroutine from a python module compiled just the way you are doing.

How are you executing the python code that is using your module? I think the problem is that you don't have the openmp dll (which is named libgomp-1.dll) in your path

I would advise you to run (from a bash shell) :

where libgomp-1.dll

If the command can't find it, then you should probably add the path to your openmp dll (which is usually "C:\tools\mingw64\bin\") to your PATH.

In order to do this, you can use:

export PATH=$PATH:C:\tools\mingw64\bin\ && python script_using_module.py

There is a good chance the way you are executing your python code doesn't account properly for the path, since you can run the parallel executable without a problem.


问:
Update view after AJAX call succeeds and returns data
I'm a beginner working on a recipe search app which returns a list of recipes based on the ingredients the user puts in the search bar. I'm learning to use Angular since it's convenient and makes my code more manageable.

So far I have succeeded in making jQuery Ajax GET requests to the API of my database and have a list of JSON objects returned.

Here's my Angular controller declaration:

```<code>    var recipesData = []; // variable that will hold the returned data
    angular
       .module("awesomeapp")
       .controller("listController", listController);

    function listController () {
         var vm = this;
         vm.data = recipesData;
    }
</code>```

And I have stuff in vm.data displayed elsewhere in my view.

The problem is, when vm.data is set to recipesData, it doesn't contain anything yet because the page has just been loaded, the user hasn't put anything in and there isn't any data returned yet.

What should I do so that vm.data can be set after the Ajax call? Or can it be set outside of the listController function?

I'm looking for an elegant solution for this so that it makes everything easier to maintain. Thank you :)

答:
The proper way to do this is to not use jQuery and use Angular's $http service to retrieve the data. The even more proper way to do this is to create your own service that internally uses Angular's $http service to get the data.

So first you would create the service. Something like this:

```<code>angular
       .module("awesomeapp")
       .service("recipeService", recipeService);

function recipeService($http) {
     return $http.get(**url**)
}
</code>```

Then your controller would look like something this:

```<code>function listController (recipeService) {
     var vm = this;
     recipeService.then(response) {
        vm.data = response.data
    }
}
</code>```

You'll probably have more things on your service eventually, but that should get you going in the right direction. I'd highly recommend referring to John Papa's Angularjs style guide https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md for guidance on how to structure your app. You want to try to avoid using jQuery with Angular in general, but in particular, you want to avoid using it for things Angular does natively.

Body:
I'm a beginner working on a recipe search app which returns a list of recipes based on the ingredients the user puts in the search bar. I'm learning to use Angular since it's convenient and makes my code more manageable.

So far I have succeeded in making jQuery Ajax GET requests to the API of my database and have a list of JSON objects returned.

Here's my Angular controller declaration:

    var recipesData = []; // variable that will hold the returned data
    angular
       .module("awesomeapp")
       .controller("listController", listController);

    function listController () {
         var vm = this;
         vm.data = recipesData;
    }

And I have stuff in vm.data displayed elsewhere in my view.

The problem is, when vm.data is set to recipesData, it doesn't contain anything yet because the page has just been loaded, the user hasn't put anything in and there isn't any data returned yet.

What should I do so that vm.data can be set after the Ajax call? Or can it be set outside of the listController function?

I'm looking for an elegant solution for this so that it makes everything easier to maintain. Thank you :)

Body:
The proper way to do this is to not use jQuery and use Angular's $http service to retrieve the data. The even more proper way to do this is to create your own service that internally uses Angular's $http service to get the data.

So first you would create the service. Something like this:

angular
       .module("awesomeapp")
       .service("recipeService", recipeService);

function recipeService($http) {
     return $http.get(**url**)
}

Then your controller would look like something this:

function listController (recipeService) {
     var vm = this;
     recipeService.then(response) {
        vm.data = response.data
    }
}

You'll probably have more things on your service eventually, but that should get you going in the right direction. I'd highly recommend referring to John Papa's Angularjs style guide https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md for guidance on how to structure your app. You want to try to avoid using jQuery with Angular in general, but in particular, you want to avoid using it for things Angular does natively.


问:
Binary addition in java
I wrote a program for a binary addition in java. But the result is sometimes not right.

For example if i add 1110+111. The result should be 10101.

But my program throws out 10001.

Maybe one of you find the mistake.

```<code> import java.util.Scanner;

 public class BinaryAdder {
 public static String add(String binary1, String binary2) {
    int a = binary1.length()-1;
    int b = binary2.length()-1;
    int sum = 0;
    int carry = 0;

    StringBuffer sb = new StringBuffer();
    while (a >= 0 || b >= 0) {
        int help1 = 0;
        int help2 = 0;
        if( a >=0){
        help1 = binary1.charAt(a) == '0' ? 0 : 1;
        a--;
    }  if( b >=0){
        help2 = binary2.charAt(b) == '0' ? 0 : 1;
        b--;
    }
         sum = help1 +help2 +carry;
         if(sum >=2){
             sb.append("0");
             carry = 1;
         } else {
             sb.append(String.valueOf(sum));
             carry = 0;
         }

    }
    if(carry == 1){
        sb.append("1");
    }

    sb.reverse();
    String s = sb.toString();
    s = s.replaceFirst("^0*", "");

    return s;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("First:  ");
    String input1 = scan.next("(0|1)*");
    System.out.print("Second:  ");
    String input2 = scan.next("(0|1)*");
    scan.close();
    System.out.println("Result: " + add(input1, input2));
}
</code>```

}

答:
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...

```<code>import java.util.Scanner;

public class Binary_Aids {
public static void main(String args[]) {
    System.out.println("Enter the value you want to be converted");
    Scanner inp = new Scanner(System.in);
    int num = inp.nextInt();

    String result = "";

    while(num > 0) {
        result = result + Math.floorMod(num,  2);
        num = Math.round(num/2);

    }

    String flippedresult = "";
    for(int i = 0; i < result.length(); i++) {
        flippedresult = result.charAt(i) + flippedresult;
    }

    System.out.println(flippedresult);

}
}
</code>```

This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...

```<code>import java.util.Scanner;

public class Binary_Aids {
public static void main(String args[]) {
    Scanner inp = new Scanner(System.in);

    String decimalToBinaryString = new String();

    System.out.println("First decimal number to be added");
    int num1 = inp.nextInt();
    String binary1 = decimalToBinaryString(num1);

    System.out.println("Input decimal number 2");
    int num2 = inp.nextInt();
    String binary2 = decimalToBinaryString(num2);

    int patternlength = Math.max[binary1.length[], binary2.length[]];

    while(binary1.length() < patternlength) {
        binary1 = "0" + binary2;
    }

    System.out.println(binary1);
    System.out.println(binary2);

    int carry = 0;
    int frequency_of_one;
    String result = "";
    for(int i = patternlength -i; i >= 0; i--) {
        frequency_of_one = carry;
        if(binary1.charAt(i) == '1') {
            frequency_of_one++;
        }
        if(binary2.charAt(i) == '1') {
            frequency_of_one++;

        }

        switch(frequency_of_one) {
        case 0 ;
        carry = 0;
        result = "1" + result;
        break;

        case 1 ;
        carry = 0;
        result = "1" + result;
        break;

        case 2;
        carry = 1;
        result = "0" + result;
        breake;

        case 3;
        carry = 1;
        result = "1" + result;
        breake;
        }
    }

    if(carry == 1) {
        result = "1" + result;

    }
    System.out.println(result);

  }

public static String decimalToBinaryString(int decimal1) {
String result = "";

while(decimal1 > 0) {
    result = result + Math.floorMod(decimal1,  2);
    decimal = Math.round(decimal1/2);
}

String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
    flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}

}
</code>```

Title: Binary addition in java

Body:
I wrote a program for a binary addition in java. But the result is sometimes not right.

For example if i add 1110+111. The result should be 10101.

But my program throws out 10001.

Maybe one of you find the mistake.

 import java.util.Scanner;

 public class BinaryAdder {
 public static String add(String binary1, String binary2) {
    int a = binary1.length()-1;
    int b = binary2.length()-1;
    int sum = 0;
    int carry = 0;

    StringBuffer sb = new StringBuffer();
    while (a >= 0 || b >= 0) {
        int help1 = 0;
        int help2 = 0;
        if( a >=0){
        help1 = binary1.charAt(a) == '0' ? 0 : 1;
        a--;
    }  if( b >=0){
        help2 = binary2.charAt(b) == '0' ? 0 : 1;
        b--;
    }
         sum = help1 +help2 +carry;
         if(sum >=2){
             sb.append("0");
             carry = 1;
         } else {
             sb.append(String.valueOf(sum));
             carry = 0;
         }

    }
    if(carry == 1){
        sb.append("1");
    }

    sb.reverse();
    String s = sb.toString();
    s = s.replaceFirst("^0*", "");

    return s;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("First:  ");
    String input1 = scan.next("(0|1)*");
    System.out.print("Second:  ");
    String input2 = scan.next("(0|1)*");
    scan.close();
    System.out.println("Result: " + add(input1, input2));
}

}

Body:
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...

import java.util.Scanner;

public class Binary_Aids {
public static void main(String args[]) {
    System.out.println("Enter the value you want to be converted");
    Scanner inp = new Scanner(System.in);
    int num = inp.nextInt();

    String result = "";

    while(num > 0) {
        result = result + Math.floorMod(num,  2);
        num = Math.round(num/2);

    }

    String flippedresult = "";
    for(int i = 0; i < result.length(); i++) {
        flippedresult = result.charAt(i) + flippedresult;
    }

    System.out.println(flippedresult);

}
}

This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...

import java.util.Scanner;

public class Binary_Aids {
public static void main(String args[]) {
    Scanner inp = new Scanner(System.in);

    String decimalToBinaryString = new String();

    System.out.println("First decimal number to be added");
    int num1 = inp.nextInt();
    String binary1 = decimalToBinaryString(num1);

    System.out.println("Input decimal number 2");
    int num2 = inp.nextInt();
    String binary2 = decimalToBinaryString(num2);

    int patternlength = Math.max[binary1.length[], binary2.length[]];

    while(binary1.length() < patternlength) {
        binary1 = "0" + binary2;
    }

    System.out.println(binary1);
    System.out.println(binary2);

    int carry = 0;
    int frequency_of_one;
    String result = "";
    for(int i = patternlength -i; i >= 0; i--) {
        frequency_of_one = carry;
        if(binary1.charAt(i) == '1') {
            frequency_of_one++;
        }
        if(binary2.charAt(i) == '1') {
            frequency_of_one++;

        }

        switch(frequency_of_one) {
        case 0 ;
        carry = 0;
        result = "1" + result;
        break;

        case 1 ;
        carry = 0;
        result = "1" + result;
        break;

        case 2;
        carry = 1;
        result = "0" + result;
        breake;

        case 3;
        carry = 1;
        result = "1" + result;
        breake;
        }
    }

    if(carry == 1) {
        result = "1" + result;

    }
    System.out.println(result);

  }

public static String decimalToBinaryString(int decimal1) {
String result = "";

while(decimal1 > 0) {
    result = result + Math.floorMod(decimal1,  2);
    decimal = Math.round(decimal1/2);
}

String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
    flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}

}


问:
Generate signed apk without typing key
First of all here goes my signinConfigs:

```<code>signingConfigs {
        development {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeydev"
            keyPassword "mykeydev"
        }
        production {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeyprod"
            keyPassword "mykeyprod"
        }
}
</code>```

And now my flavors:

```<code>productFlavors {
    development{
        applicationId "br.com.myapp.dev"
        signingConfig signingConfigs.development
        resValue "string", "app_name", "DEV"
    }

    production {
        applicationId "br.com.myapp"
        signingConfig signingConfigs.production
        resValue "string", "app_name", "PROD"
    }
}
</code>```

I have under by buildTypes this:

```<code>buildTypes {
    release {
        minifyEnabled false
        productFlavors.production.signingConfig signingConfigs.production
        productFlavors.development.signingConfig signingConfigs.development
    }
}
</code>```

And here goes my question, Why am I asked for keyPassword and storePassword every time i want to generate a new signed apk file, if all keys and stuff are inside my .gradle file?

答:
When you build from the "Build -> Generate Signed apk" you'll need to enter Android's studio password once in a while, but it saves the passwords encrypted for you. This is the safest way to go.

But since you need an automated way, you can use the "Terminal" view, and type: ./gradlew assembleRelease. (If you're in a windows machine I think it's gradlew assembleRelease).

In any case, it's not advisable to write your password inside the build.gradle file:

```<code>android {

  signingConfigs {
    release {
        storeFile file('/your/keystore/location/key')
        keyAlias 'your_alias'
        keyPasswordString ps = System.getenv("ps")
        storePasswordif System.getenv("ps"ps == null) {
             throw new GradleException('missing ps env variable')
        }
        keyPassword ps
        storePassword ps
    }
}
</code>```

Title: Generate signed apk without typing key

Body:
First of all here goes my signinConfigs:

signingConfigs {
        development {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeydev"
            keyPassword "mykeydev"
        }
        production {
            storeFile file("mykey.jks") //Path to the keystore file
            keyAlias "mykey"
            storePassword "mykeyprod"
            keyPassword "mykeyprod"
        }
}

And now my flavors:

productFlavors {
    development{
        applicationId "br.com.myapp.dev"
        signingConfig signingConfigs.development
        resValue "string", "app_name", "DEV"
    }

    production {
        applicationId "br.com.myapp"
        signingConfig signingConfigs.production
        resValue "string", "app_name", "PROD"
    }
}

I have under by buildTypes this:

buildTypes {
    release {
        minifyEnabled false
        productFlavors.production.signingConfig signingConfigs.production
        productFlavors.development.signingConfig signingConfigs.development
    }
}

And here goes my question, Why am I asked for keyPassword and storePassword every time i want to generate a new signed apk file, if all keys and stuff are inside my .gradle file?

Body:
When you build from the "Build -> Generate Signed apk" you'll need to enter Android's studio password once in a while, but it saves the passwords encrypted for you. This is the safest way to go.

But since you need an automated way, you can use the "Terminal" view, and type: ./gradlew assembleRelease. (If you're in a windows machine I think it's gradlew assembleRelease).

In any case, it's not advisable to write your password inside the build.gradle file:

android {

  signingConfigs {
    release {
        storeFile file('/your/keystore/location/key')
        keyAlias 'your_alias'
        keyPasswordString ps = System.getenv("ps")
        storePasswordif System.getenv("ps"ps == null) {
             throw new GradleException('missing ps env variable')
        }
        keyPassword ps
        storePassword ps
    }
}


问:
How can I make Web API serialize DateTime in any object into number of milliseconds since 1970?
In my ASP.NET web service I need all my dates to be serialized to JSON as numbers which represent a number of milliseconds passed since 1970 please. I'm using Newtonsoft.Json serializer. What do I need to do to set it up this way?

UPDATE:
the available documentation (http://www.newtonsoft.com/json/help/html/DatesInJSON.htm) only mentions serializing a single object with custom settings, what i am looking for is the default serialization settings that would govern serialization of any object

答: Have a look at this excellent blog post on creating your own DateTime converter to deal with your requirement. Example actually shows you creating UnixDateTimeConverter.</p>


问:
UITableViewController won't scroll on custom implementation
There are numerous posts out there stating one should avoid the use of UITableViewController. More and more I want to give in, but I'm using a CoreDataTableViewController super class that's tied into the entire application, and I don't have the time to rewrite it all.

Of course, the UITableViewController's view shouldn't take up the entire screen (iPad project), so I put it as a subview on a regular UIView instance with the frame set to a pretty size. That's when weird things start to happen.

I copied my custom class (GroupsTableViewController->CoreDataTableViewController->UITableViewController) from a test-project where everything was working fine, to my current project. I then alloc/init and addSubview the view.

At first the table would show up empty. What gives? The viewWillAppear: message is not sent. What the...? Alright, then I call it manually (at this point, I'm already starting to doubt myself). Next, the table is actually filled with content, but all interactivity is gone. No taps, no scrolling.

I tried setting userInteractionEnabled on everything, but no result. This is a n00b thing, I'm sure, too silly to be stuck on. Yet here I am, stuck.

Can anyone point me to the right direction? Did I forget a delegate somewhere? Or maybe an unsent message?

答: One issue you are running into is that nested UIViewControllers do not receive the proper events such as viewWillAppear:. According to apple's guidelines an UIViewController should fill the entire screen and not represent a partial view (of course with the exceptions of the UITabBarController, UINavigationController, and UISplitViewController). Try setting the GroupsTableViewController as the main controller (if it is in an UINavigationController try pushing it, if its a split view make it the details view, etc). If that works then there a some events not getting through causing your problems. Hope that helps!</p>


问:
Scrum and requirements
You can't just have user stories somehow the functionality of the program has to be documented.  Do you end up with a specifications document with scrum?  If you do do you end up assigning time to do this onto the task?

An example would be a complex workflow.

Another example would be a new member who comes onto the team.

答:
I think you are asking for a few different things here.  If you are adding a new team member, then the documentation for the system should be geared toward their role on the team as part of the on-boarding process.

If you are talking about documenting the system functionality; in our organization our training teams document the functionality as part of the release.  They are engaged (as a stakeholder) during the Sprint Review (demo) and then provided a training environment with the new functionality to prepare the training materials prior to release.

If you are talking about providing documentation for tractability, your backlog can serve as that with the proper process & controls added.

Each one of these different items takes planning and deliberate process development to effectively function and meet the needs of the team.  We have included each one of these items in our retrospectives as an issue was identified and then developed our processes over time.

Title: Scrum and requirements


问:
formula Subtotal 109 when hiding columns does not work in excel
I have formulas in column B which subtotal every other column starting with column E.  So column E, G, I, K, M, O, Q, S, and eventually more.  The formula in row 4 is

```<code>=SUBTOTAL(109,E4,G4,I4,K4,M4,O4,Q4,S4)
</code>```

When I hide one of these columns the total in column B does not adjust to reduce the value.

Any ideas what might be causing this.  It seems that this should be straightforward. I've used subtotal before and it works in my other workbooks.  This is a simple work book or so it seems. 55 rows on the sheet with 52 of them having this formula.  None of them work.  This will be simple I'm sure and I will be embarrased but I have tried a number of things unsuccessfully.

答:
In row 12 for example put "H" in every column you do not want to sum.
The formula in cell B4 then is</p>

```<code>=SUMIFS(E4:S4,E12:S12,"<>H")
</code>```

Body:
I have formulas in column B which subtotal every other column starting with column E.  So column E, G, I, K, M, O, Q, S, and eventually more.  The formula in row 4 is

=SUBTOTAL(109,E4,G4,I4,K4,M4,O4,Q4,S4)

When I hide one of these columns the total in column B does not adjust to reduce the value.

Any ideas what might be causing this.  It seems that this should be straightforward. I've used subtotal before and it works in my other workbooks.  This is a simple work book or so it seems. 55 rows on the sheet with 52 of them having this formula.  None of them work.  This will be simple I'm sure and I will be embarrased but I have tried a number of things unsuccessfully.

Body:
In row 12 for example put "H" in every column you do not want to sum.
The formula in cell B4 then is

=SUMIFS(E4:S4,E12:S12,"<>H")


问:
Better ways to identify objects not getting garbage collected?

In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

```<code>Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190
</code>```

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

```<code>Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here
</code>```

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?

答:
I recommend first trying JVisualVM, which distributes with the latest JDK.

Also, if you can justify the cost, I have found JProfiler to be an excellent tool, over the years.

Body:
In a nutshell

I have a program that is gradually using more and more memory over time. I am using jmap and jhat to try and diagnose it but am still not quite there.

Background

The program is a long-running server backed by an hbase datastore providing a thrift service to a bunch of other stuff. However, after running for a few days, it will eventually hit the allocated heap limit, and thrash back and forth with nearly all time spent in garbage collection. It would seem references are getting kept to a lot of data somewhere

What I've done so far

After fiddling about with jstat and jconsole some I ended up taking heapdumps with jmap of the running process, and run it through jhat, and the numbers simple don't add up to anywhere near the memory utilisation

jmap -F -dump:live,format=b,file=heap.dump 12765

jmap -F -dump:format=b,file=heap.all 12765

Some stuff off the top of the histogram

Class   Instance Count  Total Size
class [B     7493    228042570
class java.util.HashMap$Entry    2833152     79328256
class [Ljava.util.HashMap$Entry;     541     33647856
class [Ljava.lang.Object;    303698  29106440
class java.lang.Long     2851889     22815112
class org.apache.hadoop.hbase.KeyValue   303593  13358092
class org.apache.hadoop.hbase.client.Result  303592  9714944
class [I     14074   9146580
class java.util.LinkedList$Entry     303841  7292184
class [Lorg.apache.hadoop.hbase.KeyValue;    303592  7286208
class org.apache.hadoop.hbase.io.ImmutableBytesWritable  305097  4881552
class java.util.ArrayList    302633  4842128
class [Lorg.apache.hadoop.hbase.client.Result;   297     2433488
class [C     5391    320190

While the totals here don't add up to it, at the point that heap dump was taken the process was using over 1gb of memory.

The immediate apparent culprit seems like I'm leaving HBase Result and KeyValue entries all over the place. Trying to trace up the references, I eventually hit

Object at 0x2aab091e46d0

instance of org.apache.hadoop.hbase.ipc.HBaseClient$Call@0x2aab091e46d0 (53 bytes)

Class:

class org.apache.hadoop.hbase.ipc.HBaseClient$Call
Instance data members:

done (Z) : true
error (L) : <null>
id (I) : 57316
param (L) : org.apache.hadoop.hbase.ipc.HBaseRPC$Invocation@0x2aab091e4678 (48 bytes)
this$0 (L) : org.apache.hadoop.hbase.ipc.HBaseClient@0x2aaabfb78f30 (86 bytes)
value (L) : org.apache.hadoop.hbase.io.HbaseObjectWritable@0x2aab092e31c0 (40 bytes)
References to this object:

Other Queries

Reference Chains from Rootset
Exclude weak refs
Include weak refs
Objects reachable from here

Help needed:

There seems to be no references to this final HBaseCLient$Call object(or any of the others like it, each which hold a thousand or so keyvalues with all their internal data). Shouldn't it be getting GCed? Am I just misunderstanding how the gc works or the extent to which jhat will verify references? If so what further can I do to track down my "missing" memory? What other steps can I take to track this down?


问:
Reshaping pandas dataframe with a column containing lists
Let's say I have a dataframe that looks like this:

```<code>import pandas as pd

data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']},
            {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']},
            {"Name" : "Project C", "Feedback" : ['bar', 'baz']}
            ]

df = pd.DataFrame(data)
df = df[['Name','Feedback']]
df

    Name        Feedback
0   Project A   ['we should do x', 'went well']
1   Project B   ['eat pop tarts', 'boo']
2   Project C   ['bar', 'baz']
</code>```

What I would like to do is reshape the dataframe, such that Name is the key and each element in the list of the Feedback column is a value like so:

```<code>        Name          Feedback
0       Project A    'we should do x'
1       Project A    'went well'
2       Project B    'eat pop tarts'
3       Project B    'boo'
4       Project C    'bar'
5       Project C    'baz'
</code>```

What would be an efficient way to do this?

答:
Here's another method:

```<code># Separate out values (NOTE- this assumes you'll always have two strings in list)
df['pos_0'] = df['Feedback'].str[0]
df['pos_1'] = df['Feedback'].str[1]

df
        Name                     Feedback           pos_0      pos_1
0  Project A  [we should do x, went well]  we should do x  went well
1  Project B         [eat pop tarts, boo]   eat pop tarts        boo
2  Project C                   [bar, baz]             bar        baz
</code>```

Desired output:

```<code>pd.melt(df, 'Name', ['pos_0', 'pos_1'], 'Feedback').drop('Feedback', axis=1)
        Name           value
0  Project A  we should do x
1  Project B   eat pop tarts
2  Project C             bar
3  Project A       went well
4  Project B             boo
5  Project C             baz
</code>```

Body:
Let's say I have a dataframe that looks like this:

import pandas as pd

data = [{"Name" : "Project A", "Feedback" : ['we should do x', 'went well']},
            {"Name" : "Project B", "Feedback" : ['eat pop tarts', 'boo']},
            {"Name" : "Project C", "Feedback" : ['bar', 'baz']}
            ]

df = pd.DataFrame(data)
df = df[['Name','Feedback']]
df

    Name        Feedback
0   Project A   ['we should do x', 'went well']
1   Project B   ['eat pop tarts', 'boo']
2   Project C   ['bar', 'baz']

What I would like to do is reshape the dataframe, such that Name is the key and each element in the list of the Feedback column is a value like so:

        Name          Feedback
0       Project A    'we should do x'
1       Project A    'went well'
2       Project B    'eat pop tarts'
3       Project B    'boo'
4       Project C    'bar'
5       Project C    'baz'

What would be an efficient way to do this?

Body:
Here's another method:

# Separate out values (NOTE- this assumes you'll always have two strings in list)
df['pos_0'] = df['Feedback'].str[0]
df['pos_1'] = df['Feedback'].str[1]

df
        Name                     Feedback           pos_0      pos_1
0  Project A  [we should do x, went well]  we should do x  went well
1  Project B         [eat pop tarts, boo]   eat pop tarts        boo
2  Project C                   [bar, baz]             bar        baz

Desired output:

pd.melt(df, 'Name', ['pos_0', 'pos_1'], 'Feedback').drop('Feedback', axis=1)
        Name           value
0  Project A  we should do x
1  Project B   eat pop tarts
2  Project C             bar
3  Project A       went well
4  Project B             boo
5  Project C             baz


问:
Distinguish sender from receiver with Socket.io
I have built a web application using JavaScript stack (MongoDB, ExpressJS, AngularJS, NodeJS). The registration works, the authentication works, the chat is which is using Socket.io works but I need a way of distinguishing which client is sending and which client is receiving the message in order to perform further functions with the user's data.

P.S. Since this is a project that I can not publish there are no code snippets in my post, hopefully it is alright

答:
1.) Create a global server variable and bind connections property to it and whenever the authentication is true ,store socket_id against the id(user_id etc) which you get after decoding your token.

```<code>global.server=http.createServer(app);
server.connections={};
</code>```

If server.connection hasOwnProperty(id) then use socket emit to send your message ,
else store the socket_id against your id and then send your message.
In this way you just need to know the unique token of the target user to send the message.

2.) You can also use the concept of room

If authentication is true use
    socket.room=id ; socket.join(id)
when sending message use client.in(id).emit("YOUR-EVENT-NAME",message)

Note: Make your own flow , this is just an overview of what I have implemented in the past.You should consider using Redis for storing socket_ids.

Body:
1.) Create a global server variable and bind connections property to it and whenever the authentication is true ,store socket_id against the id(user_id etc) which you get after decoding your token.

global.server=http.createServer(app);
server.connections={};

If server.connection hasOwnProperty(id) then use socket emit to send your message ,
else store the socket_id against your id and then send your message.
In this way you just need to know the unique token of the target user to send the message.

2.) You can also use the concept of room

If authentication is true use
    socket.room=id ; socket.join(id)
when sending message use client.in(id).emit("YOUR-EVENT-NAME",message)

Note: Make your own flow , this is just an overview of what I have implemented in the past.You should consider using Redis for storing socket_ids.