问:
gradle tar task not executed
I am writing a Gradle build for a non-java project for assembling existing directories and tar archives into a .tar.gz The tar task skips if I use the definition like so:

```<code>task archive(dependsOn: 'initArchive',type: Tar) << {
    baseName = project.Name
    destinationDir = new File(project.buildDir.path+'/installer')
    compression = Compression.GZIP
    from (archiveDir)
    doLast{
        checksum(archivePath)
    }
}
</code>```

here's the console output

```<code>:jenkins-maven-sonar:archive
Skipping task ':jenkins-maven-sonar:archive' as it has no source files.
:jenkins-maven-sonar:archive UP-TO-DATE

BUILD SUCCESSFUL

Total time: 9.056 secs
</code>```

When I try to use tar task as a method it fails complaining cannot find method

```<code>task archive(dependsOn: 'initArchive') << {
    tar{
    baseName = project.Name
    destinationDir = new File(project.buildDir.path+'/installer')
    compression = Compression.GZIP
    from (archiveDir)
    doLast{
        checksum(archivePath)
    }
    }
}

FAILURE: Build failed with an exception.

* Where:
Build file '/home/anadi/Code/da-ci-installers/build.gradle' line: 29

* What went wrong:
Execution failed for task ':jenkins-maven-sonar:archive'.
> Could not find method tar() for arguments [build_6a2bckppv2tk8qodr6lkg5tqft$_run_closure3_closure5_closure7@4a5f634c] on task ':jenkins-maven-sonar:archive'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 8.749 secs
</code>```

Can we run the tar task in same way as Gradle allows running copy? In the same build I have a block like follows and I want to know if tar can used in the same way

```<code>            copy {
                project.logger.info("Copying bundle :: "+bundle[x])
                from(rootProject.projectDir.path+"/3rd-party-tools/"+bundle[x]) {
                    include '**/*.*'
                }
                into(archiveDir)
           }
</code>```

if not how to make sure my build does not "skip tar" task if using the first form described above.

答:
I had a funny situation where I got hit by this when using doLast{} on a tar task.

It was because of a multi-project build:

```<code>build.gradle
--> sub-project
    --> build.gradle
</code>```

In this case if you try to have a tar or a copy task in the main build file that references something from that project(":sub-project") uses it will tempt the developer to wrap it in doLast.

For example, main build.gradle file has:

```<code>  task distTar(type: Tar, dependsOn: "buildDist") {
    description "Package ProjName into a Tar file"
    group "Build"
    baseName = 'outbasename'
    archiveName = baseName + '.tar.gz'
    compression = Compression.GZIP
    destinationDir = file(project(":packaging").buildDir.path)
    extension = 'tar.gz'
    into('outdir') {
      from project(":sub-project").war
    }
  }
</code>```

So they got an error that project(":sub-project").war doesn't exist. So to get around it someone put doLast {} the task and errors went away. BAD!!

```<code>  task distTar(type: Tar, dependsOn: "buildDist") {
    doLast { // <-- BAD!!
      description "Package ProjName into a Tar file"
      group "Build"
      baseName = 'outbasename'
      archiveName = baseName + '.tar.gz'
      compression = Compression.GZIP
      destinationDir = file(project(":packaging").buildDir.path)
      extension = 'tar.gz'
      into('outdir') {
        from project(":sub-project").war
      }
    }
  }
</code>```

Then i was left to fix it. So the correct was to do it was to add

evaluationDependsOn ":sub-project"

In the main build.gradle file. Now it knows to evaluate it. I remove the incorrect doLast{} block and now the task is no longer ignored.

Title: gradle tar task not executed

Body:
I am writing a Gradle build for a non-java project for assembling existing directories and tar archives into a .tar.gz The tar task skips if I use the definition like so:

task archive(dependsOn: 'initArchive',type: Tar) << {
    baseName = project.Name
    destinationDir = new File(project.buildDir.path+'/installer')
    compression = Compression.GZIP
    from (archiveDir)
    doLast{
        checksum(archivePath)
    }
}

here's the console output

:jenkins-maven-sonar:archive
Skipping task ':jenkins-maven-sonar:archive' as it has no source files.
:jenkins-maven-sonar:archive UP-TO-DATE

BUILD SUCCESSFUL

Total time: 9.056 secs

When I try to use tar task as a method it fails complaining cannot find method

task archive(dependsOn: 'initArchive') << {
    tar{
    baseName = project.Name
    destinationDir = new File(project.buildDir.path+'/installer')
    compression = Compression.GZIP
    from (archiveDir)
    doLast{
        checksum(archivePath)
    }
    }
}

FAILURE: Build failed with an exception.

* Where:
Build file '/home/anadi/Code/da-ci-installers/build.gradle' line: 29

* What went wrong:
Execution failed for task ':jenkins-maven-sonar:archive'.
> Could not find method tar() for arguments [build_6a2bckppv2tk8qodr6lkg5tqft$_run_closure3_closure5_closure7@4a5f634c] on task ':jenkins-maven-sonar:archive'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 8.749 secs

Can we run the tar task in same way as Gradle allows running copy? In the same build I have a block like follows and I want to know if tar can used in the same way

            copy {
                project.logger.info("Copying bundle :: "+bundle[x])
                from(rootProject.projectDir.path+"/3rd-party-tools/"+bundle[x]) {
                    include '**/*.*'
                }
                into(archiveDir)
           }

if not how to make sure my build does not "skip tar" task if using the first form described above.

Body:
I had a funny situation where I got hit by this when using doLast{} on a tar task.

It was because of a multi-project build:

build.gradle
--> sub-project
    --> build.gradle

In this case if you try to have a tar or a copy task in the main build file that references something from that project(":sub-project") uses it will tempt the developer to wrap it in doLast.

For example, main build.gradle file has:

  task distTar(type: Tar, dependsOn: "buildDist") {
    description "Package ProjName into a Tar file"
    group "Build"
    baseName = 'outbasename'
    archiveName = baseName + '.tar.gz'
    compression = Compression.GZIP
    destinationDir = file(project(":packaging").buildDir.path)
    extension = 'tar.gz'
    into('outdir') {
      from project(":sub-project").war
    }
  }

So they got an error that project(":sub-project").war doesn't exist. So to get around it someone put doLast {} the task and errors went away. BAD!!

  task distTar(type: Tar, dependsOn: "buildDist") {
    doLast { // <-- BAD!!
      description "Package ProjName into a Tar file"
      group "Build"
      baseName = 'outbasename'
      archiveName = baseName + '.tar.gz'
      compression = Compression.GZIP
      destinationDir = file(project(":packaging").buildDir.path)
      extension = 'tar.gz'
      into('outdir') {
        from project(":sub-project").war
      }
    }
  }

Then i was left to fix it. So the correct was to do it was to add

evaluationDependsOn ":sub-project"

In the main build.gradle file. Now it knows to evaluate it. I remove the incorrect doLast{} block and now the task is no longer ignored.


来源: stackexchange

问:
Android: Is it ok to have multiple handlers per thread
Is it a bad practice to have multiple objects on a thread instantiating and using there own private handlers? Is an application supposed to instantiate and use only one handler per thread and pass it around among objects?</p>

答: There are benefits to have multiple Handlers per Looper/MessageQueue pair. You can send and handle different categories of Runnables or Messages on respective handlers, which reduces the number of if else to make you program more maintainable.

ContentLicense: CC BY-SA 3.0


问:
SQL SELECT WHERE field contains words
I need a select which would return results like this:

```<code>SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'
</code>```

And I need all results, i.e. this includes strings with 'word2 word3 word1' or 'word1 word3 word2' or any other combination of the three.

All words need to be in the result.

答:
Try to use the "Tesarus search" in a full text index in SQL Server. This is much better than using "%" in search if you have millions of records. Tesarus has a smaller amount of memory consumption than the others.

Try to search this functions :)

Title: SQL SELECT WHERE field contains words

Body:
I need a select which would return results like this:

SELECT * FROM MyTable WHERE Column1 CONTAINS 'word1 word2 word3'

And I need all results, i.e. this includes strings with 'word2 word3 word1' or 'word1 word3 word2' or any other combination of the three.

All words need to be in the result.

ContentLicense: CC BY-SA 4.0


问:
attempt to concatenate field ' ?' (a nil value) corona SDK
hey i'm newbie both in corona and lua, i'm making a little memory game for a school project but i keep getting the error with the concatenation for a nill value, it shows the elements from the concatenation in the screen but it dosn't work

heres my code:

