问:
Attempting to copy and paste multiple sections of a table to new word doc, keeps pasting new tables in first cell
So I am trying to copy and paste multiple columns of an excel database into a word document. Every time it completes a "round" it keeps the cursor in the first cell and therefore messes up the formatting. I am attempting to make the cursor scroll out of the previous table to create a new table below. the problematic code is indicated in 'Autofit Table so it fits inside Word Document

I have tried

    Selection.MoveDown Unit:=wdLine, Count:=54
```

<p>But it gives an error</p>

<p>Here is my full code:</p>

<pre class="lang-vb prettyprint-override"><code>Sub ReportGen()

'ROUND 1

Dim myValue As Variant
Dim atbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim aWordTable As Word.Table

'Define whos info you need
myValue = InputBox("Who are you meeting with?")

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
  Sheets("Stage Gate (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set atbl = ThisWorkbook.Worksheets("Stage Gate (Open)").Range("C6:C10,a6:a10,b6:b10,e6:e10")

'Create an Instance of MS Word
  On Error Resume Next

    'Is MS Word already opened?
      Set WordApp = GetObject(class:="Word.Application")

    'Clear the error between errors
      Err.Clear

    'If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

    'Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
      End If

  On Error GoTo 0

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Create a New Document
  Set myDoc = WordApp.Documents.Add

'Copy Excel Table Range
  atbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set aWordTable = myDoc.Tables(1)
  aWordTable.AutoFitBehavior (wdAutoFitWindow)
  myDoc.Selection.MoveDown Unit:=wdLine, Count:=54

'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

'ROUND 2

Dim btbl As Excel.Range
Dim WordTable As Word.Table

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
   Sheets("Stage Gate Support (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set btbl = ThisWorkbook.Worksheets("Stage Gate Support (Open)").Range("C3:C10,a3:a10,b3:b10,e3:e10")

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Copy Excel Table Range
  btbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set bWordTable = myDoc.Tables(1)
  bWordTable.AutoFitBehavior (wdAutoFitWindow)
  Selection.MoveDown Unit:=wdLine, Count:=54

'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

'ROUND 3

Dim ctbl As Excel.Range
Dim cWordTable As Word.Table

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
   Sheets("Bermondsey (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set ctbl = ThisWorkbook.Worksheets("Bermondsey (Open)").Range("C6:C10,a6:a10,b6:b10,e6:e10")

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Copy Excel Table Range
  ctbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set cWordTable = myDoc.Tables(1)
  cWordTable.AutoFitBehavior (wdAutoFitWindow)
  Selection.MoveDown Unit:=wdLine, Count:=54

EndRoutine:
'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub

</code>```

答:
Try the following. Note that nothing ever gets selected, which makes the code far more efficient. As coded, each table is output on its own page.</p>

```<code>Sub ReportGen()
Dim atbl As Range, btbl As Range, As Range
Dim WordApp As Object, myDoc As Object
Dim myValue As Variant

  'Define who's info you need
  myValue = InputBox("Who are you meeting with?")

  'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

  'Create an Instance of MS Word
  On Error Resume Next
  'Is MS Word already opened?
  Set WordApp = GetObject(, "Word.Application")
  'Clear the error between errors
  Err.Clear
  'If MS Word is not already open then open MS Word
  If WordApp Is Nothing Then Set WordApp = CreateObject("Word.Application")
  'Handle if the Word Application is not found
  If Err.Number = 429 Then
    MsgBox "Microsoft Word could not be found, aborting."
    GoTo EndRoutine
  End If
  On Error GoTo 0
  'Make MS Word Visible and Active
  WordApp.Visible = True

  'Set Excel Ranges
  With Sheets("Stage Gate (Open)")
    .Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
    Set atbl = .Range("C6:C10,a6:a10,b6:b10,e6:e10")
    Set btbl = .Range("C3:C10,a3:a10,b3:b10,e3:e10")
  End With
  With Sheets("Bermondsey (Open)")
    .Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
    Set ctbl = .Range("C6:C10,a6:a10,b6:b10,e6:e10")
  End With

  'Create a New Document
  Set myDoc = WordApp.Documents.Add
  With myDoc
    'Copy Excel Table Range
    atbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(1).AutoFitBehavior 2 'wdAutoFitWindow
    .Range.InsertAfter Chr(12)
    'Copy Excel Table Range
    btbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(2).AutoFitBehavior 2 'wdAutoFitWindow
    .Range.InsertAfter Chr(12)
    ctbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(3).AutoFitBehavior 2 'wdAutoFitWindow
  End With

  Set atbl = Nothing: Set btbl = Nothing: Set ctbl = Nothing
  Set myDoc = Nothing: Set WordApp = Nothing

EndRoutine:
  'Clear The Clipboard
  Application.CutCopyMode = False
  'Optimize Code
  Application.EnableEvents = True
  Application.ScreenUpdating = True
End Sub
</code>```

Body:
So I am trying to copy and paste multiple columns of an excel database into a word document. Every time it completes a "round" it keeps the cursor in the first cell and therefore messes up the formatting. I am attempting to make the cursor scroll out of the previous table to create a new table below. the problematic code is indicated in 'Autofit Table so it fits inside Word Document

I have tried

    Selection.MoveDown Unit:=wdLine, Count:=54

But it gives an error

Here is my full code:

Sub ReportGen()

'ROUND 1

Dim myValue As Variant
Dim atbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim aWordTable As Word.Table

