问:
NuGet Push Failure in TFS build
Preface: I am running NuGet Server (2.11.3) on Windows 2012 R2 / IIS 8.5. The NuGet Server manages its packages folder in separated file server (shared folder).
Additionally I am running TFS build machine (agent from TFS 2015) that uses this nuget server for both restore and push activities. Naturally,  each build, initially, reads the target solution >>> projects >>> packages.config files and restores the configured packages from the nuget server. On late step, the agent generates the required *.nupkg files and pushes them to the nuget endpoint of the same nuget server. Those are dependencies of other solutions.

Problem: the majority of the solutions running properly without any special issues. There are couple of solutions that only 1-3 projects within them, fail the TFS build with the following message:

```<code>Response status code does not indicate success: 500 (Internal Server Error).
Unexpected exit code 1 returned from tool NuGet.exe
</code>```

The IIS logs on nuget server looks like the following:

```<code>2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 31
</code>```

The following event is logged (shown in the event viewer) in the nuget server:

```<code>Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 27/03/2017 10:40:17
Event time (UTC): 27/03/2017 07:40:17
Event ID: cb897ce6dc2f4e40a07c71a9160718f2
Event sequence: 2073
Event occurrence: 4
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/1/ROOT/MainRepository-1-131350724531418170
    Trust level: Full
    Application Virtual Path: /MainRepository
    Application Path: C:\inetpub\wwwroot\NugetServerInternal\
    Machine name: NUGET-SRV

Process information:
    Process ID: 2512
    Process name: w3wp.exe
    Account name: some.domain/some.user

Exception information:
    Exception type: IndexOutOfRangeException
    Exception message: Index was outside the bounds of the array.
   at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Request information:
    Request URL: http://nuget-srv/MainRepository/nuget/
    Request path: /MainRepository/nuget/
    User host address: 192.168.1.30
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: some.domain/some.user

Thread information:
    Thread ID: 19
    Thread account name: some.domain/some.user
    Is impersonating: False
    Stack trace:    at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
</code>```

NOTE: per my checking sometime the package is created in the packages folder and sometime is not.
NOTE: I am pretty sure that all configuration is in place (including API key etc..). Of course, will be glad to know what is missing though.

Will appreciate any advice on this one.

Many thanks in advance,
Ofer

答:
Poor answer though, but still one that might help any potential issues you guys encounter :-).

I've realized that my "problematic" push requests had worked against newly created NuGet server. The new one was Windows Server 2012 R2 too. I've just raised it clean and added ONLY the necessary windows features to support the IIS/web operations against the Nuget server.

If I am not mistaken it was only ASP.NET 4.5.

Best regards,
Ofer

Title: NuGet Push Failure in TFS build

Body:
Preface: I am running NuGet Server (2.11.3) on Windows 2012 R2 / IIS 8.5. The NuGet Server manages its packages folder in separated file server (shared folder).
Additionally I am running TFS build machine (agent from TFS 2015) that uses this nuget server for both restore and push activities. Naturally,  each build, initially, reads the target solution >>> projects >>> packages.config files and restores the configured packages from the nuget server. On late step, the agent generates the required *.nupkg files and pushes them to the nuget endpoint of the same nuget server. Those are dependencies of other solutions.

Problem: the majority of the solutions running properly without any special issues. There are couple of solutions that only 1-3 projects within them, fail the TFS build with the following message:

Response status code does not indicate success: 500 (Internal Server Error).
Unexpected exit code 1 returned from tool NuGet.exe

The IIS logs on nuget server looks like the following:

2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 15
2017-03-27 16:47:26 192.168.2.116 PUT /MainRepository/nuget/ - 80 - 192.168.1.30 NuGet+Command+Line/3.5.0+(Microsoft+Windows+NT+6.2.9200.0) - 500 0 0 31

The following event is logged (shown in the event viewer) in the nuget server:

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 27/03/2017 10:40:17
Event time (UTC): 27/03/2017 07:40:17
Event ID: cb897ce6dc2f4e40a07c71a9160718f2
Event sequence: 2073
Event occurrence: 4
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/1/ROOT/MainRepository-1-131350724531418170
    Trust level: Full
    Application Virtual Path: /MainRepository
    Application Path: C:\inetpub\wwwroot\NugetServerInternal\
    Machine name: NUGET-SRV

Process information:
    Process ID: 2512
    Process name: w3wp.exe
    Account name: some.domain/some.user

Exception information:
    Exception type: IndexOutOfRangeException
    Exception message: Index was outside the bounds of the array.
   at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Request information:
    Request URL: http://nuget-srv/MainRepository/nuget/
    Request path: /MainRepository/nuget/
    User host address: 192.168.1.30
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: some.domain/some.user

Thread information:
    Thread ID: 19
    Thread account name: some.domain/some.user
    Is impersonating: False
    Stack trace:    at System.Web.HttpRawUploadedContent.get_Item(Int32 index)
   at System.Web.HttpMultipartContentTemplateParser.GetNextLine()
   at System.Web.HttpMultipartContentTemplateParser.ParseIntoElementList()
   at System.Web.HttpMultipartContentTemplateParser.Parse(HttpRawUploadedContent data, Int32 length, Byte[] boundary, Encoding encoding)
   at System.Web.HttpRequest.GetMultipartContent()
   at System.Web.HttpRequest.FillInFilesCollection()
   at System.Web.HttpRequest.EnsureFiles()
   at System.Web.HttpRequest.get_Files()
   at System.Web.HttpRequestWrapper.get_Files()
   at NuGet.Server.Publishing.PackageService.CreatePackage(HttpContextBase context)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

NOTE: per my checking sometime the package is created in the packages folder and sometime is not.
NOTE: I am pretty sure that all configuration is in place (including API key etc..). Of course, will be glad to know what is missing though.

Will appreciate any advice on this one.

Many thanks in advance,
Ofer


来源: stackexchange

问:
Displaying Kendo UI line chart on Kendo UI tooltip
I want to show a line chart on tooltip like below -
Line Chart on tooltip

For this I created chart and embedding it in tooltip using content property

```<code>content: function (e) {
          return $("#" + $(e.target).attr("id") + "_tooltip").html();
       }
</code>```

The issue is I want to display tooltip on a series, which is not happening right now. But if I plot same chart on body instead of embedding it on tooltip its working fine.

Is there anything extra I need to configure to handle such scenario?

dojo link

答:
You can make your chart tooltip a content template and then create the chart when the tooltip is shown.

DEMO

Code:

```<code><script id="template" type="text/x-kendo-template">
  <div id="myTooltip">
    <span>Some Text here</span>
    <div id="myChart"></div>
    <span>hover the connectors, not showing tootip</span>
  </div>
</script>

   function CreateTooltipChart(){
    // Satter line chart embedded in tooltip
      $("#myChart").kendoChart({
        chartArea: {
          height: 200,
          width: 310
        },
        title: {
          text: "Charge current vs. charge time"
        },
        seriesDefaults: {
          type: "scatterLine"
        },
        series: [{
          data: [[10, 10], [15, 20], [20, 25], [32, 40]]
        }],
        xAxis: {
          max: 35,
          labels: {
            format: "{0}m"
          },
        },
        yAxis: {
          max: 50,
          labels: false
        },
        //tooltip for chart is set here
        tooltip: {
          visible: true,
          format: "{1}% in {0} minutes"
        }
      });
    }

    // Tooltip on span element
    var tooltip = $('.show-tooltip').kendoTooltip({
      autoHide: false,
      position: "right",
      width: 312,
      //height: 300,
      show: function(e){
        CreateTooltipChart();
      },
      content: kendo.template($("#template").html()),
    }).data("kendoTooltip");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to show a line chart on tooltip like below -
Line Chart on tooltip

For this I created chart and embedding it in tooltip using content property

content: function (e) {
          return $("#" + $(e.target).attr("id") + "_tooltip").html();
       }

The issue is I want to display tooltip on a series, which is not happening right now. But if I plot same chart on body instead of embedding it on tooltip its working fine.

Is there anything extra I need to configure to handle such scenario?

dojo link

Body:
You can make your chart tooltip a content template and then create the chart when the tooltip is shown.

DEMO

Code:

<script id="template" type="text/x-kendo-template">
  <div id="myTooltip">
    <span>Some Text here</span>
    <div id="myChart"></div>
    <span>hover the connectors, not showing tootip</span>
  </div>
</script>

   function CreateTooltipChart(){
    // Satter line chart embedded in tooltip
      $("#myChart").kendoChart({
        chartArea: {
          height: 200,
          width: 310
        },
        title: {
          text: "Charge current vs. charge time"
        },
        seriesDefaults: {
          type: "scatterLine"
        },
        series: [{
          data: [[10, 10], [15, 20], [20, 25], [32, 40]]
        }],
        xAxis: {
          max: 35,
          labels: {
            format: "{0}m"
          },
        },
        yAxis: {
          max: 50,
          labels: false
        },
        //tooltip for chart is set here
        tooltip: {
          visible: true,
          format: "{1}% in {0} minutes"
        }
      });
    }

    // Tooltip on span element
    var tooltip = $('.show-tooltip').kendoTooltip({
      autoHide: false,
      position: "right",
      width: 312,
      //height: 300,
      show: function(e){
        CreateTooltipChart();
      },
      content: kendo.template($("#template").html()),
    }).data("kendoTooltip");


问:
Invalid number of rows in section Swift 3
I have a dictionnary of array who contain class Card(), I have a button who call a function who move one array

```<code>    static var DeliveryStatusArray =
    [
        "claimable": [Card](),
        "onTime": [Card](),
        "future": [Card](),
        "claimDone": [Card](),
        "tooOld": [Card](),
    ]
</code>```

My fonction for move my Card is

```<code>    static func moveCard(card:Card) -> Void {
    var pos:Int = -1
    var index:Int = 0
    while(index < (DashboardManager.DeliveryStatusArray["claimable"]?.count)!)
    {
        if (DashboardManager.DeliveryStatusArray["claimable"]?[index].idCard == card.idCard)
        {
            pos = index
        }
        index += 1
    }
    if (pos > -1)
    {
        let card:Card = (DashboardManager.DeliveryStatusArray["claimable"]?[pos])!
        DashboardManager.DeliveryStatusArray["claimable"]?.remove(at: pos)
        DashboardManager.DeliveryStatusArray["claimDone"]?.append(card)
    }
}
</code>```

When It's done I post a notification to my view for calling this function

```<code>    func notificationFinish(notification:Notification) -> Void{
        let sectionClaimable:Int = (api.dictionary["delivery"]?.index(of: "claimable"))! // Is 1
        let sectionClaiDone: Int = (api.dictionary["delivery"]?.index(of: "claimDone"))! // Is 4
        tableView.reloadSections(IndexSet(integer: sectionClaimable), with: .top)
        tableView.reloadSections(IndexSet(integer: sectionClaimDone), with: .top)
        return
    }