```<code>display.setStatusBar(display.HiddenStatusBar)
centerX=display.contentCenterX
centerY=display.contentCenterY
screenX=display.screenOriginX
screenY=display.screenOriginY
screenWidth=display.contentWidth-screenX * 1
screenHeight=display.contentHeight - screenY *1
screenLeft=screenX
screenRight=screenX + screenWidth
screenTop=screenY
screenBottom=screenY+screenHeight
display.contentWidht=screenWidth
display.contentHeight=screenHeight

display.cl=display.CenterLeftReferencePoint
local tileImg="images/lolo.png"
local hiddenObjects={
"cubo", "abeja", "mariposa", "flor",
"cubo", "abeja", "mariposa", "flor"}

local tileWidth=100
local tileHeigth=100
local tileAcross=6
local tileDown=4
local tileSpacing=2
local topSpacing=screenTop+tileHeigth+tileSpacing
local leftSpacing = screenLeft+tileWidth+tileSpacing

local numMatches=0
local numObjsShowing=0
local flipped={}
local pauseDelay=800
local score=0
local scoreTxt=nil

local allTiles={}
local allThings={}

local resetGame

local function shuffle(t)
    local n= #t
    while n > 2 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
    n = n-1
    end
    return t
end
 local function killObj( obj)
    display.remove( obj )
    obj = nil
 -- body
 end

 local function startOver()
    local msg
    local function start(event)
        killObj(event.target)
        resetGame()
        -- body
    end
    msg=display.newText("Tap Here To Start", 0, 0, "Helvetica", 24)
    msg.x=centerX
    msg.y=centerY+250
    msg:addEventListener("tap", start)
end
local function addToScore( addNum )
    local num = addNum or 100
    score = score +num
    scoreTxt:setReferencePoint(display.cl)
    scoreTxt.x = screenWidth+250
    -- body
end

local function checkForMatch()
    if #flipped== 2 then
        local idx1,idx2=flipped[1],flipped[2]
        local function resetNumObjsShowing()
            numObjsShowing=0

        end
        if allThings[idx1].name==allThings[idx2].name then
            audio.play(sndMatch)
            allThings[idx1]:toFront()
            allThings[idx2]:toFront()
            transition.to(allThings[idx1],{time=400, x=screenRight,                       y=screenTop, alpha=0})
            transition.to(allThings[idx2],{time=400, x=screenRight, y=screenTop, alpha=0})
            addToScore(100)
            resetNumObjsShowing()
            numMatches=numMatches+1
            if numMatches==(tileAcross * tileDown / 2) then
                audio.play(sndWinner)
                startOver()
            end
        else
            audio.play(sndNoMatch)
            transition.to(allTiles[idx1],{delay=pauseDelay, time=200,alpha=1, onComplete=resetNumObjsShowing})
            transition.to(allTiles[idx2],{delay=pauseDelay, time=200,alpha=1,})
            if score> 20 then
                addToScore(-20)
            end
    end

    flipped[1]=nil
    flipped[2]=nil
end
end

local function  tileTapped(event)
    if numObjsShowing< 2 then
        local tile=event.target
        if flipped[numObjsShowing]~=tile.idx then
            numObjsShowing=numObjsShowing+1
            flipped[numObjsShowing]=tile.idx
            transition.to(tile,{time=500,alpha=0,onComplete=checkForMatch})
        end
    end
end

local function makeTiles(things)
    local idx=1
    for x = 1, tileAcross do
        for y = 1, tileDown do
            local thing = display.newImage("images/" ..things[idx].. ".png")
            thing.x=(x+1.5)*(tileWidth + tileSpacing)+ leftSpacing
            thing.y=(y+0.9)*(tileHeigth + tileSpacing)+ topSpacing
            thing.name=things[idx]
            allThings[#allThings+1]=thing

            local tile = display.newImage(tileImg)
            tile.x =(x+1) * (tileWidth + tileSpacing)+ leftSpacing
            tile.y =(y+1) * (tileHeigth + tileSpacing)+ topSpacing
            tile.idx=idx
            tile:addEventListener("tap", tileTapped)
            allTiles[#allTiles+1]=tile

            idx=idx+1
        end
    end
end

function resetGame()
    numMatches= 0
    numObjsShowing = 0
    score = 0
    scoreTxt.text ="score: 000"
    flipped[1]=nil
    flipped[2]=nil

    if allThings ~={} then
        for x=#allThings, 1, -1 do
            killObj(allThings[x])
        end

        allThings={}
    -- body
end
if allTiles ~={} then
    for x=#allTiles,1,-1 do
        killObj(allTiles[x])
end
allTiles={}
end
makeTiles(shuffle(hiddenObjects))
end

local function setupDisplay()
local bg=display.newImage("images/paisaje1.jpg")
bg.x=centerX
bg.y=centerY
bg.width=screenWidth
bg.height=screenHeight

scoreTxt = display.newText("Score: 000", 0, 0, "Helvetica", 18)
scoreTxt.x=screenWidth-120
scoreTxt.y=screenTop+15
end
setupDisplay()
startOver()
</code>```

any suggestion is welcome

答:
The index value idx in the makeTiles() function is being incremented at the end of the inner loop, so after a couple of iterations of the outer loop, idx is referencing nil values in things, since #things is 8.

One possible fix is to use the modulus operator to keep idx between 1 and 8:

```<code>idx=(idx % 8) + 1
</code>```

This will cycle through the shuffled table repeatedly. You could also call shuffle again on things when idx is reset to 1.

Body:
hey i'm newbie both in corona and lua, i'm making a little memory game for a school project but i keep getting the error with the concatenation for a nill value, it shows the elements from the concatenation in the screen but it dosn't work

heres my code:

display.setStatusBar(display.HiddenStatusBar)
centerX=display.contentCenterX
centerY=display.contentCenterY
screenX=display.screenOriginX
screenY=display.screenOriginY
screenWidth=display.contentWidth-screenX * 1
screenHeight=display.contentHeight - screenY *1
screenLeft=screenX
screenRight=screenX + screenWidth
screenTop=screenY
screenBottom=screenY+screenHeight
display.contentWidht=screenWidth
display.contentHeight=screenHeight

display.cl=display.CenterLeftReferencePoint
local tileImg="images/lolo.png"
local hiddenObjects={
"cubo", "abeja", "mariposa", "flor",
"cubo", "abeja", "mariposa", "flor"}

local tileWidth=100
local tileHeigth=100
local tileAcross=6
local tileDown=4
local tileSpacing=2
local topSpacing=screenTop+tileHeigth+tileSpacing
local leftSpacing = screenLeft+tileWidth+tileSpacing

local numMatches=0
local numObjsShowing=0
local flipped={}
local pauseDelay=800
local score=0
local scoreTxt=nil

local allTiles={}
local allThings={}

local resetGame

local function shuffle(t)
    local n= #t
    while n > 2 do
    local k = math.random(n)
    t[n], t[k] = t[k], t[n]
    n = n-1
    end
    return t
end
 local function killObj( obj)
    display.remove( obj )
    obj = nil
 -- body
 end

 local function startOver()
    local msg
    local function start(event)
        killObj(event.target)
        resetGame()
        -- body
    end
    msg=display.newText("Tap Here To Start", 0, 0, "Helvetica", 24)
    msg.x=centerX
    msg.y=centerY+250
    msg:addEventListener("tap", start)
end
local function addToScore( addNum )
    local num = addNum or 100
    score = score +num
    scoreTxt:setReferencePoint(display.cl)
    scoreTxt.x = screenWidth+250
    -- body
end

local function checkForMatch()
    if #flipped== 2 then
        local idx1,idx2=flipped[1],flipped[2]
        local function resetNumObjsShowing()
            numObjsShowing=0

        end
        if allThings[idx1].name==allThings[idx2].name then
            audio.play(sndMatch)
            allThings[idx1]:toFront()
            allThings[idx2]:toFront()
            transition.to(allThings[idx1],{time=400, x=screenRight,                       y=screenTop, alpha=0})
            transition.to(allThings[idx2],{time=400, x=screenRight, y=screenTop, alpha=0})
            addToScore(100)
            resetNumObjsShowing()
            numMatches=numMatches+1
            if numMatches==(tileAcross * tileDown / 2) then
                audio.play(sndWinner)
                startOver()
            end
        else
            audio.play(sndNoMatch)
            transition.to(allTiles[idx1],{delay=pauseDelay, time=200,alpha=1, onComplete=resetNumObjsShowing})
            transition.to(allTiles[idx2],{delay=pauseDelay, time=200,alpha=1,})
            if score> 20 then
                addToScore(-20)
            end
    end

    flipped[1]=nil
    flipped[2]=nil
end
end

local function  tileTapped(event)
    if numObjsShowing< 2 then
        local tile=event.target
        if flipped[numObjsShowing]~=tile.idx then
            numObjsShowing=numObjsShowing+1
            flipped[numObjsShowing]=tile.idx
            transition.to(tile,{time=500,alpha=0,onComplete=checkForMatch})
        end
    end
end