'Define whos info you need
myValue = InputBox("Who are you meeting with?")

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
  Sheets("Stage Gate (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set atbl = ThisWorkbook.Worksheets("Stage Gate (Open)").Range("C6:C10,a6:a10,b6:b10,e6:e10")

'Create an Instance of MS Word
  On Error Resume Next

    'Is MS Word already opened?
      Set WordApp = GetObject(class:="Word.Application")

    'Clear the error between errors
      Err.Clear

    'If MS Word is not already open then open MS Word
      If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

    'Handle if the Word Application is not found
      If Err.Number = 429 Then
        MsgBox "Microsoft Word could not be found, aborting."
        GoTo EndRoutine
      End If

  On Error GoTo 0

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Create a New Document
  Set myDoc = WordApp.Documents.Add

'Copy Excel Table Range
  atbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set aWordTable = myDoc.Tables(1)
  aWordTable.AutoFitBehavior (wdAutoFitWindow)
  myDoc.Selection.MoveDown Unit:=wdLine, Count:=54

'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

'ROUND 2

Dim btbl As Excel.Range
Dim WordTable As Word.Table

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
   Sheets("Stage Gate Support (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set btbl = ThisWorkbook.Worksheets("Stage Gate Support (Open)").Range("C3:C10,a3:a10,b3:b10,e3:e10")

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Copy Excel Table Range
  btbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set bWordTable = myDoc.Tables(1)
  bWordTable.AutoFitBehavior (wdAutoFitWindow)
  Selection.MoveDown Unit:=wdLine, Count:=54

'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

'ROUND 3

Dim ctbl As Excel.Range
Dim cWordTable As Word.Table

'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

'Copy Range from Excel
   Sheets("Bermondsey (Open)").Select
  ActiveSheet.Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
  Set ctbl = ThisWorkbook.Worksheets("Bermondsey (Open)").Range("C6:C10,a6:a10,b6:b10,e6:e10")

'Make MS Word Visible and Active
  WordApp.Visible = True
  WordApp.Activate

'Copy Excel Table Range
  ctbl.Copy

'Paste Table into MS Word
  myDoc.Paragraphs(1).Range.PasteExcelTable _
    LinkedToExcel:=False, _
    WordFormatting:=False, _
    RTF:=False

'Autofit Table so it fits inside Word Document
  Set cWordTable = myDoc.Tables(1)
  cWordTable.AutoFitBehavior (wdAutoFitWindow)
  Selection.MoveDown Unit:=wdLine, Count:=54

EndRoutine:
'Optimize Code
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub

Body:
Try the following. Note that nothing ever gets selected, which makes the code far more efficient. As coded, each table is output on its own page.

Sub ReportGen()
Dim atbl As Range, btbl As Range, As Range
Dim WordApp As Object, myDoc As Object
Dim myValue As Variant

  'Define who's info you need
  myValue = InputBox("Who are you meeting with?")

  'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False

  'Create an Instance of MS Word
  On Error Resume Next
  'Is MS Word already opened?
  Set WordApp = GetObject(, "Word.Application")
  'Clear the error between errors
  Err.Clear
  'If MS Word is not already open then open MS Word
  If WordApp Is Nothing Then Set WordApp = CreateObject("Word.Application")
  'Handle if the Word Application is not found
  If Err.Number = 429 Then
    MsgBox "Microsoft Word could not be found, aborting."
    GoTo EndRoutine
  End If
  On Error GoTo 0
  'Make MS Word Visible and Active
  WordApp.Visible = True

  'Set Excel Ranges
  With Sheets("Stage Gate (Open)")
    .Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
    Set atbl = .Range("C6:C10,a6:a10,b6:b10,e6:e10")
    Set btbl = .Range("C3:C10,a3:a10,b3:b10,e3:e10")
  End With
  With Sheets("Bermondsey (Open)")
    .Range("$A$6:$AL$25").AutoFilter Field:=3, Criteria1:=myValue
    Set ctbl = .Range("C6:C10,a6:a10,b6:b10,e6:e10")
  End With

  'Create a New Document
  Set myDoc = WordApp.Documents.Add
  With myDoc
    'Copy Excel Table Range
    atbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(1).AutoFitBehavior 2 'wdAutoFitWindow
    .Range.InsertAfter Chr(12)
    'Copy Excel Table Range
    btbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(2).AutoFitBehavior 2 'wdAutoFitWindow
    .Range.InsertAfter Chr(12)
    ctbl.Copy
    'Paste Table into MS Word
    .Range.Characters.Last.PasteExcelTable False, False, False
    'Autofit Table so it fits inside Word Document
    .Tables(3).AutoFitBehavior 2 'wdAutoFitWindow
  End With

  Set atbl = Nothing: Set btbl = Nothing: Set ctbl = Nothing
  Set myDoc = Nothing: Set WordApp = Nothing

EndRoutine:
  'Clear The Clipboard
  Application.CutCopyMode = False
  'Optimize Code
  Application.EnableEvents = True
  Application.ScreenUpdating = True
End Sub


来源: stackexchange

问:
Unknown error (worker initialization failed: 21) in foreach() with doParallel cluster (R)
First-time poster here. Before posting, I read FAQs and posting guides as recommended so I hope I am posting my question in the correct format.

I am running foreach() tasks using the doParallel cluster backend in R 64 bit console v. 3.1.2. on Windows 8. Relevant packages are foreach v. 1.4.2 and doParallel v. 1.0.8.

Some sample code to give you an idea of what I am doing:

```<code>out <- foreach (j = 1:nsim.times, .combine=rbind, .packages=c("vegan")) %dopar% {

b<-oecosimu(list.mat[[j]], compute.function, "quasiswap", nsimul=nsim.swap) ## where list.mat is a list of matrices and compute.function is a custom function
..... # some intermediate code
return(c(A,B)) ## where A and B are some emergent properties derived from object b from above

}
</code>```

In one of my tasks, I encountered an error I have never seen before. I tried to search for the error online but couldn't find any clues.

The error was:

```<code>Error in e$fun(obj, substitute(ex), parent.frame(), e$data) :
worker initialization failed: 21
</code>```

In the one time I got this error, I ran the code after stopping a previous task (using the Stop button in R Console) but without closing the cluster via 'stopCluster()'.

I ran the same code again after stopping the cluster via 'stopCluster()' and registering a new cluster 'makeCluster()' and 'registerDoParallel()' and the task ran fine.

Has anyone encountered this error or might have any clues/tips as to how I could figure out the issue? Could the error be related to not stopping the previous doParallel cluster?

Any help or advice is much appreciated!

Cheers and thanks!

答:
After many many trials, I think I got a potential solution based on the answer by @Steve Weston.
For some reason, before the stopCluster call, you need to also call   registerDoSEQ().

Like this:

```<code>clus <- makeCluster()

... do something ...

registerDoSEQ()
stopCluster(clus)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
First-time poster here. Before posting, I read FAQs and posting guides as recommended so I hope I am posting my question in the correct format.

I am running foreach() tasks using the doParallel cluster backend in R 64 bit console v. 3.1.2. on Windows 8. Relevant packages are foreach v. 1.4.2 and doParallel v. 1.0.8.

Some sample code to give you an idea of what I am doing:

out <- foreach (j = 1:nsim.times, .combine=rbind, .packages=c("vegan")) %dopar% {

b<-oecosimu(list.mat[[j]], compute.function, "quasiswap", nsimul=nsim.swap) ## where list.mat is a list of matrices and compute.function is a custom function
..... # some intermediate code
return(c(A,B)) ## where A and B are some emergent properties derived from object b from above

}

In one of my tasks, I encountered an error I have never seen before. I tried to search for the error online but couldn't find any clues.

The error was:

Error in e$fun(obj, substitute(ex), parent.frame(), e$data) :
worker initialization failed: 21

In the one time I got this error, I ran the code after stopping a previous task (using the Stop button in R Console) but without closing the cluster via 'stopCluster()'.

I ran the same code again after stopping the cluster via 'stopCluster()' and registering a new cluster 'makeCluster()' and 'registerDoParallel()' and the task ran fine.

Has anyone encountered this error or might have any clues/tips as to how I could figure out the issue? Could the error be related to not stopping the previous doParallel cluster?

Any help or advice is much appreciated!

Cheers and thanks!

Body:
After many many trials, I think I got a potential solution based on the answer by @Steve Weston.
For some reason, before the stopCluster call, you need to also call   registerDoSEQ().

Like this:

clus <- makeCluster()

... do something ...

registerDoSEQ()
stopCluster(clus)

ContentLicense: CC BY-SA 4.0


问:
What does it mean when DataFrame invoke a drop() without parameter?
I see a code from book "Spark The Definitive Guide",it invoke a drop on a dataframe with no parameter,when I use show(),I found nothing changed,but what is the meaning of it?

I execute it,nothing changed,dfNoNull.show() is the same as dfWithDate.show()

```<code>dfWithDate.createOrReplaceTempView("dfWithDate")
// in Scala
val dfNoNull = dfWithDate.drop()
dfNoNull.createOrReplaceTempView("dfNoNull")
</code>```

does it mean, it create a new datarframe?
I know when a dataframe join itself when I using Hive sql,if I just

```<code>val df1=spark.sql("select id,date from date")
val df2=spark.sql("select id,date from date")
val joinedDf = spark.sql("select dateid1,dateid2 from sales")
.join(df1,df1["id"]===dateid1).join(df2,df2["id"]===dateid2)
</code>```

Then an error occur:Cartesian join!
because the lazy evalution will consider df1 and df1 as the same one

so here,if I

```<code>val df2=df1.drop()
</code>```

will I prevent that error?

If not,what does the drop method with no parameter mean?

Or it just mean remove the temp view name and create a new one?

but I try the code below,no exception throwed:

```<code>   val df=  Seq((1,"a")).toDF("id","name")
   df.createOrReplaceTempView("df1")
   val df2=df.drop()
    df2.createOrReplaceTempView("df2")
    spark.sql("select * from df1").show()
</code>```

Or does the book mean below?

```<code> val dfNoNull = dfWithDate.na.drop()
</code>```

because it wrote somewhere below the code:

Grouping sets depend on null values for aggregation levels. If you do
  not filter-out null values, you will get incorrect results.This
  applies to cubes, rollups, and grouping sets.

答:
drop function with no parameter behave the same as drop with column name that doesn't exist in the Dataframe.
You can follow the code in the source of spark.

Even in the function documentation you can see a hint to this behavior.

```<code>  /**
   * Returns a new Dataset with a column dropped. This is a no-op if schema doesn't contain
   * column name.
   *
   * This method can only be used to drop top level columns. the colName string is treated
   * literally without further interpretation.
   *
   * @group untypedrel
   * @since 2.0.0
   */
</code>```

So when calling the function with no parameter no-op occur and nothing changes in the returning DataFrame.

Body:
I see a code from book "Spark The Definitive Guide",it invoke a drop on a dataframe with no parameter,when I use show(),I found nothing changed,but what is the meaning of it?

I execute it,nothing changed,dfNoNull.show() is the same as dfWithDate.show()

dfWithDate.createOrReplaceTempView("dfWithDate")
// in Scala
val dfNoNull = dfWithDate.drop()
dfNoNull.createOrReplaceTempView("dfNoNull")

does it mean, it create a new datarframe?
I know when a dataframe join itself when I using Hive sql,if I just

val df1=spark.sql("select id,date from date")
val df2=spark.sql("select id,date from date")
val joinedDf = spark.sql("select dateid1,dateid2 from sales")
.join(df1,df1["id"]===dateid1).join(df2,df2["id"]===dateid2)

Then an error occur:Cartesian join!
because the lazy evalution will consider df1 and df1 as the same one

so here,if I

val df2=df1.drop()

will I prevent that error?

If not,what does the drop method with no parameter mean?

Or it just mean remove the temp view name and create a new one?

but I try the code below,no exception throwed:

   val df=  Seq((1,"a")).toDF("id","name")
   df.createOrReplaceTempView("df1")
   val df2=df.drop()
    df2.createOrReplaceTempView("df2")
    spark.sql("select * from df1").show()

Or does the book mean below?

 val dfNoNull = dfWithDate.na.drop()

because it wrote somewhere below the code:

Grouping sets depend on null values for aggregation levels. If you do
  not filter-out null values, you will get incorrect results.This
  applies to cubes, rollups, and grouping sets.

Body:
drop function with no parameter behave the same as drop with column name that doesn't exist in the Dataframe.
You can follow the code in the source of spark.

Even in the function documentation you can see a hint to this behavior.

  /**
   * Returns a new Dataset with a column dropped. This is a no-op if schema doesn't contain
   * column name.
   *
   * This method can only be used to drop top level columns. the colName string is treated
   * literally without further interpretation.
   *
   * @group untypedrel
   * @since 2.0.0
   */

So when calling the function with no parameter no-op occur and nothing changes in the returning DataFrame.


问:
Escaping regular expressions inside square brackets
I'm trying to escape a parenthesis inside square brackets.

```<code>$pattern = "/^[a-zA-Z0-9 _-\(]{1,25}$/";
$str = "TEST (ok)";

if (preg_match($pattern, $str)) {
    echo "<br />OK";
} else {
    echo "<br />FAIL";
}
</code>```

This give me the warning:

Warning: preg_match(): Compilation
  failed: range out of order in
  character class at offset 15 in
  /var/www/test.php on line 6

  FAIL

Outside the square brackets the escaping works fine.

Any ideas?

答: escape the hyphen or move it to the front or back of the char class list</p>

Body:
I'm trying to escape a parenthesis inside square brackets.

$pattern = "/^[a-zA-Z0-9 _-\(]{1,25}$/";
$str = "TEST (ok)";

if (preg_match($pattern, $str)) {
    echo "
OK";
} else {
    echo "
FAIL";
}

This give me the warning:

Warning: preg_match(): Compilation
  failed: range out of order in
  character class at offset 15 in
  /var/www/test.php on line 6

  FAIL

Outside the square brackets the escaping works fine.

Any ideas?


问:
Implementing and generating multiple dynamic SiteMapNodes in ASP.Net
Say I currently have this sitemap path:

```<code><siteMapNode url="Home" title="Home" description="Home">

    <siteMapNode url="Shop" title="Shop" description="Shop" >

        <!-- There should be dynamic categories pages here -->

            <!-- There should be dynamic product names here -->

    </siteMapNode>

    <!-- Individual Pages -->
    <siteMapNode url="Login" title="Login"/>
    <siteMapNode url="TermsAndConditions" title="Terms And Conditions"/>
    <siteMapNode url="PrivacyPolicy" title="Privacy Policy"/>
    <siteMapNode url="ProhibitionsAndRestrictions" title="Prohibitions And Restrictions" />
    <siteMapNode url="ContactUs" title="Contact Us" />

</siteMapNode>
</code>```

I don't have physical pages for my categories and products. There are all generated from query strings.

For example:

Category pages:

```<code>Shop?c=food
Shop?c=beverages
Shop?c=furniture
</code>```

Product pages:

```<code>Product/fried-chicken-abc
Product/fried-rice-def
Product/herbal-tea-123
Product/wooden-chair-xyz
</code>```

How can I have my categories and product pages be registered to my sitemap path dynamically?

I know you can do a currentnodetemplate for dynamic categories pages but what about the product pages? Since there are now 2 dynamic nodes (category & product)

答:
The article below nicely describes how to create a dynamic SiteMap (e.g. url parameters from data retrieved from a database) as well as how to dynamically expose it both in a Web Forms and an MVC application.

I've implemented it in my own projects and it really works very well.

https://www.mikesdotnetting.com/article/291/seo-for-asp-net-web-sites-getting-content-indexed

Body:
Say I currently have this sitemap path:

<siteMapNode url="Home" title="Home" description="Home">

    <siteMapNode url="Shop" title="Shop" description="Shop" >

    </siteMapNode>

    <siteMapNode url="Login" title="Login"/>
    <siteMapNode url="TermsAndConditions" title="Terms And Conditions"/>
    <siteMapNode url="PrivacyPolicy" title="Privacy Policy"/>
    <siteMapNode url="ProhibitionsAndRestrictions" title="Prohibitions And Restrictions" />
    <siteMapNode url="ContactUs" title="Contact Us" />

</siteMapNode>

I don't have physical pages for my categories and products. There are all generated from query strings.

For example:

Category pages:

Shop?c=food
Shop?c=beverages
Shop?c=furniture

Product pages:

Product/fried-chicken-abc
Product/fried-rice-def
Product/herbal-tea-123
Product/wooden-chair-xyz

How can I have my categories and product pages be registered to my sitemap path dynamically?

I know you can do a currentnodetemplate for dynamic categories pages but what about the product pages? Since there are now 2 dynamic nodes (category & product)


问:
How to get values from foreach with insert statement
I'm a newbie. I use GetSelectedIndices and foreach to get each values in array.

After that, I provided those values for the insert statement. How can I get query_TheLoai from insert statement in foreach? I work it on webform

```<code>var TheLoaiIds = lbxTheLoai.GetSelectedIndices();

foreach (var TheLoaiId in TheLoaiIds)
{
    string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}
</code>```

Sorry for the awkwardness

答:
```<code>    var TheLoaiIds = lbxTheLoai.GetSelectedIndices();
    string CStr = "YourConnectionString";

    string Query = "SELECT @MaPhim = SCOPE_IDENTITY(); INSERT INTO ChiTietTL VALUES (@TheLoaiId, @MaPhim)";

    using(var conn = new SqlConnection(CStr))
    {
        foreach (var TheLoaiId in TheLoaiIds)
        {
            using(var cmd = new SqlCommand(Query, conn))
            {
                 try
                 {
                     cmd.Parameters.AddWithValue("@TheLoaiId", TheLoaiId);
                     cmd.ExecuteNonQuery();
                 }
                 catch (SqlException ex)
                 {
                     MessageBox.Show(ex.ToString());
                 }
             }
         }

}
</code>```

Body:
I'm a newbie. I use GetSelectedIndices and foreach to get each values in array.

After that, I provided those values for the insert statement. How can I get query_TheLoai from insert statement in foreach? I work it on webform

var TheLoaiIds = lbxTheLoai.GetSelectedIndices();

foreach (var TheLoaiId in TheLoaiIds)
{
    string query_TheLoai = "SELECT @MaPhim = SCOPE_IDENTITY();INSERT INTO ChiTietTL VALUES ('" + TheLoaiId + "', @MaPhim)";
}

Sorry for the awkwardness


问:
IdentityServer4: What is the Idiomatic Way to Integrate a Custom Source for Authentication and Profile Retrieval?
Let's say I have to integrate with a legacy enterprise system which maintains users. Assume this enterprise system provides a C# SDK with two methods as follows:

Authentication:
sdk.Authenticate("Region", "Username", "Password")
Note that Region is an additional parameter selected by the user at login. So I need to be able to read this custom parameter in addition to the user credentials too. (Yes login would be interactive).

Profile Retrieval:
sdk.GetProfile(UserId)

I want to use IdentityServer to generate tokens in the usual manner but use these two methods to implement custom authentication and profile retrieval.

I can see that extending the IProfileService I should be able to integrate profile retrieval and population of custom claims. However I see the following multiple extensibility points in the docs but not sure what the best way would be;

Quick Start UI's Account Controller's Login(LoginInputModel model, string button) method: I should be able to place the sdk.Authenticate("Region", "Username", "Password") logic here and just call _signInManager.SignInAsync to sign in the user. But it does not feel as if I'm directly extending IdentityServer4 to add support for another custom authentication provider.

IExtensionGrantValidator:
This answer and IdentityServer Docs explain a way to do a custom grant which I should be able to use to call sdk.Authenticate("Region", "Username", "Password"). But this would mean I'd be using a custom grant type. I need to be able to support existing grant types such as Hybrid. I see support for custom parameters via context parameter in the ValidateAsync(ExtensionGrantValidationContext context) method

IResourceOwnerPasswordValidator:
This IdentityServer doc explains how to implement a custom password validator for the Resource Owner flow. But I need to be able to support existing grant types such as Hybrid. I see support for custom parameters via context parameter in the ValidateAsync(ResourceOwnerPasswordValidationContext context) method

External Authenticators:
This IdentityServer doc explains how to add external authenticators. But I see no .AddCustom method for non-standard authenticators. I only see support for popular authenticators such as Google.

What am I missing?

答: I chose to go with the first option mentioned in the question which is: Quick Start UI's Account Controller's Login(LoginInputModel model, string button) method


问:
Layout preview not showing ActionBar overflow options
I'm having a slight issue here where the overflow options for the ActionBar are showing up in the emulator but not the layout preview. I'm currently using Android Studio v 2.1.3.

Has anyone else come across the same issue?

Layout Preview

Emulator Screenshot

答:
In your layout file, add the tools:menu attribute directly to the Toolbar widget:

```<code><androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    tools:menu="@menu/your_menu"/>
</code>```

According to the docs:

tools:menu

Intended for: Any root <View>

This attribute specifies which menu the layout preview should show in
  the app bar. The value can be one or more menu IDs, separated by
  commas (without @menu/ or any such ID prefix and without the .xml
  extension).

However, I find that it only works if:

the attribute is added directly to the Toolbar widget

the value includes the @menu/ prefix

Body:
In your layout file, add the tools:menu attribute directly to the Toolbar widget:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    tools:menu="@menu/your_menu"/>

According to the docs:

tools:menu

Intended for: Any root <View>

This attribute specifies which menu the layout preview should show in
  the app bar. The value can be one or more menu IDs, separated by
  commas (without @menu/ or any such ID prefix and without the .xml
  extension).

However, I find that it only works if:

the attribute is added directly to the Toolbar widget

the value includes the @menu/ prefix


问:
Lua json schema validator
I have been looking for over 4 days now but I havent been able to find much support on code for lua based json schema compiler. Mainly I have been dealing with

ljsonschema (https://github.com/jdesgats/ljsonschema)

rjson (https://luarocks.org/modules/romaboy/rjson)

But either of the above have not been straight forward to use.

After dealing with issues on the luarocks, I finally got ljsonschema working but the JSON syntax looks different than normal JSON structure - For ex: equals in place of semi colon, no double quotes for key names etc.

ljsonschema supports

```<code>{ type = 'object', properties = {
foo = { type = 'string' },
bar = { type = 'number' },},}
</code>```

I require :

```<code>{ "type" : "object",
"properties" : {
"foo" : { "type" : "string" },
"bar" : { "type" : "number" }}}
</code>```

With rjson there is an issue with the installation location itself. Though the installation goes fine, it is never able to find the .so file while running the lua code. Plus there is not much development support that I could find.

Please help point in the right direction, in case I am missing something.
I have the json schema & a sample json, I just need a lua code to help write a program around it.

This is to write a custom JSON Validation Plugin for Kong CE.

UPDATED:
I would like the below code to work with ljsonschema:

```<code>local jsonschema = require 'jsonschema'

 -- Note: do cache the result of schema compilation as this is a quite
 -- expensive process
 local myvalidator = jsonschema.generate_validator{
   "type" : "object",
   "properties" : {
   "foo" : { "type" : "string" },
   "bar" : { "type" : "number" }
 }
}

print(myvalidator { "foo":"hello", "bar":42 })
</code>```

But I get the error : '}' expected (to close '{' at line 5) near ':'

答:
it looks like the argument to generate_validator and myvalidator are lua tables, not raw json strings. You'll want to parse the json first:</p>

```<code>> jsonschema = require 'jsonschema'
> dkjson = require('dkjson')
> schema = [[
>> { "type" : "object",
>> "properties" : {
>> "foo" : { "type" : "string" },
>> "bar" : { "type" : "number" }}}
>> ]]
> s = dkjson.decode(schema)
> myvalidator = jsonschema.generate_validator(s)
>
> json = '{ "foo": "bar", "bar": 42 }'
> print(myvalidator(json))
false   wrong type: expected object, got string
> print(myvalidator(dkjson.decode(json)))
true
</code>```

Title: Lua json schema validator

Body:
I have been looking for over 4 days now but I havent been able to find much support on code for lua based json schema compiler. Mainly I have been dealing with

ljsonschema (https://github.com/jdesgats/ljsonschema)

rjson (https://luarocks.org/modules/romaboy/rjson)

But either of the above have not been straight forward to use.

After dealing with issues on the luarocks, I finally got ljsonschema working but the JSON syntax looks different than normal JSON structure - For ex: equals in place of semi colon, no double quotes for key names etc.

ljsonschema supports

{ type = 'object', properties = {
foo = { type = 'string' },
bar = { type = 'number' },},}

I require :

{ "type" : "object",
"properties" : {
"foo" : { "type" : "string" },
"bar" : { "type" : "number" }}}

With rjson there is an issue with the installation location itself. Though the installation goes fine, it is never able to find the .so file while running the lua code. Plus there is not much development support that I could find.

Please help point in the right direction, in case I am missing something.
I have the json schema & a sample json, I just need a lua code to help write a program around it.

This is to write a custom JSON Validation Plugin for Kong CE.

UPDATED:
I would like the below code to work with ljsonschema:

local jsonschema = require 'jsonschema'

 -- Note: do cache the result of schema compilation as this is a quite
 -- expensive process
 local myvalidator = jsonschema.generate_validator{
   "type" : "object",
   "properties" : {
   "foo" : { "type" : "string" },
   "bar" : { "type" : "number" }
 }
}

print(myvalidator { "foo":"hello", "bar":42 })

But I get the error : '}' expected (to close '{' at line 5) near ':'

Body:
it looks like the argument to generate_validator and myvalidator are lua tables, not raw json strings. You'll want to parse the json first:

> jsonschema = require 'jsonschema'
> dkjson = require('dkjson')
> schema = [[
>> { "type" : "object",
>> "properties" : {
>> "foo" : { "type" : "string" },
>> "bar" : { "type" : "number" }}}
>> ]]
> s = dkjson.decode(schema)
> myvalidator = jsonschema.generate_validator(s)
>
> json = '{ "foo": "bar", "bar": 42 }'
> print(myvalidator(json))
false   wrong type: expected object, got string
> print(myvalidator(dkjson.decode(json)))
true


问:
Meaning of constructor with multiple pairs of parentheses
I'm not sure about this piece of code:

someClass(std::list<std::function<void(std::vector<someType>&)>>(&)(const std::vector<someType>&)) {
    ...
}
```

The constructor for someClass, I believe, takes a reference to a list of functions, each of which will return void and take a reference to a vector of someType.
What I'm not sure about is the last pair of parentheses, (const std::vector<someType>&). Is operator() of std::list being overloaded here?

In addition, I'd like to name the std::list parameter, but my initial guess of someClass(std::list<...>(& nameOfList)(...)) did not work, as I cannot access nameOfList.begin(), for example. What would I do here?

Thank you.

答:
The parameter of the constructor

```<code>someClass( std::list<std::function<void(std::vector<someType>&)>>(&)(const std::vector<someType>&)) {
</code>```

is a reference to a function that has the return type std::list<std::function<void(std::vector<someType>&)>> and one parameter of the type const std::vector<someType>&

Body:
I'm not sure about this piece of code:

someClass(std::list<std::function<void(std::vector<someType>&)>>(&)(const std::vector<someType>&)) {
    ...
}

The constructor for someClass, I believe, takes a reference to a list of functions, each of which will return void and take a reference to a vector of someType.
What I'm not sure about is the last pair of parentheses, (const std::vector<someType>&). Is operator() of std::list being overloaded here?

In addition, I'd like to name the std::list parameter, but my initial guess of someClass(std::list<...>(& nameOfList)(...)) did not work, as I cannot access nameOfList.begin(), for example. What would I do here?

Thank you.

Body:
The parameter of the constructor

someClass( std::list<std::function<void(std::vector<someType>&)>>(&)(const std::vector<someType>&)) {

is a reference to a function that has the return type std::list<std::function<void(std::vector<someType>&)>> and one parameter of the type const std::vector<someType>&


问:
Nodejs - Create modules from string with the npm package 'module'
I want to load a custom module using the npm package 'module', to be able to require it like any other local folder that exports something.

I cannot find any documentation on the use of the package https://www.npmjs.com/package/module

I tried to use it without any documentation on it, but i simply cannot as i dont understand how you use it.

```<code>    let myFunction = module.wrap(`module.exports = () => console.log("hej")`);```
```

答:
Honestly, I've never read documentation about this but I've been using Node.js for years so I'll explain how I import modules. Given a project that has the files app.js and mod1.js and the subfolder utils with the file mod2.js, you could do something like this:

prj/mod1.js

```<code>    module.exports = {
        test: "testing"
    }
</code>```

prj/utils/mod2.js

```<code>    module.exports = () => {
        console.log("testing");
    }
</code>```

prj/app.js

```<code>    var mod1 = require("mod1"),
        mod2 = require("utils/mod2");

    console.log(mod1.test);
    mod2();
</code>```

Body:
I want to load a custom module using the npm package 'module', to be able to require it like any other local folder that exports something.

I cannot find any documentation on the use of the package https://www.npmjs.com/package/module

I tried to use it without any documentation on it, but i simply cannot as i dont understand how you use it.

    let myFunction = module.wrap(`module.exports = () => console.log("hej")`);```

Body:
Honestly, I've never read documentation about this but I've been using Node.js for years so I'll explain how I import modules. Given a project that has the files app.js and mod1.js and the subfolder utils with the file mod2.js, you could do something like this:

prj/mod1.js

    module.exports = {
        test: "testing"
    }

prj/utils/mod2.js

    module.exports = () => {
        console.log("testing");
    }

prj/app.js

    var mod1 = require("mod1"),
        mod2 = require("utils/mod2");

    console.log(mod1.test);
    mod2();


问:
ScalaTest can't verify mock function invocations inside Future
I'm trying to use Scala's Future together with ScalaTest and Mockito, but with a very simple test case, I'm not able to verify any of the invocations on a mocked function inside the Future.

```<code>import org.mockito.Mockito.{timeout, verify}
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class FutureTest extends FunSpec with MockitoSugar {
  it("future test") {
    val mockFunction = mock[() => Unit]

    Future {
      mockFunction()
    }

    verify(mockFunction, timeout(1000)).apply()
  }
}
</code>```

This fails everytime with the following error:

```<code>Wanted but not invoked:
function0.apply$mcV$sp();
-> at test.FutureTest.$anonfun$new$1(FutureTest.scala:18)

However, there was exactly 1 interaction with this mock:
function0.apply();
-> at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:658)
</code>```

I have tested that it works without the Future.

Most surprising to me is that if I include a print statement inside the Future block as well, it succeeds every time, as such:

```<code>Future {
  mockFunction()
  println("test")
}
</code>```

Any idea of what the issue is and why print statement matters here?

I'm using:

Scala 2.12.8

scalatest_2.12 3.0.5

mockito 2.27.0

running the tests inside IntelliJ 2019.1.3 with Scala plugin 2019.1.8

答:
The error indicates apply$mcV$sp() is not being invoked, so let's try comparing the output of -Xprint:jvm in both cases respectively to see where it is called:

Given

```<code>Future {
  mockFunction()
  println("test")
}
</code>```

the output of -Xprint:jvm is

```<code>    final <static> <artifact> def $anonfun$new$2(mockFunction$1: Function0): Unit = {
      mockFunction$1.apply$mcV$sp();
      scala.Predef.println("test")
    };
    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.apply({
        $anonfun(mockFunction)
      }, scala.concurrent.ExecutionContext$Implicits.global());
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };
</code>```

whilst having

```<code>Future {
  mockFunction()
}
</code>```

the output of -Xprint:jvm is

```<code>    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.apply(mockFunction, scala.concurrent.ExecutionContext$Implicits.global());
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };
</code>```

Note the difference in how mockFunction gets invoked

```<code>Future.apply({$anonfun(mockFunction) ...
Future.apply(mockFunction ...
</code>```

In the first case it passed as argument to $anonfun which indeed invokes apply$mcV$sp() like so:

```<code>mockFunction$1.apply$mcV$sp();
</code>```

whilst in the second case invocation of apply$mcV$sp() is nowhere to be found.

Using Future.successful { mockFunction() } seems to make it work, and we see apply$mcV$sp() being invoked as required

```<code>    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.successful({
        mockFunction.apply$mcV$sp();
        scala.runtime.BoxedUnit.UNIT
      });
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };
</code>```

Where does apply$mcV$sp come from in the first place? Examining Function0

```<code>trait Function0[@specialized(Specializable.Primitives) +R] extends AnyRef { self =>
  def apply(): R
  override def toString() = "<function0>"
}
</code>```

we see @specialized(Specializable.Primitives) which results in

```<code>  abstract trait Function0 extends Object { self: example.Fun =>
    def apply(): Object;
    override def toString(): String = "<function0>";
    <specialized> def apply$mcZ$sp(): Boolean = scala.Boolean.unbox(Fun.this.apply());
    <specialized> def apply$mcB$sp(): Byte = scala.Byte.unbox(Fun.this.apply());
    <specialized> def apply$mcC$sp(): Char = scala.Char.unbox(Fun.this.apply());
    <specialized> def apply$mcD$sp(): Double = scala.Double.unbox(Fun.this.apply());
    <specialized> def apply$mcF$sp(): Float = scala.Float.unbox(Fun.this.apply());
    <specialized> def apply$mcI$sp(): Int = scala.Int.unbox(Fun.this.apply());
    <specialized> def apply$mcJ$sp(): Long = scala.Long.unbox(Fun.this.apply());
    <specialized> def apply$mcS$sp(): Short = scala.Short.unbox(Fun.this.apply());
    <specialized> def apply$mcV$sp(): Unit = {
      Function0.this.apply();
      ()
    };
    def /*Fun*/$init$(): Unit = {
      ()
    }
  };
</code>```

where we see apply$mcV$sp in turn calls actual apply

```<code><specialized> def apply$mcV$sp(): Unit = {
  Function0.this.apply();
  ()
};
</code>```

These seem to be some of the pieces of the problem, however I do not have sufficient knowledge to put them together. To my mind Future(mockFunction()) should work just fine, so we need someone more knowledgeable to explain it. Until then, try Future.successful as a workaround.

Body:
I'm trying to use Scala's Future together with ScalaTest and Mockito, but with a very simple test case, I'm not able to verify any of the invocations on a mocked function inside the Future.

import org.mockito.Mockito.{timeout, verify}
import org.scalatest.FunSpec
import org.scalatest.mockito.MockitoSugar

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class FutureTest extends FunSpec with MockitoSugar {
  it("future test") {
    val mockFunction = mock[() => Unit]

    Future {
      mockFunction()
    }

    verify(mockFunction, timeout(1000)).apply()
  }
}

This fails everytime with the following error:

Wanted but not invoked:
function0.apply$mcV$sp();
-> at test.FutureTest.$anonfun$new$1(FutureTest.scala:18)

However, there was exactly 1 interaction with this mock:
function0.apply();
-> at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:658)

I have tested that it works without the Future.

Most surprising to me is that if I include a print statement inside the Future block as well, it succeeds every time, as such:

Future {
  mockFunction()
  println("test")
}

Any idea of what the issue is and why print statement matters here?

I'm using:

Scala 2.12.8

scalatest_2.12 3.0.5

mockito 2.27.0

running the tests inside IntelliJ 2019.1.3 with Scala plugin 2019.1.8

Body:
The error indicates apply$mcV$sp() is not being invoked, so let's try comparing the output of -Xprint:jvm in both cases respectively to see where it is called:

Given

Future {
  mockFunction()
  println("test")
}

the output of -Xprint:jvm is

    final <static> <artifact> def $anonfun$new$2(mockFunction$1: Function0): Unit = {
      mockFunction$1.apply$mcV$sp();
      scala.Predef.println("test")
    };
    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.apply({
        $anonfun(mockFunction)
      }, scala.concurrent.ExecutionContext$Implicits.global());
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };

whilst having

Future {
  mockFunction()
}

the output of -Xprint:jvm is

    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.apply(mockFunction, scala.concurrent.ExecutionContext$Implicits.global());
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };

Note the difference in how mockFunction gets invoked

Future.apply({$anonfun(mockFunction) ...
Future.apply(mockFunction ...

In the first case it passed as argument to $anonfun which indeed invokes apply$mcV$sp() like so:

mockFunction$1.apply$mcV$sp();

whilst in the second case invocation of apply$mcV$sp() is nowhere to be found.

Using Future.successful { mockFunction() } seems to make it work, and we see apply$mcV$sp() being invoked as required

    final <static> <artifact> def $anonfun$new$1($this: FutureTest): Unit = {
      val mockFunction: Function0 = $this.mock((ClassTag.apply(classOf[scala.Function0]): scala.reflect.ClassTag)).$asInstanceOf[Function0]();
      scala.concurrent.Future.successful({
        mockFunction.apply$mcV$sp();
        scala.runtime.BoxedUnit.UNIT
      });
      org.mockito.Mockito.verify(mockFunction, org.mockito.Mockito.timeout(1000L)).$asInstanceOf[Function0]().apply$mcV$sp()
    };

Where does apply$mcV$sp come from in the first place? Examining Function0

trait Function0[@specialized(Specializable.Primitives) +R] extends AnyRef { self =>
  def apply(): R
  override def toString() = "<function0>"
}

we see @specialized(Specializable.Primitives) which results in

  abstract trait Function0 extends Object { self: example.Fun =>
    def apply(): Object;
    override def toString(): String = "<function0>";
    <specialized> def apply$mcZ$sp(): Boolean = scala.Boolean.unbox(Fun.this.apply());
    <specialized> def apply$mcB$sp(): Byte = scala.Byte.unbox(Fun.this.apply());
    <specialized> def apply$mcC$sp(): Char = scala.Char.unbox(Fun.this.apply());
    <specialized> def apply$mcD$sp(): Double = scala.Double.unbox(Fun.this.apply());
    <specialized> def apply$mcF$sp(): Float = scala.Float.unbox(Fun.this.apply());
    <specialized> def apply$mcI$sp(): Int = scala.Int.unbox(Fun.this.apply());
    <specialized> def apply$mcJ$sp(): Long = scala.Long.unbox(Fun.this.apply());
    <specialized> def apply$mcS$sp(): Short = scala.Short.unbox(Fun.this.apply());
    <specialized> def apply$mcV$sp(): Unit = {
      Function0.this.apply();
      ()
    };
    def /*Fun*/$init$(): Unit = {
      ()
    }
  };

where we see apply$mcV$sp in turn calls actual apply

<specialized> def apply$mcV$sp(): Unit = {
  Function0.this.apply();
  ()
};

These seem to be some of the pieces of the problem, however I do not have sufficient knowledge to put them together. To my mind Future(mockFunction()) should work just fine, so we need someone more knowledgeable to explain it. Until then, try Future.successful as a workaround.


问:
Can't stop form closing when background worker is in progress
I have a form with a background worker in a c# winforms application (Visual Studio 2010, .net 4). When the background worker is busy I would like to warn the user aboout it when tries to close the form and cancel form closing. I'd like to handle it in form closing event by setting form close cancellation to true.

BUT it still closes the form!

Here is the code snippet I use:

```<code>private void FormDrivenDistance_FormClosing(object sender, FormClosingEventArgs e)
{
  if (myBackgroundWorker.IsBusy)
  {
     Messenger.ShowCriticalMessage("Don't close, in progress!");
                    e.Cancel = true;
  }
}
</code>```

Where is the bug?!

Thanks in advance!

答:
What if you move e.Cancel before your message?

Note that if you're trying to prevent the race condition and stop the InvalidOperationException caused when the form closes before the worker completes, it doesn't 100% do so; you might close it in the interval between the completion itself (InProgress is now false) and the callback (OnWorkerCompleted).  You still need to handle the exception either way.

Since you have to handle it either way, you may as well just let the user close the form.  It's a nuisance for the user to have to wait for something to complete that they don't care about.

Body:
I have a form with a background worker in a c# winforms application (Visual Studio 2010, .net 4). When the background worker is busy I would like to warn the user aboout it when tries to close the form and cancel form closing. I'd like to handle it in form closing event by setting form close cancellation to true.

BUT it still closes the form!

Here is the code snippet I use:

private void FormDrivenDistance_FormClosing(object sender, FormClosingEventArgs e)
{
  if (myBackgroundWorker.IsBusy)
  {
     Messenger.ShowCriticalMessage("Don't close, in progress!");
                    e.Cancel = true;
  }
}

Where is the bug?!

Thanks in advance!


问:
ASP.NET Webservice
I may be going at this from the wrong direction. I'm fairly new to .net web services and was looking for a little help.

I have a geolocation webservice I got online and I wanted to bind the results to a listbox or a dataview but am unable too.

I've created a web proxy called net.webservicex.www that points to the webservice at.. http://www.webservicex.net/geoipservice.asmx

Here's my c# code.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace web_services
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService(); // proxy object
            string ipAddress, result;

            ipAddress = txtIpAddress.Text;

            result = myProxy.GetGeoIP("64.106.166.130");
            lstResults.DataSource = result;
            lstResults.DataMember = "IP";

        }
    }
}
</code>```

The error I'm recieving is Error

Cannot implicitly convert type 'web_services.net.webservicex.www.GeoIP' to 'string' at line 24

If someone could give me some tips or idea's that would be great.

Thanks!
Paul

答:
[WebMethod]
        public double ProcitajKursNaDan(DateTime datum, string valuta) {
            List<string> podaci = GetLines("valute.txt");

            double kurs = 0.0;

            for (int i = 0; i < podaci.Count; i++) {
                string[] linija = podaci[i].Split('|');

                string dat = linija[0];
                string val = linija[1];
                string vrednost = linija[2];

                dat = dat.Trim();
                val = val.Trim();
                vrednost = vrednost.Trim();

                DateTime datIzFajla = DateTime.ParseExact(dat, "d/M/yyyy", null);

                double kursIzFajla = Convert.ToDouble(vrednost);

                if (DateTime.Compare(datIzFajla, datum) == 0 && val == valuta)
                    kurs = kursIzFajla;
            }

            return kurs;
        }

        [WebMethod]
        public bool UpisiKursNaDan(DateTime datum, string valuta, double Kurs) {
            string date = datum.ToString("d/M/yyyy");
            string linijaZaUpis = date + " | " + valuta + " | " + Kurs.ToString();

            bool success = false;

            try
            {
                StreamWriter sw = new StreamWriter(Server.MapPath("podaci/valute.txt"), true);
                sw.WriteLine(linijaZaUpis);
                sw.Close();

                success = true;
            }
            catch {
                success = false;
            }
            return success;
        }

        [WebMethod]
        public List<string> ProcitajSveValute() {
            List<string> linije = GetLines("valute.txt");

            List<string> ValuteIzFajla = new List<string>();

            for (int i = 0; i < linije.Count; i++) {
                string linija = linije[i];
                string valuta = linija.Split('|')[1];
                valuta = valuta.Trim();
                ValuteIzFajla.Add(valuta);
            }

            List<string> ValuteKraj = ValuteIzFajla.Distinct().ToList();
            return ValuteKraj;
             //        try
    //        {
    //            if (!IsPostBack)
    //            {
    //                Service1 servis = new Service1();
    //                List<string> lista = servis.ProcitajSveValute().ToList<string>();
    //                for (int i = 0; i < lista.Count(); i++)
    //                {
    //                    DropDownList1.Items.Add(lista[i]);
    //                }

    //            }
    //        }
    //        catch (Exception ex)
    //        {
    //            Response.Write(ex.Message);
    //        }
    //    }

    //    protected void Button1_Click(object sender, EventArgs e)
    //    {
    //        try
    //        {
    //            Service1 servis = new Service1();
    //            DateTime datum = Calendar1.SelectedDate;
    //            string valuta = DropDownList1.SelectedItem.ToString();
    //            double kurs = Convert.ToDouble(TextBox1.Text);
    //            bool nesto = servis.UpisiKursNaDan(datum, valuta, kurs);
    //        }
    //        catch (Exception ex)
    //        {
    //            Response.Write(ex.Message);
    //        }
    //        TextBox1.Text = " ";
        }
    }
}
        //    try
        //    {
        //        if (!IsPostBack)
        //        {
        //            Service1 servis = new Service1();
        //            List<string> lista = servis.ProcitajSveValute().ToList<string>();
        //            for (int i = 0; i < lista.Count(); i++)
        //            {
        //                DropDownList1.Items.Add(lista[i]);
        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Response.Write(ex.Message);
        //    }
        //}

        //protected void Button1_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Service1 servis = new Service1();
        //        DateTime datum = Calendar1.SelectedDate;
        //        string valuta = DropDownList1.SelectedItem.ToString();
        //        double kurs = servis.ProcitajKursNaDan(datum, valuta);
        //        Label1.Text = kurs.ToString();
        //        if (kurs == 0)
        //        {
        //            Label1.Text = "Ne postoji kursna lista za tu valutu na taj datum!";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Response.Write(ex.Message);
        //    }
        //}```