</code>```

First loop I got 2 cards in * DeliveryStatusArray["claimDone]* and after calling moveCard() I have three card

I got the error

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 4.  The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

I can't get more items when I reload my data ?

答:
If I understand it correctly, your code is a lot more complicated than it needs to be…</p>

```<code>// Get the index of card in claimable with matching idCard
guard let index = deliveryStatusArray["claimable"]?.index(where: {$0.idCard == card.idCard }) else { return }

// Remove the card at that index
let card = deliveryStatusArray["claimable"]?.remove(at: index)

// Append the card
deliveryStatusArray["claimDone"]?.append(card)
</code>```

Body:
I have a dictionnary of array who contain class Card(), I have a button who call a function who move one array

    static var DeliveryStatusArray =
    [
        "claimable": [Card](),
        "onTime": [Card](),
        "future": [Card](),
        "claimDone": [Card](),
        "tooOld": [Card](),
    ]

My fonction for move my Card is

    static func moveCard(card:Card) -> Void {
    var pos:Int = -1
    var index:Int = 0
    while(index < (DashboardManager.DeliveryStatusArray["claimable"]?.count)!)
    {
        if (DashboardManager.DeliveryStatusArray["claimable"]?[index].idCard == card.idCard)
        {
            pos = index
        }
        index += 1
    }
    if (pos > -1)
    {
        let card:Card = (DashboardManager.DeliveryStatusArray["claimable"]?[pos])!
        DashboardManager.DeliveryStatusArray["claimable"]?.remove(at: pos)
        DashboardManager.DeliveryStatusArray["claimDone"]?.append(card)
    }
}

When It's done I post a notification to my view for calling this function

    func notificationFinish(notification:Notification) -> Void{
        let sectionClaimable:Int = (api.dictionary["delivery"]?.index(of: "claimable"))! // Is 1
        let sectionClaiDone: Int = (api.dictionary["delivery"]?.index(of: "claimDone"))! // Is 4
        tableView.reloadSections(IndexSet(integer: sectionClaimable), with: .top)
        tableView.reloadSections(IndexSet(integer: sectionClaimDone), with: .top)
        return
    }

First loop I got 2 cards in * DeliveryStatusArray["claimDone]* and after calling moveCard() I have three card

I got the error

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 4.  The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

I can't get more items when I reload my data ?

Body:
If I understand it correctly, your code is a lot more complicated than it needs to be…

// Get the index of card in claimable with matching idCard
guard let index = deliveryStatusArray["claimable"]?.index(where: {$0.idCard == card.idCard }) else { return }

// Remove the card at that index
let card = deliveryStatusArray["claimable"]?.remove(at: index)

// Append the card
deliveryStatusArray["claimDone"]?.append(card)


问:
How to display string with HHmm format
I have string value 17:00:25

how do i display in Military time like 1700 only?
im debugging it with like below

```<code>Dim time As String = String.Format("{0:hh:mm}", row("timereported"))
MessageBox.Show(time.ToString)
</code>```

and the actual code is

```<code>For Each row As DataRow In table.Rows
     rowInsert = DS.Tables(0).NewRow
     Dim time As String = String.Format("{0:hh:mm}", row("timereported"))
     rowInsert(0) = time
     DS.Tables(0).Rows.Add(rowInsert)
Next row
</code>```

but it display as 17:00:25

any other kinds of conversion or format suited to format?

答:
I personally wouldn't attempt to format a string value to get a datetime value, otherwise you're denying yourself access to .net's inherent datetime handling features.

A safer way to handle the datetime value would be the following...

If returning data from your database, return as a datetime, or datetimeoffset value.

If it is a user entry and you are handling a string (which is the only scenario I can think of that would warrant this), then validate and cast to a datetime value.

The value should be of datetime before you attempt to format it.

This would leave you with a clean way to handle this using the format code "t" where you place your parameter, and no issues with invalid values.

Importantly it also makes your code culture safe if your site is multilingual. For example en-GB would display "17:00" while en-US would display "5:00pm".

So for your code it would then simply be...

```<code>Dim time As String = String.Format("{0:t}", row("timereported"))
</code>```

This would give you the format "HH:mm" or for your example "17:00".

Title: How to display string with HHmm format

Body:
I have string value 17:00:25

how do i display in Military time like 1700 only?
im debugging it with like below

Dim time As String = String.Format("{0:hh:mm}", row("timereported"))
MessageBox.Show(time.ToString)

and the actual code is

For Each row As DataRow In table.Rows
     rowInsert = DS.Tables(0).NewRow
     Dim time As String = String.Format("{0:hh:mm}", row("timereported"))
     rowInsert(0) = time
     DS.Tables(0).Rows.Add(rowInsert)
Next row

but it display as 17:00:25

any other kinds of conversion or format suited to format?

Body:
I personally wouldn't attempt to format a string value to get a datetime value, otherwise you're denying yourself access to .net's inherent datetime handling features.

A safer way to handle the datetime value would be the following...

If returning data from your database, return as a datetime, or datetimeoffset value.

If it is a user entry and you are handling a string (which is the only scenario I can think of that would warrant this), then validate and cast to a datetime value.

The value should be of datetime before you attempt to format it.

This would leave you with a clean way to handle this using the format code "t" where you place your parameter, and no issues with invalid values.

Importantly it also makes your code culture safe if your site is multilingual. For example en-GB would display "17:00" while en-US would display "5:00pm".

So for your code it would then simply be...

Dim time As String = String.Format("{0:t}", row("timereported"))

This would give you the format "HH:mm" or for your example "17:00".


问:
RMarkdown Beamer TOC empty
Using beamer in RMarkdown for presentations, I can't figure out why the TOC is empty. I have tried using a MacBook and Windows.

```<code>---
title: "test"
author: "my name"
date: "12/6/2016"
output:
  beamer_presentation:
    keep_tex: true
    toc: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Slide 1
Slide content

# Slide 2
Slide content
</code>```

Outputs the pdf presentation with a title slide, an empty page (where the TOC should be), and then the two slides.

On Windows platform:

```<code>> R.version

platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          3.1
year           2016
month          06
day            21
svn rev        70800
language       R
version.string R version 3.3.1 (2016-06-21)
nickname       Bug in Your Hair
</code>```

RStudio:0.99.896

Rmarkdown: 1.2

knitr: 1.15.1

Somewhat related question here: Table of content in beamer generated with R markdown/knitr

Using the keep_tex: true argument in the YAML, I see from the tex file that the level 1 headers (i.e. # Section) are not being properly converted to sections in the tex file. For example, from the tex file:

```<code>\begin{frame}{Slide 1}

Slide content

\end{frame}
</code>```

It seems that RMarkdown is not making the tex file correctly.

答:
As pointed out here, the TOC will list the sections (as defined by single #'s), and the slide level must be a level below the sections (defined below in the YAML as slide_level: 2 and in the presentation by ##'s). I don't completely understand why you can't have sections at the slide level, but at least this works.</p>

```<code>---
title: "test"
author: "my name"
date: "12/6/2016"
output:
  beamer_presentation:
    keep_tex: true
    toc: true
    slide_level:2
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Section 1

## Slide 1
Slide content

# Section 2

# Slide 2
Slide content
</code>```

Title: RMarkdown Beamer TOC empty

Body:
Using beamer in RMarkdown for presentations, I can't figure out why the TOC is empty. I have tried using a MacBook and Windows.

---
title: "test"
author: "my name"
date: "12/6/2016"
output:
  beamer_presentation:
    keep_tex: true
    toc: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Slide 1
Slide content

# Slide 2
Slide content

Outputs the pdf presentation with a title slide, an empty page (where the TOC should be), and then the two slides.

On Windows platform:

> R.version

platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          3.1
year           2016
month          06
day            21
svn rev        70800
language       R
version.string R version 3.3.1 (2016-06-21)
nickname       Bug in Your Hair

RStudio:0.99.896

Rmarkdown: 1.2

knitr: 1.15.1

Somewhat related question here: Table of content in beamer generated with R markdown/knitr

Using the keep_tex: true argument in the YAML, I see from the tex file that the level 1 headers (i.e. # Section) are not being properly converted to sections in the tex file. For example, from the tex file:

\begin{frame}{Slide 1}

Slide content

\end{frame}

It seems that RMarkdown is not making the tex file correctly.

Body:
As pointed out here, the TOC will list the sections (as defined by single #'s), and the slide level must be a level below the sections (defined below in the YAML as slide_level: 2 and in the presentation by ##'s). I don't completely understand why you can't have sections at the slide level, but at least this works.

---
title: "test"
author: "my name"
date: "12/6/2016"
output:
  beamer_presentation:
    keep_tex: true
    toc: true
    slide_level:2
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# Section 1

## Slide 1
Slide content

# Section 2

# Slide 2
Slide content


问:
Does DataReader.Close() method close the connection object when using Microsoft Application Blocks for Data Access?
I am reviewing an application that uses Microsoft Application Blocks for Data Access to interact with the database. The application calls a function and pass a query into it. The function creates a DataReader object using Data Access application blocks (for the given query) and returns the DataReader to the caller.

The application closes DataReader object when it is done. The question I have is, whether closing the DataReader object automatically closes the underlying connection object or not. It is not clear to me whether the Data Access Application Block opens the command object with the "CommandBehavior.CloseConnection" flag.

Questions:

When the Close() method is called on a DataReader object, does it also close the underlying connection object (the DataReader is created using Microsoft Application Blocks - Database.ExecuteReader() method

If not, what is the recommended method to ensure that the connection is freed after we are done with the data reader?

Thanks in advance

答:
Miguel Angel Utiel's answer is right, if you use "CommandBehavior.CloseConnection", the connection will close after reader closed. just like this:

```<code> OracleDataReader odr = oc.ExecuteReader(CommandBehavior.CloseConnection);
 odr.Close();
 if (oc.Connection.State == System.Data.ConnectionState.Closed) {
    System.Diagnostics.Debug.WriteLine("connection is closed");
 }