local function makeTiles(things)
    local idx=1
    for x = 1, tileAcross do
        for y = 1, tileDown do
            local thing = display.newImage("images/" ..things[idx].. ".png")
            thing.x=(x+1.5)*(tileWidth + tileSpacing)+ leftSpacing
            thing.y=(y+0.9)*(tileHeigth + tileSpacing)+ topSpacing
            thing.name=things[idx]
            allThings[#allThings+1]=thing

            local tile = display.newImage(tileImg)
            tile.x =(x+1) * (tileWidth + tileSpacing)+ leftSpacing
            tile.y =(y+1) * (tileHeigth + tileSpacing)+ topSpacing
            tile.idx=idx
            tile:addEventListener("tap", tileTapped)
            allTiles[#allTiles+1]=tile

            idx=idx+1
        end
    end
end

function resetGame()
    numMatches= 0
    numObjsShowing = 0
    score = 0
    scoreTxt.text ="score: 000"
    flipped[1]=nil
    flipped[2]=nil

    if allThings ~={} then
        for x=#allThings, 1, -1 do
            killObj(allThings[x])
        end

        allThings={}
    -- body
end
if allTiles ~={} then
    for x=#allTiles,1,-1 do
        killObj(allTiles[x])
end
allTiles={}
end
makeTiles(shuffle(hiddenObjects))
end

local function setupDisplay()
local bg=display.newImage("images/paisaje1.jpg")
bg.x=centerX
bg.y=centerY
bg.width=screenWidth
bg.height=screenHeight

scoreTxt = display.newText("Score: 000", 0, 0, "Helvetica", 18)
scoreTxt.x=screenWidth-120
scoreTxt.y=screenTop+15
end
setupDisplay()
startOver()

any suggestion is welcome

Body:
The index value idx in the makeTiles() function is being incremented at the end of the inner loop, so after a couple of iterations of the outer loop, idx is referencing nil values in things, since #things is 8.

One possible fix is to use the modulus operator to keep idx between 1 and 8:

idx=(idx % 8) + 1

This will cycle through the shuffled table repeatedly. You could also call shuffle again on things when idx is reset to 1.


问:
Table-valued function refresh
I have a table-valued function (TVF) in SQL Server that looks like this:

```<code>CREATE FUNCTION TVF_xyz(@AuditKey INT)
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM xyz
        WHERE AUDIT_KEY = @AuditKey
GO
</code>```

Now, I added a new column to the xyz table.

When I query using TVF_xyz, it doesn't show me the new column (shows all other columns except newly added).

Query:

```<code>SELECT TOP 10 *
FROM TVF_xyz (1543)
</code>```

I would like to know, how to refresh TVF to show new column.

PS: Select * used in TVF to fetch all columns.

答:
After bit of searching, I found sp_refreshsqlmodule (Transact-SQL), its common behavior of TVF.

In order to refresh TVF, following SP needs to be executed:

```<code>EXEC sys.sp_refreshsqlmodule 'TVF_xyz'
</code>```

Title: Table-valued function refresh

Body:
I have a table-valued function (TVF) in SQL Server that looks like this:

CREATE FUNCTION TVF_xyz(@AuditKey INT)
RETURNS TABLE
AS
    RETURN
        SELECT *
        FROM xyz
        WHERE AUDIT_KEY = @AuditKey
GO

Now, I added a new column to the xyz table.

When I query using TVF_xyz, it doesn't show me the new column (shows all other columns except newly added).

Query:

SELECT TOP 10 *
FROM TVF_xyz (1543)

I would like to know, how to refresh TVF to show new column.

PS: Select * used in TVF to fetch all columns.

Body:
After bit of searching, I found sp_refreshsqlmodule (Transact-SQL), its common behavior of TVF.

In order to refresh TVF, following SP needs to be executed:

EXEC sys.sp_refreshsqlmodule 'TVF_xyz'


问:
C++: Access to a public member function from outside of a class
I have a class defined in a separate file and at some point I need to access one of the public member functions from another source file. For some reason, I forgot how to do that and compiler gives me an error.

I have classA.h with definition of class A similar to this:

```<code>class classA {
  public:
  int function1(int alpha);
}
</code>```

And a separate file classA.cpp with the implementation. And then in some other file blah.cpp I include the header and try to access it like this:

```<code> classA::function1(15);
</code>```

and my compiler refuses it with error that it could not find a match for 'classA::function1(int)'.

I use Embarcadero RAD studio 2010 if that matters.

答:
To call a 'normal' function, you need an instance.

```<code>classA a;
a.function1(15);
</code>```

If you want to call the function using classA:: then it needs to be static.

```<code>classA {
  public:
    static int function1(int alpha);
};

//...
classA::function1(15);
</code>```

Note that inside a static method, you can't access any non-static member variables, for the same reason - there is no instance to provide context.

ContentLicense: CC BY-SA 2.5

Body:
I have a class defined in a separate file and at some point I need to access one of the public member functions from another source file. For some reason, I forgot how to do that and compiler gives me an error.

I have classA.h with definition of class A similar to this:

class classA {
  public:
  int function1(int alpha);
}

And a separate file classA.cpp with the implementation. And then in some other file blah.cpp I include the header and try to access it like this:

 classA::function1(15);

and my compiler refuses it with error that it could not find a match for 'classA::function1(int)'.

I use Embarcadero RAD studio 2010 if that matters.

Body:
To call a 'normal' function, you need an instance.

classA a;
a.function1(15);

If you want to call the function using classA:: then it needs to be static.

classA {
  public:
    static int function1(int alpha);
};

//...
classA::function1(15);

Note that inside a static method, you can't access any non-static member variables, for the same reason - there is no instance to provide context.


问:
Swift 3 - Display alert controller asynchronously with long function running in background
I am using Swift 3.

The behavior I am trying to do is: the user clicks on a button, a spinning gear alert controller displays while it kicks off a long-running function.  Once that function is done executing, the spinning gear goes away and the view controller dismisses.

The code below kicks off the doProcessing function but doesn't display the spinning gear until about a second before the view dismisses.  So this isn't quite right.

```<code>func displaySpinningGear() {

    print("display spinning gear")
    // show the alert window box
    let activityAlertController = UIAlertController(title: "Processing", message: "Please wait while the photo is being processed.", preferredStyle: .alert)

    //create an activity indicator
    let indicator = UIActivityIndicatorView(frame: activityAlertController.view.bounds)
    indicator.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    indicator.hidesWhenStopped = true
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray

    //add the activity indicator as a subview of the alert controller's view
    activityAlertController.view.addSubview(indicator)
    indicator.isUserInteractionEnabled = false // required otherwise if there buttons in the UIAlertController you will not be able to press them
    indicator.startAnimating()

    print("start animating")

    self.present(activityAlertController, animated: true, completion: nil)
}

func onButtonClick() {
    self.displaySpinningGear()
    DispatchQueue.main.async {
        self.doProcessing() // long running function
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}
</code>```

The code below kicks off the doProcessing function but the view dismisses immediately and I can tell from the console that my doProcessing function is still running.  This is not right either.

```<code>function onButtonClick() {
    DispatchQueue.global(qos: .background).async {
        print("Processing")
        self.doProcessing() // run in background

        DispatchQueue.main.async {
            self.displaySpinningGear()
        }
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}
</code>```

How do I get the background function to kick off while displaying a spinning gear and dismiss the view and alert controller when the background function is done running (not before)?

EDIT

Tried moving the code to spin the gear outside the background block as per @Honey's suggestion in the comment but to no avail. The view immediately dismisses while the process function is still processing (I can tell through print statements).

```<code>func onButtonClick() {
    DispatchQueue.main.async {
        self.displaySpinningGear()
    }
    DispatchQueue.global(qos: .background).async {
        print("Processing")
        self.doProcessing() // run in background
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}
</code>```

答:
Make a Callback from long running function so when it ends returns a value and catch it to disappear the alert.

Try it:

```<code>typealias DoProcessingCallback = (_ finished: Bool) -> Void

func onButtonClick() {
    self.displaySpinningGear()

    self.doProcessing(callback: { (finished) in

        if finished {
           // Here you DismissViewController
           // Here you DismissAlert
        }

    }) // long running function

}

func doProcessing(callback: DoProcessingCallback) {
    // YOUR LONG CODE....
    // When you know it already finished
    callback(true)
}
</code>```

Hope it helps you

Body:
I am using Swift 3.

The behavior I am trying to do is: the user clicks on a button, a spinning gear alert controller displays while it kicks off a long-running function.  Once that function is done executing, the spinning gear goes away and the view controller dismisses.

The code below kicks off the doProcessing function but doesn't display the spinning gear until about a second before the view dismisses.  So this isn't quite right.

func displaySpinningGear() {

    print("display spinning gear")
    // show the alert window box
    let activityAlertController = UIAlertController(title: "Processing", message: "Please wait while the photo is being processed.", preferredStyle: .alert)

    //create an activity indicator
    let indicator = UIActivityIndicatorView(frame: activityAlertController.view.bounds)
    indicator.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    indicator.hidesWhenStopped = true
    indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray

    //add the activity indicator as a subview of the alert controller's view
    activityAlertController.view.addSubview(indicator)
    indicator.isUserInteractionEnabled = false // required otherwise if there buttons in the UIAlertController you will not be able to press them
    indicator.startAnimating()

    print("start animating")

    self.present(activityAlertController, animated: true, completion: nil)
}

func onButtonClick() {
    self.displaySpinningGear()
    DispatchQueue.main.async {
        self.doProcessing() // long running function
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}

The code below kicks off the doProcessing function but the view dismisses immediately and I can tell from the console that my doProcessing function is still running.  This is not right either.

function onButtonClick() {
    DispatchQueue.global(qos: .background).async {
        print("Processing")
        self.doProcessing() // run in background

        DispatchQueue.main.async {
            self.displaySpinningGear()
        }
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}

How do I get the background function to kick off while displaying a spinning gear and dismiss the view and alert controller when the background function is done running (not before)?

EDIT

Tried moving the code to spin the gear outside the background block as per @Honey's suggestion in the comment but to no avail. The view immediately dismisses while the process function is still processing (I can tell through print statements).

func onButtonClick() {
    DispatchQueue.main.async {
        self.displaySpinningGear()
    }
    DispatchQueue.global(qos: .background).async {
        print("Processing")
        self.doProcessing() // run in background
    }

    if let viewController = presentingViewController {
        // This block will dismiss both current and a view controller presenting current
        viewController.dismiss(animated: true, completion: nil)
    }
    else {
        // This block will dismiss only current view controller
        self.dismiss(animated: true, completion: nil)
    }
}

Body:
Make a Callback from long running function so when it ends returns a value and catch it to disappear the alert.

Try it:

typealias DoProcessingCallback = (_ finished: Bool) -> Void

func onButtonClick() {
    self.displaySpinningGear()

    self.doProcessing(callback: { (finished) in

        if finished {
           // Here you DismissViewController
           // Here you DismissAlert
        }

    }) // long running function

}

func doProcessing(callback: DoProcessingCallback) {
    // YOUR LONG CODE....
    // When you know it already finished
    callback(true)
}

Hope it helps you


问:
How to unserialize the JSON data in server part
I have a simple form which I try to post using jQuery post in JSON format. The form is getting post but my problem is at PHP part. I am unable to get the data. From other stack question I found solution of just doing $_POST['FirstName'] but I am getting result as "FirstName=john&LastName=plar&Address=home&PhoneNumber=23423423".

How can I decode this JSON data? Below are the code that I have tried so far. Thank you.

```<code><form action="user.php" method="post" id="myForm">
    First Name: <input type="text" name="FirstName" />
    Last Name: <input type="text" name="LastName" />
    Address: <input type="text" name="Address" />
    Phone: <input type="text" name="PhoneNumber" />
    <input type="submit" id="submit" value="Submit"/>
</form>

<script>
$("#submit").on('click', function(e){
    e.preventDefault();
    var data = $("#myForm input").serialize();
    $.post('user.php',{"data":JSON.stringify(data)},function(data){

    },'json');

})
</script>
</code>```

user.php

```<code>$object =$_POST['data'];
$array = json_decode($object);
print_r($object);
</code>```

答:
you can make some changes in your script and PHP code to get a native $_POST data that don't need to unserialize:

Change script to make data posted is only your serialized form:

```<code>$("#submit").on('click', function(e){
    e.preventDefault();
    $.post('user.php',{$("#myForm").serialize()},function(data){});
});
</code>```

And in your PHP code, just dump your $_POST variable:

```<code>var_dump($_POST);
</code>```

And you can get this result:

```<code>array(4) {
  ["FirstName"]=>
  string(7) "b j hhj"
  ["LastName"]=>
  string(7) "bhjbhj "
  ["Address"]=>
  string(5) "jhjjh"
  ["PhoneNumber"]=>
  string(0) ""
}
</code>```

This will efficient than serialize & unserialize many time.

Body:
I have a simple form which I try to post using jQuery post in JSON format. The form is getting post but my problem is at PHP part. I am unable to get the data. From other stack question I found solution of just doing $_POST['FirstName'] but I am getting result as "FirstName=john&LastName=plar&Address=home&PhoneNumber=23423423".

How can I decode this JSON data? Below are the code that I have tried so far. Thank you.

<form action="user.php" method="post" id="myForm">
    First Name: <input type="text" name="FirstName" />
    Last Name: <input type="text" name="LastName" />
    Address: <input type="text" name="Address" />
    Phone: <input type="text" name="PhoneNumber" />
    <input type="submit" id="submit" value="Submit"/>
</form>

user.php

$object =$_POST['data'];
$array = json_decode($object);
print_r($object);

Body:
you can make some changes in your script and PHP code to get a native $_POST data that don't need to unserialize:

Change script to make data posted is only your serialized form:

$("#submit").on('click', function(e){
    e.preventDefault();
    $.post('user.php',{$("#myForm").serialize()},function(data){});
});

And in your PHP code, just dump your $_POST variable:

var_dump($_POST);

And you can get this result:

array(4) {
  ["FirstName"]=>
  string(7) "b j hhj"
  ["LastName"]=>
  string(7) "bhjbhj "
  ["Address"]=>
  string(5) "jhjjh"
  ["PhoneNumber"]=>
  string(0) ""
}

This will efficient than serialize & unserialize many time.


问:
Auth::login($user) in laravel not able to login the user
I am using laravel 5.4 and Auth::login($user) is showing Type error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
  implement interface Illuminate\Contracts\Auth\Authenticatable,
  instance of Illuminate\Database\Eloquent\Builder given, called in
  /home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
  line 294

My User.php file is:

```<code>namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'role', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}
</code>```

My AuthController.php is:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;

class AuthController extends Controller
{
//
public function register(Request $request){
    $this->validate($request, [
        'name' => 'required|max:30',
        'email' => 'required|email|unique:users',
        'regpassword' => 'required|alpha_num|confirmed'
        ]);

    /*$user = new User();
    $user['name'] = $request['name'];
    $user['email'] = $request['email'];
    $user['password'] = bcrypt($request['password']);
    $user['role'] = 'user';
    $user->save();
    */
    $user = User::create(array(
        'email' => Input::get('email'),
        'name' => Input::get('name'),
        'password' => Hash::make(Input::get('password')),
        'role' => 'user'));
    return 'success';

 }

public function userLogin(Request $request){
    $this->validate($request,[
        'email' => 'required|email',
        'password' => 'required'
        ]);

    $user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

    if($user){
        Auth::login($user);
        return $next($request);
    }
    else{
        return redirect()->back();
    }

}
}
</code>```

My web.php

```<code>Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');
Route::post('/register', 'AuthController@register');
Route::post('/UserLogin','AuthController@userLogin');
</code>```

答:
Solved my problem as following:</p>

```<code>$user = User::where('email', '=' $request['email'])->where('role','=','user')->first();
if(Hash::check($request['password'],$user->password)){
    Auth::login($user);
    return  'success';
}
</code>```

Body:
I am using laravel 5.4 and Auth::login($user) is showing Type error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
  implement interface Illuminate\Contracts\Auth\Authenticatable,
  instance of Illuminate\Database\Eloquent\Builder given, called in
  /home/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on
  line 294

My User.php file is:

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'role', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];
}

My AuthController.php is:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use Illuminate\Support\Facades\Input;
use \Hash;

class AuthController extends Controller
{
//
public function register(Request $request){
    $this->validate($request, [
        'name' => 'required|max:30',
        'email' => 'required|email|unique:users',
        'regpassword' => 'required|alpha_num|confirmed'
        ]);

    /*$user = new User();
    $user['name'] = $request['name'];
    $user['email'] = $request['email'];
    $user['password'] = bcrypt($request['password']);
    $user['role'] = 'user';
    $user->save();
    */
    $user = User::create(array(
        'email' => Input::get('email'),
        'name' => Input::get('name'),
        'password' => Hash::make(Input::get('password')),
        'role' => 'user'));
    return 'success';

 }

public function userLogin(Request $request){
    $this->validate($request,[
        'email' => 'required|email',
        'password' => 'required'
        ]);

    $user = User::where('email', '=', $request['email'])-> where('password' ,'=', Hash::make($request['password']))->where('role','=','user');

    if($user){
        Auth::login($user);
        return $next($request);
    }
    else{
        return redirect()->back();
    }

}
}

My web.php

Route::get('/', function () {
return view('welcome');
});

Auth::routes();

Route::get('/home', 'HomeController@index');
Route::post('/register', 'AuthController@register');
Route::post('/UserLogin','AuthController@userLogin');

Body:
Solved my problem as following:

$user = User::where('email', '=' $request['email'])->where('role','=','user')->first();
if(Hash::check($request['password'],$user->password)){
    Auth::login($user);
    return  'success';
}


问:
Unable to load DLL sqlite3 in Universal Windows App running on Mobile
I am developing a UWP. I am using the sqlite-net-pcl library. After upgrading my Application from RC to RTM , I got a runtime error - sqlite3.dll could not be found - if it runs on a Mobile emulator or a device. It worked prefectly after I added a reference to C++ 2013 Runtime Package and I ran it in Local Machine.

Exception Message:

Message "The type initializer for 'SQLitePCL.raw' threw an
  exception."   string

The innerexception message:

{"Unable to load DLL 'sqlite3': The specified module could not be
  found. (Exception from HRESULT: 0x8007007E)"} System.Exception
  {System.DllNotFoundException}

Of course I could not add a referece to 'Sqlite for Universal App Platform' because I am geting the following error

Severity  Code    Description Project File    Line Error      Payload contains
  two or more files with the same destination path 'sqlite3.dll'. Source
  files:  C:\Program Files (x86)\Microsoft
  SDKs\UAP\v0.8.0.0\ExtensionSDKs\SQLite.UAP.2015\3.8.11.1\Redist\Debug\ARM\sqlite3.dll
  C:\Users\sMavrikis.nuget\packages\SQLitePCL.raw_basic\0.7.1\build\native\sqlite3_dynamic\winrt81\arm\sqlite3.dll TestApp1

答:
I fixed a similar issue by selecting x64 or arm in the compiler configuration.

Error     Payload contains two or more files with the same destination path 'e_sqlite3.dll'. Source files:
  C:\Users\xleon.nuget\packages\SQLitePCLRaw.lib.e_sqlite3.v140\1.1.0\runtimes\win10-arm\native\e_sqlite3.dll
  C:\Users\xleon.nuget\packages\sqlitepclraw.lib.e_sqlite3.v140\1.1.0\runtimes\win10-x86\native\e_sqlite3.dll

but this, of course, won´t allow you to run the emulator


问:
Best way of using masks to select sub-vectors in Python
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

```<code>def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]
</code>```

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

答:
Combining the .to_bytes method of integers with np.unpackbits is reasonably fast. A 1,000,000 bit word is converted in less than a ms:

```<code>import numpy as np
import random
from timeit import timeit

# a slower approach using builtin 'bin' function
def to_numpy_mask_1(n, bits = 120):
    return (np.frombuffer(bin(n + 2**bits)[-bits:].encode('utf8'),
                          dtype=np.uint8)-48).view(bool)

# the real thing based on '.to_bytes'
def to_numpy_mask_2(n, bits = 120):
    return np.unpackbits(np.frombuffer(n.to_bytes((bits-1)//8 + 1, 'big'),
                                       dtype=np.uint8)).view(bool)[-bits:]

# check

base = 2**np.arange(120)[::-1].astype(object)
n = random.randint(0, 2**120)
print(n, base[to_numpy_mask_1(n)].sum(), base[to_numpy_mask_2(n)].sum())

# benchmark

# translation only, no indexing
N = 10**6
n = random.randint(0, 2**N)
print('{:8.6g} secs'.format(timeit(lambda: to_numpy_mask_1(n, bits = N),
                                   number=10)/10))
print('{:8.6g} secs'.format(timeit(lambda: to_numpy_mask_2(n, bits = N),
                                   number=10)/10))

# including indexing
data = np.random.randn(N)
print('{:8.6g} secs'.format(timeit(lambda: data[to_numpy_mask_1(n, bits = N)],
                                   number=10)/10))
print('{:8.6g} secs'.format(timeit(lambda: data[to_numpy_mask_2(n, bits = N)],
                                   number=10)/10))
</code>```

sample output:

```<code># 303734588154968662776606530859339928 303734588154968662776606530859339928 303734588154968662776606530859339928
# 0.00622677 secs
# 0.00051558 secs
# 0.0121338 secs
# 0.00697929 secs
</code>```

Body:
We want to select some elements of a 1D array v_data. The processing we need to do requires looping over sub-vectors of v_data.

Right now I use byte logic like Gosper's hack to create an integer n_mask whose binary representation corresponds to the indices of v_data I want.  n_mask can be converted to a binary vector through a method:

def num2bv(num, n_len):
    """Convert a number to a binary vector of some length"""
    return [bool((2**ii & num)//(2**ii)) for ii in reversed(range(0, n_len))]

Setting bv_mask = num2bv(n_mask, len(v_data)), the sub-vector can be recovered by running v_data[bv_using]

Is this a bad way to do it? In particular I am concerned that:

Indexing with binary vectors will be slow in practice

num2bv will be slow in practice

Ability to use this technique for vectors of any length depends on Python's arbitrary-precision integers, which might be slow or nonportable

Are these valid concerns?

Body:
Combining the .to_bytes method of integers with np.unpackbits is reasonably fast. A 1,000,000 bit word is converted in less than a ms:

import numpy as np
import random
from timeit import timeit

# a slower approach using builtin 'bin' function
def to_numpy_mask_1(n, bits = 120):
    return (np.frombuffer(bin(n + 2**bits)[-bits:].encode('utf8'),
                          dtype=np.uint8)-48).view(bool)

# the real thing based on '.to_bytes'
def to_numpy_mask_2(n, bits = 120):
    return np.unpackbits(np.frombuffer(n.to_bytes((bits-1)//8 + 1, 'big'),
                                       dtype=np.uint8)).view(bool)[-bits:]

# check

base = 2**np.arange(120)[::-1].astype(object)
n = random.randint(0, 2**120)
print(n, base[to_numpy_mask_1(n)].sum(), base[to_numpy_mask_2(n)].sum())

# benchmark

# translation only, no indexing
N = 10**6
n = random.randint(0, 2**N)
print('{:8.6g} secs'.format(timeit(lambda: to_numpy_mask_1(n, bits = N),
                                   number=10)/10))
print('{:8.6g} secs'.format(timeit(lambda: to_numpy_mask_2(n, bits = N),
                                   number=10)/10))

# including indexing
data = np.random.randn(N)
print('{:8.6g} secs'.format(timeit(lambda: data[to_numpy_mask_1(n, bits = N)],
                                   number=10)/10))
print('{:8.6g} secs'.format(timeit(lambda: data[to_numpy_mask_2(n, bits = N)],
                                   number=10)/10))

sample output:

# 303734588154968662776606530859339928 303734588154968662776606530859339928 303734588154968662776606530859339928
# 0.00622677 secs
# 0.00051558 secs
# 0.0121338 secs
# 0.00697929 secs


问:
Establishing a second connection in Rails app without using abstract class
Initially, this worked to create a second connection:

```<code>class OtherDb < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :crawler_production

  def self.notify_changes
    sql = ActiveRecord::Base.send(:sanitize_sql_array, ["UPDATE ...", attr1, attr2])
    connection.execute(sql)
</code>```

However, this prevents me from instantiating OtherDb. I would get an error that I can't instantiate an abstract class. So I tried changing to this:

```<code>class VtigerDb
  def initialize
    ActiveRecord::Base.establish_connection(:crawler_production)
  end

  def notify_changes
    sql = ActiveRecord::Base.send(:sanitize_sql_array, ["UPDATE ...", attr1, attr2])
    ActiveRecord::Base.connection.execute(sql)
  end
</code>```

However, this gives me another error:

```<code>Mysql2::Error: Table 'original_db.other_db_table' doesn't exist:
</code>```

How can I access a second connection in a Rails app, without forcing that class to be an abstract class?

答: Check out the octopus gem. You can use it for database sharding in a Rails app.</p>

Body:
Initially, this worked to create a second connection:

class OtherDb < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :crawler_production

  def self.notify_changes
    sql = ActiveRecord::Base.send(:sanitize_sql_array, ["UPDATE ...", attr1, attr2])
    connection.execute(sql)

However, this prevents me from instantiating OtherDb. I would get an error that I can't instantiate an abstract class. So I tried changing to this:

class VtigerDb
  def initialize
    ActiveRecord::Base.establish_connection(:crawler_production)
  end

  def notify_changes
    sql = ActiveRecord::Base.send(:sanitize_sql_array, ["UPDATE ...", attr1, attr2])
    ActiveRecord::Base.connection.execute(sql)
  end

However, this gives me another error:

Mysql2::Error: Table 'original_db.other_db_table' doesn't exist:

How can I access a second connection in a Rails app, without forcing that class to be an abstract class?


问:
How to get all messages from the queue in php-amqplib (RabbitMQ)?
Currently, I'm using https://github.com/php-amqplib/php-amqplib and I've read a lot of examples in this repository but I still don't understand how to get all the messages from the queue?

I just need to receive some messages, group them by value and perform an action.

Is it possible to do with RabbitMQ at all?

How can I implement this in php?

答:
You cannot get all messages currently available by calling single method.

Closest possible solution is by using basic_consume method.

For example:

```<code>function process_message($message)
{
    echo "Received message '" . $message->body . "'\n";

    /** Do your grouping here **/

}

$channel->basic_consume($queue, '', false, false, false, false, 'process_message');

// Loop as long as the channel has callbacks registered
while (count($channel->callbacks)) {
    $channel->wait();
}
</code>```

You can check official RabbitMQ PHP tutorial or demo from php-amqplib.

Body:
You cannot get all messages currently available by calling single method.

Closest possible solution is by using basic_consume method.

For example:

function process_message($message)
{
    echo "Received message '" . $message->body . "'\n";

    /** Do your grouping here **/

}

$channel->basic_consume($queue, '', false, false, false, false, 'process_message');

// Loop as long as the channel has callbacks registered
while (count($channel->callbacks)) {
    $channel->wait();
}

You can check official RabbitMQ PHP tutorial or demo from php-amqplib.


问:
C++ object passing error
So I'm trying to rotate a stack up and down using the functions upRotate and downRotate.  The code compiles, but when I run it, the first rotation I do is fine, but all of my other rotations are missing part of the stack.  When I checked the original stack that I passed into the function, that stack had also changed even though I passed the Stack objects by value. Here's my code.

```<code>#include "Stack.h"

Stack upRotate(Stack s)
{
 Stack t,r;
 t.push(s.pop());
 while(!s.empty())
  r.push(s.pop());
 while(!r.empty())
  t.push(r.pop());
 return t;
}

Stack downRotate(Stack s)
{
 Stack t,r;
 while(!s.empty())
  r.push(s.pop());
 s.push(r.pop());
 while(!r.empty())
  t.push(r.pop());
 t.push(s.pop());
 return t;
}

int main() {
 Stack s;
  s.push(1);
  s.push(1);
  s.push(2);
  s.push(3);
  s.print();
  downRotate(s).print();
  upRotate(s).print();
</code>```

}

Here's the code for the Stack class.

```<code>#ifndef STACK_H
#define STACK_H

#include <cstdlib>
#include <iostream>

/**
 * StackNode class: contains key and pointer to next node. Constructor creates
 * new node and loads key into it.
 */
class StackNode {
  public:
    int key;
    StackNode *next;
    StackNode(int);
};

StackNode::StackNode(int key) {
  this->key  = key;
  this->next = NULL;
}

/**
 * Stack class: contains pointer to top node. Constructor sets top node to NULL.
 * Supports push, pop, peek operations.  Pop adds a node to the top of the stack;
 * push removes node from the top of the stack and returns its key.  Peek views
 * the key of the node on the top of the stack.
 */
class Stack {
  private:
    StackNode *top;
  public:
    Stack();
    void push(int);
    int  peek();
    int  pop();
    bool empty();
    void print();
};

Stack::Stack() {
  top = NULL;
}

/**
 * Delete top node and return key.
 * @return  the key of the top node
 */
int Stack::pop() {
  int popkey = -1;
  StackNode *popme = top;
  if (top)
    popkey = top->key;
  top = popme->next;
  delete popme;
  return popkey;
}

/**
 * Add node to top of the stack.
 * @param key  key to insert into new top node
 */
void Stack::push(int key) {
  StackNode *newtop = new StackNode(key);
  newtop->next = top;
  top = newtop;
}

/**
 * Delete top node and return key.
 * @return  the key of the top node
 */
int Stack::peek() {
  int key = -1;
  if (top)
    key = top->key;
  return key;
}

/**
 * Tell if stack is empty.
 * @return  true if stack is empty
 */
bool Stack::empty() {
  if (top)
    return false;
  return true;
}

/**
 * Print the stack from top to bottom.
 */
void Stack::print() {
  StackNode *node = top;
  while (node) {
    std::cout << '\t' << node->key;
    node = node->next;
  }
  std::cout << std::endl;
}

#endif
</code>```

答:
You should write a copy constructor of Stack.

```<code>Stack::Stack(const Stack &s)
{
    Stack temp;
    this->top = NULL;
    if(s.top != NULL)
    {
        StackNode *node = s.top;
        while (node) {
            temp.push(node->key);
            node = node->next;
        }
    }
    if(temp.top != NULL)
    {
        StackNode *node1 = temp.top;
        while (node1) {
            this->push(node1->key);
            node1 = node1->next;
        }
    }
    //free temp's heap space
    StackNode *node2 = temp.top;
    StackNode *node3 = node2;
    while(node2)
    {
        node2 = node2->next;
        delete node3;
        node3 = node2;
    }
}
</code>```

Title: C++ object passing error

Body:
So I'm trying to rotate a stack up and down using the functions upRotate and downRotate.  The code compiles, but when I run it, the first rotation I do is fine, but all of my other rotations are missing part of the stack.  When I checked the original stack that I passed into the function, that stack had also changed even though I passed the Stack objects by value. Here's my code.

#include "Stack.h"

Stack upRotate(Stack s)
{
 Stack t,r;
 t.push(s.pop());
 while(!s.empty())
  r.push(s.pop());
 while(!r.empty())
  t.push(r.pop());
 return t;
}

Stack downRotate(Stack s)
{
 Stack t,r;
 while(!s.empty())
  r.push(s.pop());
 s.push(r.pop());
 while(!r.empty())
  t.push(r.pop());
 t.push(s.pop());
 return t;
}

int main() {
 Stack s;
  s.push(1);
  s.push(1);
  s.push(2);
  s.push(3);
  s.print();
  downRotate(s).print();
  upRotate(s).print();

}

Here's the code for the Stack class.

#ifndef STACK_H
#define STACK_H

#include <cstdlib>
#include <iostream>

/**
 * StackNode class: contains key and pointer to next node. Constructor creates
 * new node and loads key into it.
 */
class StackNode {
  public:
    int key;
    StackNode *next;
    StackNode(int);
};

StackNode::StackNode(int key) {
  this->key  = key;
  this->next = NULL;
}

/**
 * Stack class: contains pointer to top node. Constructor sets top node to NULL.
 * Supports push, pop, peek operations.  Pop adds a node to the top of the stack;
 * push removes node from the top of the stack and returns its key.  Peek views
 * the key of the node on the top of the stack.
 */
class Stack {
  private:
    StackNode *top;
  public:
    Stack();
    void push(int);
    int  peek();
    int  pop();
    bool empty();
    void print();
};

Stack::Stack() {
  top = NULL;
}

/**
 * Delete top node and return key.
 * @return  the key of the top node
 */
int Stack::pop() {
  int popkey = -1;
  StackNode *popme = top;
  if (top)
    popkey = top->key;
  top = popme->next;
  delete popme;
  return popkey;
}

/**
 * Add node to top of the stack.
 * @param key  key to insert into new top node
 */
void Stack::push(int key) {
  StackNode *newtop = new StackNode(key);
  newtop->next = top;
  top = newtop;
}

/**
 * Delete top node and return key.
 * @return  the key of the top node
 */
int Stack::peek() {
  int key = -1;
  if (top)
    key = top->key;
  return key;
}

/**
 * Tell if stack is empty.
 * @return  true if stack is empty
 */
bool Stack::empty() {
  if (top)
    return false;
  return true;
}

/**
 * Print the stack from top to bottom.
 */
void Stack::print() {
  StackNode *node = top;
  while (node) {
    std::cout << '\t' << node->key;
    node = node->next;
  }
  std::cout << std::endl;
}

#endif

Body:
You should write a copy constructor of Stack.

Stack::Stack(const Stack &s)
{
    Stack temp;
    this->top = NULL;
    if(s.top != NULL)
    {
        StackNode *node = s.top;
        while (node) {
            temp.push(node->key);
            node = node->next;
        }
    }
    if(temp.top != NULL)
    {
        StackNode *node1 = temp.top;
        while (node1) {
            this->push(node1->key);
            node1 = node1->next;
        }
    }
    //free temp's heap space
    StackNode *node2 = temp.top;
    StackNode *node3 = node2;
    while(node2)
    {
        node2 = node2->next;
        delete node3;
        node3 = node2;
    }
}


问:
SyntaxError: Unexpected token ... (82:8) in Browserify
I'm trying to use the mapActions in Vuex as given in Vuex Actions

```<code>methods:{
            ...mapActions([
                'increment' // map this.increment() to this.$store.dispatch('increment')
            ])
}
</code>```

But, it is giving me SyntaxError: Unexpected token at ... . I'm not sure what the problem is and what details I would need to include in the question.

答:
1:Install the label plugin:

```<code>npm install --save-dev babel-plugin-transform-object-rest-spread
</code>```

2:Then fix the .babelrc file as follow:

```<code>{
    "presets": [["latest", {"es2015": { "modules": false }}]],
    "plugins": ["transform-object-rest-spread"]
}
</code>```

Body:
I'm trying to use the mapActions in Vuex as given in Vuex Actions

methods:{
            ...mapActions([
                'increment' // map this.increment() to this.$store.dispatch('increment')
            ])
}

But, it is giving me SyntaxError: Unexpected token at ... . I'm not sure what the problem is and what details I would need to include in the question.

Body:
1:Install the label plugin:

npm install --save-dev babel-plugin-transform-object-rest-spread

2:Then fix the .babelrc file as follow:

{
    "presets": [["latest", {"es2015": { "modules": false }}]],
    "plugins": ["transform-object-rest-spread"]
}


问:
Link Python3 with CMake on Mac OS X
I am using CMake. I want to link Python3 libraries to my project. I installed Python3 by homebrew, and write CMakeLists.txt like this:

```<code>find_package(PythonLibs 3.6 REQUIRED)
</code>```

But then it gave me an error:

```<code>Could NOT find PythonLibs: Found unsuitable version "2.7.10", but required
is at least "3.6" (found /usr/lib/libpython2.7.dylib)
</code>```

This error happens on Mac OS X. Could anybody tell me how to solve it? Thanks.

答:
I have solved this problem so I am answering this question by myself.

Python installed by Homebrew cannot be found by CMake. However, you can build Python from source and make install it, then CMake can find this.

Title: Link Python3 with CMake on Mac OS X

Body:
I am using CMake. I want to link Python3 libraries to my project. I installed Python3 by homebrew, and write CMakeLists.txt like this:

find_package(PythonLibs 3.6 REQUIRED)

But then it gave me an error:

Could NOT find PythonLibs: Found unsuitable version "2.7.10", but required
is at least "3.6" (found /usr/lib/libpython2.7.dylib)

This error happens on Mac OS X. Could anybody tell me how to solve it? Thanks.


问:
Redirect if not logged in
I have a PHP login script and I only want certain pages to be accessed if the user is logged in (if they're not, they're re-directed to the login page).

I have this in login.php which starts the session:

```<code><?php

session_start();
$con = mysqli_connect("localhost","Username","SomeData","Privatestuff");
$User = $_SESSION['username'];

if(isset($_POST['loginsubmit'])) {

$username = $_POST['username'];
$password = md5($_POST['password']);

$username = stripslashes($username);
$password = stripslashes($password);

$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);

$logincheck = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
$result = mysqli_query($con, $logincheck);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if(mysqli_num_rows($result) == 1){
$_SESSION['username']=$username;
header('Location: index.php');
die();
}else{
echo "Username or password is invalid.";
}

}
}
}

?>
</code>```

I have this on index.php which redirects the user if they're not logged in, hover it doesn't prevent users from visiting the page if they're not logged in

```<code><?php

session_start();
$con = DB INFO
$User = $_SESSION['username'];

if(!$User){
header('Location: welcome.php');
die();
}

?>
</code>```

Could someone please help determine why users can still visit index.php if they're not logged in?

答:
Add this at the top of your index.php or header.php

```<code><?php
        // First execute a common code to connect to the database and start the session
        include ("includes/connect.php");

        // At the top of the page check to see whether the user is logged in or not
        if(empty($_SESSION['users']))
        {
            // If they are not, redirect them to the login page.
            header("Location: login.php");

            // Remember that this die statement is absolutely critical.  Without it,
            // people can view your members-only content without logging in.
            die("Redirecting to login.php");
        }
    ?>
</code>```

And add or do this one  to your login page or login.php.

```<code><?php
session_start();
include ('includes/connect.php');

$message="";
if(!empty($_POST["login"])) {
    $result = mysqli_query($conn,"SELECT * FROM users WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
    $row  = mysqli_fetch_array($result);
    if(is_array($row)) {
        $_SESSION["users"] = $row['usersid'];
        $_SESSION['login'] = true;
        header("Location:index.php");
        exit();
    } else {
    $message = "Invalid Username or Password!";
    }
}
?>
</code>```

Title: Redirect if not logged in

Body:
I have a PHP login script and I only want certain pages to be accessed if the user is logged in (if they're not, they're re-directed to the login page).

I have this in login.php which starts the session:

<?php

session_start();
$con = mysqli_connect("localhost","Username","SomeData","Privatestuff");
$User = $_SESSION['username'];

if(isset($_POST['loginsubmit'])) {

$username = $_POST['username'];
$password = md5($_POST['password']);

$username = stripslashes($username);
$password = stripslashes($password);

$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);

$logincheck = "SELECT * FROM `users` WHERE username='$username' and password='$password'";
$result = mysqli_query($con, $logincheck);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if(mysqli_num_rows($result) == 1){
$_SESSION['username']=$username;
header('Location: index.php');
die();
}else{
echo "Username or password is invalid.";
}

}
}
}

?>

I have this on index.php which redirects the user if they're not logged in, hover it doesn't prevent users from visiting the page if they're not logged in

<?php

session_start();
$con = DB INFO
$User = $_SESSION['username'];

if(!$User){
header('Location: welcome.php');
die();
}

?>

Could someone please help determine why users can still visit index.php if they're not logged in?

Body:
Add this at the top of your index.php or header.php

<?php
        // First execute a common code to connect to the database and start the session
        include ("includes/connect.php");

        // At the top of the page check to see whether the user is logged in or not
        if(empty($_SESSION['users']))
        {
            // If they are not, redirect them to the login page.
            header("Location: login.php");

            // Remember that this die statement is absolutely critical.  Without it,
            // people can view your members-only content without logging in.
            die("Redirecting to login.php");
        }
    ?>

And add or do this one  to your login page or login.php.

<?php
session_start();
include ('includes/connect.php');

$message="";
if(!empty($_POST["login"])) {
    $result = mysqli_query($conn,"SELECT * FROM users WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
    $row  = mysqli_fetch_array($result);
    if(is_array($row)) {
        $_SESSION["users"] = $row['usersid'];
        $_SESSION['login'] = true;
        header("Location:index.php");
        exit();
    } else {
    $message = "Invalid Username or Password!";
    }
}
?>


问:
How to debug the SQL Server error `the function "function name" is not a valid windowing function, and cannot be used with the OVER clause`
I get an error displayed as subject.

Here is my query.

```<code>select
    X.*,
    x.not_due + X.[1_30] + X.[31_60] + x.[61_90] + X.[91_120] + x.[121_150] + x.[151_over][ob],
    case
       when row_Number() over (partition by x.member_name order by x.partner_name, x.member_name, x.id) = 1
          then dbo.LedgerS_RB_AsOf(X.member, 1, @asof2) over (partition by 1)
    end as savings
from
    table X
</code>```

答: I already resolved it, I created a subquery instead of function. </p>

Body:
I get an error displayed as subject.

Here is my query.

select
    X.*,
    x.not_due + X.[1_30] + X.[31_60] + x.[61_90] + X.[91_120] + x.[121_150] + x.[151_over][ob],
    case
       when row_Number() over (partition by x.member_name order by x.partner_name, x.member_name, x.id) = 1
          then dbo.LedgerS_RB_AsOf(X.member, 1, @asof2) over (partition by 1)
    end as savings
from
    table X


问:
How to get the transpose in sql (HANA)?
I have a query which returns the table which is like

```<code> SELECT (CASE WHEN type=1 THEN 'A'
                 WHEN type=2 THEN 'B'

           END) as TYPE,COUNT(*) AS COUNT
            from TYPE_TABLE GROUP BY TYPE
</code>```

(I use case to have the count in each types).

```<code>count     type
_____     _____
123         A
124         B
120         C
</code>```

I want to have the table to be like this

```<code> A       B       C
___     ___     ___
123      124     120
</code>```

So actually I need the transpose of the column count.How do I get this in HANA?

答:
Since there are only 3

you could just

```<code>SELECT SUM(CASE WHEN TYPE = 1 THEN 1 ELSE 0 END) AS A,
       SUM(CASE WHEN TYPE = 2 THEN 1 ELSE 0 END) AS B,
       SUM(CASE WHEN TYPE = 3 THEN 1 ELSE 0 END) AS C
FROM yourTable
</code>```

Title: How to get the transpose in sql (HANA)?

Body:
I have a query which returns the table which is like

 SELECT (CASE WHEN type=1 THEN 'A'
                 WHEN type=2 THEN 'B'

           END) as TYPE,COUNT(*) AS COUNT
            from TYPE_TABLE GROUP BY TYPE

(I use case to have the count in each types).

count     type
_____     _____
123         A
124         B
120         C

I want to have the table to be like this

 A       B       C
___     ___     ___
123      124     120

So actually I need the transpose of the column count.How do I get this in HANA?

Body:
Since there are only 3

you could just

SELECT SUM(CASE WHEN TYPE = 1 THEN 1 ELSE 0 END) AS A,
       SUM(CASE WHEN TYPE = 2 THEN 1 ELSE 0 END) AS B,
       SUM(CASE WHEN TYPE = 3 THEN 1 ELSE 0 END) AS C
FROM yourTable


问:
How to correctly override `errResponse` which is passed to the `catch(function(errResponse){` function?
This is my controller:

```<code>angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        self.add = function() {
            BaseService.add.user(self.user)
                .catch(function(errorResponse) {
                    self.cerrorMessages = errorResponse.data;
                });
        };
</code>```

This is my BaseApp / factory:

```<code>angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    });
                // if there are errors, rewrite the error messages
                }).catch(function(response) {
                     for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                         }
                     }
                });
            }
         };
