问:
gradle error The filename, directory name, or volume label syntax is incorrect
I get the below error when I try to build the war using gradle.

The stack trace is below  .

The error happens when I add a specific dependency to my war .Is there any way I can find out what is causing this issue ?

The dependency that I am trying to add has many transitive dependencies

```<code>11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed w
ith an exception.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] Failed to capture snaps
hot of output files for task 'war' during up-to-date check.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] > Could not normalize p
ath for file 'D:\\distribution\combined\build\
libs\masters:qams-1.0.0.war'.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.Unchecke
dIOException: Failed to capture snapshot of output files for task 'war' during u
p-to-date check.
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.createSnap
shotPreCheck(AbstractFileSnapshotTaskStateChanges.java:49)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.OutputFilesTaskStateChanges.saveCurrent(OutputF
ilesTaskStateChanges.java:79)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.snapshotAf
terTask(AbstractFileSnapshotTaskStateChanges.java:89)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.OutputFilesTaskStateChanges.snapshotAfterTask(O
utputFilesTaskStateChanges.java:28)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.CachingTaskStateChanges.snapshotAfterTask(Cachi
ngTaskStateChanges.java:84)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.SummaryTaskStateChanges.snapshotAfterTask(Summa
ryTaskStateChanges.java:73)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifa
ctStateImpl.afterTask(DefaultTaskArtifactStateRepository.java:134)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExec
uter.java:68)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter
.java:58)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySou
rceFilesTaskExecuter.java:52)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoA
ctionsExecuter.java:52)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter
.java:53)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOn
ceTaskExecuter.java:43)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(Default
TaskGraphExecuter.java:203)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(Default
TaskGraphExecuter.java:185)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(Abstra
ctTaskPlanExecutor.java:66)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPl
anExecutor.java:50)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.in
ternal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy
.java:54)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.in
ternal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: org.gradle.a
pi.UncheckedIOException: Could not normalize path for file 'D:\M\combined\build\libs\masters:qams-1.0.0.war'.
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.FileNormaliser.normalise(FileNormaliser.java:90)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:82)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:62)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionCo
nverter.convertInto(DefaultFileCollectionResolveContext.java:162)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(Defaul
tFileCollectionResolveContext.java:123)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCol
lections(DefaultFileCollectionResolveContext.java:81)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionCo
nverter.convertInto(DefaultFileCollectionResolveContext.java:146)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(Defaul
tFileCollectionResolveContext.java:98)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCol
lections(DefaultFileCollectionResolveContext.java:81)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.CompositeFileCollection.getSourceCollections(CompositeFileCollec
tion.java:162)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.CompositeFileCollection.getFiles(CompositeFileCollection.java:45
)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.state.OutputFilesCollectionSnapshotter.getRoots(Outpu
tFilesCollectionSnapshotter.java:71)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.state.OutputFilesCollectionSnapshotter.preCheck(Outpu
tFilesCollectionSnapshotter.java:66)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.createSnap
shotPreCheck(AbstractFileSnapshotTaskStateChanges.java:47)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        ... 18 more
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.io.IOEx
ception: The filename, directory name, or volume label syntax is incorrect
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.FileNormaliser.normalise(FileNormaliser.java:54)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        ... 31 more
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger]
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger]
</code>```

答:
This does not seem to be related to dependencies.

It more seems that you set masters:qams-1.0.0.war as name for the generated WAR file which is not a valid path on Windows as paths must not contain colons, except after the drive letter.

To point to the concrete error you need to provide your buildscript, but maybe this information is already enough for you, thus I post it as answer, not comment.

Body:
I get the below error when I try to build the war using gradle.

The stack trace is below  .

The error happens when I add a specific dependency to my war .Is there any way I can find out what is causing this issue ?

The dependency that I am trying to add has many transitive dependencies

11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed w
ith an exception.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] Failed to capture snaps
hot of output files for task 'war' during up-to-date check.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] > Could not normalize p
ath for file 'D:\\distribution\combined\build\
libs\masters:qams-1.0.0.war'.
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.507 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.Unchecke
dIOException: Failed to capture snapshot of output files for task 'war' during u
p-to-date check.
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.createSnap
shotPreCheck(AbstractFileSnapshotTaskStateChanges.java:49)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.OutputFilesTaskStateChanges.saveCurrent(OutputF
ilesTaskStateChanges.java:79)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.snapshotAf
terTask(AbstractFileSnapshotTaskStateChanges.java:89)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.OutputFilesTaskStateChanges.snapshotAfterTask(O
utputFilesTaskStateChanges.java:28)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.CachingTaskStateChanges.snapshotAfterTask(Cachi
ngTaskStateChanges.java:84)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.SummaryTaskStateChanges.snapshotAfterTask(Summa
ryTaskStateChanges.java:73)
11:29:56.508 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.changes.DefaultTaskArtifactStateRepository$TaskArtifa
ctStateImpl.afterTask(DefaultTaskArtifactStateRepository.java:134)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExec
uter.java:68)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter
.java:58)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySou
rceFilesTaskExecuter.java:52)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoA
ctionsExecuter.java:52)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter
.java:53)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOn
ceTaskExecuter.java:43)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(Default
TaskGraphExecuter.java:203)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(Default
TaskGraphExecuter.java:185)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(Abstra
ctTaskPlanExecutor.java:66)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ex
ecution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPl
anExecutor.java:50)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.in
ternal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy
.java:54)
11:29:56.509 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.in
ternal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: org.gradle.a
pi.UncheckedIOException: Could not normalize path for file 'D:\M\combined\build\libs\masters:qams-1.0.0.war'.
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.FileNormaliser.normalise(FileNormaliser.java:90)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:82)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.AbstractFileResolver.resolve(AbstractFileResolver.java:62)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionCo
nverter.convertInto(DefaultFileCollectionResolveContext.java:162)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(Defaul
tFileCollectionResolveContext.java:123)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCol
lections(DefaultFileCollectionResolveContext.java:81)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext$FileCollectionCo
nverter.convertInto(DefaultFileCollectionResolveContext.java:146)
11:29:56.510 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.doResolve(Defaul
tFileCollectionResolveContext.java:98)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.collections.DefaultFileCollectionResolveContext.resolveAsFileCol
lections(DefaultFileCollectionResolveContext.java:81)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.CompositeFileCollection.getSourceCollections(CompositeFileCollec
tion.java:162)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.CompositeFileCollection.getFiles(CompositeFileCollection.java:45
)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.state.OutputFilesCollectionSnapshotter.getRoots(Outpu
tFilesCollectionSnapshotter.java:71)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.state.OutputFilesCollectionSnapshotter.preCheck(Outpu
tFilesCollectionSnapshotter.java:66)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.changedetection.rules.AbstractFileSnapshotTaskStateChanges.createSnap
shotPreCheck(AbstractFileSnapshotTaskStateChanges.java:47)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        ... 18 more
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.io.IOEx
ception: The filename, directory name, or volume label syntax is incorrect
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        at org.gradle.ap
i.internal.file.FileNormaliser.normalise(FileNormaliser.java:54)
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]        ... 31 more
11:29:56.511 [ERROR] [org.gradle.BuildExceptionReporter]
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger]
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
11:29:56.512 [LIFECYCLE] [org.gradle.BuildResultLogger]


来源: stackexchange

问:
using vba i fetched 5000 records from db, how to loop to paste evrey 1000 records into a new worksheet?
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!</p>

```<code>Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub
</code>```

答:
Use the fields collection, since you're looping over the recordset anyway.

```<code>Do Until rs.EOF
Range("A1").Value = rs.Fields("SAP Code 1")
...
Loop
</code>```

You could use 2 indexer variables in the loop: One to go to the next sheet and one to keep track of the row loop.