</code>```

if your ExecuteReader() with no parameter,just like

```<code>OracleDataReader odr = oc.ExecuteReader();
odr.Close();
if (oc.Connection.State != System.Data.ConnectionState.Closed) {
    System.Diagnostics.Debug.WriteLine("connection is openning");
}
</code>```

read:http://msdn.microsoft.com/en-us/library/system.data.commandbehavior.aspx

Body:
Miguel Angel Utiel's answer is right, if you use "CommandBehavior.CloseConnection", the connection will close after reader closed. just like this:

 OracleDataReader odr = oc.ExecuteReader(CommandBehavior.CloseConnection);
 odr.Close();
 if (oc.Connection.State == System.Data.ConnectionState.Closed) {
    System.Diagnostics.Debug.WriteLine("connection is closed");
 }

if your ExecuteReader() with no parameter,just like

OracleDataReader odr = oc.ExecuteReader();
odr.Close();
if (oc.Connection.State != System.Data.ConnectionState.Closed) {
    System.Diagnostics.Debug.WriteLine("connection is openning");
}

read:http://msdn.microsoft.com/en-us/library/system.data.commandbehavior.aspx


问:
Jasper breaking lines even with sufficient space to render just one line
I'm developing a Jasper report that has to be exported as a PDF from my web app.
The jasperreport.version is 5.5.1 and the web app is running on a Tomcat6 instance.

I've defined the following elements in my .jrxml:

```<code><rectangle>
    <reportElement positionType="Float" stretchType="RelativeToTallestObject" mode="Transparent" x="415" y="21" width="140" height="28" uuid="52ceec4a-26bb-4efa-a4d2-af32c107d1d3"/>
    <graphicElement>
        <pen lineWidth="0.5"/>
    </graphicElement>
</rectangle>
<textField isStretchWithOverflow="true">
    <reportElement style="label" positionType="Float" x="415" y="20" width="140" height="14" uuid="f1394c5b-4921-4ccd-84ed-b1d3e44dc499"/>
    <textElement markup="none">
        <font size="9" isBold="true" isItalic="false"/>
    </textElement>
    <textFieldExpression><![CDATA[$R{nivel.gestao}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
    <reportElement style="campo" positionType="Float" stretchType="RelativeToTallestObject" x="415" y="34" width="140" height="15" uuid="3e1d2402-8b21-4f8e-9ee8-d57f1a870077"/>
    <box bottomPadding="2"/>
    <textElement verticalAlignment="Middle" markup="none">
        <font size="9" isBold="false"/>
    </textElement>
    <textFieldExpression><![CDATA[$P{nivelGestao}]]></textFieldExpression>
</textField>
</code>```

The problem is that Jasper renders the text with line breaks depending on which font family I use.

Using Helvetica:

Using Courier (the font I need):

How can I use the Courier font family and avoid the unintended line breaks?

答:
Text with Courier font is wider. I suppose if you write some long text with Helvetica you see same stuff. Check out padding and margins.

And remove <box bottomPadding="2"/>.

Body:
I'm developing a Jasper report that has to be exported as a PDF from my web app.
The jasperreport.version is 5.5.1 and the web app is running on a Tomcat6 instance.

I've defined the following elements in my .jrxml:

<rectangle>
    <reportElement positionType="Float" stretchType="RelativeToTallestObject" mode="Transparent" x="415" y="21" width="140" height="28" uuid="52ceec4a-26bb-4efa-a4d2-af32c107d1d3"/>
    <graphicElement>
        <pen lineWidth="0.5"/>
    </graphicElement>
</rectangle>
<textField isStretchWithOverflow="true">
    <reportElement style="label" positionType="Float" x="415" y="20" width="140" height="14" uuid="f1394c5b-4921-4ccd-84ed-b1d3e44dc499"/>
    <textElement markup="none">

    </textElement>
    <textFieldExpression><![CDATA[$R{nivel.gestao}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
    <reportElement style="campo" positionType="Float" stretchType="RelativeToTallestObject" x="415" y="34" width="140" height="15" uuid="3e1d2402-8b21-4f8e-9ee8-d57f1a870077"/>
    <box bottomPadding="2"/>
    <textElement verticalAlignment="Middle" markup="none">

    </textElement>
    <textFieldExpression><![CDATA[$P{nivelGestao}]]></textFieldExpression>
</textField>

The problem is that Jasper renders the text with line breaks depending on which font family I use.

Using Helvetica:

Using Courier (the font I need):

How can I use the Courier font family and avoid the unintended line breaks?


问:
How to hard code credentials in a PHP process to avoid the user from getting prompts for username/password when they are forwarded
Hello – I am looking to create a PHP process that will forward users to a page that requires authentication but I would like to hard code service account credentials in my PHP process to avoid the user from getting prompts for username/password when they are forwarded.
The pseudo code I have looks like this:

```<code><?php

// User Login LDAP

$ldap = ldap_connect("example");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['Password'])) {
  echo "success";
} else {
  echo "not a success";
}

?>
</code>```

I don’t expect any HTML as a user will hit the PHP file and should get auto forwarded to the page that requires credentials (in this case the page I am forwarding them to is an enterprise SharePoint site that requires Active Directory authentication).

Thank you in advance for any info/help!

答:
You should be able to post credentials to SharePoint's page using curl:

```<code>$params=['name'=>'John', 'surname'=>'Doe', 'age'=>36)
$defaults = array(
CURLOPT_URL => 'http://myremoteservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
</code>```

http://php.net/manual/en/curl.examples-basic.php

Maybe you'll need to encrypt the password before sending it to SharePoint.

Body:
Hello – I am looking to create a PHP process that will forward users to a page that requires authentication but I would like to hard code service account credentials in my PHP process to avoid the user from getting prompts for username/password when they are forwarded.
The pseudo code I have looks like this:

<?php

// User Login LDAP

$ldap = ldap_connect("example");
if ($bind = ldap_bind($ldap, $_POST['username'], $_POST['Password'])) {
  echo "success";
} else {
  echo "not a success";
}

?>

I don’t expect any HTML as a user will hit the PHP file and should get auto forwarded to the page that requires credentials (in this case the page I am forwarding them to is an enterprise SharePoint site that requires Active Directory authentication).

Thank you in advance for any info/help!

Body:
You should be able to post credentials to SharePoint's page using curl:

$params=['name'=>'John', 'surname'=>'Doe', 'age'=>36)
$defaults = array(
CURLOPT_URL => 'http://myremoteservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));

http://php.net/manual/en/curl.examples-basic.php

Maybe you'll need to encrypt the password before sending it to SharePoint.


问:
Conditional dateadd in procedure
I have a procedure that receives 3 parameters:

```<code>@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5
</code>```

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

```<code>select dateadd(@interval, @duration, @startdate)
</code>```

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

答:
One method is to use dynamic SQL.  Another is a giant case statement.  Something like:

```<code>declare @endDate date;
declare @sql nvarchar(max);

set @sql = 'select @endDate = dateadd(@interval, @duration, @startdate)';
set @sql = replace(@sql, '@interval', @interval);

exec sp_executesql @sql, N'@duration int, @startdate date, @endDate date output',
                   @duration = @duration, @startdate = @startdate,
                   @endDate = @endDate output;
</code>```

The problem is that the first argument is a keyword, not a string.  So, it cannot be passed in as a parameter.

Title: Conditional dateadd in procedure

Body:
I have a procedure that receives 3 parameters:

@startdate  = '2017-01-01'
@interval   = 'DD'
@duration   = 5

What I need to do is output a new date, based on the above. A dateadd does not work, courtesy of that @interval not being correct.

select dateadd(@interval, @duration, @startdate)

Invalid parameter 1 specified for dateadd.

Can anyone steer me right?

Body:
One method is to use dynamic SQL.  Another is a giant case statement.  Something like:

declare @endDate date;
declare @sql nvarchar(max);

set @sql = 'select @endDate = dateadd(@interval, @duration, @startdate)';
set @sql = replace(@sql, '@interval', @interval);

exec sp_executesql @sql, N'@duration int, @startdate date, @endDate date output',
                   @duration = @duration, @startdate = @startdate,
                   @endDate = @endDate output;

The problem is that the first argument is a keyword, not a string.  So, it cannot be passed in as a parameter.


问:
Concatenate Spark Dataframe N times
I have a dataframe with N lines in it and it has only one column. I want to copy it N times and concatenate. So at the end I want to create another dataframe with N^2 lines.

How can I achieve that simply using Scala? I do not want to use for loops etc. because N is large.

答:
You can do this using a fold function:

```<code>(0 until df.count.toInt).foldLeft(df){case (acc,_) => acc.unionAll(df)}.show
</code>```

The only constraint is that N must be less than Int.Max_Value. Hope this helps :)

You can test with a small df:

```<code>val df = sc.parallelize(List(("r1"),("r2"),("r3"))).toDF("c")
</code>```

Title: Concatenate Spark Dataframe N times

Body:
You can do this using a fold function:

(0 until df.count.toInt).foldLeft(df){case (acc,_) => acc.unionAll(df)}.show

The only constraint is that N must be less than Int.Max_Value. Hope this helps :)

You can test with a small df:

val df = sc.parallelize(List(("r1"),("r2"),("r3"))).toDF("c")


问:
Use function to create plot objects, then place them into figure
So I've been working with an example like that shown in the Usage Page. The code for it is:

```<code>import numpy as np
import matplotlib.pyplot as plt

n1 = 5
n2 = 30

x1 = np.linspace(0,10,n1)
y1 = np.random.rand(n1)
x2 = np.linspace(0,10,n2)
y2 = np.random.rand(n2)

#Matplotlib example copy paste
def my_plotter(ax, data1, data2, param_dict):
    out = ax.plot(data1, data2, **param_dict)
    return out

fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, x1, y1, {'marker':'x'})
my_plotter(ax2, x2, y2, {'marker':'o'})

plt.show()
</code>```

Note that the docstring from the example has been deleted for space savings.

Issue is that if I get rid of the param_dict argument,

```<code>my_plotter(ax1, x1, y1)
my_plotter(ax2, x2, y2)
</code>```

, not only does it not work (nothing is displayed upon running the script and running plt.show() in the console after the script has run brings up blank subplots), but not a single error is raised. If I run only the first instance of my_plotter, the figure will display, the first subplot will plot x1 and y1, and the second will be blank; exactly what I would be expecting. Snooping around, I found a similar format of code:

```<code>def axtest(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    ret = ax.plot(x, y)
    return(ret)

fig, (ax1, ax2) = plt.subplots(1,2)
print('blah')
axtest(x1, y1, ax1)
axtext(x2, y2, ax2)

plt.show()
</code>```

This code shows the same exact behavior as the functions above; one instance of axtest will plot a non-blank and blank subplot and two instances of axtest will do nothing, no errors to speak of.

What am I missing? Do I have to pass parameters to the axes to get this to work? Because that makes no sense to me.

My end goal in this is to take some code I have that does this:

```<code>def orig_func(x, y, z):
   X, Y, Z = interpolate_to_grid(x, y, z)
   fig = plt.figure()
   plt.imshow(Z)
   plt.contour(X, Y, Z)
   plt.scatter(X, Y, c=Z)
   #do formating of the data
   plt.show()
</code>```

and make it do this:

```<code>def new_func(x, y, z):
   X, Y, Z = interpolate_to_grid(x, y, z)
   fig = plt.figure()
   plt.imshow(Z)
   plt.contour(X, Y, Z)
   plt.scatter(X, Y, c=Z)
   #do formating of the data
   return(the plot info)

plot_info1 = new_func(x1, y1, z1)
plot_info2 = new_func(x2, y2, z2)

fig, (ax1, ax2) = plt.subplots(1,2)

ax1 = plot_info1
ax2 = plot_info2

plt.show()
</code>```

I thought this wouldn't be that difficult, but hey, shows you what I know. Any help would be quite nice.

答:
Are you sure that you didn't have a small mistake in your first attempt.  The following works fine for me.

```<code>import numpy as np
import matplotlib.pyplot as plt

n1 = 5
n2 = 30

x1 = np.linspace(0,10,n1)
y1 = np.random.rand(n1)
x2 = np.linspace(0,10,n2)
y2 = np.random.rand(n2)

#Matplotlib example copy paste
def my_plotter(ax, data1, data2):
    out = ax.plot(data1, data2)
    return out

fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, x1, y1)
my_plotter(ax2, x2, y2)