</code>```

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

What should I do to properly override the errResponse parameter which is passed to the controller's .catch() function (without having a .then() function because nothing is needed to be done if it is successful)?

答:
It seems like you don't have a solid understand of promises :) I recommend learning more about them.

When you call BaseService.add.user, this should return a promise. You can only use .catch if this is a promise. Also note that when chaining promises, you need to return a promise!

So something like this:

```<code>self.add = {
  user: function(user) {
    return $http.post("/users/", user)
      .then(function(response) {
        return $http.post("/api-auth/login", user)
      })
      .then(function(response) {
        $window.location.href = "/";
      })
      .catch(function(response) {
        // error stuff
      });
  }
};
</code>```

Body:
This is my controller:

angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        self.add = function() {
            BaseService.add.user(self.user)
                .catch(function(errorResponse) {
                    self.cerrorMessages = errorResponse.data;
                });
        };

This is my BaseApp / factory:

angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        self.add = {
            user: function(user) {
                $http.post("/users/", user)
                .then(function(response) {
                    $http.post("/api-auth/login", user)
                    .then(function(response) {
                        $window.location.href = "/";
                    });
                // if there are errors, rewrite the error messages
                }).catch(function(response) {
                     for (prop in response.data) {
                         if (prop == "email") {
                             response.data[prop] = "Please enter a valid email address.";
                         } else if (prop == "username") {
                             response.data[prop] = "Please enter a valid username";
                         }
                     }
                });
            }
         };

When I try to run this code and call self.add() on my controller, I get an error saying TypeError: Cannot read property 'catch' of undefined pointing to the line .catch(function(errorResponse) { in my controller. I'm guessing this is because there is no then() function.

What should I do to properly override the errResponse parameter which is passed to the controller's .catch() function (without having a .then() function because nothing is needed to be done if it is successful)?

Body:
It seems like you don't have a solid understand of promises :) I recommend learning more about them.

When you call BaseService.add.user, this should return a promise. You can only use .catch if this is a promise. Also note that when chaining promises, you need to return a promise!

So something like this:

self.add = {
  user: function(user) {
    return $http.post("/users/", user)
      .then(function(response) {
        return $http.post("/api-auth/login", user)
      })
      .then(function(response) {
        $window.location.href = "/";
      })
      .catch(function(response) {
        // error stuff
      });
  }
};


问:
Using localStorage to store numerical value
I am trying to use localStorage to hold the value of the players health in an HTML5 based game, and when the HP value is below 0, nothing happens.

```<code><!--Calling Statement-->
<ul>
    <li><a href="../S5/S5.html" onclick="alterHP(-3);"
        class="ghost-button">Go on to the next scene</a></li>