```<code>Dim i as integer
Dim j as integer
Dim ws as worksheet

j = 1
i = 1
Set ws = Worksheets(j)
Do Until rs.EOF
    i = i + 1
    If i % 1000 = 0 then
        i = 1
        j = j + 1
        set ws = Worksheets(j)
    End if
    ws.range("A" & i).value = rs.Fields("SAP Code 1")
    ....
Loop
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am not sure how to loop to fetch only 1000 records and paste values in a new sheet so that as a result the workbook has 5 sheets.
Any help would be really appreciated.
Thanks!

Sub text_analysis()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim cmd As ADODB.Command
Dim NewWorkbook As Workbook
Set NewWorkbook = Workbooks.Add

Set cmd = New ADODB.Command
Set conn = New ADODB.Connection

sConnString = "Provider=SQLOLEDB;Data Source=localhost\SQLEXPRESS;" & _
              "Initial Catalog=MDM-FINAL;" & _
              "Integrated Security=SSPI;"

Set rs = New ADODB.Recordset

conn.Open sConnString
rsstring = "exec text_analysis;"
rs.Open rsstring, sConnString

NewWorkbook.Activate
Do Until rs.EOF
Worksheets("sheet1").Range("A2").CopyFromRecordset rs, MaxRows:=100000
ActiveSheet.Name = "Text Analysis"
Range("A1").Value = "SAP Code 1"
Range("B1").Value = "SAP Desc 1"
Range("C1").Value = "SAP Code 2"
Range("D1").Value = "SAP Desc 2"
Range("E1").Value = "Diff Count"
Range("F1").Value = "Diff Value"
Range("G1").Value = "Similar %"
Range("H1").Value = "Similar Partial %"
Range("I1").Value = "Similar Sort %"
Range("J1").Value = "Similar Set %"
Loop

rs.Close
conn.Close

End Sub

Body:
Use the fields collection, since you're looping over the recordset anyway.

Do Until rs.EOF
Range("A1").Value = rs.Fields("SAP Code 1")
...
Loop

You could use 2 indexer variables in the loop: One to go to the next sheet and one to keep track of the row loop.

Dim i as integer
Dim j as integer
Dim ws as worksheet

j = 1
i = 1
Set ws = Worksheets(j)
Do Until rs.EOF
    i = i + 1
    If i % 1000 = 0 then
        i = 1
        j = j + 1
        set ws = Worksheets(j)
    End if
    ws.range("A" & i).value = rs.Fields("SAP Code 1")
    ....
Loop


问:
SQL SERVER: SELECT TOP 1 entire row into "ROW" variable
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

```<code>DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)
</code>```

And I would like to do something like this, if possible:

Desired scenario:

```<code>DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once
</code>```

答:
You can do it this way:

```<code>SELECT Aux.Field1, Aux.Field2, Aux.Field3
    INTO #tmpTbl
    FROM  ( SELECT TOP 1 Field1, Field2, Field3 FROM OneTable ) Aux
</code>```

By doing this you will create #tmpTbl, if it already exists, you will have to DROP before creating it again.

Body:
I am trying to store the entire row as a result of the SELECT TOP * into a kind of "datarow" variable because later, depending on some condition, I need to insert this entire row to a temporary table.

For example, I have done below. The problem is that first I have to assign the values resulting from select top 1 * to variables and then using all these variables to insert into the temporary table, so I want to avoid this, I would like to insert the entire row of select top 1 * into the temporary table at once, see below.

Current scenario:

DECLARE @Field1 varchar(50)
DECLARE @Field2 int
DECLARE @Field3 DateTime

CREATE TABLE #tmpTbl(Field1 varchar(50),  Field2 int, Field3 DateTime)

SELECT TOP 1 @Field1 = field1, @Field2 = field2, @Field3 = field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES (@Field1, @Field2, @Field3)

And I would like to do something like this, if possible:

Desired scenario:

DECLARE @Row SOME_KIND_OF_DATA_ROW_VARIABLE

SET @Row = SELECT TOP 1 field1, field2, field3 from OneTable

// EXECUTE STORE PROCEDURE
DECLARE @ReturnValue int
EXEC @ReturnValue=MySp @Field1

IF @ReturnValue > 0
   INSERT INTO #tmpTbl (Field1, Field2, Field3)
          VALUES @Row <-- Obviously, this is incorrect, but I would like to insert the entire row at once

Body:
You can do it this way:

SELECT Aux.Field1, Aux.Field2, Aux.Field3
    INTO #tmpTbl
    FROM  ( SELECT TOP 1 Field1, Field2, Field3 FROM OneTable ) Aux

By doing this you will create #tmpTbl, if it already exists, you will have to DROP before creating it again.


问:
Using ?: shorthand in laravel
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

```<code>public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {
</code>```

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;

答:
You are imediatly trying to get the email property of an object you're trying to fetch.
I would suggest using the method findOrFail, when there is no result found a NotFoundException will be thrown, which will return a 404 not found.

Overall it will look like this:

```<code>$user = User::where('users_telephone_number', '=',$phone )->findOrFail();
$email = $user->email;
</code>```

Title: Using ?: shorthand in laravel

Body:
I have a login function that i am using to login users using telephone numbers. I am getting the phone numbers from the user and then using the phone number to fetch the matching email address.

For that i have this code

public function processLogin(Request $request){
    $phone = $request->get('phone');
    $getEmail = User::where('users_telephone_number', '=',$phone )->first()->email;
    $email = $getEmail;
    $password = $request->get('password');
    //echo $email.$password;
    $data = array(
        'email' => $email,
        'password' => $password
        );

    if (Auth::attempt($data,true)) {

When the number is wrong, i get this error

Trying to get property of non-object

To solve the problem i want to have the variable $getEmail to be equal to  none@dont.com which will fail well like all other wrong email and password combos.

How can i make sure i catch errors in this one line i am using to fetch the email

User::where('users_telephone_number', '=',$phone )->first()->email;

Body:
You are imediatly trying to get the email property of an object you're trying to fetch.
I would suggest using the method findOrFail, when there is no result found a NotFoundException will be thrown, which will return a 404 not found.

Overall it will look like this:

$user = User::where('users_telephone_number', '=',$phone )->findOrFail();
$email = $user->email;


问:
Using EFCore with Identity for Core
For the last few days I've been fighting the Identity system in combination with Entity framework Core. Here's some information prior to revealing my problem:

Entity framework Core doesn't support lazy loading, this means that I'm using eager loading by saying which items to include

In order to say which items of an object I would like to retrieve I override a method in each repository ( the properties retrieved are constant for now )

The Identity system I'm using is configured as :

```<code>services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
    options.Cookies.ApplicationCookie.AutomaticChallenge = false;
})  .AddUserManager<UserManager>()
    .AddRoleManager<RoleManager>()
    .AddUserStore<UserStore>()
    .AddRoleStore<RoleStore>()
    .AddEntityFrameworkStores<ApplicationDbContext, int>()
    .AddDefaultTokenProviders();