Title: ASP.NET Webservice

Body:
I may be going at this from the wrong direction. I'm fairly new to .net web services and was looking for a little help.

I have a geolocation webservice I got online and I wanted to bind the results to a listbox or a dataview but am unable too.

I've created a web proxy called net.webservicex.www that points to the webservice at.. http://www.webservicex.net/geoipservice.asmx

Here's my c# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace web_services
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            net.webservicex.www.GeoIPService myProxy = new net.webservicex.www.GeoIPService(); // proxy object
            string ipAddress, result;

            ipAddress = txtIpAddress.Text;

            result = myProxy.GetGeoIP("64.106.166.130");
            lstResults.DataSource = result;
            lstResults.DataMember = "IP";

        }
    }
}

The error I'm recieving is Error

Cannot implicitly convert type 'web_services.net.webservicex.www.GeoIP' to 'string' at line 24

If someone could give me some tips or idea's that would be great.

Thanks!
Paul


答:
It is a function by itself.

```<code>std::list<
         std::function<
            void(std::vector<someType>&)
         >
> (&)(const std::vector<someType>&)
</code>```

This is a reference to a function that takes as an argument a reference to const std::vector of someType and returns a list of std::functions that take a reference to a std::vector of someType and return void.

Usage example:

```<code>#include <vector>
#include <list>
#include <functional>
class someType {};
void func(std::list<std::function<void(std::vector<someType>&)>> (& par)(const std::vector<someType>&)) {
    // some input
    const std::vector<someType> input;
    // the function returns the list
    std::list<std::function<void(std::vector<someType>&)>> res = par(input);
    // we can iterate over the list
    for (auto & i : res) {
        std::vector<someType> other;
        // and call the functions inside
        i(other);
    }
}
</code>```