</ul>
</code>```

in a separate .js file

```<code>function declareHP() {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem("HP", "20");
    } else {
        /*Can't Store, Oh well*/
    }
}

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}
</code>```

答:
```<code>function setterfunc(targetedelement, presetting) {
    if(localStorage.getItem(targetedelement) == undefined) {
        localStorage.setItem(targetedelement, presetting);
    }
}
setterfunc('HP', 0);
</code>```

Now you can run your script ,based on the comment you haven't initialize the value localStorage.HP for the initial use.Now you can run your script.

```<code>/*Function*/
function alterHP(value) {
if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.getItem("HP"));
        localStorage.setItem("HP", currentHP + value);
        if (!(parseInt(localStorage.getItem("HP") > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}
</code>```

Body:
I am trying to use localStorage to hold the value of the players health in an HTML5 based game, and when the HP value is below 0, nothing happens.

Go on to the next scene

in a separate .js file

function declareHP() {
    if (typeof (Storage) !== "undefined") {
        localStorage.setItem("HP", "20");
    } else {
        /*Can't Store, Oh well*/
    }
}

function alterHP(value) {
    if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.HP);
        localStorage.HP = currentHP + value;
        if (!(parseInt(localStorage.HP) > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}

Body:
function setterfunc(targetedelement, presetting) {
    if(localStorage.getItem(targetedelement) == undefined) {
        localStorage.setItem(targetedelement, presetting);
    }
}
setterfunc('HP', 0);

Now you can run your script ,based on the comment you haven't initialize the value localStorage.HP for the initial use.Now you can run your script.

/*Function*/
function alterHP(value) {
if (typeof (Storage) !== "undefined") {
        var currentHP = parseInt(localStorage.getItem("HP"));
        localStorage.setItem("HP", currentHP + value);
        if (!(parseInt(localStorage.getItem("HP") > 0)) {
            window.location.assign('../youLose.html');
        }
    }
}


问:
How we can create RemoveBlack Image Filtering same like RemoveWhite in FabricJs?
how we can remove black pixels from image? Can we create RemoveBlack Image filtering same like RemoveWhite?</p>

答:
This should get you going:

Here's the relevant code for a custom filter:

```<code>fabric.Image.filters.RemoveBlack = fabric.util.createClass({
  type: 'RemoveBlack',
  applyTo: function(canvasEl) {
    var context = canvasEl.getContext('2d');
    var imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
      data32 = new Uint32Array(imageData.data.buffer), // create a uint32 buffer
      i = 0,
      len = data32.length;
    while (i < len) {
      if (data32[i] < 0xff300000) data32[i] = 0; // if close to black, set transparent
      i++
    }
    context.putImageData(imageData, 0, 0);
  }
});
fabric.Image.filters.RemoveBlack.fromObject = function(object) {
  return new fabric.Image.filters.RemoveBlack(object);
};
</code>```

And here's the all important JSFiddle, https://jsfiddle.net/rekrah/pf072kxs/.

Let me know if you have any questions.  Happy to help further.

Body:
This should get you going:

Here's the relevant code for a custom filter:

fabric.Image.filters.RemoveBlack = fabric.util.createClass({
  type: 'RemoveBlack',
  applyTo: function(canvasEl) {
    var context = canvasEl.getContext('2d');
    var imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
      data32 = new Uint32Array(imageData.data.buffer), // create a uint32 buffer
      i = 0,
      len = data32.length;
    while (i < len) {
      if (data32[i] < 0xff300000) data32[i] = 0; // if close to black, set transparent
      i++
    }
    context.putImageData(imageData, 0, 0);
  }
});
fabric.Image.filters.RemoveBlack.fromObject = function(object) {
  return new fabric.Image.filters.RemoveBlack(object);
};

And here's the all important JSFiddle, https://jsfiddle.net/rekrah/pf072kxs/.

Let me know if you have any questions.  Happy to help further.


问:
Failed to drop/rename a corrupted table in SQL Server
In my SQL, a table has corrupted.
When renaming or removing it, I get this message：

Possible schema corruption. Run DBCC CHECKCATALOG.  A severe error
  occurred on the current command.  The results, if any, should be
  discarded.

I did tried DELETE, TRUNCATE and DROP but none of these works.

This corrupted table exist in every backup file. The data inside this table is not important, but the main point is to recreate it.
How do I removing this corrupted/damaged table?

答:
http://www.sqlskills.com/blogs/paul/checkdb-from-every-angle-emergency-mode-repair-the-very-very-last-resort/

Hack the system tables to get the database into EMERGENCY mode. Use
  the undocumented and unsupported DBCC REBUILD_LOG command to build a
  new transaction log. Run DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS
  option to fix up corruptions in the data files – both those that may
  have caused the issue, and those caused by rebuilding the transaction
  log (e.g. because an active transaction altering the database
  structure was lost). Figure out what data was lost or is
  transactionally inconsistent (e.g. because a transaction altering
  multiple tables was lost) as far as your business logic is concerned
  Take the database out of EMERGENCY mode And then all the other stuff
  like root-cause analysis and getting a better backup strategy


问:
Python discrete differentiation
I am reading in a file with two columns of numerical data. Let the first column be 'x', and the second column be 'y'.

The data in 'x' is not uniformly spaced. That is, it goes something like this:

2.4 2.6 2.7 3.0 3.2 3.5 ...

The data is finite obviously. It has an initial and a final value.

I need to find "discontinuities" in this data. I want to do this my differentiating the data: dy/dx

I've done a search, but all the differentiation answers I found involve an analytical function, such as y=x**2+1

My data is discrete and does not fit an analytical function. I need to find the derivative at each value of 'x' over this data, keeping in mind that 'x' is not evenly spaced.

So, suppose I have read in the data from my data file, and stored them in variables 'x' and 'y'.

Now I want dy/dx, and I want to plot dy/dx vs x.

What can I "import" that will do this derivative? Or am I going to have to write the algorithm myself?

答:
I wrote a simple algorithm which breaks my array into smaller arrays of 3 points. Then fit a 2nd order function through those three points, take its derivative, and calculate the value at the middle point. For the end points, I only use two values.

It's a bit messy. And I know there are more efficient ways to do the loop. Here is what I did:

```<code>dydx=[]

for i in range(len(x)):
    if i==0:
        dx=x[i:i+2]
        dy=y[i:i+2]
        order=1
    elif i==len(x)-1:
        dx=x[i-1:i+1]
        dy=y[i-1:i+1]
        order=1
    else:
        dx=x[i-1:i+2]
        dy=y[i-1:i+2]
        order=2
    z=np.polyfit(dx,dy,len(dx)-1)
    f=np.poly1d(z)
    df=np.polyder(f)
    dydx.append(float(df(x[i])))
dydx=np.array(dydx)
</code>```

Any suggestions on cleaning this loop up in a way that eliminates the if-elif statements?

Title: Python discrete differentiation

Body:
I wrote a simple algorithm which breaks my array into smaller arrays of 3 points. Then fit a 2nd order function through those three points, take its derivative, and calculate the value at the middle point. For the end points, I only use two values.

It's a bit messy. And I know there are more efficient ways to do the loop. Here is what I did:

dydx=[]

for i in range(len(x)):
    if i==0:
        dx=x[i:i+2]
        dy=y[i:i+2]
        order=1
    elif i==len(x)-1:
        dx=x[i-1:i+1]
        dy=y[i-1:i+1]
        order=1
    else:
        dx=x[i-1:i+2]
        dy=y[i-1:i+2]
        order=2
    z=np.polyfit(dx,dy,len(dx)-1)
    f=np.poly1d(z)
    df=np.polyder(f)
    dydx.append(float(df(x[i])))
dydx=np.array(dydx)

Any suggestions on cleaning this loop up in a way that eliminates the if-elif statements?


问:
(C) When calling function, store multiple values in array
So, when calling a function I wish to put two values in, then those two values to be saved in an array in the function argument.

i.e

```<code>function(1,2); (calling the function)

void function(int x[2]); (declaration of function)
</code>```

with x[0] and x[1] being the two arguments when calling the function (i.e the 1 and 2).

Any help would be appreciated.

答:
If you want to call a function that expects an array of two, passing 2 separate values is not the same thing.

This is as close as I can get:

```<code>void function(int x[2]) {....}

void caller(int a, int b)
{
    int args[2] = {a, b};  /* Convert two args into an array */
    function(args);        /* Call the function with an array */
}

int main(void)
{
    caller(1, 2);
}
</code>```

Body:
So, when calling a function I wish to put two values in, then those two values to be saved in an array in the function argument.

i.e

function(1,2); (calling the function)

void function(int x[2]); (declaration of function)

with x[0] and x[1] being the two arguments when calling the function (i.e the 1 and 2).

Any help would be appreciated.

Body:
If you want to call a function that expects an array of two, passing 2 separate values is not the same thing.

This is as close as I can get:

void function(int x[2]) {....}

void caller(int a, int b)
{
    int args[2] = {a, b};  /* Convert two args into an array */
    function(args);        /* Call the function with an array */
}

int main(void)
{
    caller(1, 2);
}


问:
Swift Playgrounds Error: Unrecognized Selector sent to instance (related to UITapGestureRecognizer)
I keep getting the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILabel theUserClicked:]: unrecognized selector sent to instance 0x7fd8c5404380'

I'm not very familiar with programmatically using UITapGestureRecognizers so any help would be great!
Not all variables shown

```<code>class NoteCard:NSObject {
   let tap:UITapGestureRecognizer
   let NoteCardView:UILabel

 init(cardValue:Int, vc:MainViewController) {
   NoteCardView = UILabel(frame: .zero)
   tap = UITapGestureRecognizer(target: NoteCardView, action: "theUserClicked:")
   NoteCardView.isUserInteractionEnabled = true
   NoteCardView.addGestureRecognizer(tap)
 }
}

class MainViewController:UIViewController {

func theUserClicked(_ recognizer:UITapGestureRecognizer) {
    let card:NoteCard = recognizer.view as! NoteCard
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        card.NoteCardView.leftAnchor.constraint(equalTo: card.NoteCardView.leftAnchor, constant: (self.elementPlacement/4)+20).isActive = true
        card.NoteCardView.bottomAnchor.constraint(equalTo: card.NoteCardView.bottomAnchor, constant: 100).isActive = true
    }, completion: { (true) in
        self.elementPlacement = self.elementPlacement + 1
        if self.elementPlacement == 5 {
            card.tap.isEnabled = false
        }

    })
}
}
</code>```

答:
UILabel doesn't have a method declaration matching theUserClicked.

Instead, move the method theUserClicked in to NotesCardView and pass self to the UITapGestureRecognizer. Then, following the MVC pattern, create a delegate protocol for the MainViewController to conform to. Also, why not just use a UIButton?

I think you may be slightly confused about the MVC pattern. IMO, it looks like your trying to combine the model and the view.

I highly recommend reading about the patterns used in iOS. This way you can progress and write better code.

Here's a description, by Apple, about the MVC pattern: Model-View-Controller

Here is an example of some code that may help you (May have some errors but, I'm sure you can fix them):

```<code>// Essentially, this is the command line version of the note card,
// known as the Model. Based on personal opinion and problem domain,
// put your business logic here or use a composition pattern with PO*Os
// (Plain old * Language Name * objects).