</code>```

Now on to the problem itself:

I would like to use the identity system in order to generate tokens, get users etc. but I cannot do eager loading on the UserManager object itself as it's methods return Task<ApplicationUser> and the Include() method itself requires IQueryable ( to do eager loading ). What is the general way to be both be able to use eager loading and UserManager?

答:
The simplest way maybe to call UserManger.Users directly. Like this:</p>

```<code>ApplicationUser user = await userManager.Users.Include(s => s.Sales).Where(e => e.Email == "t@t.net").FirstOrDefaultAsync();
</code>```

Title: Using EFCore with Identity for Core

Body:
For the last few days I've been fighting the Identity system in combination with Entity framework Core. Here's some information prior to revealing my problem:

Entity framework Core doesn't support lazy loading, this means that I'm using eager loading by saying which items to include

In order to say which items of an object I would like to retrieve I override a method in each repository ( the properties retrieved are constant for now )

The Identity system I'm using is configured as :

services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
    options.Cookies.ApplicationCookie.AutomaticChallenge = false;
})  .AddUserManager<UserManager>()
    .AddRoleManager<RoleManager>()
    .AddUserStore<UserStore>()
    .AddRoleStore<RoleStore>()
    .AddEntityFrameworkStores<ApplicationDbContext, int>()
    .AddDefaultTokenProviders();

Now on to the problem itself:

I would like to use the identity system in order to generate tokens, get users etc. but I cannot do eager loading on the UserManager object itself as it's methods return Task<ApplicationUser> and the Include() method itself requires IQueryable ( to do eager loading ). What is the general way to be both be able to use eager loading and UserManager?

Body:
The simplest way maybe to call UserManger.Users directly. Like this:

ApplicationUser user = await userManager.Users.Include(s => s.Sales).Where(e => e.Email == "t@t.net").FirstOrDefaultAsync();


问:
parse multiple json string into one object in javascript
I have a json output where it gets two strings with format such as

```<code>   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
   [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
</code>```

I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.

i want the output should be

```<code>   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
   {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
</code>```

Body:
I have a json output where it gets two strings with format such as

   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
   [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.

i want the output should be

   [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
   {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

Body:
You can do:

var obj1 = [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
var obj2 = [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
/* or */
var obj1 = JSON.parse('[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]')
var obj2 = JSON.parse('[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]')

// then flatten into one array
var combined = [].concat.apply([], [obj1, obj2])
console.log(combined);
//  [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}, {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]


问:
Wix Burn, how do I allow downgrading?
So I've got a pretty simple burn installer, primarily to include .net upgrades or occasionally a driver pack for hardware our app needs to talk to.

The MSI's we create support upgrading or downgrading.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
    <Bundle Name="My App Name" Manufacturer="Company Name" Version="!(bind.packageVersion.MyAPP_MSI)"
            IconSourceFile="MyIcon.ico"  DisableModify="yes" DisableRemove="yes"
            UpgradeCode="{15E598EF-89CE-470B-8CEF-E32C8983DA33}" >
        <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" >
            <bal:WixStandardBootstrapperApplication
                LogoFile="$(var.CoreComponents.TargetDir)InstallerGraphics\Bootstrapper_Logo.png"
                LicenseFile="$(var.CoreComponents.TargetDir)AppRoot\App License.rtf"
                SuppressOptionsUI="yes" />
        </BootstrapperApplicationRef>

        <Chain>
            <PackageGroupRef Id="NetFx451Web"/>

            <MsiPackage DisplayName="My full Application Name"  Id="MyAPP_MSI" SourceFile="$(var.Installer_MyAppMSI_TargetPath)"
                        DisplayInternalUI="yes" ForcePerMachine="yes" Visible="yes" />

        <MsiPackage DisplayName="My Hardware Driver" Id="Installer_MSI_Driver" SourceFile="$(var.Installer_Driver.TargetPath)"
                    DisplayInternalUI="yes" ForcePerMachine="yes" Visible="yes" />

        </Chain>
    </Bundle>
</Wix>
</code>```

We typically have beta releases and when a user wants to downgrade from a beta back to our stable releases they can't simply execute the old EXE installer.  They have to remove previous package from Add/Remove Programs explicitly to installer the older Burn EXE.

This wasn't an issue with the MSI based install.  How do we get back to that functionality?

Log

```<code>[0CB8:067C][2014-06-23T11:10:04]i001: Burn v3.8.1128.0, Windows v6.1(Build 7601: Service Pack 1), path:\\iop-filesvr\IOP\Builds\Main\8.1.240\IO Practiceware Client Setup.exe, cmdline: '-burn.unelevated BurnPipe.{197B8193-6EFC-4ED0-AF90-DE7205F13E65} {CD23A8AB-520B-4F5D-BCB9-98998C5A1EC0} 2216'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\jeff\AppData\Local\Temp\IO_Practiceware_Client_8.1.240.0_20140623111004.log'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable'WixBundleOriginalSource' to value '\\iop-filesvr\IOP\Builds\Main\8.1.240\IO Practiceware ClientSetup.exe'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable 'WixBundleName' to value 'IO Practiceware Client 8.1.240.0'

[0CB8:067C][2014-06-23T11:10:05]i100: Detect begin, 2 packages

[0CB8:067C][2014-06-23T11:10:05]i000: Setting string variable 'PrerequisitesVersion' to value '1.0.0.0'

[0CB8:067C][2014-06-23T11:10:05]i102: Detected related bundle: {8d398d25-606f-419a-9b29-e3434aeb2485}, type: Upgrade, scope: PerUser, version: 8.1.241.0, operation: Downgrade

[0CB8:067C][2014-06-23T11:10:05]i103: Detected related package: {7EA877FF-CE7A-49CE-8F76-D5A11EA7DD7A}, scope: PerMachine, version: 1.0.0.0, language: 0 operation: MajorUpgrade

[0CB8:067C][2014-06-23T11:10:05]i103: Detected related package: {8E8A7689-FB1C-4FE5-AF7C-95D499A342DE}, scope: PerUser, version: 8.1.241.0, language: 0 operation: MajorUpgrade

[0CB8:067C][2014-06-23T11:10:05]i101: Detected package: PrerequisitesMsi, state: Absent, cached: None

[0CB8:067C][2014-06-23T11:10:05]i101: Detected package: ClientMsi, state: Absent, cached: None

[0CB8:067C][2014-06-23T11:10:05]i199:Detect complete, result: 0x0

[0CB8:076C][2014-06-23T11:10:16]i000: Setting numeric variable 'EulaAcceptCheckbox' to value 0

[0CB8:076C][2014-06-23T11:10:16]e000: Error 0x80070666: Cannot install a product when a newer version is installed.
</code>```

答:
This worked for me:

```<code><MajorUpgrade Schedule="afterInstallInitialize" AllowDowngrades="yes"  />
</code>```

See WIX docs on MajorUpgrade Element.

Title: Wix Burn, how do I allow downgrading?

Body:
So I've got a pretty simple burn installer, primarily to include .net upgrades or occasionally a driver pack for hardware our app needs to talk to.

The MSI's we create support upgrading or downgrading.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
    <Bundle Name="My App Name" Manufacturer="Company Name" Version="!(bind.packageVersion.MyAPP_MSI)"
            IconSourceFile="MyIcon.ico"  DisableModify="yes" DisableRemove="yes"
            UpgradeCode="{15E598EF-89CE-470B-8CEF-E32C8983DA33}" >
        <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" >
            <bal:WixStandardBootstrapperApplication
                LogoFile="$(var.CoreComponents.TargetDir)InstallerGraphics\Bootstrapper_Logo.png"
                LicenseFile="$(var.CoreComponents.TargetDir)AppRoot\App License.rtf"
                SuppressOptionsUI="yes" />
        </BootstrapperApplicationRef>

        <Chain>
            <PackageGroupRef Id="NetFx451Web"/>

            <MsiPackage DisplayName="My full Application Name"  Id="MyAPP_MSI" SourceFile="$(var.Installer_MyAppMSI_TargetPath)"
                        DisplayInternalUI="yes" ForcePerMachine="yes" Visible="yes" />

        <MsiPackage DisplayName="My Hardware Driver" Id="Installer_MSI_Driver" SourceFile="$(var.Installer_Driver.TargetPath)"
                    DisplayInternalUI="yes" ForcePerMachine="yes" Visible="yes" />

        </Chain>
    </Bundle>
</Wix>

We typically have beta releases and when a user wants to downgrade from a beta back to our stable releases they can't simply execute the old EXE installer.  They have to remove previous package from Add/Remove Programs explicitly to installer the older Burn EXE.

This wasn't an issue with the MSI based install.  How do we get back to that functionality?

Log

[0CB8:067C][2014-06-23T11:10:04]i001: Burn v3.8.1128.0, Windows v6.1(Build 7601: Service Pack 1), path:\\iop-filesvr\IOP\Builds\Main\8.1.240\IO Practiceware Client Setup.exe, cmdline: '-burn.unelevated BurnPipe.{197B8193-6EFC-4ED0-AF90-DE7205F13E65} {CD23A8AB-520B-4F5D-BCB9-98998C5A1EC0} 2216'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable 'WixBundleLog' to value 'C:\Users\jeff\AppData\Local\Temp\IO_Practiceware_Client_8.1.240.0_20140623111004.log'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable'WixBundleOriginalSource' to value '\\iop-filesvr\IOP\Builds\Main\8.1.240\IO Practiceware ClientSetup.exe'

[0CB8:067C][2014-06-23T11:10:04]i000: Setting string variable 'WixBundleName' to value 'IO Practiceware Client 8.1.240.0'

[0CB8:067C][2014-06-23T11:10:05]i100: Detect begin, 2 packages

[0CB8:067C][2014-06-23T11:10:05]i000: Setting string variable 'PrerequisitesVersion' to value '1.0.0.0'

[0CB8:067C][2014-06-23T11:10:05]i102: Detected related bundle: {8d398d25-606f-419a-9b29-e3434aeb2485}, type: Upgrade, scope: PerUser, version: 8.1.241.0, operation: Downgrade

[0CB8:067C][2014-06-23T11:10:05]i103: Detected related package: {7EA877FF-CE7A-49CE-8F76-D5A11EA7DD7A}, scope: PerMachine, version: 1.0.0.0, language: 0 operation: MajorUpgrade

[0CB8:067C][2014-06-23T11:10:05]i103: Detected related package: {8E8A7689-FB1C-4FE5-AF7C-95D499A342DE}, scope: PerUser, version: 8.1.241.0, language: 0 operation: MajorUpgrade

[0CB8:067C][2014-06-23T11:10:05]i101: Detected package: PrerequisitesMsi, state: Absent, cached: None

[0CB8:067C][2014-06-23T11:10:05]i101: Detected package: ClientMsi, state: Absent, cached: None

[0CB8:067C][2014-06-23T11:10:05]i199:Detect complete, result: 0x0

[0CB8:076C][2014-06-23T11:10:16]i000: Setting numeric variable 'EulaAcceptCheckbox' to value 0

[0CB8:076C][2014-06-23T11:10:16]e000: Error 0x80070666: Cannot install a product when a newer version is installed.

Body:
This worked for me:

<MajorUpgrade Schedule="afterInstallInitialize" AllowDowngrades="yes"  />

See WIX docs on MajorUpgrade Element.


问:
producer-consumer using synchronization
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

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

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

         }
         return false;
     }
}
</code>```

答:
What you have tried to do is implement synchronization using busy-waiting. In pseudo code what you are basically doing is:

```<code>Producer()
{
   if (buffer.hasemptyspaces())
   {
      produce(buffer);
   }
   else
   {
      sleep(n);
   }
}