Title: Meaning of constructor with multiple pairs of parentheses

Body:
It is a function by itself.

std::list<
         std::function<
            void(std::vector<someType>&)
         >
> (&)(const std::vector<someType>&)

This is a reference to a function that takes as an argument a reference to const std::vector of someType and returns a list of std::functions that take a reference to a std::vector of someType and return void.

Usage example:

#include <vector>
#include <list>
#include <functional>
class someType {};
void func(std::list<std::function<void(std::vector<someType>&)>> (& par)(const std::vector<someType>&)) {
    // some input
    const std::vector<someType> input;
    // the function returns the list
    std::list<std::function<void(std::vector<someType>&)>> res = par(input);
    // we can iterate over the list
    for (auto & i : res) {
        std::vector<someType> other;
        // and call the functions inside
        i(other);
    }
}


答:
This is the way I would do it, using LEAD. You can use LEAD to check if the next StartDate has the same value as the current EndDate. If it does I return 0, and if not 1, and provided the SUM of those values is 0, we know all the dates were continuous:

```<code>WITH CTE AS(
    SELECT ID,
           StartDate,
           EndDate,
           CASE LEAD(StartDate,1, EndDate) OVER (PARTITION BY ID ORDER BY StartDate) WHEN EndDate THEN 0 ELSE 1 END AS IsContinous
    FROM (VALUES(222,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-16')),
                (222,CONVERT(date,'2019-04-16'),CONVERT(date,'2019-04-30')),
                (562,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-08')),
                (562,CONVERT(date,'2019-04-08'),CONVERT(date,'2019-04-15')),
                (562,CONVERT(date,'2019-04-15'),CONVERT(date,'2019-04-22')),
                (562,CONVERT(date,'2019-04-22'),CONVERT(date,'2019-04-29')),
                (228,CONVERT(date,'2019-04-02'),CONVERT(date,'2019-04-09')),
                (228,CONVERT(date,'2019-04-10'),CONVERT(date,'2019-04-16')),
                (228,CONVERT(date,'2019-04-15'),CONVERT(date,'2019-04-23')),
                (228,CONVERT(date,'2019-04-26'),CONVERT(date,'2019-04-30')),
                (228,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-16'))) V (ID, StartDate, EndDate))
SELECT ID,
       MIN(StartDate) AS StartDate,
       MAX(EndDate) AS EndDate
FROM CTE
GROUP BY ID
HAVING SUM(IsContinous) = 0;
</code>```