public class NoteCard: NSObject
{
    internal(set) var cardValue: Int!

    required init(cardValue value: Int)
    {
        cardValue = value

        super.init()
    }
}

// This protocol is used to delegate "actions" to your ViewController.
public protocol NoteCardViewDelegate
{
    func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView) -> Bool
}

// This class just represents what things should look like. That's it.
public class NoteCardView: UIView
{
    // This is the reference to the UIViewController or whatever may
    // happen to need to use this view.
    @IBInspectable weak var delegate: NoteCardViewDelegate?

    // A content view will come in handy more than likely at some
    // point. Plus, it's a common pattern to use. You might even want
    // to use a stackView as well.
    @IBInspectable let contentView = UIView()

    // I'm not sure why you want to use a UILabel with a tapGestureRecognizer instead of a UIButton, but that's up to you.
    @IBInspectable let titleLabel = UILabel()

    internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?

    override func updateConstraints()
    {
        // add constraints for the contentView and titleLabel
        super.updateConstraints()
    }

    // We'll create a common initialization method to follow the DRY
    // rule (Don't Repeat Yourself). Since we want to be able to use
    // this view with Interface Builder. This will come in handy.
    // Especially if we have more than one initialization method.
    internal func commonInit()
    {
        // add label and contentView

        self.titleLabelGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTitleLabelTap(_:))
        self.addGestureRecognizer(titleLabelTapGestureRecognizer)
    }

    // This method is called if you create an instance of this view in
    // Interface Builder. It's a good idea to override it and call the
    // commonInit.
    override func awakeFromNib()
    {
        super.awakeFromNib()

        self.commonInit()
    }

    override init(withFrame frame: CGRect)
    {
        super.init(withFrame: frame)

        self.commonInit()
    }

    internal func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
         self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
    }
}