Consumer()
{
   if (buffer.hasfullspaces())
   {
      consume(buffer);
   }
   else
   {
      sleep(n);
   }
}
</code>```

You code will work fine, till the the Producer and Consumer simultaneously try to execute produce() and consume(). In other words, either one of the This might not be very often, but is definitely possible and will definitely happen!

In Java, ConcurrentLinkedQueue to implements a wait-free algorithm for a shared buffer. I'm sure that are other implementations if you look around.

Title: producer-consumer using synchronization

Body:
I wrote code to implement the Producer-Consumer problem and it seems to be working fine without the need to synchronize.Is it possible?

How do I test the code and check if it is actually working right or not? How do I know if deadlock will occur? Right now,I am not breaking out of the loops(i.e. the Producer keeps inserting and the consumer keeps consuming in an infinite loop).I am using a circular queue of size 3(for sake of simplicity) as the shared resource.

Here is my code:

import java.util.*;

public class PCImpl implements Runnable
{
Thread t;
QforPC qObj;

 public static void main(String[] args)
 {
     QforPC qObject=new QforPC();

     //These create 2 different objects! Each object has it's own thread of execution.
     //Synchronization is needed when 2 threads use the same object
    new PCImpl("Producer",qObject);
    new PCImpl("Consumer",qObject);
 }

 PCImpl(String name,QforPC qObj)
 {
     this.qObj=qObj;
     t=new Thread(this,name);
     t.start();
 }

 public void run()
 {
         if(Thread.currentThread().getName().equals("Producer"))
         {
             while(true)
             {
                  Random rgen=new Random();
                  int n=rgen.nextInt(100);
                  if(n!=0)
                              qObj.Producer(n);
                         try
                    {
                       Thread.sleep(200);
                     }
                      catch(InterruptedException e)
                    {

                    }
               }

            }

         if(Thread.currentThread().getName().equals("Consumer"))
         {
             while(true)
                  {
                 try
               {
                 Thread.sleep(1500);
               }
                catch(InterruptedException e)
               {
                  }
              qObj.Consumer();

              }
         }

  }
}

public class QforPC
{
int[] q={0,0,0};
int r=0,f=0;
  public void Producer(int item)
     {

         if(r!=q.length && canProducer())
         {
             q[r]=item;
             System.out.println("The item inserted into the queue is:"+ item);
             r++;
         }
         if(r==q.length && f>0)
             r=0;
         else if(r==q.length && f==q.length)
         {
             r=0;
             f=0;
         }
     }

     public void Consumer()
     {
         int item;
         System.out.println("The value of isQueue empty is:"+ isEmpty());

         if(f!=q.length && isEmpty()==false)
         {
             System.out.println("Entered the consumer method");
             item=q[f];
             System.out.println("The item fetched from the queue is:"+item);
             q[f]=0;
             f++;
         }
         if(f==q.length && r<f)
             f=0;

     }

     public boolean isEmpty()
     {
         for(int k=0;k<q.length;k++)
         {
             if(q[k]==0 && k==q.length-1)
                 return true;

         }
         return false;
     }

     public boolean canProducer()
     {
         for(int k=0;k<q.length;k++)
         {
                 if(q[k]==0)
                 return true;

         }
         return false;
     }
}

Body:
What you have tried to do is implement synchronization using busy-waiting. In pseudo code what you are basically doing is:

Producer()
{
   if (buffer.hasemptyspaces())
   {
      produce(buffer);
   }
   else
   {
      sleep(n);
   }
}

Consumer()
{
   if (buffer.hasfullspaces())
   {
      consume(buffer);
   }
   else
   {
      sleep(n);
   }
}

You code will work fine, till the the Producer and Consumer simultaneously try to execute produce() and consume(). In other words, either one of the This might not be very often, but is definitely possible and will definitely happen!

In Java, ConcurrentLinkedQueue to implements a wait-free algorithm for a shared buffer. I'm sure that are other implementations if you look around.

ContentLicense: CC BY-SA 2.5


问:
Split strings using mysql
I want to create a stored procedure which will do matching of two tables. My requirement is to match two tables based on the columns user passes as an input.

Syntax:

```<code>CREATE PROCEDURE reconcile.matchTables(
  IN TAB1 VARCHAR(25),
  IN TAB1 VARCHAR(25),
  IN COLS1 VARCHAR(250) ,
  IN COLS2 VARCHAR(250))
</code>```

EX:

```<code>matchTables('table1', 'table2', 'col1#col2#col3#col4' , 'col2#col13#col1#col8')
</code>```

Now the stored procedure should form the where clause like the following

```<code>table1.col1 = table2.col2
  and table1.col2 = table2.col13
  and table1.col3 = table2.col1
  and table1.col4 = table2.col8
</code>```

答:
```<code>CREATE PROCEDURE matchTables
@TAB1 VARCHAR(25),
@TAB2 VARCHAR(25),
@COLS1 VARCHAR(250) ,
@COLS2 VARCHAR(250)

AS

BEGIN
DECLARE @WHEREstring VARCHAR(MAX)
SET @WHEREstring =
'
WHERE
        '
SELECT @WHEREstring = @WHEREstring + @TAB1 +'.'+ tab1.col+' = '+@TAB2+'.' + tab2.col +' AND
        '
            FROM
            (
                SELECT QUOTENAME(split.a.value('.','VARCHAR(100)')) AS col, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNum
                    FROM
                    (
                        SELECT Cast ('<M>' + Replace(@COLS1, '#', '</M><M>')+ '</M>' AS XML) AS Tab1Data
                    ) AS A
                    CROSS apply Tab1Data.nodes ('/M') AS Split(a)
            ) tab1
            INNER JOIN
            (
                Select QUOTENAME(AliasSplit.c.value('.', 'varchar(100)')) AS col, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNum
                FROM
                (
                    SELECT Cast ('<A>' + Replace(@COLS2, '#', '</A><A>')+ '</A>' AS XML) AS Tab2Data
                ) AS A
                CROSS apply Tab2Data.nodes ('/A') AS AliasSplit(c)
            ) tab2
            ON tab1.RowNum = tab2.RowNum
        SET @WHEREstring= LEFT(@WHEREstring, LEN(@WHEREstring) - 8)

        print @WHEREstring
END
</code>```

Now, execute it using :::

```<code> EXEC matchTables 'table1', 'table2', 'col1#col2#col3#col4' , 'col2#col13#col1#col8'
</code>```

i hope you got the desired where clause. cheers

Title: Split strings using mysql

Body:
I want to create a stored procedure which will do matching of two tables. My requirement is to match two tables based on the columns user passes as an input.

Syntax:

CREATE PROCEDURE reconcile.matchTables(
  IN TAB1 VARCHAR(25),
  IN TAB1 VARCHAR(25),
  IN COLS1 VARCHAR(250) ,
  IN COLS2 VARCHAR(250))

EX:

matchTables('table1', 'table2', 'col1#col2#col3#col4' , 'col2#col13#col1#col8')

Now the stored procedure should form the where clause like the following

table1.col1 = table2.col2
  and table1.col2 = table2.col13
  and table1.col3 = table2.col1
  and table1.col4 = table2.col8

Body:
CREATE PROCEDURE matchTables
@TAB1 VARCHAR(25),
@TAB2 VARCHAR(25),
@COLS1 VARCHAR(250) ,
@COLS2 VARCHAR(250)

AS

BEGIN
DECLARE @WHEREstring VARCHAR(MAX)
SET @WHEREstring =
'
WHERE
        '
SELECT @WHEREstring = @WHEREstring + @TAB1 +'.'+ tab1.col+' = '+@TAB2+'.' + tab2.col +' AND
        '
            FROM
            (
                SELECT QUOTENAME(split.a.value('.','VARCHAR(100)')) AS col, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNum
                    FROM
                    (
                        SELECT Cast ('<M>' + Replace(@COLS1, '#', '</M><M>')+ '</M>' AS XML) AS Tab1Data
                    ) AS A
                    CROSS apply Tab1Data.nodes ('/M') AS Split(a)
            ) tab1
            INNER JOIN
            (
                Select QUOTENAME(AliasSplit.c.value('.', 'varchar(100)')) AS col, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS RowNum
                FROM
                (
                    SELECT Cast ('<A>' + Replace(@COLS2, '#', '</A><A>')+ '</A>' AS XML) AS Tab2Data
                ) AS A
                CROSS apply Tab2Data.nodes ('/A') AS AliasSplit(c)
            ) tab2
            ON tab1.RowNum = tab2.RowNum
        SET @WHEREstring= LEFT(@WHEREstring, LEN(@WHEREstring) - 8)

        print @WHEREstring
END

Now, execute it using :::

 EXEC matchTables 'table1', 'table2', 'col1#col2#col3#col4' , 'col2#col13#col1#col8'

i hope you got the desired where clause. cheers


问:
Long term retention not available in Canada East?
I attempted to configure long term retention for my Azure SQL server but it informs me it is not available in the region used by the database - Canada East. Anyone know why? How do I find what regions it is available in? I can find no clue on the Azure site or MS forums as to why it would not be available here.</p>

答: As per BOL 'Long-term backup retention is currently in preview and available in the following regions: Australia East, Australia Southeast, Brazil South, Central US, East Asia, East US, East US 2, India Central, India South, Japan East, Japan West, North Central US, North Europe, South Central US, Southeast Asia, West Europe, and West US.'. That does not include Canada East at this moment.


问:
scala object modules is not a member of package play
I'm trying to use mongo with Scala Play 2.5

I created a basic project from a template from the Play website. I'm now trying to create a class that imports the mongo module and I'm getting the following error:

object modules is not a member of package play

at this line:

import play.modules.reactivemongo.ReactiveMongoApi

I've enabled mongo in my application.conf like so:

play.modules {
  enabled += "play.modules.reactivemongo.ReactiveMongoModule"
}

and I've also added:

libraryDependencies += "org.reactivemongo" %% "play2-reactivemongo" % "0.11.14"

to build.sbt

Am I missing something?

Any ideas?

Why does it not find the "modules" package?

答: Ok, so here's the solution. Once the build config files are updated, you need to restart sbt. Otherwise it doesn't recognise the new dependencies.</p>


问:
image preview on change does not work
I have been searching for 2 days on "how to preview an image before upload". I see online live demo and copy past all code as it was. I rename my class name to match the additional js code. My code is:

```<code>    $('#edit-image-upload-wrapper').prepend('<div id="imagePreview"></div>');

     $(function() {
    $("#edit-image-upload-wrapper").bind("change", function()
    {
       // alert("it works");
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) alert("no file selected");//return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div

                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
    });
});
</code>```

I inspect my html dom and see the following code :

```<code><div class="form-item" id="edit-image-upload-wrapper"><div id="imagePreview"></div>
 <label for="edit-image-upload">Upload Your Picture: <span class="form-required" title="This field is required.">*</span></label>
 <input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60">

 <div class="description"><p>You need to provide a passport sized image in jpg/jpeg or png format. The image size has to be 100kb or lower.</p>