Title: How to get StartDate and EndDate by comparing multiple rows and columns

Body:
I have the following data in my table:

ID     StartDate    EndDate
-------------------------------
222    2019-04-01   2019-04-16
222    2019-04-16   2019-04-30
562    2019-04-01   2019-04-08
562    2019-04-08   2019-04-15
562    2019-04-15   2019-04-22
562    2019-04-22   2019-04-29
228    2019-04-02   2019-04-09
228    2019-04-10   2019-04-16
228    2019-04-15   2019-04-23
228    2019-04-26   2019-04-30
228    2019-04-01   2019-04-16

The condition is if Enddate = StartDate, then it has to check their StartDate and EndDate and the expected output as below:

ID      StartDate       EndDate
-----------------------------------
222     2019-04-01      2019-04-30
562     2019-04-01      2019-04-29

Body:
This is the way I would do it, using LEAD. You can use LEAD to check if the next StartDate has the same value as the current EndDate. If it does I return 0, and if not 1, and provided the SUM of those values is 0, we know all the dates were continuous:

WITH CTE AS(
    SELECT ID,
           StartDate,
           EndDate,
           CASE LEAD(StartDate,1, EndDate) OVER (PARTITION BY ID ORDER BY StartDate) WHEN EndDate THEN 0 ELSE 1 END AS IsContinous
    FROM (VALUES(222,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-16')),
                (222,CONVERT(date,'2019-04-16'),CONVERT(date,'2019-04-30')),
                (562,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-08')),
                (562,CONVERT(date,'2019-04-08'),CONVERT(date,'2019-04-15')),
                (562,CONVERT(date,'2019-04-15'),CONVERT(date,'2019-04-22')),
                (562,CONVERT(date,'2019-04-22'),CONVERT(date,'2019-04-29')),
                (228,CONVERT(date,'2019-04-02'),CONVERT(date,'2019-04-09')),
                (228,CONVERT(date,'2019-04-10'),CONVERT(date,'2019-04-16')),
                (228,CONVERT(date,'2019-04-15'),CONVERT(date,'2019-04-23')),
                (228,CONVERT(date,'2019-04-26'),CONVERT(date,'2019-04-30')),
                (228,CONVERT(date,'2019-04-01'),CONVERT(date,'2019-04-16'))) V (ID, StartDate, EndDate))
SELECT ID,
       MIN(StartDate) AS StartDate,
       MAX(EndDate) AS EndDate
FROM CTE
GROUP BY ID
HAVING SUM(IsContinous) = 0;


问:
php - Insert data from checkbox array into MySQL
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

```<code><div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
</code>```

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

```<code>
    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}</p>

<p>// The above to create a comma separated string</p>

<p>$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma</p>

<p>$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
```

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

```<code>
if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]<br />";
}
}
```

答:
I think you should be looking at implode and you can easily add addition strings to it...

so e.g.

```<code>$comma_seperated = implode(',', $boxes);

$subscribed = $regid . ',' .  $comma_seperated;
</code>```

Body:
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

<input type="checkbox" class="psc" name="camps[]" value="psc_1"/>AM - Week 1: Camp Description

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}

// The above to create a comma separated string

$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma

$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]
";
}
}

Body:
I think you should be looking at implode and you can easily add addition strings to it...

so e.g.

$comma_seperated = implode(',', $boxes);

$subscribed = $regid . ',' .  $comma_seperated;


问:
Linker command failed with exit code 1 - duplicate symbol __TMRbBp
Since I've updated to Xcode 8.1 I can't archive and also not run in Release mode (in debug mode its working). The error is that there are several "duplicate symbols for architecture arm64" and all are "duplicate symbol __TMRbBp". Whats that?</p>

答: I had removed files from Compile Sources in Build Phases in Targets. I added main.m and it worked.


问:
How to use MongoDB built-in access control in Flask?
I have a Flask application that uses pymongo to access a mongo database and satisfy users' requests.
I have enabled access control in Mongo and now there are several users associated with different roles. More specifically, each user has read-write privileges only in a specific subset of collections in the db.

I would like to have users logging into the application and having access only to their specific subset of collections. This means that each user request that needs to fetch some data from the db is binded to a (specific) db-authenticated connection.

The main extensions of flask like flask-login and flask-security do not seem to use MongoDB own authentication mechanism.

Have been looking for a while now but I was not able to solve this.

答:
You might want to reconsider that approach as opening a new db connection with each user that logs into your app might not scale very well, since Mongo creates a new thread for each new connection.

See: mongodb-max-connections

I would consider some RBAC for flask like flask-security.


问:
v<int>pos(MAX) v<int> tmp Which is of non-class type ‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type {aka int}’ pos[i].push_back(tmp);
C++ (STL):

```<code>Request for member ‘push_back’ in ‘pos.std::vector<int>::operator[](((std::vector<int>::size_type)i))’, which is of non-class type ‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type {aka int}’
   pos[i].push_back(tmp);
vector<int> pos(MAX), vector<int> tmp;
</code>```

I can't figure out why my code is getting wrong.
So, Please tell, why is this error coming

Goal: I can't give the whole code as i faced the problem now only while coding a solution to a part of a code in a running contest. So, Please
just tell me about this error. Then, my all other parts of code will work fine.

MY CODE:

```<code>/*
 Name: SUSHANT OBEROI
 College: MNNIT ALLAHABAD
 Email: sushantoberoi3@gmail.com
 Handle: soc3
*/

#include<bits/stdc++.h>
using namespace std;

#define sd(a) scanf("%d", &a)
#define slld(a) scanf("%lld", &a)
#define fl(i, a, b) for(int i=a; i<b; i++)
#define fle(i, a, b) for(int i=a; i<=b; i++)
#define ll long long
#define wl(q) while(q--)
#define MAX 300005
#define mp make_pair
#define fi first
#define se second
#define mod 1000000007

void print_output() {
    vector<int> pos(MAX);
    fl(i, 0, 100) {
        pos[i].clear();
        vector<int> tmp;
        fl(j, 0, 100)
            tmp.push_back(j);
        pos[i].push_back(tmp);
    }
}

int main() {
    print_output();
    return 0;
}
</code>```

I think (according to me only, i don't what's the correct answer is?)
that i am doing it correctly but compiler is wrong. (Sorry for saying this, but i think).

答:
You've defined vector<int> pos(MAX); which is a vector of int. The expression pos[i] returns a reference to an element of the vector, which in this case is an int. The statement pos[i].push_back(tmp); tries to call a push_back() member function on an int, which is not a class and does not have that member function.

Perhaps you meant to create a vector<vector<int>> pos(MAX);, a vector of vectors. I don't know and after seeing #include<bits/stdc++.h> and those #define lines I'm not interested in the rest of the code.

Body:
C++ (STL):

Request for member ‘push_back’ in ‘pos.std::vector<int>::operator[](((std::vector<int>::size_type)i))’, which is of non-class type ‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type {aka int}’
   pos[i].push_back(tmp);
vector<int> pos(MAX), vector<int> tmp;

I can't figure out why my code is getting wrong.
So, Please tell, why is this error coming

Goal: I can't give the whole code as i faced the problem now only while coding a solution to a part of a code in a running contest. So, Please
just tell me about this error. Then, my all other parts of code will work fine.

MY CODE:

/*
 Name: SUSHANT OBEROI
 College: MNNIT ALLAHABAD
 Email: sushantoberoi3@gmail.com
 Handle: soc3
*/

#include<bits/stdc++.h>
using namespace std;

#define sd(a) scanf("%d", &a)
#define slld(a) scanf("%lld", &a)
#define fl(i, a, b) for(int i=a; i<b; i++)
#define fle(i, a, b) for(int i=a; i<=b; i++)
#define ll long long
#define wl(q) while(q--)
#define MAX 300005
#define mp make_pair
#define fi first
#define se second
#define mod 1000000007

void print_output() {
    vector<int> pos(MAX);
    fl(i, 0, 100) {
        pos[i].clear();
        vector<int> tmp;
        fl(j, 0, 100)
            tmp.push_back(j);
        pos[i].push_back(tmp);
    }
}

int main() {
    print_output();
    return 0;
}

I think (according to me only, i don't what's the correct answer is?)
that i am doing it correctly but compiler is wrong. (Sorry for saying this, but i think).


问:
Leaked Window but want to finish activity when user click on positive button
I already read this: Activity has leaked window that was originally added
and some other post also.