plt.show()
</code>```

So the question left is what is wrong with your second example.  In the example listed above, we have a function which is given an axis object (ax) as well as the data.  It returns that very same axis object which now has plotting on it.

You had a figure being created within the function, but that is not needed since we already have the figure created here

```<code>fig, (ax1, ax2) = plt.subplots(1, 2)
</code>```

and then we markup that first ax1 with

```<code>my_plotter(ax1, x1, y1)
</code>```

and then markup that second ax2 with

```<code>my_plotter(ax2, x2, y2)
</code>```

And finally make sure that your function is altering the axis object.  Before, you had ax.plot().  You changed to plt.scatter.  Try ax.scatter() instead.

Body:
So I've been working with an example like that shown in the Usage Page. The code for it is:

import numpy as np
import matplotlib.pyplot as plt

n1 = 5
n2 = 30

x1 = np.linspace(0,10,n1)
y1 = np.random.rand(n1)
x2 = np.linspace(0,10,n2)
y2 = np.random.rand(n2)

#Matplotlib example copy paste
def my_plotter(ax, data1, data2, param_dict):
    out = ax.plot(data1, data2, **param_dict)
    return out

fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, x1, y1, {'marker':'x'})
my_plotter(ax2, x2, y2, {'marker':'o'})

plt.show()

Note that the docstring from the example has been deleted for space savings.

Issue is that if I get rid of the param_dict argument,

my_plotter(ax1, x1, y1)
my_plotter(ax2, x2, y2)

, not only does it not work (nothing is displayed upon running the script and running plt.show() in the console after the script has run brings up blank subplots), but not a single error is raised. If I run only the first instance of my_plotter, the figure will display, the first subplot will plot x1 and y1, and the second will be blank; exactly what I would be expecting. Snooping around, I found a similar format of code:

def axtest(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    ret = ax.plot(x, y)
    return(ret)

fig, (ax1, ax2) = plt.subplots(1,2)
print('blah')
axtest(x1, y1, ax1)
axtext(x2, y2, ax2)

plt.show()

This code shows the same exact behavior as the functions above; one instance of axtest will plot a non-blank and blank subplot and two instances of axtest will do nothing, no errors to speak of.

What am I missing? Do I have to pass parameters to the axes to get this to work? Because that makes no sense to me.

My end goal in this is to take some code I have that does this:

def orig_func(x, y, z):
   X, Y, Z = interpolate_to_grid(x, y, z)
   fig = plt.figure()
   plt.imshow(Z)
   plt.contour(X, Y, Z)
   plt.scatter(X, Y, c=Z)
   #do formating of the data
   plt.show()

and make it do this:

def new_func(x, y, z):
   X, Y, Z = interpolate_to_grid(x, y, z)
   fig = plt.figure()
   plt.imshow(Z)
   plt.contour(X, Y, Z)
   plt.scatter(X, Y, c=Z)
   #do formating of the data
   return(the plot info)

plot_info1 = new_func(x1, y1, z1)
plot_info2 = new_func(x2, y2, z2)

fig, (ax1, ax2) = plt.subplots(1,2)

ax1 = plot_info1
ax2 = plot_info2

plt.show()

I thought this wouldn't be that difficult, but hey, shows you what I know. Any help would be quite nice.

Body:
Are you sure that you didn't have a small mistake in your first attempt.  The following works fine for me.

import numpy as np
import matplotlib.pyplot as plt

n1 = 5
n2 = 30

x1 = np.linspace(0,10,n1)
y1 = np.random.rand(n1)
x2 = np.linspace(0,10,n2)
y2 = np.random.rand(n2)

#Matplotlib example copy paste
def my_plotter(ax, data1, data2):
    out = ax.plot(data1, data2)
    return out

fig, (ax1, ax2) = plt.subplots(1, 2)
my_plotter(ax1, x1, y1)
my_plotter(ax2, x2, y2)

plt.show()

So the question left is what is wrong with your second example.  In the example listed above, we have a function which is given an axis object (ax) as well as the data.  It returns that very same axis object which now has plotting on it.

You had a figure being created within the function, but that is not needed since we already have the figure created here

fig, (ax1, ax2) = plt.subplots(1, 2)

and then we markup that first ax1 with

my_plotter(ax1, x1, y1)

and then markup that second ax2 with

my_plotter(ax2, x2, y2)

And finally make sure that your function is altering the axis object.  Before, you had ax.plot().  You changed to plt.scatter.  Try ax.scatter() instead.


问:
Python: 'list' object has no attribute 'read'
I have a list with a single string that contains non-ascii characters. My goal is to get rid of the non-ascii characters and convert the list to a string.

Every time I try to strip out the non-ascii characters, I get this error: 'list' object has no attribute 'read'

I've tried most of these and I still get this error every time. I'm not sure what I am doing wrong, any help would be appreciated.

答:
Py3:

```<code>thelist[0].encode('ascii','ignore').decode()
</code>```

this works for python 2.x:

```<code>import string
filter(lambda c:c in string.printable, thelist[0])
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Py3:

thelist[0].encode('ascii','ignore').decode()

this works for python 2.x:

import string
filter(lambda c:c in string.printable, thelist[0])