</div>
</div>
</code>```

Which is exactly same as this demo: http://www.phpgang.com/how-to-show-image-thumbnail-before-upload-with-jquery_573.html

But when I change the image , alert("no file selected"); works that proves no file selected.  What am I doing wrong. please help.

答:
Check my previews answer is work fine show image before upload

Show an image preview before upload

Title: image preview on change does not work

Body:
I have been searching for 2 days on "how to preview an image before upload". I see online live demo and copy past all code as it was. I rename my class name to match the additional js code. My code is:

    $('#edit-image-upload-wrapper').prepend('

');

     $(function() {
    $("#edit-image-upload-wrapper").bind("change", function()
    {
       // alert("it works");
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) alert("no file selected");//return; // no file selected, or no FileReader support

        if (/^image/.test( files[0].type)){ // only image file
            var reader = new FileReader(); // instance of the FileReader
            reader.readAsDataURL(files[0]); // read the local file

            reader.onloadend = function(){ // set image data as background of div

                $("#imagePreview").css("background-image", "url("+this.result+")");
            }
        }
    });
});

I inspect my html dom and see the following code :

 Upload Your Picture: *
 <input type="file" name="files[image_upload]" class="form-file required" id="edit-image-upload" size="60">

You need to provide a passport sized image in jpg/jpeg or png format. The image size has to be 100kb or lower.

Which is exactly same as this demo: http://www.phpgang.com/how-to-show-image-thumbnail-before-upload-with-jquery_573.html

But when I change the image , alert("no file selected"); works that proves no file selected.  What am I doing wrong. please help.


问:
Firebase storage throws authentication error on Android Things
Since Android Things SDK does not support Firebase Authentication, when connecting to Firebase Storage, I receive the error:

W/NetworkRequest: no auth token for request

E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.android.gms.internal.zzbqn: Please sign in before trying to get a token.

This error is repeated several times (several seconds) then eventually uploads.  Any suggestion on how to anonymously upload to Firebase Storage without the Firebase Authentication Package and without runtime errors?

答:
The only way I think this may be achieved is by looking at:

how the Web API for Authentication performs authentication, then make your own REST calls from your app to retrieve access token (please be aware you also need to refresh the token when it expires)

how the Web API for Storage performs requests on the network, so you can mimic the behaviour, which will have to be reimplemented with some REST library

Have a read here to know what you can actually do with and without Play Services.


问:
mysql Load data local infile for one csv fields terminated by , and for another csv field terminated by ;
I already written a query i have posted here but that is working with similar kinds of csv.I need a load data local infile query which will work with all kinds of csv file.Please look into it.

The below query works with all kinds of csv files in which fields separated by ,.
example csv

```<code>1,114300,1790,2,2,2,No,East
2,114200,2030,4,2,3,No,East
3,114800,1740,3,2,1,No,East
4,94700,1980,3,2,3,No,East
</code>```

Query looks like this:

```<code> LOAD DATA    LOCAL  INFILE '$pathname'
              IGNORE INTO TABLE $name
              FIELDS TERMINATED BY ','
              OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"'
              LINES TERMINATED BY '\\n'
              IGNORE 1 LINES"
</code>```

Another csv is like this

```<code>Agfa ePhoto 1280;1997;1024.0;640.0;0.0;38.0;114.0;70.0;40.0;4.0;420.0;95.0;179.0
Agfa ePhoto 1680;1998;1280.0;640.0;1.0;38.0;114.0;50.0;0.0;4.0;420.0;158.0;179.0
Agfa ePhoto CL18;2000;640.0;0.0;0.0;45.0;45.0;0.0;0.0;2.0;0.0;0.0;179.0
Agfa ePhoto CL30;1999;1152.0;640.0;0.0;35.0;35.0;0.0;0.0;4.0;0.0;0.0;269.0
Agfa ePhoto CL30 Clik!;1999;1152.0;640.0;0.0;43.0;43.0;50.0;0.0;40.0;300.0;128.0;1299.0
</code>```

In the query i just changed Fields terminated by ',' to ';'.It works for me.I need everything to be done by in a single query.I am looking for help.

答:
I extracted the csv filename and its path and stored it in a variable named $filename.

```<code>$file = new SplFileObject($filename);//it holds the name and location means path to csv
$file->seek(0);//It holds the first line of csv
if (strpos($file, ';') == true){

$field = "FIELDS TERMINATED BY ';'";
 }
if (strpos($file, ',') == true){
 $field = "FIELDS TERMINATED BY ','";
 }
</code>```

Then edit the query like this

```<code>LOAD DATA    LOCAL  INFILE '$pathname'
              IGNORE INTO TABLE $name
              $field
              OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"'
              LINES TERMINATED BY '\\n'
              IGNORE 1 LINES"
</code>```

It works for all the csv files which fields end by , and ;.

Body:
I already written a query i have posted here but that is working with similar kinds of csv.I need a load data local infile query which will work with all kinds of csv file.Please look into it.

The below query works with all kinds of csv files in which fields separated by ,.
example csv

1,114300,1790,2,2,2,No,East
2,114200,2030,4,2,3,No,East
3,114800,1740,3,2,1,No,East
4,94700,1980,3,2,3,No,East

Query looks like this:

 LOAD DATA    LOCAL  INFILE '$pathname'
              IGNORE INTO TABLE $name
              FIELDS TERMINATED BY ','
              OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"'
              LINES TERMINATED BY '\\n'
              IGNORE 1 LINES"

Another csv is like this

Agfa ePhoto 1280;1997;1024.0;640.0;0.0;38.0;114.0;70.0;40.0;4.0;420.0;95.0;179.0
Agfa ePhoto 1680;1998;1280.0;640.0;1.0;38.0;114.0;50.0;0.0;4.0;420.0;158.0;179.0
Agfa ePhoto CL18;2000;640.0;0.0;0.0;45.0;45.0;0.0;0.0;2.0;0.0;0.0;179.0
Agfa ePhoto CL30;1999;1152.0;640.0;0.0;35.0;35.0;0.0;0.0;4.0;0.0;0.0;269.0
Agfa ePhoto CL30 Clik!;1999;1152.0;640.0;0.0;43.0;43.0;50.0;0.0;40.0;300.0;128.0;1299.0

In the query i just changed Fields terminated by ',' to ';'.It works for me.I need everything to be done by in a single query.I am looking for help.

Body:
I extracted the csv filename and its path and stored it in a variable named $filename.

$file = new SplFileObject($filename);//it holds the name and location means path to csv
$file->seek(0);//It holds the first line of csv
if (strpos($file, ';') == true){

$field = "FIELDS TERMINATED BY ';'";
 }
if (strpos($file, ',') == true){
 $field = "FIELDS TERMINATED BY ','";
 }

Then edit the query like this

LOAD DATA    LOCAL  INFILE '$pathname'
              IGNORE INTO TABLE $name
              $field
              OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\"'
              LINES TERMINATED BY '\\n'
              IGNORE 1 LINES"

It works for all the csv files which fields end by , and ;.


问:
Is this TypeError linked to a wrong this.$emit?
I am building a component which is supposed to get an Array of Objects from the parent, display them and allow for some of the Objects to be deleted (= the child sends to the parent a new Array).

A previous answer was very useful to understand the child -> parent communication but I am now stuck on an error I do no understand:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      var user = _.filter(this.who, function(w) {
        return w.id === p.id
      })
      this.$emit('delete-id', user)
    }
  }
})
var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="who"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template></code>```

Running this code correcly lists the users, but when trying to delete one I get in the console

```<code>vue.js:1739 Uncaught TypeError: fns[i].apply is not a function
    at VueComponent.invoker (vue.js:1739)
    at VueComponent.Vue.$emit (vue.js:2210)
    at VueComponent.deleteID (search.html:31)
    at Proxy.boundFn (vue.js:170)
    at click (eval at makeFunction (vue.js:9323), <anonymous>:2:164)
    at HTMLButtonElement.invoker (vue.js:1743)
invoker @   vue.js:1739
Vue.$emit   @   vue.js:2210
deleteID    @   search.html:31
boundFn @   vue.js:170
click   @   VM9358:2
invoker @   vue.js:1743
</code>```