This is the exception line: E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.(ViewRootImpl.java:534!isEditReminder)
    {

Exception:

```<code>E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.<init>(ViewRootImpl.java:534!isEditReminder)
    {
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
       message at= android.view.WindowManagerImplgetResources().addViewgetString(WindowManagerImplR.java:94string.reminder_added_successfully);
        at android.app.Dialog.show(Dialog.java:329)
} else {
      at android.app.AlertDialog$Builder.show(AlertDialog.java:1125)
       message at= com.tekitsolutions.remindme.Activity.AddReminderActivitygetResources().saveMessagegetString(AddReminderActivityR.java:1179string.reminder_update_successfully);
        at com.tekitsolutions.remindme.Activity.AddReminderActivity.onResponse(AddReminderActivity.java:1547)
   reminderId = tempReminderId;
   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
        atnew android.os.Handler.handleCallbackAlarmReceiver(Handler).java:873cancelAlarm(this, reminderId);
        at android.os.Handler.dispatchMessage(Handler.java:99)}

        at androidandroidx.osappcompat.Looperapp.loop(LooperAlertDialog.java:201)
     Builder alertDialogBuilder = atnew androidandroidx.appcompat.app.Activit
</code>```

My code:

```<code>private void saveMessage() {
        String message = "";
        if (!isEditReminder) {
            message = getResources().getString(R.string.reminder_added_successfully);
        } else {
            message = getResources().getString(R.string.reminder_update_successfully);
            reminderId = tempReminderId;
            new AlarmReceiver().cancelAlarm(this, reminderId);
        }

        androidx.appcompat.app.AlertDialog.Builder alertDialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(this, R.style.dialogBoxStyle);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("").setMessage(message).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = getIntent();
                showLog("ARA: "+ reminderId);
                intent.putExtra(REMINDER_ID, reminderId);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        androidx.appcompat.app.AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();

    }
</code>```

答:
```<code> @Override
    public void onBackPressed() {
       if (!etTitle.getText().toString().isEmpty()) {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setCancelable(false);
           builder.setMessage("Do you want to save Reminder?");
           builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //if user pressed "yes", then he is allowed to exit from application
                finish();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //if user select "No", just cancel this dialog and continue with app
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
      }
    }
</code>```

Please try it.
I hope it'll help you...!

Body:
I already read this: Activity has leaked window that was originally added
and some other post also.

This is the exception line: E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.(ViewRootImpl.java:534!isEditReminder)
    {

Exception:

E/WindowManager:private android.view.WindowLeaked:void ActivitysaveMessage() com.tekitsolutions.remindme.Activity.AddReminderActivity{
 has leaked window DecorView@87ebe2a[AddReminderActivity] that was originally addedString heremessage = "";
        atif android.view.ViewRootImpl.<init>(ViewRootImpl.java:534!isEditReminder)
    {
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
       message at= android.view.WindowManagerImplgetResources().addViewgetString(WindowManagerImplR.java:94string.reminder_added_successfully);
        at android.app.Dialog.show(Dialog.java:329)
} else {
      at android.app.AlertDialog$Builder.show(AlertDialog.java:1125)
       message at= com.tekitsolutions.remindme.Activity.AddReminderActivitygetResources().saveMessagegetString(AddReminderActivityR.java:1179string.reminder_update_successfully);
        at com.tekitsolutions.remindme.Activity.AddReminderActivity.onResponse(AddReminderActivity.java:1547)
   reminderId = tempReminderId;
   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
        atnew android.os.Handler.handleCallbackAlarmReceiver(Handler).java:873cancelAlarm(this, reminderId);
        at android.os.Handler.dispatchMessage(Handler.java:99)}

        at androidandroidx.osappcompat.Looperapp.loop(LooperAlertDialog.java:201)
     Builder alertDialogBuilder = atnew androidandroidx.appcompat.app.Activit

My code:

private void saveMessage() {
        String message = "";
        if (!isEditReminder) {
            message = getResources().getString(R.string.reminder_added_successfully);
        } else {
            message = getResources().getString(R.string.reminder_update_successfully);
            reminderId = tempReminderId;
            new AlarmReceiver().cancelAlarm(this, reminderId);
        }

        androidx.appcompat.app.AlertDialog.Builder alertDialogBuilder = new androidx.appcompat.app.AlertDialog.Builder(this, R.style.dialogBoxStyle);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setTitle("").setMessage(message).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = getIntent();
                showLog("ARA: "+ reminderId);
                intent.putExtra(REMINDER_ID, reminderId);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        androidx.appcompat.app.AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();

    }

Body:
 @Override
    public void onBackPressed() {
       if (!etTitle.getText().toString().isEmpty()) {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setCancelable(false);
           builder.setMessage("Do you want to save Reminder?");
           builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //if user pressed "yes", then he is allowed to exit from application
                finish();
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //if user select "No", just cancel this dialog and continue with app
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
      }
    }

Please try it.
I hope it'll help you...!


问:
JVM performance tuning for large applications
The default JVM parameters are not optimal for running large applications. Any insights from people who have tuned it on a real application would be helpful. We are running the application on a 32-bit windows machine, where the client JVM is used by default. We have added -server and changed the NewRatio to 1:3 (A larger young generation).

Any other parameters/tuning which you have tried and found useful?

[Update] The specific type of application I'm talking about is a server application that are rarely shutdown, taking at least -Xmx1024m. Also assume that the application is profiled already. I'm looking for general guidelines in terms of JVM performance only.

答:
This will be highly dependent on your application and the vendor and version of the JVM.  You need to be clear about what you consider to be a performance problem.  Are you concerned with certain critical sections of code? Have you profiled the app yet?  Is the JVM spending too much time garbage collecting?

I would probably start with the -verbose:gc JVM option to watch how garbage collecting is working.  Many times, the simplest fix to just increase the max heap size with -Xmx .   If you learn to interpret the -verbose:gc output, it will tell you nearly all you need to know about tuning the JVM as a whole.  But doing this alone will not magically make badly tuned code just go faster.  Most of the JVM tuning options are designed to improve the performance of the garbage collector and/or memory sizes.

For profiling, I like yourkit.com

ContentLicense: CC BY-SA 2.5


问:
Data visualization for geographical map
I am doing a dissertation on data visualization of land prices in Tanzania.

My intendants want me to use a GIS software to map the data on a map and use python code to visualize it.

My question is how can i use python to draw the maps ?

答:
If you want to perform data visualisation, you can use the python library called matplotlib

To perform the mapping of data on geographical maps using matplotlib, here are the examples which helps you to get started.

I hope this helps you.

Title: Data visualization for geographical map


问:
Process Workflow: Given key is not present in the dictionary in UiPath
I am doing UiPath level-3 Assignment 1. I have made all the workflows using Ui Studio and I am stuck in the process workflow. While I run the WFs, it says

Process WF: Given dictionary is not present.

I checked all the values and arguments and they seem correct too.

Also when I run the Process WF separately, it gets stuck for each loop and say

object reference not set to an instance of an object.

Could someone help resolving these issues? Thanks in advance.

答:
You are passing null value/trying to get value from dictionary using the key which doesn't exist. Please also remember that before using dictionary you have to create it.

It will be easier to help if you can provide status window logs at least.


问:
Setting state of Date Picker onChange
I am trying to update my two states based on the currently selected date using html date picker. The two states; startdate and enddate, none of them is getting updated onChange. Based on those updated states, I need to fetch data using those states data as query paramters. It consoles only initial state dates.

Here is the code:

```<code>import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();

    var date = new Date();

    var newdate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + (date.getDate())) ;

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  setStartDate = e => {
      this.setState({
        startdate: e.target.value
      })

      console.log(this.state.startdate, 'STARTDATE');
  }

  setEndDate = e => {
    //console.log(e.target.value)

    this.setState({
      enddate: e.target.value,
    });

    console.log(this.state.enddate, 'ENDDATE');
    axios.post('http://132.148.144.133:5000/api/v2/resources/sentiments', {
        sentiment_type: 'positive',
        startdate:this.state.startdate,
        enddate: this.state.enddate
    })
    .then( (result) => {

        console.log(result.data)
    })
    .catch(err => {
        console.log(err)
    })
  }

  render() {
    return (
      <div>
        <label>From</label>
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setStartDate}
        />

        <label>To</label>
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setEndDate}
        />
      </div>
    );
  }
}
</code>```

I have got to fetch the data as soon as the second input box gets updated with the selected date from the picker.

答: i think you should try instead of this.setStartDate , (e)=> this.setStartDate(e) and for other one too

Title: Setting state of Date Picker onChange

Body:
I am trying to update my two states based on the currently selected date using html date picker. The two states; startdate and enddate, none of them is getting updated onChange. Based on those updated states, I need to fetch data using those states data as query paramters. It consoles only initial state dates.

Here is the code:

import React, { Component } from "react";
import axios from "axios";

export default class Main extends Component {
  constructor() {
    super();

    var date = new Date();

    var newdate =
      date.getFullYear() +
      "-" +
      ("0" + (date.getMonth() + 1)) +
      "-" +
      ("0" + (date.getDate())) ;

    this.state = {
      startdate: newdate,
      enddate: newdate,
      clicked: false
    };
  }

  setStartDate = e => {
      this.setState({
        startdate: e.target.value
      })

      console.log(this.state.startdate, 'STARTDATE');
  }

  setEndDate = e => {
    //console.log(e.target.value)

    this.setState({
      enddate: e.target.value,
    });

    console.log(this.state.enddate, 'ENDDATE');
    axios.post('http://132.148.144.133:5000/api/v2/resources/sentiments', {
        sentiment_type: 'positive',
        startdate:this.state.startdate,
        enddate: this.state.enddate
    })
    .then( (result) => {

        console.log(result.data)
    })
    .catch(err => {
        console.log(err)
    })
  }

  render() {
    return (

        From
        <input
          type="date"
          name="startdate"
          value={this.state.startdate}
          onChange={this.setStartDate}
        />

        To
        <input
          type="date"
          name="enddate"
          value={this.state.enddate}
          onChange={this.setEndDate}
        />

    );
  }
}

I have got to fetch the data as soon as the second input box gets updated with the selected date from the picker.


问:
JavaScript date to firestore timestamp
I have a form with datepicker which stores the date like "1559389274032".

Is there a way to convert this to a firestore timestamp?

答:
To know about the firestore timestamp format :
https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp.html#constructor

If you have imported firebase sdk..... then you can try this:

```<code>let d=new Date(milliseconds) //pass in your milliseconds, this will return the js date object
let timestamp=firebase.firestore.Timestamp.fromDate(d)
</code>```

Title: JavaScript date to firestore timestamp

Body:
To know about the firestore timestamp format :
https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp.html#constructor

If you have imported firebase sdk..... then you can try this:

let d=new Date(milliseconds) //pass in your milliseconds, this will return the js date object
let timestamp=firebase.firestore.Timestamp.fromDate(d)


问:
CodeIgniter : Undefined variable get from __construct()
I'm working on a project. Here's my code :

Controller

```<code>public function __construct(){
  parent::__construct();

  $x = $this->input->get('x');
  $this->model->val = $this->model->checkval($x);
}

public function save(){
  // some code to input to database
  echo $this->model->val;
}
</code>```

Model

```<code>public function checkval($x){
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}
</code>```

(That's the simple version)

Message : Undefined variable: y

Filename : models/Test_model.php

I want to access save(), and it will process the $this->model->val ($this->model->val has been declared as public $val in Model). $this->model->val is get from $this->model->checkval($x) where $x is get from GET method. But, it shows this error. What did I do wrong?

答:
If $x is not equal to 1, 2, or 3 it is never defined. To prevent this you need a default value for $y which then can be changed if $x matches one of those values:

```<code>public function checkval($x){
  $y = 0; // This can be false or whatever other value makes sense for your business logic
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}
</code>```

Body:
I'm working on a project. Here's my code :

Controller

public function __construct(){
  parent::__construct();

  $x = $this->input->get('x');
  $this->model->val = $this->model->checkval($x);
}

public function save(){
  // some code to input to database
  echo $this->model->val;
}

Model

public function checkval($x){
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}

(That's the simple version)

Message : Undefined variable: y

Filename : models/Test_model.php

I want to access save(), and it will process the $this->model->val ($this->model->val has been declared as public $val in Model). $this->model->val is get from $this->model->checkval($x) where $x is get from GET method. But, it shows this error. What did I do wrong?

Body:
If $x is not equal to 1, 2, or 3 it is never defined. To prevent this you need a default value for $y which then can be changed if $x matches one of those values:

public function checkval($x){
  $y = 0; // This can be false or whatever other value makes sense for your business logic
  switch($x){
    case 1 : $y = 10; break;
    case 2 : $y = 20; break;
    case 3 : $y = 30; break;
  }
  return $y;
}


问:
Is there an accepted pattern for forms that can be used for "adding new" and "editing existing"?
I have what is surely a common issue, and that is that I want to have a reactive form that can be used to "add a new entry" or "edit an existing entry."

Right now the form is its own component, and on submit, it uses an event emitter with the new object.

The add and edit actions are separate components that use the form, and communication between them is handled with a service that has an Observable.

The above things "work" in that I can add and edit items, however there are certain issues I encounter that make me think I am missing something.

For instance, if you are adding many things, once you add the first item, how would I re-initialize the form for the next add new?  Since I am using event emitter, I never know when or if the action succeeds.

I also find it harder to handle form disabling while waiting for the action to complete.

I am thinking that having three components for this is not the right way, or maybe it is, which means how I handle the service is not correct?

答:
I supouse that the "clasic" way is using an interface and a function to create the form,e.g.

```<code>interface IData
{
   name:string;
   surname:string;
}

createForm(data:any)
{
   data = data || {} as IData;
   return new FormGroup({
       name:new FormControl(data.name,Validators.required),
       surname:new FormControl(data.surname,Validators.required),
   })
}
</code>```

So,

```<code>  this.form=this.createForm(null); //our form is an empy form
  data={name:"Name",surname:"Surname"}
  this.form=this.createForm(data); //our form is form with data
</code>```

Body:
I supouse that the "clasic" way is using an interface and a function to create the form,e.g.

interface IData
{
   name:string;
   surname:string;
}

createForm(data:any)
{
   data = data || {} as IData;
   return new FormGroup({
       name:new FormControl(data.name,Validators.required),
       surname:new FormControl(data.surname,Validators.required),
   })
}

So,

  this.form=this.createForm(null); //our form is an empy form
  data={name:"Name",surname:"Surname"}
  this.form=this.createForm(data); //our form is form with data


答:
Try something like this:

```<code>var myDate = firebase.firestore.Timestamp.fromDate(new Date());
</code>```

Where new Date() would be your timestamp constructor.

Also I'm 99% sure that you dont even need it, this should save the value as a date, just make sure you dont convert it to a string on your end.

```<code>ref.update({ created_at: new Date() })
</code>```

Title: JavaScript date to firestore timestamp

Body:
I have a form with datepicker which stores the date like "1559389274032".

Is there a way to convert this to a firestore timestamp?

Body:
Try something like this:

var myDate = firebase.firestore.Timestamp.fromDate(new Date());

Where new Date() would be your timestamp constructor.

Also I'm 99% sure that you dont even need it, this should save the value as a date, just make sure you dont convert it to a string on your end.

ref.update({ created_at: new Date() })


问:
Need C# client to connect to server with low latency bi-direction communication
I'm in the process of learning C# and just need a pointing in the right direction. I want to build a client in C# that communicates with a server running PHP/mySQL. There will need to be almost constant communication between the two. It will be for a game, so low-latency and bi-directional communication. I'm not looking for an exact how-to, but rather what method I need to use to connect the two for the fastest and most reliable connection. I have read others use XML, but that seems like it would be slower if used near-constantly, like once or more a second, but I could be totally wrong. Thanks in advance!</p>

答:
Ah, writing a game in C# as a means to get started with the language! How many have started this way.

Have you defined your client-server protocol yet? I'm not talking about TCP vs. UDP, which TomTom and Jon have discussed. I mean, what is the data stream going to look like?

Packet fragmentation is the enemy of low-latency network code. Learn about MTU and packet fragmentation, Nagle's algorithm, etc. and write down some notes for later when you implement the network code. Make sure you calculate the smallest size packet you would be interested in sending, how big its headers might be, and how large of a payload you can fit into that packet. Then see if you can come up with a protocol that uses the available space efficiently.

You may gain a lot more by optimizing your server application and/or porting it to a different language. Just because you CAN use PHP for everything server side doesn't mean you SHOULD. Keep the part that shows you useful information in a web browser, and evaluate whether you should rewrite the time-critical and game client communication parts in another language. Interpreted languages are not especially well known for their speed when crunching real-time game world data. Sure, I once wrote something like that in Perl using POE, but ultimately it was a lot less performant than the C code I was mimicking.

Finally, I would recommend you look into XNA, since it has a lot of this stuff already.