public class MainViewController: UIViewController { }

public extension MainViewController: NoteCardViewDelegate
{
    func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView)
    {
        let card: NoteCardView = (recognizer.view as! NoteCardView)

         UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

             card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)
             card.titleLabel.leftAnchor.isActive = true

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)
             card.titleLabel.leftAnchor.isActive = true

        }, completion: { (finished: Bool) in

            self.elementPlacement = (self.elementPlacement + 1)
            card.tap.isEnabled = !(self.elementPlacement == 5)
        })
     }
}
</code>```

Body:
I keep getting the following error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILabel theUserClicked:]: unrecognized selector sent to instance 0x7fd8c5404380'

I'm not very familiar with programmatically using UITapGestureRecognizers so any help would be great!
Not all variables shown

class NoteCard:NSObject {
   let tap:UITapGestureRecognizer
   let NoteCardView:UILabel

 init(cardValue:Int, vc:MainViewController) {
   NoteCardView = UILabel(frame: .zero)
   tap = UITapGestureRecognizer(target: NoteCardView, action: "theUserClicked:")
   NoteCardView.isUserInteractionEnabled = true
   NoteCardView.addGestureRecognizer(tap)
 }
}

class MainViewController:UIViewController {

func theUserClicked(_ recognizer:UITapGestureRecognizer) {
    let card:NoteCard = recognizer.view as! NoteCard
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {
        card.NoteCardView.leftAnchor.constraint(equalTo: card.NoteCardView.leftAnchor, constant: (self.elementPlacement/4)+20).isActive = true
        card.NoteCardView.bottomAnchor.constraint(equalTo: card.NoteCardView.bottomAnchor, constant: 100).isActive = true
    }, completion: { (true) in
        self.elementPlacement = self.elementPlacement + 1
        if self.elementPlacement == 5 {
            card.tap.isEnabled = false
        }

    })
}
}

Body:
UILabel doesn't have a method declaration matching theUserClicked.

Instead, move the method theUserClicked in to NotesCardView and pass self to the UITapGestureRecognizer. Then, following the MVC pattern, create a delegate protocol for the MainViewController to conform to. Also, why not just use a UIButton?

I think you may be slightly confused about the MVC pattern. IMO, it looks like your trying to combine the model and the view.

I highly recommend reading about the patterns used in iOS. This way you can progress and write better code.

Here's a description, by Apple, about the MVC pattern: Model-View-Controller

Here is an example of some code that may help you (May have some errors but, I'm sure you can fix them):

// Essentially, this is the command line version of the note card,
// known as the Model. Based on personal opinion and problem domain,
// put your business logic here or use a composition pattern with PO*Os
// (Plain old * Language Name * objects).

public class NoteCard: NSObject
{
    internal(set) var cardValue: Int!

    required init(cardValue value: Int)
    {
        cardValue = value

        super.init()
    }
}

// This protocol is used to delegate "actions" to your ViewController.
public protocol NoteCardViewDelegate
{
    func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView) -> Bool
}

// This class just represents what things should look like. That's it.
public class NoteCardView: UIView
{
    // This is the reference to the UIViewController or whatever may
    // happen to need to use this view.
    @IBInspectable weak var delegate: NoteCardViewDelegate?

    // A content view will come in handy more than likely at some
    // point. Plus, it's a common pattern to use. You might even want
    // to use a stackView as well.
    @IBInspectable let contentView = UIView()

    // I'm not sure why you want to use a UILabel with a tapGestureRecognizer instead of a UIButton, but that's up to you.
    @IBInspectable let titleLabel = UILabel()

    internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?

    override func updateConstraints()
    {
        // add constraints for the contentView and titleLabel
        super.updateConstraints()
    }

    // We'll create a common initialization method to follow the DRY
    // rule (Don't Repeat Yourself). Since we want to be able to use
    // this view with Interface Builder. This will come in handy.
    // Especially if we have more than one initialization method.
    internal func commonInit()
    {
        // add label and contentView

        self.titleLabelGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTitleLabelTap(_:))
        self.addGestureRecognizer(titleLabelTapGestureRecognizer)
    }

    // This method is called if you create an instance of this view in
    // Interface Builder. It's a good idea to override it and call the
    // commonInit.
    override func awakeFromNib()
    {
        super.awakeFromNib()

        self.commonInit()
    }

    override init(withFrame frame: CGRect)
    {
        super.init(withFrame: frame)

        self.commonInit()
    }

    internal func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
         self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
    }
}

public class MainViewController: UIViewController { }

public extension MainViewController: NoteCardViewDelegate
{
    func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView)
    {
        let card: NoteCardView = (recognizer.view as! NoteCardView)

         UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

             card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)
             card.titleLabel.leftAnchor.isActive = true

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)
             card.titleLabel.leftAnchor.isActive = true

        }, completion: { (finished: Bool) in

            self.elementPlacement = (self.elementPlacement + 1)
            card.tap.isEnabled = !(self.elementPlacement == 5)
        })
     }
}


问:
How to connect menu click with action in Qt Creator?
I am completely new to Qt.

I started with a new Qt4 GUI Application.

Using the designer, I have created a menu like so:

```<code>File
 - Exit
</code>```

How do I get an action associated with the menu item?

I found something called the 'Signals and slots editor' but have no idea how to use it.

答:
Go to the Slots Editor and then click on the Action Editor Tab on the bottem left side. There are all Menu Actions listed.

Right click -> go to Slot provides a slot function.

Body:
I am completely new to Qt.

I started with a new Qt4 GUI Application.

Using the designer, I have created a menu like so:

File
 - Exit

How do I get an action associated with the menu item?

I found something called the 'Signals and slots editor' but have no idea how to use it.


答: Your tap gesture recognizer is NoteCardView whose class is UILabel. So theUserClicked: action will be sent to NoteCardView. To solve this, set target to a MainViewController instance. Or move that action function to an available class and make target an instance of that class.

Title: Swift Playgrounds Error: Unrecognized Selector sent to instance (related to UITapGestureRecognizer)