问:
MySQL Different results from same query/data
I have two servers running MySQL. Both are on windows. One, is my local machime (Windows 7, MySQL 5.6.25, 32bit) and the other is my production webserver (Windows 2012, MySQL 5.7.11-log, 64bit (that's what show variables showed me).

The data is identical between the two. I backed the data up from the windows 7 (using MySQL Workbench) and restored it on the 2012 machine.

I am running a query on both machine but I am getting different results. I have two tables, projects and projectsnotes with a 1:m relationship between them related on projects.id to projectsnotes.idProject. Each note is marked with a date (dComment). The goal of the query is to retrieve project information and the latest comment only.

Here's the query:

```<code>select space(1) as cAction,
    p.id,
    p.iNum,
    p.cStatus,
    p.cName,
    p.cDesc,
    ifnull(pl.cNickName, 'UNASSIGNED') as cProjectLeader,
    IFNULL(concat (
            date_format(pn.dComment, '%Y-%m-%d'),
            ': ',
            pn.cComment
            ), '') as cComment,
    date_format(p.dRequested, '%Y-%m-%d') as dRequested,
    date_format(p.dRequired, '%Y-%m-%d') as dRequired,
    format(p.nPercentComplete, 2) as nPercentComplete,
    p.tLastUpdated,
    p.bCompleted,
    p.idProjectLeader
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (
    select idProject,
        dComment,
        cComment
    from projectnotes
    order by dComment desc,
        tLastUpdated desc
    ) pn on p.id = pn.idProject
where p.cInstallCode = 'ITM'
    and cStatus in ('Pending', 'Active', 'On Hold', 'Completed', 'Cancelled')
    and bCompleted = 0
group by iNum
order by iNum;
</code>```

Now, here's the weird part. When I run this on my Windows 7 machine, I get the right value for cComment. Specifically:

2017-03-28: Text from note replace

That is the latest note. When I run it on the 2012 server:

2016-05-17: Text from this note replaced too

If I run the subquery alone on the 2012 server, I get the right values (namely, a list of all the notes in the reverse order.

Oh, and this note is neither the first nor the last in the notes for this project.

So I am honestly wondering what is going on. Any thoughts on this would be greatly appreciated.

Thanks in advance.

答:
This is expected behavior.

```<code>select ...
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (...) pn on p.id = pn.idProject
where ...
group by iNum
order by iNum;
</code>```

Due to MySQL's peculiar handling of GROUP BY, it will not report an error on this query. However, you must keep in mind that, since you use no aggregates, and the GROUP BY will eliminate lots of rows, the rows that are kept in the final result set are determined by rather obscure criteria...

For example:

```<code>SELECT a,b FROM t GROUP BY a
</code>```

Which b will be returned? In some MySQL versions, this will be the first value of b that is found in table t. If table t is ordered in a certain way, this can be exploited. But I would definitely not trust that behavior to stay unchanged between versions... Also, remember MySQL is free to change your join order...

Body:
I have two servers running MySQL. Both are on windows. One, is my local machime (Windows 7, MySQL 5.6.25, 32bit) and the other is my production webserver (Windows 2012, MySQL 5.7.11-log, 64bit (that's what show variables showed me).

The data is identical between the two. I backed the data up from the windows 7 (using MySQL Workbench) and restored it on the 2012 machine.

I am running a query on both machine but I am getting different results. I have two tables, projects and projectsnotes with a 1:m relationship between them related on projects.id to projectsnotes.idProject. Each note is marked with a date (dComment). The goal of the query is to retrieve project information and the latest comment only.

Here's the query:

select space(1) as cAction,
    p.id,
    p.iNum,
    p.cStatus,
    p.cName,
    p.cDesc,
    ifnull(pl.cNickName, 'UNASSIGNED') as cProjectLeader,
    IFNULL(concat (
            date_format(pn.dComment, '%Y-%m-%d'),
            ': ',
            pn.cComment
            ), '') as cComment,
    date_format(p.dRequested, '%Y-%m-%d') as dRequested,
    date_format(p.dRequired, '%Y-%m-%d') as dRequired,
    format(p.nPercentComplete, 2) as nPercentComplete,
    p.tLastUpdated,
    p.bCompleted,
    p.idProjectLeader
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (
    select idProject,
        dComment,
        cComment
    from projectnotes
    order by dComment desc,
        tLastUpdated desc
    ) pn on p.id = pn.idProject
where p.cInstallCode = 'ITM'
    and cStatus in ('Pending', 'Active', 'On Hold', 'Completed', 'Cancelled')
    and bCompleted = 0
group by iNum
order by iNum;

Now, here's the weird part. When I run this on my Windows 7 machine, I get the right value for cComment. Specifically:

2017-03-28: Text from note replace

That is the latest note. When I run it on the 2012 server:

2016-05-17: Text from this note replaced too

If I run the subquery alone on the 2012 server, I get the right values (namely, a list of all the notes in the reverse order.

Oh, and this note is neither the first nor the last in the notes for this project.

So I am honestly wondering what is going on. Any thoughts on this would be greatly appreciated.

Thanks in advance.

Body:
This is expected behavior.

select ...
from projects p
left outer join projectleaders pl on p.idProjectLeader = pl.id
left outer join (...) pn on p.id = pn.idProject
where ...
group by iNum
order by iNum;

Due to MySQL's peculiar handling of GROUP BY, it will not report an error on this query. However, you must keep in mind that, since you use no aggregates, and the GROUP BY will eliminate lots of rows, the rows that are kept in the final result set are determined by rather obscure criteria...

For example:

SELECT a,b FROM t GROUP BY a

Which b will be returned? In some MySQL versions, this will be the first value of b that is found in table t. If table t is ordered in a certain way, this can be exploited. But I would definitely not trust that behavior to stay unchanged between versions... Also, remember MySQL is free to change your join order...


问:
Evaluation of list-comprehensions in Haskell
I am wondering exactly how list-comprehensions are evaluated in Haskell. After reading this Removing syntactic sugar: List comprehension in Haskell and this: Haskell Lazy Evaluation and Reuse I still don't really understand if

```<code>[<function> x|x <- <someList>, <somePredicate>]
</code>```

is actually exactly equivalent (not just in outcome but in evaluation) to

```<code>filter (<somePredicate>) . map (<function>) $ <someList>
</code>```

and if so, does this mean it can potentially reduce time complexity drastically to build up the desired list with only desired elements?
Also, how does this work in terms of infinite lists? To be specific: I assume something like:

```<code>[x|x <- [1..], x < 20]
</code>```

will be evaluated in finite time, but how "obvious" does the fact that there are no more elements above some value which satisfy the predicate need to be, for the compiler to consider it? Would

```<code>[x|x <- [1..], (sum.map factorial $ digits x) == x]
</code>```

work (see project Euler problem 34 https://projecteuler.net/problem=34). There is obviously an upper bound because from some x on x*9! < 10^n -1 always holds, but do I need to supply that bound or will the compiler find it?

答:
There's nothing obvious about the fact that a particular infinite sequence has no more elements matching a predicate. When you pass a list to filter, it has no way of knowing any other properties of the elements than that an element can be passed to the predicate.

You can write your own version of Ord a => List a which can describe a sequence as ascending or not, and a version of filter that can use this information to stop looking at elements past a particular threshold. Unfortunately, list comprehensions won't use either of them.

Instead, I'd use a combination of takeWhile and a comprehension without a predicate / a plain map. Somewhere in the takeWhile arguments, you will supply the compiler the information about the expected upper bound; for a number of n decimal digits, it would be 10^n.

Body:
I am wondering exactly how list-comprehensions are evaluated in Haskell. After reading this Removing syntactic sugar: List comprehension in Haskell and this: Haskell Lazy Evaluation and Reuse I still don't really understand if

[<function> x|x <- <someList>, <somePredicate>]

is actually exactly equivalent (not just in outcome but in evaluation) to

filter (<somePredicate>) . map (<function>) $ <someList>

and if so, does this mean it can potentially reduce time complexity drastically to build up the desired list with only desired elements?
Also, how does this work in terms of infinite lists? To be specific: I assume something like:

[x|x <- [1..], x < 20]

will be evaluated in finite time, but how "obvious" does the fact that there are no more elements above some value which satisfy the predicate need to be, for the compiler to consider it? Would

[x|x <- [1..], (sum.map factorial $ digits x) == x]

work (see project Euler problem 34 https://projecteuler.net/problem=34). There is obviously an upper bound because from some x on x*9! < 10^n -1 always holds, but do I need to supply that bound or will the compiler find it?


问:
How do I obtain "model name" for a networked device (potentially using Bonjour)?
Apple's Finder.app is able to consistently determine the exact model of each physical computer that uses bonjour (as evidenced by the icons being unique for each individual device type: iMac, MacPro, MBP, etc). How do they do this and what APIs do they use?

On a side note, Bonjour provides Name, Service Type, Domain and Port for all services on the network - but I haven't been able to find information on how to find the device model itself.

答:
I believe this uses the _device-info._tcp. mDNS record for the IP address. You can see this for yourself. In the terminal, you can use dig @224.0.0.251 -p5353 to perform mDNS requests. You can use dig @224.0.0.251 -p5353 Foo.local. to resolve the IP address of the computer Foo.local. Take that IP and plug it back into dig @224.0.0.251 -p5353 -x $IP and you should see something like the following:

```<code>> dig @224.0.0.251 -p5353 -x 10.0.1.1
; <<>> DiG 9.6.0-APPLE-P2 <<>> @224.0.0.251 -p5353 -x 10.0.1.1
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22887
;; flags: qr aa; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; QUESTION SECTION:
;1.0.0.10.in-addr.arpa.     IN  PTR

;; ANSWER SECTION:
1.0.0.10.in-addr.arpa.  10  IN  PTR Foo.local.

;; ADDITIONAL SECTION:
Foo._device-info._tcp.local. 10 IN TXT  "model=MacBookPro5,3"

;; Query time: 4 msec
;; SERVER: 10.0.0.1#5353(224.0.0.251)
;; WHEN: Mon Nov 29 18:00:23 2010
;; MSG SIZE  rcvd: 131
</code>```

Notice the ADDITIONAL SECTION.

Unfortunately, I don't know how to get at this information using the Bonjour APIs.

Edit: You can also get this info in a single query with dig @224.0.0.251 -p5353 Foo._device-info._tcp.local. TXT.

Body:
I believe this uses the _device-info._tcp. mDNS record for the IP address. You can see this for yourself. In the terminal, you can use dig @224.0.0.251 -p5353 to perform mDNS requests. You can use dig @224.0.0.251 -p5353 Foo.local. to resolve the IP address of the computer Foo.local. Take that IP and plug it back into dig @224.0.0.251 -p5353 -x $IP and you should see something like the following:

> dig @224.0.0.251 -p5353 -x 10.0.1.1
; <<>> DiG 9.6.0-APPLE-P2 <<>> @224.0.0.251 -p5353 -x 10.0.1.1
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22887
;; flags: qr aa; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; QUESTION SECTION:
;1.0.0.10.in-addr.arpa.     IN  PTR

;; ANSWER SECTION:
1.0.0.10.in-addr.arpa.  10  IN  PTR Foo.local.

;; ADDITIONAL SECTION:
Foo._device-info._tcp.local. 10 IN TXT  "model=MacBookPro5,3"

;; Query time: 4 msec
;; SERVER: 10.0.0.1#5353(224.0.0.251)
;; WHEN: Mon Nov 29 18:00:23 2010
;; MSG SIZE  rcvd: 131

Notice the ADDITIONAL SECTION.

Unfortunately, I don't know how to get at this information using the Bonjour APIs.

Edit: You can also get this info in a single query with dig @224.0.0.251 -p5353 Foo._device-info._tcp.local. TXT.


问:
PHP Upload File
I'm trying to upload file to server with php script. I'm Using MAMP with PHP7.0.8

I have HTML form:

```<code><form enctype="multipart/form-data" action="hi" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>
</code>```

And simple php:

```<code>  <?php

$uploaddir = 'img/';
print_r($uploadfile = $uploaddir.basename($_FILES['userfile']['name']));

  echo '```';
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
      echo "File is valid, and was successfully uploaded.\n";
  } else {
      echo "Possible file upload attack!\n";
  }

  echo 'info:';
  print_r($_FILES);
  echo "
";
  print_r($_FILES['userfile']['error']);
  print "```";

?>
</code>```

My result is:

Possible file upload attack!

```<code>info:Array
(
    [userfile] => Array
        (
            [name] => high-school-icon.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpoaPmYv
            [error] => 0
            [size] => 1807
        )

)
</code>```

答: Sorry, it was stupid mistake. Wrong way for $uploaddir = 'img/';

Title: PHP Upload File

Body:
I'm trying to upload file to server with php script. I'm Using MAMP with PHP7.0.8

I have HTML form:

<form enctype="multipart/form-data" action="hi" method="POST">
  <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    Send File: <input name="userfile" type="file" />
  <input type="submit" value="Send File" />
</form>

And simple php:

  <?php

$uploaddir = 'img/';
print_r($uploadfile = $uploaddir.basename($_FILES['userfile']['name']));

  echo '
';
  if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
      echo "File is valid, and was successfully uploaded.\n";
  } else {
      echo "Possible file upload attack!\n";
  }

  echo 'info:';
  print_r($_FILES);
  echo "
";
  print_r($_FILES['userfile']['error']);
  print "
";

?>

My result is:

Possible file upload attack!

info:Array
(
    [userfile] => Array
        (
            [name] => high-school-icon.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpoaPmYv
            [error] => 0
            [size] => 1807
        )

)


问:
c - dynamically allocate variable names
I am trying to take number of inputs from a user and take the inputs then and store them under dynamically created variable names. can anyone help?

I want to take the number of array user want to input then create the exact number of variables which maintains a common pattern so I can know which array is under which variable and I can call them for further processing.

My current code is as follows

```<code> int input, eqn, m, i,n,x;
    char inputarr[100], eqnarr[100];
    printf("Enter number of variables: ");
    scanf("%d",&n);
    m=n;
    printf("Enter your variables: \n");
    while(n!=-1){
    gets(inputarr[n]);
    n--;
    }
    while(m!=0){
    puts(inputarr[m]);
    printf("\n");
    m--;
    }
</code>```

my inputs are like

2 (here 2 is number of inputs user intended to give)

a = 3

b = 4

I need to save them  in 2 variables say var1 and var2 as I need to work with them later.

答:
C does not support dynamically created variables. You can instantiate dynamic objects through calls to malloc(), but these will not be named. In C, names are just labels used to associate names to memory locations at compile time, and resolved at link time. It is way too late at run time.

You can create a mapping from names to int values, but you cannot create new variables. A Mapping will work for you. You need to create a method to add a named value to your mapping, a method to retrieve the value, a method to update its value, and for completeness, you need a fourth method to delete an element when you no longer need it.

Here is a simple example of mapping variable names to int values using a dynamic lookup table. To be complete, you would need to add methods for updating values, and deleting them, etc.

```<code>#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MAX_VARIABLES 100

typedef struct Lookup_Entry_Struct {
           char* Name;
           int   Value;
        } LookUp_Entry;

typedef struct Mapping_Struct {
           int   MaxEntries;
           int   NumEntries;
           LookUp_Entry* mapping;
        } Mapping;

void initMapping(Mapping* map, int MaxEntries)
{
 map->NumEntries = 0;
 map->MaxEntries = MaxEntries;
 map->mapping = calloc(sizeof(LookUp_Entry), MaxEntries);

 if (map->mapping == NULL) {
    // Failed to allocate the Mapping table
    fprintf(stderr, "Failed to alloc Mapping table of %d entries\n", MaxEntries);
    map->MaxEntries = 0;
 }
}

bool addMap(Mapping* map, char* Name, int Val)
{
 bool Added = false;

 if (map->NumEntries < map->MaxEntries) {
    // There is still room in the table, add this new variable
    LookUp_Entry* newEntry = &(map->mapping[map->NumEntries]);
    newEntry->Value = Val;
    newEntry->Name  = malloc(strlen(Name)+1);
    strcpy(newEntry->Name, Name);
    map->NumEntries++;
    Added = true;
 }

 return Added;
}

int lookup(Mapping* map, char* Name)
{
 int  val   = -1;
 int  i     = 0;
 bool Found = false;

 // Search the map to see if we can find Name
 for(i=0; i < map->NumEntries && !Found; i++)
   {
    LookUp_Entry* entry = &(map->mapping[i]);
    if (strcmp(entry->Name, Name) == 0) {
       // Found a match, return the value in *Val
       val   = entry->Value;
       Found = true;
    }
   }

 if (!Found)
    fprintf(stderr, "lookup of \"%s\" not found in map\n", Name);

 // Found value, or -1 if not found
 return val;
}

void getVariablesFromUser(Mapping* map)
{
 #define MAXNAMELEN  100
 // Code modified from Buno's sample
 int  NumVariables = 0;
 int  i;

 char inputName[100];
 int  inputVal;

 while ((NumVariables<1) || (NumVariables > MAX_VARIABLES)) {
    printf("Enter number of variables: ");
    scanf("%d", &NumVariables);
    if (NumVariables<0 || NumVariables>MAX_VARIABLES)
       fprintf(stderr, "Please enter no more than %d variables!\n", MAX_VARIABLES);
 }

 printf("Init mapping for %d variables\n", NumVariables);
 initMapping(map, NumVariables);

 for(i=0; i<NumVariables; i++) {
    printf("Enter variable #%d name and initial value: ", i+1);
    scanf("%s %d", &(inputName[0]), &inputVal);
    printf("Adding variable %s with initial value %d\n", inputName, inputVal);
    addMap(map, inputName, inputVal);

 }
}

int main(int argc, char** argv)
{
 Mapping myVarMap;
 char*   varName;
 int     i;

 getVariablesFromUser(&myVarMap);

 // Display all the variables to show how to retrieve values
 printf("%d variables added by user\n", myVarMap.NumEntries);
 for(i=0; i<myVarMap.NumEntries; i++) {
    LookUp_Entry *entry =  &(myVarMap.mapping[i]);
    char*         name  = entry->Name;
    printf("Entry #%d: %s = %d\n", i+1, name, lookup(&myVarMap,name));
 }
}
</code>```

Save this in file lookup.c, then to compile it:

```<code>gcc lookup.c -o lookup
</code>```

Here is sample run:

```<code>scott> lookup
Enter number of variables: 3
Init mapping for 3 variables
Enter variable #1 name and initial value: Bob 123
Adding variable Bob with initial value 123
Enter variable #2 name and initial value: Ted 999
Adding variable Ted with initial value 999
Enter variable #3 name and initial value: Sally 0
Adding variable Sally with initial value 0
3 variables added by user
Entry #1: Bob = 123
Entry #2: Ted = 999
Entry #3: Sally = 0
scott>
</code>```

Title: c - dynamically allocate variable names

Body:
I am trying to take number of inputs from a user and take the inputs then and store them under dynamically created variable names. can anyone help?

I want to take the number of array user want to input then create the exact number of variables which maintains a common pattern so I can know which array is under which variable and I can call them for further processing.

My current code is as follows

 int input, eqn, m, i,n,x;
    char inputarr[100], eqnarr[100];
    printf("Enter number of variables: ");
    scanf("%d",&n);
    m=n;
    printf("Enter your variables: \n");
    while(n!=-1){
    gets(inputarr[n]);
    n--;
    }
    while(m!=0){
    puts(inputarr[m]);
    printf("\n");
    m--;
    }

my inputs are like

2 (here 2 is number of inputs user intended to give)

a = 3

b = 4

I need to save them  in 2 variables say var1 and var2 as I need to work with them later.

Body:
C does not support dynamically created variables. You can instantiate dynamic objects through calls to malloc(), but these will not be named. In C, names are just labels used to associate names to memory locations at compile time, and resolved at link time. It is way too late at run time.

You can create a mapping from names to int values, but you cannot create new variables. A Mapping will work for you. You need to create a method to add a named value to your mapping, a method to retrieve the value, a method to update its value, and for completeness, you need a fourth method to delete an element when you no longer need it.

Here is a simple example of mapping variable names to int values using a dynamic lookup table. To be complete, you would need to add methods for updating values, and deleting them, etc.

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#define MAX_VARIABLES 100

typedef struct Lookup_Entry_Struct {
           char* Name;
           int   Value;
        } LookUp_Entry;

typedef struct Mapping_Struct {
           int   MaxEntries;
           int   NumEntries;
           LookUp_Entry* mapping;
        } Mapping;

void initMapping(Mapping* map, int MaxEntries)
{
 map->NumEntries = 0;
 map->MaxEntries = MaxEntries;
 map->mapping = calloc(sizeof(LookUp_Entry), MaxEntries);

 if (map->mapping == NULL) {
    // Failed to allocate the Mapping table
    fprintf(stderr, "Failed to alloc Mapping table of %d entries\n", MaxEntries);
    map->MaxEntries = 0;
 }
}

bool addMap(Mapping* map, char* Name, int Val)
{
 bool Added = false;

 if (map->NumEntries < map->MaxEntries) {
    // There is still room in the table, add this new variable
    LookUp_Entry* newEntry = &(map->mapping[map->NumEntries]);
    newEntry->Value = Val;
    newEntry->Name  = malloc(strlen(Name)+1);
    strcpy(newEntry->Name, Name);
    map->NumEntries++;
    Added = true;
 }

 return Added;
}

int lookup(Mapping* map, char* Name)
{
 int  val   = -1;
 int  i     = 0;
 bool Found = false;

 // Search the map to see if we can find Name
 for(i=0; i < map->NumEntries && !Found; i++)
   {
    LookUp_Entry* entry = &(map->mapping[i]);
    if (strcmp(entry->Name, Name) == 0) {
       // Found a match, return the value in *Val
       val   = entry->Value;
       Found = true;
    }
   }

 if (!Found)
    fprintf(stderr, "lookup of \"%s\" not found in map\n", Name);

 // Found value, or -1 if not found
 return val;
}

void getVariablesFromUser(Mapping* map)
{
 #define MAXNAMELEN  100
 // Code modified from Buno's sample
 int  NumVariables = 0;
 int  i;

 char inputName[100];
 int  inputVal;

 while ((NumVariables<1) || (NumVariables > MAX_VARIABLES)) {
    printf("Enter number of variables: ");
    scanf("%d", &NumVariables);
    if (NumVariables<0 || NumVariables>MAX_VARIABLES)
       fprintf(stderr, "Please enter no more than %d variables!\n", MAX_VARIABLES);
 }

 printf("Init mapping for %d variables\n", NumVariables);
 initMapping(map, NumVariables);

 for(i=0; i<NumVariables; i++) {
    printf("Enter variable #%d name and initial value: ", i+1);
    scanf("%s %d", &(inputName[0]), &inputVal);
    printf("Adding variable %s with initial value %d\n", inputName, inputVal);
    addMap(map, inputName, inputVal);

 }
}

int main(int argc, char** argv)
{
 Mapping myVarMap;
 char*   varName;
 int     i;

 getVariablesFromUser(&myVarMap);

 // Display all the variables to show how to retrieve values
 printf("%d variables added by user\n", myVarMap.NumEntries);
 for(i=0; i<myVarMap.NumEntries; i++) {
    LookUp_Entry *entry =  &(myVarMap.mapping[i]);
    char*         name  = entry->Name;
    printf("Entry #%d: %s = %d\n", i+1, name, lookup(&myVarMap,name));
 }
}

Save this in file lookup.c, then to compile it:

gcc lookup.c -o lookup

Here is sample run:

scott> lookup
Enter number of variables: 3
Init mapping for 3 variables
Enter variable #1 name and initial value: Bob 123
Adding variable Bob with initial value 123
Enter variable #2 name and initial value: Ted 999
Adding variable Ted with initial value 999
Enter variable #3 name and initial value: Sally 0
Adding variable Sally with initial value 0
3 variables added by user
Entry #1: Bob = 123
Entry #2: Ted = 999
Entry #3: Sally = 0
scott>


问:
Jackson 2.0 with Spring 3.1
Is Spring MVC 3.1 compatible with Jackson 2.0? Will Spring MVC's automatic detection of Jackson on the classpath, and delegation to Jackson for requests with a JSON content-type still work?</p>

答: I didn't test Spring MVC 3.1 compatible with Jackson 2.0. But I encounter 3.0.5 compatible issue. Finally I find Spring MVC 3.0.5 is only compatible with Jackson 1.0.0, definitely Jackson 1.5.3 isn't compatible!!!</p>

Title: Jackson 2.0 with Spring 3.1


问:
Load CSV into Redshift, injecting additional information
I have some exported_data.csv, and I have some corresponding Redshift table, and I have a COPY:

```<code>COPY(
  c1,
  c2,
  c3,
  ...
) from "s3://bucket/exported_data.csv"
</code>```

What I want to do is add a column source_file to the table, and populate it with arbitrary information defined in the COPY statement (or some other set of statements); in this example, the name of the file the row came from.

I can't use UPDATE due to how much data I'm interacting with (takes just plain too long).

It doesn't look like I can just use DEFAULT, since I need to be able to change the information when the name of the source file is different, but Redshift doesn't let you change the default value of a column. (Otherwise, I'd just change the default val for the column, do the copy, change the default val, do the copy from the next CSV file...)

I'm exploring "staging tables", but figured I'd ask here if someone has a ready-made answer while I explore.

答:
I would suggest using a staging table as well.

Redshift doesn't allow to add columns in the copy statements. So you need to copy the csv file as is to a staging table, and then insert from there to your final table with the additional column.

Body:
I have some exported_data.csv, and I have some corresponding Redshift table, and I have a COPY:

COPY(
  c1,
  c2,
  c3,
  ...
) from "s3://bucket/exported_data.csv"

What I want to do is add a column source_file to the table, and populate it with arbitrary information defined in the COPY statement (or some other set of statements); in this example, the name of the file the row came from.

I can't use UPDATE due to how much data I'm interacting with (takes just plain too long).

It doesn't look like I can just use DEFAULT, since I need to be able to change the information when the name of the source file is different, but Redshift doesn't let you change the default value of a column. (Otherwise, I'd just change the default val for the column, do the copy, change the default val, do the copy from the next CSV file...)

I'm exploring "staging tables", but figured I'd ask here if someone has a ready-made answer while I explore.


问:
c# datetime to string for default values
I've read quite a few threads about nullable DateTime and string formatting.

In my case, I "simply" want to to differentiate default(DateTime), i.e. DateTime.MinValue from any other value when converting to string. Output should be the result of following logic:

```<code>string res = myDateTime == DateTime.MinValue ? string.Empty : myDateTime.ToString("MM/dd/yyyy");
</code>```

I know that for numbers, we have a very convenient way to define what to display depending on the value - we can handle positive, negative and 0 values differently, and even better, display mask applies rounding, i.e.

```<code>String.Format("{0:#,#####0.00;#;#}", 0.001)
</code>```

will display an empty string, which is just exactly what I'd like to have for dates. So is there one such magic formatting string around? Or any other workaround?

答:
You appear to be asking about the ; section separator - which is valid for custom numeric format strings.  There's nothing magic about it.  It has a specific implementation, which only works on numeric data types.  Unfortunately, there is no similar separator token available in the custom date and time format strings.

If you use a nullable type, DateTime? you will get the output you're looking for without any conditional logic.

```<code>DateTime? dt;
string.Format("{0:MM/dd/yyyy}", dt)  // ""

dt = DateTime.Now;
string.Format("{0:MM/dd/yyyy}", dt)  // "03/29/2017"
</code>```

But without nullables, you have to use conditional logic.

```<code>DateTime dt;
string.Format("{0}", dt == default(DateTime) ? "" : dt.ToString("MM/dd/yyyy"))
</code>```

Body:
I've read quite a few threads about nullable DateTime and string formatting.

In my case, I "simply" want to to differentiate default(DateTime), i.e. DateTime.MinValue from any other value when converting to string. Output should be the result of following logic:

string res = myDateTime == DateTime.MinValue ? string.Empty : myDateTime.ToString("MM/dd/yyyy");

I know that for numbers, we have a very convenient way to define what to display depending on the value - we can handle positive, negative and 0 values differently, and even better, display mask applies rounding, i.e.

String.Format("{0:#,#####0.00;#;#}", 0.001)

will display an empty string, which is just exactly what I'd like to have for dates. So is there one such magic formatting string around? Or any other workaround?

Body:
You appear to be asking about the ; section separator - which is valid for custom numeric format strings.  There's nothing magic about it.  It has a specific implementation, which only works on numeric data types.  Unfortunately, there is no similar separator token available in the custom date and time format strings.

If you use a nullable type, DateTime? you will get the output you're looking for without any conditional logic.

DateTime? dt;
string.Format("{0:MM/dd/yyyy}", dt)  // ""

dt = DateTime.Now;
string.Format("{0:MM/dd/yyyy}", dt)  // "03/29/2017"

But without nullables, you have to use conditional logic.

DateTime dt;
string.Format("{0}", dt == default(DateTime) ? "" : dt.ToString("MM/dd/yyyy"))


问:
Node Synchronous functions
Hi there i am having awful trouble with a function I am trying to execute.
I am trying to concat, compile and minify some js and coffeescript which i had working fine when i had it hard coded. My issue is i now created a function that search for the files and returns an array with the file paths. But i cant get the the function to in a synchronous fashion. I have tried so many thing just cant figure it out.

At this stage this is what i have,

This function is used to compile the coffee script this is also called by a async.series which works fine. You can see it calls getFiles which should return the array. But the callback seem to fire before the data s retured

```<code>function compileCoffee() {

    async.series([
        function(callback) {
            data = getFiles("coffee");
            callback(null, data)
        },
        function(data, callback) {
            console.log(data)
            shell.echo(grey("Compiling CoffeeScript files .... "));
            if (shell.cat(data).exec('coffee -sc').exec('uglifyjs --compress', {
                    silent: true
                }).to('./public/assets/js/app.min.js').code !== 0) {
                shell.echo(red('Coffee script compile error'));
                shell.exit(1);
            }
            shell.echo(green("CoffeeScript files compiled succesfully"));
        },
    ], () => {});
}
</code>```

Then this is the get files function. I am probly going abut this all wrong, if i am please let me know a better way. If not and you know how to get it working would be amazing.

```<code>function getFiles(filetype, callback) {

    var files = [];

    // Walker options
    var walker = walk.walkSync('./frontend/js', {
        followLinks: false
    });

    walker.on('file', function(root, stat, next) {
            // Add this file to the list of files
        var ext = stat.name.substr(stat.name.lastIndexOf('.') + 1);
        if (ext == filetype) {
            files.push(root + '/' + stat.name);
        }
        next();
    });

    walker.on('end', function() {
        console.lof(files)
        return files
    })

}
</code>```

Please some one help :D Thanks

答:
getFiles doesn't actually return anything, but it does take a callback that should be called when getFiles completes. Pass the async callback to getFiles (or create another function that calls the callback):

```<code>function(callback) {
  data = getFiles("coffee", callback);
},
</code>```

You need to actually call this callback in your getFiles function:

```<code>walker.on('error', function(error) {
    console.log(error)
    callback(error);
});
walker.on('end', function() {
    console.log(files)
    callback(null, files);
});
</code>```

Title: Node Synchronous functions

Body:
Hi there i am having awful trouble with a function I am trying to execute.
I am trying to concat, compile and minify some js and coffeescript which i had working fine when i had it hard coded. My issue is i now created a function that search for the files and returns an array with the file paths. But i cant get the the function to in a synchronous fashion. I have tried so many thing just cant figure it out.

At this stage this is what i have,

This function is used to compile the coffee script this is also called by a async.series which works fine. You can see it calls getFiles which should return the array. But the callback seem to fire before the data s retured

function compileCoffee() {

    async.series([
        function(callback) {
            data = getFiles("coffee");
            callback(null, data)
        },
        function(data, callback) {
            console.log(data)
            shell.echo(grey("Compiling CoffeeScript files .... "));
            if (shell.cat(data).exec('coffee -sc').exec('uglifyjs --compress', {
                    silent: true
                }).to('./public/assets/js/app.min.js').code !== 0) {
                shell.echo(red('Coffee script compile error'));
                shell.exit(1);
            }
            shell.echo(green("CoffeeScript files compiled succesfully"));
        },
    ], () => {});
}

Then this is the get files function. I am probly going abut this all wrong, if i am please let me know a better way. If not and you know how to get it working would be amazing.

function getFiles(filetype, callback) {

    var files = [];

    // Walker options
    var walker = walk.walkSync('./frontend/js', {
        followLinks: false
    });

    walker.on('file', function(root, stat, next) {
            // Add this file to the list of files
        var ext = stat.name.substr(stat.name.lastIndexOf('.') + 1);
        if (ext == filetype) {
            files.push(root + '/' + stat.name);
        }
        next();
    });

    walker.on('end', function() {
        console.lof(files)
        return files
    })

}

Please some one help :D Thanks

Body:
getFiles doesn't actually return anything, but it does take a callback that should be called when getFiles completes. Pass the async callback to getFiles (or create another function that calls the callback):

function(callback) {
  data = getFiles("coffee", callback);
},

You need to actually call this callback in your getFiles function:

walker.on('error', function(error) {
    console.log(error)
    callback(error);
});
walker.on('end', function() {
    console.log(files)
    callback(null, files);
});


问:
Device number in stat command output
```<code>  stat test.log
  File: `test.log'
  Size: 573         Blocks: 8          IO Block: 4096   regular file
Device: 804h/2052d  Inode: 7091301     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1001/   abc)   Gid: ( 1001/   abc)
Access: 2010-11-29 17:56:22.000000000 -0800
Modify: 2010-11-29 17:56:22.000000000 -0800
Change: 2010-11-29 17:56:22.000000000 -0800
</code>```

In the stat o/p above what does the Device entry signify ?

答:
It's the major and minor device number combined into one value (in hex and decimal) of the device on which the file resides.

For your example, 804h is major device 8, minor device 4. if you run df . while you're in the directory where that file is, you'll get the device name such as /dev/sda1. If you were to then do ls -al /dev/sda1, it would show you the device numbers. Here's an example:

```<code>pax$ stat newfile # note device 801h, hex 801 = 2049 decimal
  File: 'newfile'
  Size: 2097152     Blocks: 4096       IO Block: 4096   regular file
Device: 801h/2049d  Inode: 2888080     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/     pax)   Gid: ( 1000/     pax)
Access: 2010-11-29 07:32:22.011271661 +0800
Modify: 2010-08-30 15:43:14.286796827 +0800
Change: 2010-08-30 15:43:14.286796827 +0800

pax$ df . # to get current device mount
Filesystem           1K-blocks Used Available Use% Mounted on
/dev/sda1            470301088 182471788 263939332  41% /

pax$ ls -al /dev/sda1 # to get major/minor = 8/1
brw-rw---- 1 root disk 8, 1 2010-11-30 07:02 /dev/sda1
</code>```

Title: Device number in stat command output

Body:
  stat test.log
  File: `test.log'
  Size: 573         Blocks: 8          IO Block: 4096   regular file
Device: 804h/2052d  Inode: 7091301     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1001/   abc)   Gid: ( 1001/   abc)
Access: 2010-11-29 17:56:22.000000000 -0800
Modify: 2010-11-29 17:56:22.000000000 -0800
Change: 2010-11-29 17:56:22.000000000 -0800

In the stat o/p above what does the Device entry signify ?

Body:
It's the major and minor device number combined into one value (in hex and decimal) of the device on which the file resides.

For your example, 804h is major device 8, minor device 4. if you run df . while you're in the directory where that file is, you'll get the device name such as /dev/sda1. If you were to then do ls -al /dev/sda1, it would show you the device numbers. Here's an example:

pax$ stat newfile # note device 801h, hex 801 = 2049 decimal
  File: 'newfile'
  Size: 2097152     Blocks: 4096       IO Block: 4096   regular file
Device: 801h/2049d  Inode: 2888080     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/     pax)   Gid: ( 1000/     pax)
Access: 2010-11-29 07:32:22.011271661 +0800
Modify: 2010-08-30 15:43:14.286796827 +0800
Change: 2010-08-30 15:43:14.286796827 +0800

pax$ df . # to get current device mount
Filesystem           1K-blocks Used Available Use% Mounted on
/dev/sda1            470301088 182471788 263939332  41% /

pax$ ls -al /dev/sda1 # to get major/minor = 8/1
brw-rw---- 1 root disk 8, 1 2010-11-30 07:02 /dev/sda1


问:
list __iadd__, += and return value
I have noticed some strange behaviour with list extension return values.

I have read this thread Why does += behave unexpectedly on lists?

but it still does not make sense.

This is what I did:

```<code>Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1, 2]
>>> print(l.extend([1]))
None
>>> print(l.__iadd__([1]))
[1, 2, 1, 1]
>>> print(l += [1])
  File "<stdin>", line 1
print(l += [1])
         ^
SyntaxError: invalid syntax
>>>
</code>```

I understand that extend does not return the extended object, but None. Not helpful, but I get it.

Now __iadd__ behaves differently, which is weird, since I read that this basically calls extend for a list.

But the third one baffles me. I thought += was shorthand for __iadd__, so why do I get a SyntaxError here? Especially since __iadd__ returns the modified list, which would make sense to pass on as a return value. But it seems I can't use += (or *= for that matter, e.g. with integers) in function calls.

Is that by design?

答:
l.__iadd__(val) is a function call, that is, an expression.

l += [1] is an assignment, that is, a statement.

Argument values (the ones you have supplied to print in this case) are not allowed to be statements, only expressions, simple as that.

Title: list __iadd__, += and return value

Body:
I have noticed some strange behaviour with list extension return values.

I have read this thread Why does += behave unexpectedly on lists?

but it still does not make sense.

This is what I did:

Python 3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1, 2]
>>> print(l.extend([1]))
None
>>> print(l.__iadd__([1]))
[1, 2, 1, 1]
>>> print(l += [1])
  File "<stdin>", line 1
print(l += [1])
         ^
SyntaxError: invalid syntax
>>>

I understand that extend does not return the extended object, but None. Not helpful, but I get it.

Now __iadd__ behaves differently, which is weird, since I read that this basically calls extend for a list.

But the third one baffles me. I thought += was shorthand for __iadd__, so why do I get a SyntaxError here? Especially since __iadd__ returns the modified list, which would make sense to pass on as a return value. But it seems I can't use += (or *= for that matter, e.g. with integers) in function calls.

Is that by design?


问:
Vignere Cipher Decryption function not return correct decrypt python 2.7
I created a Encrypter and Decrypter for the Vignere cipher. The encrypter works it turned "THE EAGLE HAS LANDED" into "WHZ RCOOE PNU OAILRF". However when I try to decrypt "WHZ RCOOE PNU OAILRF" using DAVINCI, it doesn't return THE EAGLE HAS LANDED. Instead it returns a random jumble "ZHU EEWRE XAW RADTEH". Is the issue in the decryptVignere or is it the previous functions? I know encryptVignere works perfectly.</p>

```<code>"""
This program will decrypt/encrypt a Vignere with the Keyword: DaVinci
"""

# helper functions
# letter to index
def letterToIndex(ch):
   alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
   idx = alphabet.find(ch)
   if idx < 0:
      print ("error: letter not in the alphabet", ch)
   return idx

# index to letter
def indexToLetter(idx):
   alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
   if idx > 25:
      print ('error: ', idx, ' is too large')
      letter = ' '
   elif idx < 0:
      print ('error: ', idx, ' is less than 0')
      letter = ' '
   else:
      letter = alphabet[idx]
   return letter

# looking up a letter in the Vignere square
def vignereIndex(keyLetter, plainTextLetter):
   keyIndex = letterToIndex(keyLetter)
   ptIndex = letterToIndex(plainTextLetter)
   newIdx = (ptIndex + keyIndex) % 26
   return indexToLetter(newIdx)

def decryptVignere(key, cipherText):
   plainText = ""
   keyLen = len(key)
   for i in range (len(cipherText)):
      ch = cipherText[i]
      if ch == ' ':
         plainText = plainText + ch
      else:
         plainText = plainText + vignereIndex(key[i%keyLen], ch)
   return plainText

#encrypting a message using the Vignere cipher
def encryptVignere(key, plainText):
   cipherText = ""
   keyLen = len(key)
   for i in range (len(plainText)):
      ch = plainText[i]
      if ch == ' ':
         cipherText = cipherText + ch
      else:
         cipherText = cipherText + vignereIndex(key[i%keyLen], ch)
   return cipherText

# decrypt
messageOne = "WHZ RCOOE PNU OAILRF" # raw_input("Enter your string: ")?
keyOne = "DAVINCI"

deStr = decryptVignere(keyOne, messageOne)
print deStr
</code>```

答:
Your decrypt method is exactly identical to your encrypt method! The decrypt method should do the opposite, i.e. subtract the key instead of adding it.

A possible solution is to add a parameter to your vignereIndex method to toggle between encrypting and decrypting.

```<code>def vignereIndex(keyLetter, plainTextLetter, encrypt):
    keyIndex = letterToIndex(keyLetter)
    ptIndex = letterToIndex(plainTextLetter)
    if not encrypt:
        keyIndex *= -1
    newIdx = (ptIndex + keyIndex) % 26
    return indexToLetter(newIdx)
</code>```

Body:
I created a Encrypter and Decrypter for the Vignere cipher. The encrypter works it turned "THE EAGLE HAS LANDED" into "WHZ RCOOE PNU OAILRF". However when I try to decrypt "WHZ RCOOE PNU OAILRF" using DAVINCI, it doesn't return THE EAGLE HAS LANDED. Instead it returns a random jumble "ZHU EEWRE XAW RADTEH". Is the issue in the decryptVignere or is it the previous functions? I know encryptVignere works perfectly.

"""
This program will decrypt/encrypt a Vignere with the Keyword: DaVinci
"""

# helper functions
# letter to index
def letterToIndex(ch):
   alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
   idx = alphabet.find(ch)
   if idx < 0:
      print ("error: letter not in the alphabet", ch)
   return idx

# index to letter
def indexToLetter(idx):
   alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "
   if idx > 25:
      print ('error: ', idx, ' is too large')
      letter = ' '
   elif idx < 0:
      print ('error: ', idx, ' is less than 0')
      letter = ' '
   else:
      letter = alphabet[idx]
   return letter

# looking up a letter in the Vignere square
def vignereIndex(keyLetter, plainTextLetter):
   keyIndex = letterToIndex(keyLetter)
   ptIndex = letterToIndex(plainTextLetter)
   newIdx = (ptIndex + keyIndex) % 26
   return indexToLetter(newIdx)

def decryptVignere(key, cipherText):
   plainText = ""
   keyLen = len(key)
   for i in range (len(cipherText)):
      ch = cipherText[i]
      if ch == ' ':
         plainText = plainText + ch
      else:
         plainText = plainText + vignereIndex(key[i%keyLen], ch)
   return plainText

#encrypting a message using the Vignere cipher
def encryptVignere(key, plainText):
   cipherText = ""
   keyLen = len(key)
   for i in range (len(plainText)):
      ch = plainText[i]
      if ch == ' ':
         cipherText = cipherText + ch
      else:
         cipherText = cipherText + vignereIndex(key[i%keyLen], ch)
   return cipherText

# decrypt
messageOne = "WHZ RCOOE PNU OAILRF" # raw_input("Enter your string: ")?
keyOne = "DAVINCI"

deStr = decryptVignere(keyOne, messageOne)
print deStr

Body:
Your decrypt method is exactly identical to your encrypt method! The decrypt method should do the opposite, i.e. subtract the key instead of adding it.

A possible solution is to add a parameter to your vignereIndex method to toggle between encrypting and decrypting.

def vignereIndex(keyLetter, plainTextLetter, encrypt):
    keyIndex = letterToIndex(keyLetter)
    ptIndex = letterToIndex(plainTextLetter)
    if not encrypt:
        keyIndex *= -1
    newIdx = (ptIndex + keyIndex) % 26
    return indexToLetter(newIdx)


答: __iadd__ is used to implement +=, but the two are not identical. l += [1] is still a statement, while l.__iadd__([1]) is an expression.

Title: list __iadd__, += and return value


问:
Applying multiple CSS classes to an angular select?
I had a normal select in a component's template like this:

```<code><select id='target-region' multiple="" class="ui dropdown">
    <option selected value="01">Europe</option>
    <option value="02">North America</option>
    <option value="03">South America</option>
    <option value="04">Asia</option>
    <option value="05">Africa</option>
</select>
</code>```

This dropdown looks something like this:

I tried to turn it into an angular select like so:

```<code><select id="target-region" class="ui dropdown" ng-model="$ctrl.targetRegion" ng-options="item.name for item in $ctrl.TARGET_REGIONS track by item.value" multiple=""></select>
</code>```

And I placed the following in the JS for the component:

```<code>this.TARGET_REGIONS = [
    { value: '01', name: 'Europe' },
    { value: '02', name: 'North America' },
    { value: '03', name: 'South America' },
    { value: '04', name: 'Asia' },
    { value: '05', name: 'Africa' },
];
this.targetRegion = [this.TARGET_REGIONS[0]];
</code>```

There are no errors, but the dropdown select is now displaying in an odd way:

My styling seems to not take effect and clicking on the different options does not select them, so it's not even functional.

I inspected the select and saw this:

This indicates that the ui dropdown classes are being applied to an outer wrapper div created by angular rather than being applied to the select.

At the very least, I'm wondering: how do I make the ui dropdown classes apply directly to the select?

答:
Hi i got it to work this way. heres a working fiddle. http://plnkr.co/edit/pNiKKDHQEZ6KoZhEuDlO?p=preview

I suppose you might have forgotten to initialise your dropdown.

```<code>$(function () {
$('.tag .ui.dropdown').dropdown({allowAdditions: true});
 });
</code>```

Body:
I had a normal select in a component's template like this:

<select id='target-region' multiple="" class="ui dropdown">
    <option selected value="01">Europe</option>
    <option value="02">North America</option>
    <option value="03">South America</option>
    <option value="04">Asia</option>
    <option value="05">Africa</option>
</select>

This dropdown looks something like this:

I tried to turn it into an angular select like so:

<select id="target-region" class="ui dropdown" ng-model="$ctrl.targetRegion" ng-options="item.name for item in $ctrl.TARGET_REGIONS track by item.value" multiple=""></select>

And I placed the following in the JS for the component:

this.TARGET_REGIONS = [
    { value: '01', name: 'Europe' },
    { value: '02', name: 'North America' },
    { value: '03', name: 'South America' },
    { value: '04', name: 'Asia' },
    { value: '05', name: 'Africa' },
];
this.targetRegion = [this.TARGET_REGIONS[0]];

There are no errors, but the dropdown select is now displaying in an odd way:

My styling seems to not take effect and clicking on the different options does not select them, so it's not even functional.

I inspected the select and saw this:

This indicates that the ui dropdown classes are being applied to an outer wrapper div created by angular rather than being applied to the select.

At the very least, I'm wondering: how do I make the ui dropdown classes apply directly to the select?

Body:
Hi i got it to work this way. heres a working fiddle. http://plnkr.co/edit/pNiKKDHQEZ6KoZhEuDlO?p=preview

I suppose you might have forgotten to initialise your dropdown.

$(function () {
$('.tag .ui.dropdown').dropdown({allowAdditions: true});
 });


答: You cannot create variable names dynamically, however you can dynamically allocate memory using a function called 'malloc()'. You need to first understand pointers and then learn how to create and access memory during run-time.</p>

Title: c - dynamically allocate variable names