What does this error mean? Is the $emit correct?

答:
There's two problems:

You _.filter returns an arry, so you don't emit the user, but an array containing the user. That filter is also completely unnecessary, because palready is the user object that you intend to filter for. But that code is not the cause of the error.

v-on:delete-id="who" ere you pass an object (who) to the event listener, but it expects a function. That's what's raising the error.

A working version of your code would look like this:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      this.$emit('delete-id', p)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(person) {
      const index = this.who.indexOf(person)
      this.who.splice(index, 1)
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template></code>```

Body:
I am building a component which is supposed to get an Array of Objects from the parent, display them and allow for some of the Objects to be deleted (= the child sends to the parent a new Array).

A previous answer was very useful to understand the child -> parent communication but I am now stuck on an error I do no understand:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      var user = _.filter(this.who, function(w) {
        return w.id === p.id
      })
      this.$emit('delete-id', user)
    }
  }
})
var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  }
})

  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="who"></search-box>
  who is: {{who}}

<template id="search-box-template">

person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button>

</template>

Running this code correcly lists the users, but when trying to delete one I get in the console

vue.js:1739 Uncaught TypeError: fns[i].apply is not a function
    at VueComponent.invoker (vue.js:1739)
    at VueComponent.Vue.$emit (vue.js:2210)
    at VueComponent.deleteID (search.html:31)
    at Proxy.boundFn (vue.js:170)
    at click (eval at makeFunction (vue.js:9323), <anonymous>:2:164)
    at HTMLButtonElement.invoker (vue.js:1743)
invoker @   vue.js:1739
Vue.$emit   @   vue.js:2210
deleteID    @   search.html:31
boundFn @   vue.js:170
click   @   VM9358:2
invoker @   vue.js:1743

What does this error mean? Is the $emit correct?

Body:
There's two problems:

You _.filter returns an arry, so you don't emit the user, but an array containing the user. That filter is also completely unnecessary, because palready is the user object that you intend to filter for. But that code is not the cause of the error.

v-on:delete-id="who" ere you pass an object (who) to the event listener, but it expects a function. That's what's raising the error.

A working version of your code would look like this:

Vue.component('search-box', {
  template: '#search-box-template',
  props: ['who'],
  methods: {
    deleteID: function(p) {
      this.$emit('delete-id', p)
    }
  }
})

var vm = new Vue({
  el: '#root',
  data: {
    who: [{
      "name": "john",
      "id": 1
    }, {
      "name": "mary",
      "id": 2
    }]
  },
  methods: {
    handleDelete(person) {
      const index = this.who.indexOf(person)
      this.who.splice(index, 1)
    }
  }
})

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<div id="root">
  Hello in parent
  <search-box v-bind:who="who" v-on:delete-id="handleDelete"></search-box>
  who is: {{who}}
</div>

<template id="search-box-template">
    <div>
        <ul>
            <li v-for="p in who">person: {{p.name}}, id: {{p.id}} <button v-on:click="deleteID(p)">delete</button></li>
        </ul>
    </div>
</template>


问:
python - test that class has been instantiated with arguments
I'm pretty new with python, and I'm trying to figure out how to test this code.

Here is my class:

```<code>#!/usr/bin/python

import argparse
from generator import *

parse = argparse.ArgumentParser(description='XOS Generative Toolchain')
parse.add_argument('--rev', dest='rev', action='store_true',default=False, help='Convert proto to xproto')
parse.add_argument('--target', dest='target', action='store',default=None, help='Output format, corresponding to <output>.yaml file', required=True)
parse.add_argument('--output', dest='output', action='store',default=None, help='Destination dir', required=True)
parse.add_argument('--attic', dest='attic', action='store',default=None, help='The location at which static files are stored')
parse.add_argument('--kvpairs', dest='kv', action='store',default=None, help='Key value pairs to make available to the target')
parse.add_argument('inputs', metavar='<input file>', nargs='+', action='store', help='xproto files to compile')

class XosGen:

    @staticmethod
    def init(args=None):

        if not args:
            args = parse.parse_args()

        args.quiet = False

        # convert output to absolute path
        if not os.path.isabs(args.output):
            args.output = os.path.abspath(os.getcwd() + '/' + args.output)
        if not os.path.isabs(args.target):
            args.target = os.path.abspath(os.getcwd() + '/' + args.target)

        inputs = []
        for fname in args.inputs:
            if not os.path.isabs(fname):
                inputs.append(os.path.abspath(os.getcwd() + '/' + fname))
            else:
                inputs.append(fname)
        args.inputs = inputs

        print args.output

        generator = XOSGenerator(args)
        generator.generate()
</code>```

And here is the test:
    import unittest
    from mock import patch
    from xosgen.xosgen import XosGen

```<code>class Args:
    pass

class XOSGeneratorTest(unittest.TestCase):
    """
    Testing the CLI binding for the XOS Generative Toolchain
    """

    def test_generator(self):
        """
        [XOS-GenX] The CLI entry point should correctly parse params
        """
        args = Args()
        args.inputs = ['../test.xproto']
        args.target = '../test.xtarget'
        args.output = '../out/dir'

        expected_args = Args()
        expected_args.inputs = ['/Users/teone/Sites/opencord/orchestration/xos/lib/test.xproto']
        expected_args.target = '/Users/teone/Sites/opencord/orchestration/xos/lib/test.xtarget'
        expected_args.output = '/Users/teone/Sites/opencord/orchestration/xos/lib/out/dir'

        with patch("xosgen.xosgen.XOSGenerator") as generator:
            XosGen.init(args)
            generator.assert_called_with(expected_args)

if __name__ == '__main__':
    unittest.main()
</code>```

What I want to test is if the passed arguments were changed correctly, but my test is failing with:

```<code>AssertionError: Expected call: XOSGenerator(<test_cli.Args instance at 0x10abc29e0>)
Actual call: XOSGenerator(<test_cli.Args instance at 0x10abc2950>)
</code>```

What would be the correct way to test this?

答:
By calling both

```<code>args = Args()
</code>```

and

```<code>expected_args = Args()
</code>```

you are assigning these two variables to two different objects, thus they fail the test case even though their attributes are the same.

To overcome this, you might want to specifically compare their attributes. Referring to call_args,

```<code>with patch("xosgen.xosgen.XOSGenerator") as generator:
    XosGen.init(args)
    actual_args = generator.call_args[1]['args'] # if XOSGenerator takes in a keyword argument
    actual_args = generator.call_args[0][0] # otherwise, so comment one of these lines out
    assert actual_args.inputs == expected_args.inputs
    assert actual_args.target == expected_args.target
    assert actual_args.output == expected_args.output
</code>```

Body:
I'm pretty new with python, and I'm trying to figure out how to test this code.

Here is my class:

#!/usr/bin/python

import argparse
from generator import *

parse = argparse.ArgumentParser(description='XOS Generative Toolchain')
parse.add_argument('--rev', dest='rev', action='store_true',default=False, help='Convert proto to xproto')
parse.add_argument('--target', dest='target', action='store',default=None, help='Output format, corresponding to <output>.yaml file', required=True)
parse.add_argument('--output', dest='output', action='store',default=None, help='Destination dir', required=True)
parse.add_argument('--attic', dest='attic', action='store',default=None, help='The location at which static files are stored')
parse.add_argument('--kvpairs', dest='kv', action='store',default=None, help='Key value pairs to make available to the target')
parse.add_argument('inputs', metavar='<input file>', nargs='+', action='store', help='xproto files to compile')

class XosGen:

    @staticmethod
    def init(args=None):

        if not args:
            args = parse.parse_args()

        args.quiet = False

        # convert output to absolute path
        if not os.path.isabs(args.output):
            args.output = os.path.abspath(os.getcwd() + '/' + args.output)
        if not os.path.isabs(args.target):
            args.target = os.path.abspath(os.getcwd() + '/' + args.target)

        inputs = []
        for fname in args.inputs:
            if not os.path.isabs(fname):
                inputs.append(os.path.abspath(os.getcwd() + '/' + fname))
            else:
                inputs.append(fname)
        args.inputs = inputs

        print args.output

        generator = XOSGenerator(args)
        generator.generate()

And here is the test:
    import unittest
    from mock import patch
    from xosgen.xosgen import XosGen

class Args:
    pass

class XOSGeneratorTest(unittest.TestCase):
    """
    Testing the CLI binding for the XOS Generative Toolchain
    """

    def test_generator(self):
        """
        [XOS-GenX] The CLI entry point should correctly parse params
        """
        args = Args()
        args.inputs = ['../test.xproto']
        args.target = '../test.xtarget'
        args.output = '../out/dir'

        expected_args = Args()
        expected_args.inputs = ['/Users/teone/Sites/opencord/orchestration/xos/lib/test.xproto']
        expected_args.target = '/Users/teone/Sites/opencord/orchestration/xos/lib/test.xtarget'
        expected_args.output = '/Users/teone/Sites/opencord/orchestration/xos/lib/out/dir'

        with patch("xosgen.xosgen.XOSGenerator") as generator:
            XosGen.init(args)
            generator.assert_called_with(expected_args)

if __name__ == '__main__':
    unittest.main()

What I want to test is if the passed arguments were changed correctly, but my test is failing with:

AssertionError: Expected call: XOSGenerator(<test_cli.Args instance at 0x10abc29e0>)
Actual call: XOSGenerator(<test_cli.Args instance at 0x10abc2950>)

What would be the correct way to test this?

Body:
By calling both

args = Args()

and

expected_args = Args()

you are assigning these two variables to two different objects, thus they fail the test case even though their attributes are the same.

To overcome this, you might want to specifically compare their attributes. Referring to call_args,

with patch("xosgen.xosgen.XOSGenerator") as generator:
    XosGen.init(args)
    actual_args = generator.call_args[1]['args'] # if XOSGenerator takes in a keyword argument
    actual_args = generator.call_args[0][0] # otherwise, so comment one of these lines out
    assert actual_args.inputs == expected_args.inputs
    assert actual_args.target == expected_args.target
    assert actual_args.output == expected_args.output


问:
shell scripts runs manually but not in crontab
i have shell script to FTP a file from one server to another server called abc.sh below is the code inside it

```<code>#!/bin/bash

HOST='10.18.11.168'
USER='india'
PASS='India@2017'
FILE='inload.dat'
DIRECTORY='/inloading'

ftp -n $HOST <<END_SCRIPT
user $USER $PASS
cd $DIRECTORY
put $FILE
quit
END_SCRIPT
exit 0
</code>```

i am able to run it using ./abc.sh and file also gets copied to remote server.

But when i use in crontab it is not ftp the file
below is the crontab entry

```<code>15 01 * * * /user/loader/abc.sh > /user/loader/error.log 2>&1
</code>```

in the error.log it shows as local: inload.dat: No such file or directory

答:
You're referencing the file inload.dat, which is relative to the directory the script is run from. When you run the script as ./abc.sh it looks for an inload.dat in the same directory.

Cron chooses which directory to run your script from when it executes (IIRC it generally defaults to /root or your HOME directory, but the specific location doesn't matter), and it's not necesarily the same directory that you're in when you run ./abc.sh.

The right solution is to make FILE and absolute path to the full location of inload.dat, so that your script no longer depends on being run from a certain directory in order to succeed.

There are other options, such as dynamically determining the directory the script lives in, but simply using absolute paths is generally the better choice.

Body:
i have shell script to FTP a file from one server to another server called abc.sh below is the code inside it

#!/bin/bash

HOST='10.18.11.168'
USER='india'
PASS='India@2017'
FILE='inload.dat'
DIRECTORY='/inloading'

ftp -n $HOST <<END_SCRIPT
user $USER $PASS
cd $DIRECTORY
put $FILE
quit
END_SCRIPT
exit 0

i am able to run it using ./abc.sh and file also gets copied to remote server.

But when i use in crontab it is not ftp the file
below is the crontab entry

15 01 * * * /user/loader/abc.sh > /user/loader/error.log 2>&1

in the error.log it shows as local: inload.dat: No such file or directory


问:
How to prevent Sql-Injection on User-Generated Sql Queries
I have a project (private, ASP.net website, password protected with https) where one of the requirements is that the user be able to enter Sql queries that will directly query the database. I need to be able to allow these queries, while preventing them from doing damage to the database itself, and from accessing or updating data that they shouldn't be able to access/update.

I have come up with the following rules for implementation:

Use a db user that only has permission for Select Table/View and Update Table (thus any other commands like drop/alter/truncate/insert/delete will just not run).

Verify that the statement begins with the words "Select" or "Update"

Verify (using Regex) that there are no instances of semi-colons in the statement that are not surrounded by single-quotes, white space and letters. (The thought here is that the only way that they could include a second query would be to end the first with a semi-colon that is not part of an input string).

Verify (using Regex) that the user has permission to access the tables being queried/updated, included in joins, etc. This includes any subqueries. (Part of the way that this will be accomplished is that the user will be using a set of table names that do not actually exist in the database, part of the query parsing will be to substitute in the correct corresponding table names into the query).

Am I missing anything?

The goal is that the users be able to query/update tables to which they have access in any way that they see fit, and to prevent any accidental or malicious attempts to damage the db. (And since a requirement is that the user generate the sql, I have no way to parametrize the query or sanitize it using any built-in tools that I know of).

答:
This is a bad idea, and not just from an injection-prevention perspective.  It's really easy for a user that doesn't know any better to accidentally run a query that will hog all your database resources (memory/cpu), effectively resulting in a denial of service attack.

If you must allow this, it's best to keep a completely separate server for these queries, and use replication to keep it pretty close to an exact mirror of your production system.  Of course, that won't work with your UPDATE requirement.

But I want to say again:  this just won't work.  You can't protect your database if users can run ad hoc queries.

OwnerDisplayName: Yaakov Ellis

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Joel Coehoorn

LastEditorDisplayName: Joel Coehoorn


问:
Distance measure between two sets of possibly different size
I have 2 sets of integers, A and B, not necessarily of the same size. For my needs, I take the distance between each 2 elements a and b (integers) to be just abs(a-b).

I am defining the distance between the two sets as follows:

If the sets are of the same size, minimize the sum of distances of all pairs [a,b] (a from A and b from B), minimization over all possible 'pairs partitions' (there are n! possible partitions).

If the sets are not of the same size, let's say A of size m and B of size n, with m < n, then minimize the distance from (1) over all subsets of B which are of size m.

My question is, is the following algorithm (just an intuitive guess) gives the right answer, according to the definition written above.

Construct a matrix D of size m X n, with D(i,j) = abs(A(i)-B(j))

Find the smallest element of D, accumulate it, and delete the row and the column of that element. Accumulate the next smallest entry, and keep accumulating until all rows and columns are deleted.

for example, if A={0,1,4} and B={3,4}, then D is (with the elements above and to the left):

  3 4

0 3 4

1 2 3

4 1 0

And the distance is 0 + 2 = 2, coming from pairing 4 with 4 and 3 with 1.

答:
Note that this problem is referred to sometimes as the skis and skiers problem, where you have n skis and m skiers of varying lengths and heights. The goal is to match skis with skiers so that the sum of the differences between heights and ski lengths is minimized.

To solve the problem you could use minimum weight bipartite matching, which requires O(n^3) time.

Even better, you can achieve O(n^2) time with O(n) extra memory using the simple dynamic programming algorithm below.

Optimally, you can solve the problem in linear time if the points are already sorted using the algorithm described in this paper.

O(n^2) dynamic programming algorithm:

```<code>if (size(B) > size(A))
  swap(A, B);
sort(A);
sort(B);
opt = array(size(B));
nopt = array(size(B));
for (i = 0; i < size(B); i++)
  opt[i] = abs(A[0] - B[i]);
for (i = 1; i < size(A); i++) {
  fill(nopt, infinity);
  for (j = 1; j < size(B); j++) {
    nopt[j] = min(nopt[j - 1], opt[j - 1] + abs(A[i] - B[j]));
  swap(opt, nopt);
}
return opt[size(B) - 1];
</code>```

After each iteration i of the outer for loop above, opt[j] contains the optimal solution matching {A[0],..., A[i]} using the elements {B[0],..., B[j]}.

The correctness of this algorithm relies on the fact that in any optimal matching if a1 is matched with b1, a2 is matched with b2, and a1 < a2, then b1 <= b2.

Body:
Note that this problem is referred to sometimes as the skis and skiers problem, where you have n skis and m skiers of varying lengths and heights. The goal is to match skis with skiers so that the sum of the differences between heights and ski lengths is minimized.

To solve the problem you could use minimum weight bipartite matching, which requires O(n^3) time.

Even better, you can achieve O(n^2) time with O(n) extra memory using the simple dynamic programming algorithm below.

Optimally, you can solve the problem in linear time if the points are already sorted using the algorithm described in this paper.

O(n^2) dynamic programming algorithm:

if (size(B) > size(A))
  swap(A, B);
sort(A);
sort(B);
opt = array(size(B));
nopt = array(size(B));
for (i = 0; i < size(B); i++)
  opt[i] = abs(A[0] - B[i]);
for (i = 1; i < size(A); i++) {
  fill(nopt, infinity);
  for (j = 1; j < size(B); j++) {
    nopt[j] = min(nopt[j - 1], opt[j - 1] + abs(A[i] - B[j]));
  swap(opt, nopt);
}
return opt[size(B) - 1];

After each iteration i of the outer for loop above, opt[j] contains the optimal solution matching {A[0],..., A[i]} using the elements {B[0],..., B[j]}.

The correctness of this algorithm relies on the fact that in any optimal matching if a1 is matched with b1, a2 is matched with b2, and a1 < a2, then b1 <= b2.


问:
How to let user create a page via a URL?
I am thinking along the lines of /mysite/blogs/new. I know about add_child and about Routablepage, also the 'permissions route' but I still don't see how to permit page creation via a URL.

I am surprised that there do not appear to be any instructions for doing this, as relying on the admin method surely isn't acceptable for many 'naive' users. Indeed, it took me a while to realise that Wagtail isn't like Wordpress, in the sense of having an 'Add Post' button or the like.

The documentation does not clearly state that users are (apparently) expected to create pages via the Admin section either. In fact, there seems to be an assumption that developers will be familiar with Django, even though a CMS ought to be easier to use IMO.

Just to be clear, I think that Wagtail is great but the instructions leave something to be desired. Perhaps I will attempt to update them myself!

答:
If you have the Edit Bird/Userbar enabled, then it presents a button to add a child page at any point in the page tree so long as you have permission to add one there. If you wish to give naïve users this option then you could make their permissions fairly restrictive, so that they only see this option at certain locations, and they don't see any of the other 'settings' areas of the Admin.

The admin page for adding this does have its own URL: it typically looks like http://www.example.com/admin/pages/13/add_subpage/, where 13 is the ID of the current page. If instead you want to present that link yourself, you can manually add the link in the template as

```<code><a href="{% url 'wagtailadmin_pages:add_subpage' page.id %}">Add a child page</a>
</code>```

but first you should ensure that the user has the relevant permission. This is best done in Python, rather than in the template. See https://github.com/wagtail/wagtail/blob/master/wagtail/wagtailadmin/userbar.py for how Wagtail does this.

To get closer to your original request, you could combine all the above with RoutablePageMixin, by creating a route 'add' which redirects to the same URL:

```<code>@route(r'^add$')
def add_child_page(self, request):
    return redirect(reverse('wagtailadmin_pages:add_subpage', args=[self.pk]))
</code>```

Body:
If you have the Edit Bird/Userbar enabled, then it presents a button to add a child page at any point in the page tree so long as you have permission to add one there. If you wish to give naïve users this option then you could make their permissions fairly restrictive, so that they only see this option at certain locations, and they don't see any of the other 'settings' areas of the Admin.

The admin page for adding this does have its own URL: it typically looks like http://www.example.com/admin/pages/13/add_subpage/, where 13 is the ID of the current page. If instead you want to present that link yourself, you can manually add the link in the template as

<a href="{% url 'wagtailadmin_pages:add_subpage' page.id %}">Add a child page</a>

but first you should ensure that the user has the relevant permission. This is best done in Python, rather than in the template. See https://github.com/wagtail/wagtail/blob/master/wagtail/wagtailadmin/userbar.py for how Wagtail does this.

To get closer to your original request, you could combine all the above with RoutablePageMixin, by creating a route 'add' which redirects to the same URL:

@route(r'^add$')
def add_child_page(self, request):
    return redirect(reverse('wagtailadmin_pages:add_subpage', args=[self.pk]))


问:
Is object empty?
What is the fastest way to check if an object is empty or not?

Is there a faster and better way than this:

```<code>function count_obj(obj){
    var i = 0;
    for(var key in obj){
        ++i;
    }

    return i;
}
</code>```

答:
```<code>var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)

true
false
</code>```

http://jsfiddle.net/j7ona6hz/1/

Title: Is object empty?

Body:
What is the fastest way to check if an object is empty or not?

Is there a faster and better way than this:

function count_obj(obj){
    var i = 0;
    for(var key in obj){
        ++i;
    }

    return i;
}

Body:
var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)

true
false

http://jsfiddle.net/j7ona6hz/1/

ContentLicense: CC BY-SA 4.0


问:
Passing non-const arguments to const function parameters in C
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:

```<code>int func1(const char *some_string)
{
    // Do something non-destructive with some_string
}
</code>```

I pass a non-const variable as an argument to func1:

```<code>int func2(void)
{
    char *my_string = "my text";
    func1(my_string);
}
</code>```

gcc reports:

```<code>warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
</code>```

What is the correct way to deal with this situation? Creating a const copy of my_string seems a bit much, but simply casting seems like burying the warning.

答:
The issue you're having stems from your main function.

When you declare char *my_string = "my text";,you are creating a non-const pointer to a string literal. By design, string literals such as "my text" are immutable, and therefore const in the language. (In practice, the compilers usually put the string literals into a specific section of the executable which contains read-only memory, so attempting to modify the literal using the non-const pointer can lead to a segfault.)

By declaring a non-const pointer to the string literal, you end up with a pointer which you could use to modify the immutable string literal, which is considered undefined behavior in C.

See this question for more information.

The easiest way to solve this is to simply change char *my_string into const char *my_string.

Body:
I have a function that specifies a const parameter to indicate to the caller that it won't be modfied:

int func1(const char *some_string)
{
    // Do something non-destructive with some_string
}

I pass a non-const variable as an argument to func1:

int func2(void)
{
    char *my_string = "my text";
    func1(my_string);
}

gcc reports:

warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]

What is the correct way to deal with this situation? Creating a const copy of my_string seems a bit much, but simply casting seems like burying the warning.


答: Your local path is probably not what you want it to be. Before executing the ftp command, add a cd to the directory of where the file is located. Or have the full path name to the file $FILE.</p>

Title: shell scripts runs manually but not in crontab


问:
Creating a trigger gives "function does not exist" error in PostgreSQL
I'm working on a project right now where I'm trying to build a trigger that updates a column "lastedit" (in the table Person), which is a timestamp storing when the last change was made to the table in the schema specified in the trigger creation (in this case Certifications).

Now, my problem is that when I try to create the trigger, after creating the function "update_lastedit()", it gives me an error saying that the function does not exist. I think I might have a mismatch in my function somewhere, but I cannot seem to find it.

Could any of you help me out? I'm running PostgreSQL 9.5.5. Please let me know if I need to give a more extensive explanation, this is my first question, so I might have overlooked something important.

My code for the trigger and the function are as follows:

```<code>CREATE OR REPLACE FUNCTION update_lastedit() RETURNS TRIGGER AS
$update_edit$
BEGIN
    UPDATE ovsoftware.person
    SET lastedit = now();
END;
$update_edit$
LANGUAGE plpgsql;
</code>```

and

```<code>CREATE TRIGGER cert_edit_trigger
    BEFORE INSERT OR UPDATE ON ovsoftware.certifications
    FOR EACH ROW
    EXECUTE PROCEDURE update_lastedit();
</code>```

The exact error:

```<code>SQL fout:

ERROR:  function update_lastedit() does not exist
In statement:

CREATE TRIGGER cert_edit_trigger
    BEFORE INSERT OR UPDATE ON ovsoftware.certifications
    FOR EACH ROW
    EXECUTE PROCEDURE update_lastedit();
</code>```

答:
The solution was to use a fully qualified name for the function as follows: ovsoftware.update_lastedit(). I am not sure why that is the case, as I did not need to do so in other cases.
Either way, the scope apparently did not include the ovsoftware schema, leading to the error.

Body:
I'm working on a project right now where I'm trying to build a trigger that updates a column "lastedit" (in the table Person), which is a timestamp storing when the last change was made to the table in the schema specified in the trigger creation (in this case Certifications).

Now, my problem is that when I try to create the trigger, after creating the function "update_lastedit()", it gives me an error saying that the function does not exist. I think I might have a mismatch in my function somewhere, but I cannot seem to find it.

Could any of you help me out? I'm running PostgreSQL 9.5.5. Please let me know if I need to give a more extensive explanation, this is my first question, so I might have overlooked something important.

My code for the trigger and the function are as follows:

CREATE OR REPLACE FUNCTION update_lastedit() RETURNS TRIGGER AS
$update_edit$
BEGIN
    UPDATE ovsoftware.person
    SET lastedit = now();
END;
$update_edit$
LANGUAGE plpgsql;

and

CREATE TRIGGER cert_edit_trigger
    BEFORE INSERT OR UPDATE ON ovsoftware.certifications
    FOR EACH ROW
    EXECUTE PROCEDURE update_lastedit();

The exact error:

SQL fout:

ERROR:  function update_lastedit() does not exist
In statement:

CREATE TRIGGER cert_edit_trigger
    BEFORE INSERT OR UPDATE ON ovsoftware.certifications
    FOR EACH ROW
    EXECUTE PROCEDURE update_lastedit();


问:
MS SQL Server Row GUID Column
I apologize for asking what seems like a tired question, but no forum response or documentation I've read seems to provide an adequate answer.

What is the purpose of the Row GUID Column property in MS SQL Server 2008?

Let me extend on that. I've seen "Don't use GUID as the PK" repeated as the answer for this question, which seems to be completely unrelated to me. If I set Row GUID Column is it forcing that GUID column to be the primary key or something?

To rephrase my original question: If I have a GUID column in my table that does not play any role in indexing, do I stand to gain anything from setting that GUID column as the Row GUID Column?

答:
It enables you to use the $ROWGUID variable instead of the column name.
It's used mostly for merge replication.
It doesn't force the GUID column for PK, you can only declare PKs explicitly.
The answer to your last question is no, unless you plan on implementing Merge Replication.</p>

Title: MS SQL Server Row GUID Column