问:
How to print the table from a website using python script?
Here is my python script so far.

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'my_company_website'

#opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div",{"class":"navigator-content"})

print (containers)
</code>```

After this, in inspect element it is like below,

```<code><div class ="issue-table-container">
<div>
<table id ="issuetable" class>
<thead>...</thead>
<tbody>...<t/body> (This contains all the information i want to print)
</table>
</code>```

How to print the table and export to csv

答:
For each of the containers you should grab the table [1], then you have to find the body of the table and iterate over its rows [2] and compile a line for your csv file with the table cells (td) [3]

```<code>for container in containers:
    table = container.find(id="issuetable") [1]
    #if you are exactly sure of the structure and/or if the tables have different/unique ids and there is only one table per container you can also do:
    table = container.table [1]

    for tr in table.tbody.find_all("tr"): [2]
        line = ""
        for td in tr: [3]
            line += td.text+"," #Adding the text in the td to the line followed by the separator of your choice in this case comma
        csvfile.write(line[:-1]+"/n") #add the line (replace "/n" with your system's new line character for extra portability)
</code>```

There are different ways of navigating the soup tree depending on your need and on how flexible you script needs to be.
Have a look at https://www.crummy.com/software/BeautifulSoup/bs4/doc/ and check out the find / find_all sections.

Good luck!

/Teo

Body:
Here is my python script so far.

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'my_company_website'

#opening up connection, grabbing the page
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsing
page_soup = soup(page_html, "html.parser")

#grabs each product
containers = page_soup.findAll("div",{"class":"navigator-content"})

print (containers)

After this, in inspect element it is like below,

...

...<t/body> (This contains all the information i want to print)

How to print the table and export to csv

Body:
For each of the containers you should grab the table [1], then you have to find the body of the table and iterate over its rows [2] and compile a line for your csv file with the table cells (td) [3]

for container in containers:
    table = container.find(id="issuetable") [1]
    #if you are exactly sure of the structure and/or if the tables have different/unique ids and there is only one table per container you can also do:
    table = container.table [1]

    for tr in table.tbody.find_all("tr"): [2]
        line = ""
        for td in tr: [3]
            line += td.text+"," #Adding the text in the td to the line followed by the separator of your choice in this case comma
        csvfile.write(line[:-1]+"/n") #add the line (replace "/n" with your system's new line character for extra portability)

There are different ways of navigating the soup tree depending on your need and on how flexible you script needs to be.
Have a look at https://www.crummy.com/software/BeautifulSoup/bs4/doc/ and check out the find / find_all sections.

Good luck!

/Teo


来源: stackexchange

问:
'Cannot find module 'process-nextick-args' npm error after reinstalling node.js in Windows10
I downloaded Node.js (4.4.5 LTS) from the official site  and installed it to update node in my Windows10, and found npm not working(node worked).I uninstalled node by installing it in "remove" mode, and then reinstalled, but the error persisted. The error upon npm -v is as follows:
```
    module.js:327
    throw err;
    ^</p>

```Error: Cannot find module 'process-nextick-args'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous>

(C:\Users\<my-name>\AppData\Roaming\npm\node_modules\np
    m\node_modules\readable-stream\lib\_stream_readable.js:6:23)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
```

<p><code>
Per suggestions from [this link][2] I have edited the PATH of Environmental Variables (in both User and System) to include:
</code>
    C:\Users\\AppData\Roaming\npm
<code>
 and
</code>
    C:\Program Files\nodejs
<code>
With 'which npm' it produced:
</code>
    /c/Program Files/nodejs/npm
<code>
With 'whereis npm' it showed:
</code>
    npm: /cygdrive/c/Program Files/nodejs/npm
    /cygdrive/c/Program Files/nodejs/npm.cmd
<code>
With 'which node' I got
</code>
    /c/Program Files/nodejs/node
```

Would appreciate any suggestions.

link2: Installing Node.js (and npm) on Windows 10

答: I had this problem after a brew update. I'm using nvm so I just reconfigured nvm to use my version with nvm use vx.x.x

ContentLicense: CC BY-SA 3.0

Body:
I downloaded Node.js (4.4.5 LTS) from the official site  and installed it to update node in my Windows10, and found npm not working(node worked).I uninstalled node by installing it in "remove" mode, and then reinstalled, but the error persisted. The error upon npm -v is as follows:
```
    module.js:327
    throw err;
    ^</p>

<pre><code>Error: Cannot find module 'process-nextick-args'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous>

(C:\Users\<my-name>\AppData\Roaming\npm\node_modules\np
    m\node_modules\readable-stream\lib\_stream_readable.js:6:23)
        at Module._compile (module.js:409:26)
        at Object.Module._extensions..js (module.js:416:10)
        at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
</code></pre>

<p><code>
Per suggestions from [this link][2] I have edited the PATH of Environmental Variables (in both User and System) to include:
</code>
    C:\Users\\AppData\Roaming\npm
<code>
 and
</code>
    C:\Program Files\nodejs
<code>
With 'which npm' it produced:
</code>
    /c/Program Files/nodejs/npm
<code>
With 'whereis npm' it showed:
</code>
    npm: /cygdrive/c/Program Files/nodejs/npm
    /cygdrive/c/Program Files/nodejs/npm.cmd
<code>
With 'which node' I got
</code>
    /c/Program Files/nodejs/node
```

Would appreciate any suggestions.

link2: Installing Node.js (and npm) on Windows 10


问:
to redirect non-existing subdomain to a rewritten existing url using part of the subdomain
I have tried this with .htaccess but was getting error searched the internet but could not get it.

When a non existing subdomain (like subname.domain.com) is entered into the address bar, i want it to redirects to something like domain.com/subname which would be checked through php routing script if the uri exists. I have developed the php routing script which works well.

Please how do I achieve this, i know mod-rewrite with .htaccess is all I need, and i already have a .htaccess file which works for redirecting to index.php tested on localhost server (xampp) containing the following

But please what do I need to add to the code below to make non-existing subdomain link like subname.domain.com redirect to domain.com/subname Please note that the subname used in the subdomain is needed in the redirect uri as written above

```<code>Options +FollowSymLinks +ExecCGI
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitefolder/
RewriteCond %{REQUEST_URI} !(\.css|\.png|\.jpg|\.PNG|\.JPG|\.gif)$
RewriteCond %{REQUEST_URI} !(\.js)$
RewriteRule ^(.*)$ index.php [NC,L,QSA]
RewriteRule ^(uploads)  - [L]
RewriteRule ^(uploads/*)  - [L]

</IfModule>
</code>```

Please, any help will be appreciated, thanks alot

答:
There is something called

_wildcard_domain

record in the DNS zone. You can refer this wiki link for more details :

WildCard DNS

However If you will have that option of setting that wildcard domain name server depends upon Domain service provider.

Body:
I have tried this with .htaccess but was getting error searched the internet but could not get it.

When a non existing subdomain (like subname.domain.com) is entered into the address bar, i want it to redirects to something like domain.com/subname which would be checked through php routing script if the uri exists. I have developed the php routing script which works well.

Please how do I achieve this, i know mod-rewrite with .htaccess is all I need, and i already have a .htaccess file which works for redirecting to index.php tested on localhost server (xampp) containing the following

But please what do I need to add to the code below to make non-existing subdomain link like subname.domain.com redirect to domain.com/subname Please note that the subname used in the subdomain is needed in the redirect uri as written above

Options +FollowSymLinks +ExecCGI
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sitefolder/
RewriteCond %{REQUEST_URI} !(\.css|\.png|\.jpg|\.PNG|\.JPG|\.gif)$
RewriteCond %{REQUEST_URI} !(\.js)$
RewriteRule ^(.*)$ index.php [NC,L,QSA]
RewriteRule ^(uploads)  - [L]
RewriteRule ^(uploads/*)  - [L]

</IfModule>

Please, any help will be appreciated, thanks alot


问:
How to have two sql queries in a prepared statement?
I would like to do something like this.

```<code>PREPARE addFriend(INTEGER, INTEGER) AS
    INSERT INTO friendRelation (u_id, friendid) VALUES ($1, $2),
    INSERT INTO friendRelation (u_id, friendid) VALUES ($2, $1);
</code>```

I do not see this in the docs, so either it can't be done or I am doing it wrong. If you can't have 2 queries in a prepared statment, is there some other feature of postgres that I don't know about that can do this?

答:
The accepted answer is partially true, in your particular case you can run one insert for multiples rows.
But in case if you need to run more than one different queries you can use WITH syntax</p>

```<code>WITH data_t (u1_id, u2_id) AS (
  VALUES($1::INTEGER, $2::INTEGER)
), inserted1 AS (
  INSERT INTO friendRelation (u_id, friendid) SELECT u1_id, u2_id FROM data_t
)
INSERT INTO friendRelation (u_id, friendid) SELECT u2_id, u1_id FROM data_t;
</code>```

Body:
I would like to do something like this.

PREPARE addFriend(INTEGER, INTEGER) AS
    INSERT INTO friendRelation (u_id, friendid) VALUES ($1, $2),
    INSERT INTO friendRelation (u_id, friendid) VALUES ($2, $1);

I do not see this in the docs, so either it can't be done or I am doing it wrong. If you can't have 2 queries in a prepared statment, is there some other feature of postgres that I don't know about that can do this?

Body:
The accepted answer is partially true, in your particular case you can run one insert for multiples rows.
But in case if you need to run more than one different queries you can use WITH syntax

WITH data_t (u1_id, u2_id) AS (
  VALUES($1::INTEGER, $2::INTEGER)
), inserted1 AS (
  INSERT INTO friendRelation (u_id, friendid) SELECT u1_id, u2_id FROM data_t
)
INSERT INTO friendRelation (u_id, friendid) SELECT u2_id, u1_id FROM data_t;


问:
Run ASP.NET Web API Hourly to fetch data from Database
I am looking for the best way to call web api hourly to retrieve data from SQL server. I have the asp.net web API but not sure which approach/technology I should use to run it hourly. Any suggestion/piece of code or technological idea would be great help. </p>

答:
Use either a Windows Service or a Console App that's executed via a scheduled task.

Of course, this would only make sense if the machine your hoping to initiate the calls from doesn't already have access to your database. If it does, consider just making the database call directly. If you can't make the database call directly, just be sure you can reach your Web API via port 80 or 443.


问:
Binding a Combobox control to a separate source within a DataGrid
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

```<code><my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>
</code>```

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

答:
You should look at this answer from Aran Mulholland.

It has a nice sample for using a DataGridComboBoxColumn

Adapted this article for your XAML

```<code><my:DataGridComboBoxColumn SelectedValueBinding="{Binding TERMINAL_TYPE_ID}"
  SelectedValuePath="TERMINAL_TYPE_ID"
  DisplayMemberPath="TERMINAL_TYPE"
  Header="Terminal Type"
  ItemsSource="{Binding TerminalTypes}" />

</my:DataGridComboBoxColumn>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Im attempting to use a ComboBox within a DataGrid which will allow the user to select a value coming from a different table. Im using a ViewModel class as the DataContext and this contains an ObservableCollection for Terminals and another for TerminalTypes.

The binding on the grid is fine, all the rows are populated and the DataGridTextColumns all show the correct data, my ComboBox however is empty.

I know that the ObservableCollection Im attempting to bind to has been populated and if I move the ComboBox outside of the DataGrid it works as expected.

<my:DataGrid Name="MenuDetailGrid" AutoGenerateColumns="False" ItemsSource="{Binding Terminals}">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Header="Terminal Type ID" Binding="{Binding TERMINAL_TYPE_ID}" IsReadOnly="True" />
        <my:DataGridTemplateColumn Header="Terminal Type">
            <my:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox DisplayMemberPath="TTYPE_NAME" SelectedValuePath="TERMINAL_TYPE"
                              SelectedValue="{Binding TERMINAL_TYPE_ID}"
                              ItemsSource="{Binding TerminalTypes}" />

                </DataTemplate>
            </my:DataGridTemplateColumn.CellTemplate>
        </my:DataGridTemplateColumn>

Obviously the binding behaviour is different on the ComboBox when part of the DataGrid but Im a bit stumped as to why?

Can someone please help me understand what I am doing wrong?

Body:
You should look at this answer from Aran Mulholland.

It has a nice sample for using a DataGridComboBoxColumn

Adapted this article for your XAML

<my:DataGridComboBoxColumn SelectedValueBinding="{Binding TERMINAL_TYPE_ID}"
  SelectedValuePath="TERMINAL_TYPE_ID"
  DisplayMemberPath="TERMINAL_TYPE"
  Header="Terminal Type"
  ItemsSource="{Binding TerminalTypes}" />

</my:DataGridComboBoxColumn>


问:
How can I set UIGestureRecognizer's Speed as the velocity for my Physicsbody in SpriteKit?
I calculated the speed of UIGestureRecognizer and I want to use it as velocity of Physicsbody in SpriteKit.

How can I do that since Speed is calculated in touches began and touches ended method, while my Physicsbody is wrapped in swipeUp & swipeDown etc functions, which does not have access to the Speed variable?

Here is my code:

```<code>class GameScene: SKScene, SKPhysicsContactDelegate, SKViewDelegate, UIGestureRecognizerDelegate, UIViewControllerTransitioningDelegate {

    var Kite = SKSpriteNode(imageNamed: "ASC_8025_large.jpg")

@objc let minusButton = SKSpriteNode(imageNamed: "minus.jpg")
@objc let plusButton = SKSpriteNode(imageNamed: "plus.png")

//override init(Kite: SKSpriteNode) {

//For long Long press gesture to work
let longPressGestureRecPlus = UILongPressGestureRecognizer()

let longPressGestureRecMinus = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(press:)))

//First we declare all of our Gestures...

//swipes

let swipeRightRec = UISwipeGestureRecognizer()
let swipeLeftRec = UISwipeGestureRecognizer()
let swipeUpRec = UISwipeGestureRecognizer()
let swipeDownRec = UISwipeGestureRecognizer()

//rotate

let rotateRec = UIRotationGestureRecognizer()

//taps

let tapRec = UITapGestureRecognizer()
let tapRec2 = UITapGestureRecognizer()

override func didMove(to view: SKView) {

    // Get label node from scene and store it for use later

    Kite.size = CGSize(width: 40.0, height: 40.0)
    Kite.position = CGPoint(x: frame.midX, y: frame.midY)

    plusButton.size =  CGSize(width: 30.0, height: 30.0)
    plusButton.position = CGPoint(x: frame.midX, y: frame.minY + 20.0)

    plusButton.name = "plusButton"
    //plusButton.isUserInteractionEnabled = true

    addChild(Kite)
    addChild(plusButton)

    swipeRightRec.addTarget(self, action: #selector(GameScene.swipedRight) )
    swipeRightRec.direction = .right
    self.view!.addGestureRecognizer(swipeRightRec)

    swipeLeftRec.addTarget(self, action: #selector(GameScene.swipedLeft) )
    swipeLeftRec.direction = .left
    self.view!.addGestureRecognizer(swipeLeftRec)

    swipeUpRec.addTarget(self, action: #selector(GameScene.swipedUp) )
    swipeUpRec.direction = .up
    self.view!.addGestureRecognizer(swipeUpRec)

    swipeDownRec.addTarget(self, action: #selector(GameScene.swipedDown) )
    swipeDownRec.direction = .down
    self.view!.addGestureRecognizer(swipeDownRec)

    //notice the function this calls has (_:) after it because we are passing in info about the gesture itself (the sender)

    rotateRec.addTarget(self, action: #selector (GameScene.rotatedView (_:) ))
    self.view!.addGestureRecognizer(rotateRec)

    // again notice (_:), we'll need this to find out where the tap occurred.

    tapRec.addTarget(self, action:#selector(GameScene.tappedView(_:) ))
    tapRec.numberOfTouchesRequired = 1
    tapRec.numberOfTapsRequired = 1
    self.view!.addGestureRecognizer(tapRec)

    tapRec2.addTarget(self, action:#selector(GameScene.tappedView2(_:) ))
    tapRec2.numberOfTouchesRequired = 1
    tapRec2.numberOfTapsRequired = 2  //2 taps instead of 1 this time
    self.view!.addGestureRecognizer(tapRec2)

   longPressGestureRecPlus.addTarget(self, action: #selector(longPressed(press:)))
   longPressGestureRecPlus.minimumPressDuration = 2.0
   self.view?.addGestureRecognizer(longPressGestureRecPlus)

}

//the functions that get called when swiping...

@objc func swipedRight() {

    print("Right")

    Kite.physicsBody?.velocity = CGVector(dx: 60, dy: 60)

    //Tilts the Kite towards Right

    let tiltRight = SKAction.rotate(toAngle: -1.00, duration: 0.1)

    Kite.run(tiltRight)

}

@objc func swipedLeft() {

    Kite.physicsBody?.velocity = CGVector(dx: -60, dy: 60)

     //Tilts the Kite towards Right

    let tiltLeft = SKAction.rotate(toAngle: 1.00, duration: 0.1)

    Kite.run(tiltLeft)

    print("Left")
}

@objc func swipedUp() {

   Kite.physicsBody?.velocity = CGVector(dx: 60, dy: 60)

    //Straightens the Kite

    let straightens = SKAction.rotate(toAngle: 0.00, duration: 0.1)

    Kite.run(straightens)

    print("Up")
}

@objc func swipedDown() {

   Kite.physicsBody?.velocity = CGVector(dx: 0, dy: -60)

    print("Down")
}

// what gets called when there's a single tap...

//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func tappedView(_ sender:UITapGestureRecognizer) {

    let point:CGPoint = sender.location(in: self.view)

    print("Single tap")

    print(point)

}

// what gets called when there's a double tap...

//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func tappedView2(_ sender:UITapGestureRecognizer) {

    let point:CGPoint = sender.location(in: self.view)

    print("Double tap")

    print(point)

}

//what gets called when there's a rotation gesture
//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func rotatedView(_ sender:UIRotationGestureRecognizer) {

    if (sender.state == .began) {

        print("rotation began")

    }
    if (sender.state == .changed) {

        print("rotation changed")

        //you could easily make any sprite's rotation equal this amount like so...
        //thePlayer.zRotation = -sender.rotation

        //convert rotation to degrees...
        let rotateAmount = Measurement(value: Double(sender.rotation), unit: UnitAngle.radians).converted(to: .degrees).value

        print("\(rotateAmount) degreess" )

    }
    if (sender.state == .ended) {

        print("rotation ended")

    }

}

func removeAllGestures(){

    //if you need to remove all gesture recognizers with Swift you can do this....

    for gesture in (self.view?.gestureRecognizers)! {

        self.view?.removeGestureRecognizer(gesture)
    }

    //this is good to do before a SKScene transitions to another SKScene.

}
func removeAGesture()
{

    //To remove a single gesture you can use...

    self.view?.removeGestureRecognizer(swipeUpRec)
}

//Fix the gesture recognizing the plusButton

@objc func longPressed(press: UILongPressGestureRecognizer) {

    if press.state == .began {
        isUserInteractionEnabled = true

        let positionInScene = press.location(in: self.view)
        let touchedNode = self.atPoint(positionInScene)

        plusButton.name = "plusButton"
       Kite.physicsBody?.velocity = CGVector(dx: 0, dy: 60.0*3)

        print("Pressed on the screen")

        if let name = touchedNode.name {

            if name == "plusButton" {

                print("LONG TAPPED")

            }

        }
    }

}

var start: CGPoint?
var startTime: TimeInterval?

 var taps = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("Began")

    Kite.physicsBody = SKPhysicsBody(rectangleOf: Kite.size)

    Kite.physicsBody?.affectedByGravity = false

    //Kite.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

    Kite.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 5))

    plusButton.name = "plusButton"
    plusButton.isUserInteractionEnabled = false

    //We figure how to interact with BUTTON in Spritekit
    let touch = touches.first
    let positionInScene = touch!.location(in: self)
    let touchedNode = self.atPoint(positionInScene)

    if let name = touchedNode.name {
        if name == "plusButton" {

            taps +=  1

            Kite.size = CGSize(width: 200, height: 200)

            print("tapped")
            print("Taps", taps)

    }
    }

    for touch in touches {
        let location:CGPoint = touch.location(in: self.view!)
        start = location
        startTime = touch.timestamp

    }

}

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("Ended")

        //Calculating Speed of the Gestures
        for touch in touches {
            let location:CGPoint = touch.location(in: self.view!)
            var dx:CGFloat = location.x - start!.x;
            var dy:CGFloat = location.y - start!.y;
            var magnitude:CGFloat = sqrt(dx*dx+dy*dy)

            //Calculate Time
            var dt:CGFloat = CGFloat(touch.timestamp - startTime!)
            //Speed = Distance / Time
            var speed:CGFloat = magnitude / dt

            var speedX:CGFloat = dx/dt
            var speedY:CGFloat = dy/dt

            print("SpeedY", speedX)
            print("SpeedY", speedY)

            }

}
</code>```

答:
so calculating the speed from a vector like dx and dy is

```<code>let speed = sqrtf(Float(pow(dx!, 2) + pow(dy!, 2)))
</code>```

So if you want apply the speed as velocity to an object you need at least one of the directions.

```<code>let newDx = 0 // means in no x direction

// next you can change the formula to your new dy to match the given speed

let newDy = sqrtf(pow(speed, 2) - Float(pow(newDx, 2)))

yourNode.physicsBody?.velocity = CGVector(dx: newDx, dy: CGFloat(newDy))
</code>```

Body:
I calculated the speed of UIGestureRecognizer and I want to use it as velocity of Physicsbody in SpriteKit.

How can I do that since Speed is calculated in touches began and touches ended method, while my Physicsbody is wrapped in swipeUp & swipeDown etc functions, which does not have access to the Speed variable?

Here is my code:

class GameScene: SKScene, SKPhysicsContactDelegate, SKViewDelegate, UIGestureRecognizerDelegate, UIViewControllerTransitioningDelegate {

    var Kite = SKSpriteNode(imageNamed: "ASC_8025_large.jpg")

@objc let minusButton = SKSpriteNode(imageNamed: "minus.jpg")
@objc let plusButton = SKSpriteNode(imageNamed: "plus.png")

//override init(Kite: SKSpriteNode) {

//For long Long press gesture to work
let longPressGestureRecPlus = UILongPressGestureRecognizer()

let longPressGestureRecMinus = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(press:)))

//First we declare all of our Gestures...

//swipes

let swipeRightRec = UISwipeGestureRecognizer()
let swipeLeftRec = UISwipeGestureRecognizer()
let swipeUpRec = UISwipeGestureRecognizer()
let swipeDownRec = UISwipeGestureRecognizer()

//rotate

let rotateRec = UIRotationGestureRecognizer()

//taps

let tapRec = UITapGestureRecognizer()
let tapRec2 = UITapGestureRecognizer()

override func didMove(to view: SKView) {

    // Get label node from scene and store it for use later

    Kite.size = CGSize(width: 40.0, height: 40.0)
    Kite.position = CGPoint(x: frame.midX, y: frame.midY)

    plusButton.size =  CGSize(width: 30.0, height: 30.0)
    plusButton.position = CGPoint(x: frame.midX, y: frame.minY + 20.0)

    plusButton.name = "plusButton"
    //plusButton.isUserInteractionEnabled = true

    addChild(Kite)
    addChild(plusButton)

    swipeRightRec.addTarget(self, action: #selector(GameScene.swipedRight) )
    swipeRightRec.direction = .right
    self.view!.addGestureRecognizer(swipeRightRec)

    swipeLeftRec.addTarget(self, action: #selector(GameScene.swipedLeft) )
    swipeLeftRec.direction = .left
    self.view!.addGestureRecognizer(swipeLeftRec)

    swipeUpRec.addTarget(self, action: #selector(GameScene.swipedUp) )
    swipeUpRec.direction = .up
    self.view!.addGestureRecognizer(swipeUpRec)

    swipeDownRec.addTarget(self, action: #selector(GameScene.swipedDown) )
    swipeDownRec.direction = .down
    self.view!.addGestureRecognizer(swipeDownRec)

    //notice the function this calls has (_:) after it because we are passing in info about the gesture itself (the sender)

    rotateRec.addTarget(self, action: #selector (GameScene.rotatedView (_:) ))
    self.view!.addGestureRecognizer(rotateRec)

    // again notice (_:), we'll need this to find out where the tap occurred.

    tapRec.addTarget(self, action:#selector(GameScene.tappedView(_:) ))
    tapRec.numberOfTouchesRequired = 1
    tapRec.numberOfTapsRequired = 1
    self.view!.addGestureRecognizer(tapRec)

    tapRec2.addTarget(self, action:#selector(GameScene.tappedView2(_:) ))
    tapRec2.numberOfTouchesRequired = 1
    tapRec2.numberOfTapsRequired = 2  //2 taps instead of 1 this time
    self.view!.addGestureRecognizer(tapRec2)

   longPressGestureRecPlus.addTarget(self, action: #selector(longPressed(press:)))
   longPressGestureRecPlus.minimumPressDuration = 2.0
   self.view?.addGestureRecognizer(longPressGestureRecPlus)

}

//the functions that get called when swiping...

@objc func swipedRight() {

    print("Right")

    Kite.physicsBody?.velocity = CGVector(dx: 60, dy: 60)

    //Tilts the Kite towards Right

    let tiltRight = SKAction.rotate(toAngle: -1.00, duration: 0.1)

    Kite.run(tiltRight)

}

@objc func swipedLeft() {

    Kite.physicsBody?.velocity = CGVector(dx: -60, dy: 60)

     //Tilts the Kite towards Right

    let tiltLeft = SKAction.rotate(toAngle: 1.00, duration: 0.1)

    Kite.run(tiltLeft)

    print("Left")
}

@objc func swipedUp() {

   Kite.physicsBody?.velocity = CGVector(dx: 60, dy: 60)

    //Straightens the Kite

    let straightens = SKAction.rotate(toAngle: 0.00, duration: 0.1)

    Kite.run(straightens)

    print("Up")
}

@objc func swipedDown() {

   Kite.physicsBody?.velocity = CGVector(dx: 0, dy: -60)

    print("Down")
}

// what gets called when there's a single tap...

//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func tappedView(_ sender:UITapGestureRecognizer) {

    let point:CGPoint = sender.location(in: self.view)

    print("Single tap")

    print(point)

}

// what gets called when there's a double tap...

//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func tappedView2(_ sender:UITapGestureRecognizer) {

    let point:CGPoint = sender.location(in: self.view)

    print("Double tap")

    print(point)

}

//what gets called when there's a rotation gesture
//notice the sender is a parameter. This is why we added (_:) that part to the selector earlier

@objc func rotatedView(_ sender:UIRotationGestureRecognizer) {

    if (sender.state == .began) {

        print("rotation began")

    }
    if (sender.state == .changed) {

        print("rotation changed")

        //you could easily make any sprite's rotation equal this amount like so...
        //thePlayer.zRotation = -sender.rotation

        //convert rotation to degrees...
        let rotateAmount = Measurement(value: Double(sender.rotation), unit: UnitAngle.radians).converted(to: .degrees).value

        print("\(rotateAmount) degreess" )

    }
    if (sender.state == .ended) {

        print("rotation ended")

    }

}

func removeAllGestures(){

    //if you need to remove all gesture recognizers with Swift you can do this....

    for gesture in (self.view?.gestureRecognizers)! {

        self.view?.removeGestureRecognizer(gesture)
    }

    //this is good to do before a SKScene transitions to another SKScene.

}
func removeAGesture()
{

    //To remove a single gesture you can use...

    self.view?.removeGestureRecognizer(swipeUpRec)
}

//Fix the gesture recognizing the plusButton

@objc func longPressed(press: UILongPressGestureRecognizer) {

    if press.state == .began {
        isUserInteractionEnabled = true

        let positionInScene = press.location(in: self.view)
        let touchedNode = self.atPoint(positionInScene)

        plusButton.name = "plusButton"
       Kite.physicsBody?.velocity = CGVector(dx: 0, dy: 60.0*3)

        print("Pressed on the screen")

        if let name = touchedNode.name {

            if name == "plusButton" {

                print("LONG TAPPED")

            }

        }
    }

}

var start: CGPoint?
var startTime: TimeInterval?

 var taps = 0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("Began")

    Kite.physicsBody = SKPhysicsBody(rectangleOf: Kite.size)

    Kite.physicsBody?.affectedByGravity = false

    //Kite.physicsBody?.velocity = CGVector(dx: 0, dy: 0)

    Kite.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 5))

    plusButton.name = "plusButton"
    plusButton.isUserInteractionEnabled = false

    //We figure how to interact with BUTTON in Spritekit
    let touch = touches.first
    let positionInScene = touch!.location(in: self)
    let touchedNode = self.atPoint(positionInScene)

    if let name = touchedNode.name {
        if name == "plusButton" {

            taps +=  1

            Kite.size = CGSize(width: 200, height: 200)

            print("tapped")
            print("Taps", taps)

    }
    }

    for touch in touches {
        let location:CGPoint = touch.location(in: self.view!)
        start = location
        startTime = touch.timestamp

    }

}

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        print("Ended")

        //Calculating Speed of the Gestures
        for touch in touches {
            let location:CGPoint = touch.location(in: self.view!)
            var dx:CGFloat = location.x - start!.x;
            var dy:CGFloat = location.y - start!.y;
            var magnitude:CGFloat = sqrt(dx*dx+dy*dy)

            //Calculate Time
            var dt:CGFloat = CGFloat(touch.timestamp - startTime!)
            //Speed = Distance / Time
            var speed:CGFloat = magnitude / dt

            var speedX:CGFloat = dx/dt
            var speedY:CGFloat = dy/dt

            print("SpeedY", speedX)
            print("SpeedY", speedY)

            }

}

Body:
so calculating the speed from a vector like dx and dy is

let speed = sqrtf(Float(pow(dx!, 2) + pow(dy!, 2)))

So if you want apply the speed as velocity to an object you need at least one of the directions.

let newDx = 0 // means in no x direction

// next you can change the formula to your new dy to match the given speed

let newDy = sqrtf(pow(speed, 2) - Float(pow(newDx, 2)))

yourNode.physicsBody?.velocity = CGVector(dx: newDx, dy: CGFloat(newDy))


问:
python - How to parse numbers around a specific word/phrase
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']
```

<p>I tried using regex for that but I've failed so far. What's the most logical way to do this?</p>

<p>Edit: After reading @LouiseDavies's question, I'll add another example below:</p>

<p><code>Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.</code></p>

<p>So in this example, my output should be something like this (the order doesn't matter):</p>

```['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']
```

答:
This is a bit longer than the other answers, but the state machine approach might turn out more maintainable if your needs change.</p>

```<code>import re

text = """
Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.
"""

r = re.compile(r"(\d+|[a-zA-Z ]+)")

faves = False
lst = []

while True:
    s = r.search(text)
    if s is None:
        break
    x = s.group(1).strip()
    if x:
        if x == 'and':
            pass
        elif re.search(r'favou?rite numbers?', x):
            faves = True
        elif re.match(r"^\d+$", x) and faves:
            lst.append(x)
        else:
            faves = False
    text = text[s.end():]

print lst
</code>```

Body:
Suppose that I have a text like this:

Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.

Let's say I'd like to get favorite numbers only in this text, for instance. I won't be able to know if there's a favorite number in this text, unless the phrase favorite number is present. So I'm basically trying to parse numbers around the phrase favorite number (or favorite numbers). The expected result should be something like this:

['5', '6', '7', '0']

I tried using regex for that but I've failed so far. What's the most logical way to do this?

Edit: After reading @LouiseDavies's question, I'll add another example below:

Alice has 2 favorite numbers: 11 and 12. Bob has 10 favorite numbers: 0, 100, 1264, 598, 78496, 33546, 1028896, 23, 48, 6.

So in this example, my output should be something like this (the order doesn't matter):

['11', '12', '0', '100', '1264', '598', '78496', '33546', '1028896', '23', '48', '6']

Body:
This is a bit longer than the other answers, but the state machine approach might turn out more maintainable if your needs change.

import re

text = """
Our favorite numbers are 5, 6, and 7, but his favorite number is 0. Also, this text contains 2 sentences.
"""

r = re.compile(r"(\d+|[a-zA-Z ]+)")

faves = False
lst = []

while True:
    s = r.search(text)
    if s is None:
        break
    x = s.group(1).strip()
    if x:
        if x == 'and':
            pass
        elif re.search(r'favou?rite numbers?', x):
            faves = True
        elif re.match(r"^\d+$", x) and faves:
            lst.append(x)
        else:
            faves = False
    text = text[s.end():]

print lst


问:
Is there a reason we cannot name a non-static member function in an unevaluated context?
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

```<code>#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");
</code>```

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

答:
I don't see any reason.

Look at this:

```<code>typedef void Func();

Func freeFunction;

struct Foo {
    Func memberFunction;
};
</code>```

freeFunction's declaration is Func freeFunction;. So, decltype(freeFunction) is void(), i.e. Func.

Using the same logic, As Foo::memberFunction is declared as Func too, I'd expect decltype(Foo::memberFunction) to be Func too. But that's not the case, as this doesn't compile.

Just like a int a; decltype(a) resolves to int, even if int a; is a member, decltype(Foo::memberFunction) should be OK.

Note, that qualifiers can be handled too, there is nothing special about them (of course, in this case, Func can only be used for declaring non-static member functions):

```<code>typedef void Func() const volatile &&;

struct Foo {
    Func memberFunction;
};
</code>```

Here, I'd expect that decltype(Foo::memberFunction) to be void() const volatile &&, so I can copy its declaration:

```<code>struct Bar {
    decltype(Foo::memberFunction) myMemFn;
};
</code>```

Quote from the C++14 standard (9.2/11):

[ Note: The type of a non-static member function is an ordinary
  function type, and the type of a non-static data member is an ordinary
  object type. There are no special member function types or data member
  types. — end note ]

This quote means that it would be sensible, if decltype(<member_function>) returned a type of ordinary function.

Body:
When reading [expr.prim.id], one will see that

An id-expression that denotes a non-static data member or non-static
  member function of a class can only be used:

if that id-expression denotes a non-static data member and it appears in an unevaluated operand.

The fact that the bullet above applies only to data members is unclear to me. Intuitively I'd expect the following to be well formed:

#include <type_traits>

using func = int();

class bar {
  func foo; // This is valid, and not the subject of the question
};

static_assert(std::is_same<decltype(bar::foo), func>::value, "No Symmetry!");

But the decltype() is ill-formed even before the static assertion is checked.

Is there some ambiguity I'm missing?

Body:
I don't see any reason.

Look at this:

typedef void Func();

Func freeFunction;

struct Foo {
    Func memberFunction;
};

freeFunction's declaration is Func freeFunction;. So, decltype(freeFunction) is void(), i.e. Func.

Using the same logic, As Foo::memberFunction is declared as Func too, I'd expect decltype(Foo::memberFunction) to be Func too. But that's not the case, as this doesn't compile.

Just like a int a; decltype(a) resolves to int, even if int a; is a member, decltype(Foo::memberFunction) should be OK.

Note, that qualifiers can be handled too, there is nothing special about them (of course, in this case, Func can only be used for declaring non-static member functions):

typedef void Func() const volatile &&;

struct Foo {
    Func memberFunction;
};

Here, I'd expect that decltype(Foo::memberFunction) to be void() const volatile &&, so I can copy its declaration:

struct Bar {
    decltype(Foo::memberFunction) myMemFn;
};

Quote from the C++14 standard (9.2/11):

[ Note: The type of a non-static member function is an ordinary
  function type, and the type of a non-static data member is an ordinary
  object type. There are no special member function types or data member
  types. — end note ]

This quote means that it would be sensible, if decltype(<member_function>) returned a type of ordinary function.


问:
Perform Incremental Sqoop on table that contains joins?
I have some very large tables that I am trying to sqoop from a Source System Data Warehouse into HDFS, but limited bandwidth to do so. I would like to only pull the columns I need, and minimize the run-time for getting the tables stood up.

The sqoop currently pulls something like this:

```<code>SELECT
    ColumnA,
    ColumnB,
    ....
    ColumnN
FROM
    TABLE_A
LEFT JOIN
    TABLE_B
ON
     ...
LEFT JOIN
    TABLE_N
....
</code>```

Is It possible to perform an incremental sqoop, given that the data is stored in a star-schema format, and the dimensions could update independently of the facts?

Or, is the only solution to sqoop the entire table, for the columns that I need, incrementally, and perform the joins on the HDFS side?

答:
For incremental imports you need to use --incremental flag. Please refer to below link for more info :-

https://sqoop.apache.org/docs/1.4.2/SqoopUserGuide.html#_incremental_imports

you need to specify —incremental to tell sqoop that you want an incremental load —check-column to specify which column is used for incremental sqooping and —last-value to say from which value you want to start sqooping the next load.
This is just half the picture. There are more ways to do this.for eg. you can use —query option and your query would be like Select * from table where column > 123. This is basically the same thing. You would need to record the last/max value for the selected column and use it for next import.

Body:
I have some very large tables that I am trying to sqoop from a Source System Data Warehouse into HDFS, but limited bandwidth to do so. I would like to only pull the columns I need, and minimize the run-time for getting the tables stood up.

The sqoop currently pulls something like this:

SELECT
    ColumnA,
    ColumnB,
    ....
    ColumnN
FROM
    TABLE_A
LEFT JOIN
    TABLE_B
ON
     ...
LEFT JOIN
    TABLE_N
....

Is It possible to perform an incremental sqoop, given that the data is stored in a star-schema format, and the dimensions could update independently of the facts?

Or, is the only solution to sqoop the entire table, for the columns that I need, incrementally, and perform the joins on the HDFS side?


问:
How to configure Solr to do partial and prefix word matching
for example,search:cent point

should be match

cent point

centrepoint

centre points

no need match "point cent".

I try to use NGramFilterFactory in solr6.0,but it always get result that the match order is reversed.
like this:

```<code>  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.NGramFilterFactory" minGramSize="1" maxGramSize="25"/>
  </analyzer>
  <analyzer type="query">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>
</code>```

I try to use PatternReplaceFilterFactory to replace space to  * .But it's didn't work ,only match it as an String.

答:
1) cent point

2) centrepoint

3) centre points

To solve 1 and 3, and keep the positions as important, I would recommend to use just phrase queries and edge ngram index time analysis :

search:"cent point"

<fieldType name="text_autocomplete" class="solr.TextField">
            <analyzer type="index">
                <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
                <tokenizer class="solr.StandardTokenizerFactory"/>
                <filter class="solr.WordDelimiterFilterFactory"
                        generateWordParts="1" generateNumberParts="1" catenateWords="0"
                        catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
                <filter class="solr.EdgeNGramFilterFactory" maxGramSize="20" minGramSize="2"/>
            </analyzer>
            <analyzer type="query">
                <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
                <tokenizer class="solr.StandardTokenizerFactory"/>
                <filter class="solr.WordDelimiterFilterFactory"
                        generateWordParts="1" generateNumberParts="1" catenateWords="0"
                        catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
            </analyzer>
        </fieldType>```

For point 2 it is more difficult as you have a compound token in the index which Solr doesn't know it is composed by 2 words.

You could take a look to this spellchecker[1], it may help

[1] https://lucene.apache.org/solr/guide/6_6/spell-checking.html#SpellChecking-WordBreakSolrSpellChecker

Body:
for example,search:cent point

should be match

cent point

centrepoint

centre points

no need match "point cent".

I try to use NGramFilterFactory in solr6.0,but it always get result that the match order is reversed.
like this:

  <analyzer type="index">
    <tokenizer class="solr.StandardTokenizerFactory"/>
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.NGramFilterFactory" minGramSize="1" maxGramSize="25"/>
  </analyzer>
  <analyzer type="query">
  <tokenizer class="solr.WhitespaceTokenizerFactory"/>
  <filter class="solr.LowerCaseFilterFactory"/>

I try to use PatternReplaceFilterFactory to replace space to  * .But it's didn't work ,only match it as an String.

Body:
1) cent point

2) centrepoint

3) centre points

To solve 1 and 3, and keep the positions as important, I would recommend to use just phrase queries and edge ngram index time analysis :

search:"cent point"

<fieldType name="text_autocomplete" class="solr.TextField">
            <analyzer type="index">
                <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
                <tokenizer class="solr.StandardTokenizerFactory"/>
                <filter class="solr.WordDelimiterFilterFactory"
                        generateWordParts="1" generateNumberParts="1" catenateWords="0"
                        catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
                <filter class="solr.EdgeNGramFilterFactory" maxGramSize="20" minGramSize="2"/>
            </analyzer>
            <analyzer type="query">
                <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
                <tokenizer class="solr.StandardTokenizerFactory"/>
                <filter class="solr.WordDelimiterFilterFactory"
                        generateWordParts="1" generateNumberParts="1" catenateWords="0"
                        catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
                <filter class="solr.LowerCaseFilterFactory"/>
            </analyzer>
        </fieldType>

For point 2 it is more difficult as you have a compound token in the index which Solr doesn't know it is composed by 2 words.

You could take a look to this spellchecker[1], it may help

[1] https://lucene.apache.org/solr/guide/6_6/spell-checking.html#SpellChecking-WordBreakSolrSpellChecker


问:
How do I loop through or enumerate a JavaScript object?
I have a JavaScript object like the following:

```<code>var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};
</code>```

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?

答:
An object becomes an iterator when it implements the .next() method

const james = {
  name: 'James',
  height: `5'10"`,
  weight: 185,

  [Symbol.iterator]() {
    let properties = []
    for (let key of Object.keys(james)) {
      properties.push(key);
    }

    index = 0;
    return {
      next: () => {
        let key = properties[index];
        let value = this[key];
        let done = index >= properties.length - 1;
        index++;
        return {
          key,
          value,
          done
        };
      }
    };
  }

};

const iterator = james[Symbol.iterator]();

console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185```

OwnerDisplayName: Tanmoy Rajguru

ContentLicense: CC BY-SA 4.0

Body:
I have a JavaScript object like the following:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

How do I loop through all of p's elements (p1, p2, p3...) and get their keys and values?


问:
How To Check Whether User is Disabled or Not in Firebase Auth
I have a Login System implemented using Firebase Auth, But Whenever I Disable any user he/she can still be logged.

But When he/she log out and login him/her by themselves, then the disable system is working.

So what should I do to check every time, whether a user is disabled or not?
Is there any function or something?

Thanks.

答:
Edit: 20th April 2022

Since the answer is some kind of old, I'll add another approach that we have nowadays, which is by calling FirebaseUser#reload() method, which:

Manually refreshes the data of the current user (for example, attached providers, display name, and so on).

So when calling the reload() method, it means that we reload the user's profile data from the Firebase server. Another thing to mention is that a FirebaseAuthInvalidUserException will be thrown if:

The current user's account has been disabled or deleted, or its credentials are no longer valid.

But remember, this also doesn't mean that auth state is changed. You need to call this method explicitly, for example, when the user opens the app. Also remember, that the method is asynchronous, it returns a Task object. So you need to attach a listener in order to get the new profile data from the server.

If you disable or delete a user account does not mean that it also fires an auth state change. Nor should it, because the user is still authenticated in the application. You need to know that in at most an hour, Firebase Authentication will try to refresh the access token for that particular user that was disabled or deleted. But in this case, that refresh will fail, at which point the user will become unauthenticated. This is the point at which the auth state change event will fire.

If you want to revoke the user's authorization immediately, you'll have to do so in another part of your application logic. A common practice when it comes to Firebase is to create a new node in your database called blacklist that should look like this:

```<code>Firebase-root
   |
   --- bannedUsers
          |
          uidOfBannedUser: true
</code>```

Now when you delete/disable a user's account in your Firebase console, you also need to add the corresponding UID to the list of banned users in the database.

The database can then be secured against access from unauthorized users with the help of Firebase Database Security Rules. This can be done by adding a clause to your database security rules like this:

```<code>{
  "rules": {
    "bannedUsers": {
      ".read": true,
      ".write": false // only admins can write these
    },
    "messages": {
      ".read": "auth != null && !root.child('bannedUsers').child(auth.uid).exists()"
    }
  }
}
</code>```

If you use a different back-end, the implementation will be different. There can be orher more examples but a blacklist like this is a common approach to ban users. You'll find that you may even care little enough about their authentication that you only ban them, instead of deleting their credentials, which they could simply recreate.

Body:
Edit: 20th April 2022

Since the answer is some kind of old, I'll add another approach that we have nowadays, which is by calling FirebaseUser#reload() method, which:

Manually refreshes the data of the current user (for example, attached providers, display name, and so on).

So when calling the reload() method, it means that we reload the user's profile data from the Firebase server. Another thing to mention is that a FirebaseAuthInvalidUserException will be thrown if:

The current user's account has been disabled or deleted, or its credentials are no longer valid.

But remember, this also doesn't mean that auth state is changed. You need to call this method explicitly, for example, when the user opens the app. Also remember, that the method is asynchronous, it returns a Task object. So you need to attach a listener in order to get the new profile data from the server.

If you disable or delete a user account does not mean that it also fires an auth state change. Nor should it, because the user is still authenticated in the application. You need to know that in at most an hour, Firebase Authentication will try to refresh the access token for that particular user that was disabled or deleted. But in this case, that refresh will fail, at which point the user will become unauthenticated. This is the point at which the auth state change event will fire.

If you want to revoke the user's authorization immediately, you'll have to do so in another part of your application logic. A common practice when it comes to Firebase is to create a new node in your database called blacklist that should look like this:

Firebase-root
   |
   --- bannedUsers
          |
          uidOfBannedUser: true

Now when you delete/disable a user's account in your Firebase console, you also need to add the corresponding UID to the list of banned users in the database.

The database can then be secured against access from unauthorized users with the help of Firebase Database Security Rules. This can be done by adding a clause to your database security rules like this:

{
  "rules": {
    "bannedUsers": {
      ".read": true,
      ".write": false // only admins can write these
    },
    "messages": {
      ".read": "auth != null && !root.child('bannedUsers').child(auth.uid).exists()"
    }
  }
}

If you use a different back-end, the implementation will be different. There can be orher more examples but a blacklist like this is a common approach to ban users. You'll find that you may even care little enough about their authentication that you only ban them, instead of deleting their credentials, which they could simply recreate.


问:
Checkbox to select all or deselect all in a listview not bound to dataset
I have a report page which displays a view for a set of data that we report off of. This view has about 40 fields. The user can query and filter the data to get what they need and then export it to an excel report which is then automatically emailed to management that needs to see the information.

Because not all of the fields are needed for every report I also have a list box next to the view with checkboxes to hide or show any fields. I have been trying to figure out how to get all checkboxes checked or unchecked by selecting checkbox in header. The xaml for the list box is bound to the IsVisible property of the fields in the grid and looks like so.

```<code><ListView  ItemsSource="{Binding Columns, ElementName=reportGrid}"  SelectionMode="Multiple">
   <ListView.View>
        <GridView>
           <GridViewColumn Width="50">
               <GridViewColumn.HeaderTemplate>
                     <DataTemplate>
                           <CheckBox x:Name="checkall" IsChecked="{Binding IsMainSelected}" Tag="{Binding Source={StaticResource Spy}, Path=DataContext}" />
                     </DataTemplate>
               </GridViewColumn.HeaderTemplate>                                                     <GridViewColumn.CellTemplate>
                    <DataTemplate >
                       <CheckBox IsChecked="{Binding IsVisible}" />
                    </DataTemplate>
            </GridViewColumn.CellTemplate>
             </GridViewColumn>
                                <GridViewColumn Header="Field" DisplayMemberBinding="{Binding Header}" Width="100"></GridViewColumn>
           </GridView>
    </ListView.View>
</code>```

The reference to the Spy static resource came from this article. http://www.codeproject.com/Articles/27432/Artificial-Inheritance-Contexts-in-WPF

However, the problem I am encountering with every solution is the fact that the checkboxes in the listview are bound to a dataset. In this case the checkboxes are bound to the visibility of a column in a grid (on object on a page). Everything I have tried has failed. It's probably a simple solution but darned if I can figure it out. Any help would be appreciated.

UPDATE:
I came up with a solution to this problem using code behind. If there is  a way to do this without using code behind I am all ears, but this was fairly simple and straight forward number one and number two it doesn't really break the rules of keeping logic out of code behind.

The xaml

```<code><ListView x:Name="lv" ItemsSource="{Binding Columns, ElementName=reportGrid}" Grid.Column="0" Grid.Row="1"
                              Margin="5,160,25,30" SelectionMode="Multiple">
                        <ListView.View>
                            <GridView x:Name="gl">
                                <GridViewColumn Width="50">
                                    <GridViewColumn.CellTemplate >
                                        <DataTemplate x:Name="fieldChecked"  >
                                            <CheckBox  IsChecked="{Binding IsVisible}" />
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                    <CheckBox Margin="0" x:Name="chkSelectAll" Click="chkSelectAll_Click" IsChecked="True" />
                                </GridViewColumn>
                                <GridViewColumn Header="Check/Uncheck All" DisplayMemberBinding="{Binding Header}" Width="110"></GridViewColumn>
                            </GridView>
                        </ListView.View>
                    </ListView>
</code>```

The code behind

```<code> private void chkSelectAll_Click(object sender, RoutedEventArgs e)
    {
        if (chkSelectAll.IsChecked.Value == true)
        {
            for (int i = 0; i < lv.Items.Count; i++)
            {
                ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(lv.Items[i]);

                if (lvi != null)
                {
                    CheckBox c = lvi.FindChildByType<CheckBox>();
                    c.IsChecked = true;
                }
            }
        }
        else
        {
            for (int i = 0; i < lv.Items.Count; i++)
            {
                ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(lv.Items[i]);
                if (lvi != null)
                {
                    CheckBox c = lvi.FindChildByType<CheckBox>();
                    c.IsChecked = false;
                }
            }
        }
    }
</code>```

One caveat was that the list view I had to scroll down to bottom to see all of the fields. If I didn't do this it wouldn't uncheck all of the fields. I also had to put in the line of code
if(lvi != null) as well because if you didn't scroll down it would think an item in the list was null and crash.

Anyway it isn't perfect but that is how I fixed it. Any better solutions using MVVM that isn't so blanking complicated to implement please enlighten me.

Thanks

答:
In case anyone stumbles upon this anwser like I did, there is a nice way to solve the scrolling issue Paul mentioned: just scroll in the code-behind!

```<code>listView.ScrollIntoView(listView.Items[listView.Items.Count - 1]);
listView.ScrollIntoView(listView.Items[0]);
</code>```

After that you can do the ItemContainerGenerator stuff without getting null.

And if you want to optimize responsiveness (especially for larger lists that do not change often): you only have to query the ItemContainerGenerator when the source content of your listView has changed. So if you put the CheckBoxes in a separate list, you only have to query the ItemContainerGenerator the first time the user clicks the (De)Select All checkbox...

But you should do this in the Event handler of the (De)Select All checkbox, because if you query the ItemContainerGenerator for the CheckBoxes right after you set the itemsSource and do the scrolling, you still end up with nulls (I assume because the GUI hasn't had the time to render the ListView properly yet at that time).

Body:
I have a report page which displays a view for a set of data that we report off of. This view has about 40 fields. The user can query and filter the data to get what they need and then export it to an excel report which is then automatically emailed to management that needs to see the information.

Because not all of the fields are needed for every report I also have a list box next to the view with checkboxes to hide or show any fields. I have been trying to figure out how to get all checkboxes checked or unchecked by selecting checkbox in header. The xaml for the list box is bound to the IsVisible property of the fields in the grid and looks like so.

<ListView  ItemsSource="{Binding Columns, ElementName=reportGrid}"  SelectionMode="Multiple">
   <ListView.View>
        <GridView>
           <GridViewColumn Width="50">
               <GridViewColumn.HeaderTemplate>
                     <DataTemplate>
                           <CheckBox x:Name="checkall" IsChecked="{Binding IsMainSelected}" Tag="{Binding Source={StaticResource Spy}, Path=DataContext}" />
                     </DataTemplate>
               </GridViewColumn.HeaderTemplate>                                                     <GridViewColumn.CellTemplate>
                    <DataTemplate >
                       <CheckBox IsChecked="{Binding IsVisible}" />
                    </DataTemplate>
            </GridViewColumn.CellTemplate>
             </GridViewColumn>
                                <GridViewColumn Header="Field" DisplayMemberBinding="{Binding Header}" Width="100"></GridViewColumn>
           </GridView>
    </ListView.View>

The reference to the Spy static resource came from this article. http://www.codeproject.com/Articles/27432/Artificial-Inheritance-Contexts-in-WPF

However, the problem I am encountering with every solution is the fact that the checkboxes in the listview are bound to a dataset. In this case the checkboxes are bound to the visibility of a column in a grid (on object on a page). Everything I have tried has failed. It's probably a simple solution but darned if I can figure it out. Any help would be appreciated.

UPDATE:
I came up with a solution to this problem using code behind. If there is  a way to do this without using code behind I am all ears, but this was fairly simple and straight forward number one and number two it doesn't really break the rules of keeping logic out of code behind.

The xaml

<ListView x:Name="lv" ItemsSource="{Binding Columns, ElementName=reportGrid}" Grid.Column="0" Grid.Row="1"
                              Margin="5,160,25,30" SelectionMode="Multiple">
                        <ListView.View>
                            <GridView x:Name="gl">
                                <GridViewColumn Width="50">
                                    <GridViewColumn.CellTemplate >
                                        <DataTemplate x:Name="fieldChecked"  >
                                            <CheckBox  IsChecked="{Binding IsVisible}" />
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                    <CheckBox Margin="0" x:Name="chkSelectAll" Click="chkSelectAll_Click" IsChecked="True" />
                                </GridViewColumn>
                                <GridViewColumn Header="Check/Uncheck All" DisplayMemberBinding="{Binding Header}" Width="110"></GridViewColumn>
                            </GridView>
                        </ListView.View>
                    </ListView>

The code behind

 private void chkSelectAll_Click(object sender, RoutedEventArgs e)
    {
        if (chkSelectAll.IsChecked.Value == true)
        {
            for (int i = 0; i < lv.Items.Count; i++)
            {
                ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(lv.Items[i]);

                if (lvi != null)
                {
                    CheckBox c = lvi.FindChildByType<CheckBox>();
                    c.IsChecked = true;
                }
            }
        }
        else
        {
            for (int i = 0; i < lv.Items.Count; i++)
            {
                ListViewItem lvi = (ListViewItem)lv.ItemContainerGenerator.ContainerFromItem(lv.Items[i]);
                if (lvi != null)
                {
                    CheckBox c = lvi.FindChildByType<CheckBox>();
                    c.IsChecked = false;
                }
            }
        }
    }

One caveat was that the list view I had to scroll down to bottom to see all of the fields. If I didn't do this it wouldn't uncheck all of the fields. I also had to put in the line of code
if(lvi != null) as well because if you didn't scroll down it would think an item in the list was null and crash.

Anyway it isn't perfect but that is how I fixed it. Any better solutions using MVVM that isn't so blanking complicated to implement please enlighten me.

Thanks

Body:
In case anyone stumbles upon this anwser like I did, there is a nice way to solve the scrolling issue Paul mentioned: just scroll in the code-behind!

listView.ScrollIntoView(listView.Items[listView.Items.Count - 1]);
listView.ScrollIntoView(listView.Items[0]);

After that you can do the ItemContainerGenerator stuff without getting null.

And if you want to optimize responsiveness (especially for larger lists that do not change often): you only have to query the ItemContainerGenerator when the source content of your listView has changed. So if you put the CheckBoxes in a separate list, you only have to query the ItemContainerGenerator the first time the user clicks the (De)Select All checkbox...

But you should do this in the Event handler of the (De)Select All checkbox, because if you query the ItemContainerGenerator for the CheckBoxes right after you set the itemsSource and do the scrolling, you still end up with nulls (I assume because the GUI hasn't had the time to render the ListView properly yet at that time).


问:
Custom handling WinKey+ArrowKey combination
Is there a possibility to handle WinKey+ArrowKey key combination before Windows handle it for WPFWindow? With OnPreviewKeyDown(KeyEventArgs e) I can catch when WinKey and ArrowKey are pressed separately, but not WinKey+ArrowKey combination. Seems that it is handled by system and window only get resizing command. Is there any way to handle this combination before system?

答:
To do this, you will need to use a Global Keyboard Hook.  There is a good project that would get you started in the right direction here: https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook

To reiterate Hans Passant's warning, this will catch the key combination even if your program is running in the background.  If this is not what you want, then you will need to subscribe and unsubscribe to the events when your program is focused/unfocused or put additional logic in there to detect whether your program is the focused program before taking any action.

If you import the classes from the link, then you can implement them in your code like this (EDIT: this seems to work with KeyValue, but not with KeyCode):

```<code>GlobalKeyboardHook gkh = new GlobalKeyboardHook();
private bool _winKeyPressed;

public MyConstructor()
{
    gkh.HookedKeys.Add(Keys.Left); //37
    gkh.HookedKeys.Add(Keys.Up); //38
    gkh.HookedKeys.Add(Keys.Right); //39
    gkh.HookedKeys.Add(Keys.Down); //40

    gkh.HookedKeys.Add(Keys.LWin); //91
    gkh.HookedKeys.Add(Keys.RWin); //92

    gkh.KeyDown += gkh_KeyDown;
    gkh.KeyUp += gkh_KeyUp;
}

private void gkh_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 91 || e.KeyValue == 92)
    {
        // left or right windows key was released
        _winKeyPressed = false;
    }
}

void gkh_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 91 || e.KeyValue == 92)
    {
        // left or right windows key was pressed
        _winKeyPressed = true;
    }

    if (e.KeyValue == 39 && _winKeyPressed == true)
    {
        // right key
        MessageBox.Show("This works.");
    }
}
</code>```

Body:
To do this, you will need to use a Global Keyboard Hook.  There is a good project that would get you started in the right direction here: https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook

To reiterate Hans Passant's warning, this will catch the key combination even if your program is running in the background.  If this is not what you want, then you will need to subscribe and unsubscribe to the events when your program is focused/unfocused or put additional logic in there to detect whether your program is the focused program before taking any action.

If you import the classes from the link, then you can implement them in your code like this (EDIT: this seems to work with KeyValue, but not with KeyCode):

GlobalKeyboardHook gkh = new GlobalKeyboardHook();
private bool _winKeyPressed;

public MyConstructor()
{
    gkh.HookedKeys.Add(Keys.Left); //37
    gkh.HookedKeys.Add(Keys.Up); //38
    gkh.HookedKeys.Add(Keys.Right); //39
    gkh.HookedKeys.Add(Keys.Down); //40

    gkh.HookedKeys.Add(Keys.LWin); //91
    gkh.HookedKeys.Add(Keys.RWin); //92

    gkh.KeyDown += gkh_KeyDown;
    gkh.KeyUp += gkh_KeyUp;
}

private void gkh_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 91 || e.KeyValue == 92)
    {
        // left or right windows key was released
        _winKeyPressed = false;
    }
}

void gkh_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyValue == 91 || e.KeyValue == 92)
    {
        // left or right windows key was pressed
        _winKeyPressed = true;
    }

    if (e.KeyValue == 39 && _winKeyPressed == true)
    {
        // right key
        MessageBox.Show("This works.");
    }
}


问:
Should ViewModel in MVVM only have code for request to the helpers?
I've been reading Dependency Injection book by Mark Seemann and thoughts are all messed up once again. The point of DI is to make sure that every single class would only know about the task it handles. So would it be wise, for a ViewModel only to make requests to other classes that would handle all the work, and ViewModel would be just for binding everything to the View?</p>

答:
The role of the ViewModel is to adapt the Model to work with the View.

But there is some missing part in this definition - your business logic. Of course you can put it in your ViewModel, but following SOLID principles in most cases it is a good idea to use some sort of services to get things done and DI is the right way to do this.

Although this approach might not be proper for all cases.


问:
Make QToolButton show menu on top in Qt 5.9
Is there a way for a QToolButton to display its associated QMenu on top of it instead of below?

I have seen this answer which pleased me but it's in Python and I don't really know how to port it properly.

I also took a look at the source code for QMenu but it's quite overwhelming so I don't really know how to tackle this issue.

There also is a little arrow on the button showing that it'll pop down.

This is the very bottom of my window so I'd like it to pop up in case it becomes too big to fit.

答:
You could do it using an event filter:

```<code>QMenu* yourMenu;
yourButton->setMenu(yourMenu);
yourMenu->installEventFilter(this);

bool yourClass::eventFilter(QObject * obj, QEvent *event)
{
    if (event->type() == QEvent::Show && obj == yourButton->menu())
    {
        QPoint pos = /*the position expected*/;
        yourButton->menu()->move(pos);
        return true;
    }
    return false;
}
</code>```

To remove the little arrow, add this to your stylesheet:

```<code>QToolButton::menu-indicator{
    image: none;
}
</code>```

Body:
You could do it using an event filter:

QMenu* yourMenu;
yourButton->setMenu(yourMenu);
yourMenu->installEventFilter(this);

bool yourClass::eventFilter(QObject * obj, QEvent *event)
{
    if (event->type() == QEvent::Show && obj == yourButton->menu())
    {
        QPoint pos = /*the position expected*/;
        yourButton->menu()->move(pos);
        return true;
    }
    return false;
}

To remove the little arrow, add this to your stylesheet:

QToolButton::menu-indicator{
    image: none;
}


问:
Howto synchronize file access in a shared folder using Java (OR: ReadWriteLock on network level)
I have multiple applications running in one virtual machine. I have multiple virtual machines running on one server. And I have multiple servers. They all share a file using a shared folder on linux. The file is read and written by all applications. During the write process no application is allowed to read this file. The same for writing: If an application is reading the file no application is allowed to write it.

How do I manage to synchronize the applications so they will wait for the write process to finish before they read, and vice versa? (the applications inside a vm have to be synchronized and also applications across servers)

Curent implementation uses "file semaphores". If the file is about to be written the application tries to "acquire" the semaphore by creating an additional file (lets name it "file.semaphore") in the shared folder. If the "file.semaphore" file already exists this means the semaphore is already locked by a different application. This approach has the problem that I cannot make sure that the "file exists"-test and "create file"- operation are executed atomic. This way it is possible that two applications test for the "file.semaphore" file, see it does not exist and try to create the file at the same time.

答:
Have a look at the Javadocs for the createNewFile() method - it specifically states that creating files is not a reliable method for synchronization, and recommends the FileLock class instead (it's another package in java.nio.channels so is essentially the same as what Ivan Dubrov is suggesting).

This would imply that your identification of the problem is accurate, and no amount of playing around will solve this with traditional file creation.  My first thought was to check the return code from createNewFile(), but if the Javadocs say it's not suitable then it's time to move on.

OwnerDisplayName: dtsazza


问:
Storing BLOB in Database Spring Hibernate Persistence
This is a problem iv encountered and tried most of the solutions that i have been offered so far and little seems to work , the problem making this harder to fix is for some reason the hibernate session wont print its details to the log providing me with very little in terms of error tracing. I want to upload a string of Json converted to a blob into the database . If anyone knows where i am going wrong or can provide and pointers this would be great as im struggling to solve this alone.

```<code>@Entity
@Table(name="workout")
public class Workout implements Serializable{

    private static Logger logger = Logger.getLogger(Workout.class);

    @Id
    @Column(name="workout_id")
    private int workout_id;

    @Column(name="username")
    private String username;

    @Column(name="added_date")
    private String added_date;

    @Lob
    @Column(name="workout")
    Blob workout;

    public int getWorkout_id() {
        return workout_id;
    }

    public void setWorkout_id(int workout_id) {
        this.workout_id = workout_id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAdded_date() {
        return added_date;
    }

    public void setAdded_date(String added_date) {
        this.added_date = added_date;
    }

    public Blob getWorkout() {
        return workout;
    }

    public void setWorkout(Blob workout) {
        this.workout = workout;
    }

    }
</code>```

method from Service that trys to upload

```<code>public String uploadWorkout(String json){
    Workout w = new Workout();
    w.setUsername("cmac458");
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    w.setAdded_date(date.toGMTString());
    w.setWorkout(getBLOBfromJSON(json));
    w.setWorkout_id(4);
    workoutDao.getSession().save(w);
    return "done";

    }
</code>```

I am using the basic hibernatetemplate.save(entity) that works in other parts of my application.

Any help here is much appreciated.
Thanks
Chris

答:
I use byte[] instead ob Blob type, and that works fine.

```<code>@Lob
@Column(nullable = false, length = 2097152)
private byte[] data;
</code>```

Body:
This is a problem iv encountered and tried most of the solutions that i have been offered so far and little seems to work , the problem making this harder to fix is for some reason the hibernate session wont print its details to the log providing me with very little in terms of error tracing. I want to upload a string of Json converted to a blob into the database . If anyone knows where i am going wrong or can provide and pointers this would be great as im struggling to solve this alone.

@Entity
@Table(name="workout")
public class Workout implements Serializable{

    private static Logger logger = Logger.getLogger(Workout.class);

    @Id
    @Column(name="workout_id")
    private int workout_id;

    @Column(name="username")
    private String username;

    @Column(name="added_date")
    private String added_date;

    @Lob
    @Column(name="workout")
    Blob workout;

    public int getWorkout_id() {
        return workout_id;
    }

    public void setWorkout_id(int workout_id) {
        this.workout_id = workout_id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAdded_date() {
        return added_date;
    }

    public void setAdded_date(String added_date) {
        this.added_date = added_date;
    }

    public Blob getWorkout() {
        return workout;
    }

    public void setWorkout(Blob workout) {
        this.workout = workout;
    }

    }

method from Service that trys to upload

public String uploadWorkout(String json){
    Workout w = new Workout();
    w.setUsername("cmac458");
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    w.setAdded_date(date.toGMTString());
    w.setWorkout(getBLOBfromJSON(json));
    w.setWorkout_id(4);
    workoutDao.getSession().save(w);
    return "done";

    }

I am using the basic hibernatetemplate.save(entity) that works in other parts of my application.

Any help here is much appreciated.
Thanks
Chris

Body:
I use byte[] instead ob Blob type, and that works fine.

@Lob
@Column(nullable = false, length = 2097152)
private byte[] data;


问:
OpenGl Plane Drawing
I am trying to make a ground plane. My points and indices are correctly generated by functions makeplaneverts and makeplaneindices but the ground plane is not displayed. Can anyone see a mistake ?

```<code>void makePlaneVerts(int dimensions){

    num = (dimensions)*(dimensions);
    number = num * 3;
    PlaneVerts = new GLfloat[number];
    int counter = 0;
    for (int i = 0; i < dimensions; i++)
    {
        for (int j = 0; j < dimensions; j++)
        {
            PlaneVerts[counter++] = (float)j; cout << counter << j<<endl;
            PlaneVerts[counter++] = (float)0; cout << counter << 0<<endl;
            PlaneVerts[counter++] = (float)i; cout << counter << i<<endl;
        }
    }
    return ;
}

GLushort *Planeindices;
int NumIndices;

void makePlaneIndices(int dimensions) {

    NumIndices = (dimensions - 1) * (dimensions - 1) * 2 * 3;
    Planeindices = new GLushort[NumIndices];
    int count = 0;

    for (int row = 0; row < dimensions - 1; row++)
    {
        for (int col = 0; col < dimensions - 1; col++)
        {
            Planeindices[count++] = dimensions * row + col;
            cout << count << ":" << dimensions * row + col;
            Planeindices[count++] = dimensions * row + col + dimensions;
            cout << count << ":" << dimensions * row + col + dimensions;
            Planeindices[count++] = dimensions * row + col + dimensions + 1;
            cout << count << ":" << dimensions * row + col + dimensions + 1 << endl;
            Planeindices[count++] = dimensions * row + col;
            cout << count << ":" << dimensions * row + col;
            Planeindices[count++] = dimensions * row + col + dimensions + 1;
            cout << count << ":" << dimensions * row + col + dimensions + 1;
            Planeindices[count++] = dimensions * row + col + 1;
            cout << count << ":" << dimensions * row + col + 1 << endl;
        }
    }
    return;
}
</code>```

initializing plane opening vbo one for vertices one for indices

```<code>void initPlane() {

    GLuint myBufferID;
    glGenBuffers(1, &myBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(PlaneVerts), PlaneVerts, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    GLuint indexBufferID;
    glGenBuffers(1, &indexBufferID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Planeindices), Planeindices, GL_STATIC_DRAW);
}
</code>```

Displaying playing by matching indices with vertices

```<code>void displayPlane() {
   glDrawElements(GL_TRIANGLES, number/3, GL_UNSIGNED_SHORT, 0);
}
</code>```

答:
You don't even seem to have variables names. When you define a variable you need to give it a name:

```<code>PlaneVerts myVariableName;
</code>```

If you're not familiar with this concept then you likely haven't done much programming before, take a step back and look at basic C++ tutorials.

Title: OpenGl Plane Drawing

Body:
I am trying to make a ground plane. My points and indices are correctly generated by functions makeplaneverts and makeplaneindices but the ground plane is not displayed. Can anyone see a mistake ?

void makePlaneVerts(int dimensions){

    num = (dimensions)*(dimensions);
    number = num * 3;
    PlaneVerts = new GLfloat[number];
    int counter = 0;
    for (int i = 0; i < dimensions; i++)
    {
        for (int j = 0; j < dimensions; j++)
        {
            PlaneVerts[counter++] = (float)j; cout << counter << j<<endl;
            PlaneVerts[counter++] = (float)0; cout << counter << 0<<endl;
            PlaneVerts[counter++] = (float)i; cout << counter << i<<endl;
        }
    }
    return ;
}

GLushort *Planeindices;
int NumIndices;

void makePlaneIndices(int dimensions) {

    NumIndices = (dimensions - 1) * (dimensions - 1) * 2 * 3;
    Planeindices = new GLushort[NumIndices];
    int count = 0;

    for (int row = 0; row < dimensions - 1; row++)
    {
        for (int col = 0; col < dimensions - 1; col++)
        {
            Planeindices[count++] = dimensions * row + col;
            cout << count << ":" << dimensions * row + col;
            Planeindices[count++] = dimensions * row + col + dimensions;
            cout << count << ":" << dimensions * row + col + dimensions;
            Planeindices[count++] = dimensions * row + col + dimensions + 1;
            cout << count << ":" << dimensions * row + col + dimensions + 1 << endl;
            Planeindices[count++] = dimensions * row + col;
            cout << count << ":" << dimensions * row + col;
            Planeindices[count++] = dimensions * row + col + dimensions + 1;
            cout << count << ":" << dimensions * row + col + dimensions + 1;
            Planeindices[count++] = dimensions * row + col + 1;
            cout << count << ":" << dimensions * row + col + 1 << endl;
        }
    }
    return;
}

initializing plane opening vbo one for vertices one for indices

void initPlane() {

    GLuint myBufferID;
    glGenBuffers(1, &myBufferID);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(PlaneVerts), PlaneVerts, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

    GLuint indexBufferID;
    glGenBuffers(1, &indexBufferID);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Planeindices), Planeindices, GL_STATIC_DRAW);
}

Displaying playing by matching indices with vertices

void displayPlane() {
   glDrawElements(GL_TRIANGLES, number/3, GL_UNSIGNED_SHORT, 0);
}

Body:
You don't even seem to have variables names. When you define a variable you need to give it a name:

PlaneVerts myVariableName;

If you're not familiar with this concept then you likely haven't done much programming before, take a step back and look at basic C++ tutorials.


问:
Regex in R - omit group
I'm starting to work with regex in R and need some help.
I would like to match a string but without some specific group in the middle of it.Example:

```<code>string <- "ABCDEFG"
</code>```

I want to capture:

```<code>"ABFG"
</code>```

I have tried:

```<code>stringi::stri_extract_first(str = string, regex = "AB(?!CDE)FG")
</code>```

but I get:

```<code>  [NA]
</code>```

Can anyone help me?

Edit:

I'll try to be more specific. I have some positions each in one line that are separated with page numers and footers. Something like:

```<code>8151A0 ZAX
8131A9)
7421A7
8481A1

FOOTER
PAGE1

BRAK NR
1211Q2
865100)
BN

FOOTER
PAGE2

616100)
BRAK NR
</code>```

I would like to extract all positions without footers and pages so my expected output is:

```<code>8151A0 ZAX
8131A9)
7421A7
8481A1
BRAK NR
1211Q2
865100)
BN
616100)
BRAK NR
</code>```

答:
This pattern should work, it will capture 2 groups if CDE is in the middle, $1 and $2, and will capture a single one if it is not.

```<code>^((?:(?!CDE).)*)(?:CDE)?(.*)$
</code>```

Substitute with $1$2 to extract the CDE

Test it here

Title: Regex in R - omit group

Body:
I'm starting to work with regex in R and need some help.
I would like to match a string but without some specific group in the middle of it.Example:

string <- "ABCDEFG"

I want to capture:

"ABFG"

I have tried:

stringi::stri_extract_first(str = string, regex = "AB(?!CDE)FG")

but I get:

  [NA]

Can anyone help me?

Edit:

I'll try to be more specific. I have some positions each in one line that are separated with page numers and footers. Something like:

8151A0 ZAX
8131A9)
7421A7
8481A1

FOOTER
PAGE1

BRAK NR
1211Q2
865100)
BN

FOOTER
PAGE2

616100)
BRAK NR

I would like to extract all positions without footers and pages so my expected output is:

8151A0 ZAX
8131A9)
7421A7
8481A1
BRAK NR
1211Q2
865100)
BN
616100)
BRAK NR

Body:
This pattern should work, it will capture 2 groups if CDE is in the middle, $1 and $2, and will capture a single one if it is not.

^((?:(?!CDE).)*)(?:CDE)?(.*)$

Substitute with $1$2 to extract the CDE

Test it here


问:
Need to limit my results to one row when connected to another table with multiple rows
Table1

```<code>SaleID  |  Name
123     |  John Doe
456     |  Jane Doe
</code>```

Table2

```<code>SaleID  |  ProductID    |  ProductCost  |  ProductSize
123     |  1            |  $200         |  Medium
123     |  2            |  $250         |  Large
123     |  3            |  $100         |  Small
</code>```

Results:

```<code>SaleID     |  Name         | Product1Cost | Product1Size  | Product2Cost | Product2Size   | Product3Cost  | Product3Size
123        |  John Doe     | $200         | Medium
123        |  John Doe     |              |               | $250         | Large
123        |  John Doe     |              |               |                               | $100          | Small
</code>```

Expected Results:

```<code>SaleID    |  Name        | Product1Cost  | Product1Size | Product2Cost  | Product2Size | Product3Cost  | Product3Size
123       |  John Doe    | $200          | Medium       | $250          | Large        | $100          | Small
</code>```

Here is my query:

```<code>Select
    SaleID    = a.SaleID,
    Name = a.Name,
    Product1Cost = case when b.ProductID = '1'then b.Product1Cost end,
    Product1Size = case when b.ProductID = '1'then b.Product1Size end,
    Product2Cost = case when b.ProductID = '2'then b.Product2Cost end,
    Product2Size = case when b.ProductID = '2'then b.Product2Size end,
    Product3Cost = case when b.ProductID = '3'then b.Product3Cost end,
    Product3Size = case when b.ProductID = '3'then b.Product3Size end

from Table1 a

    OUTER APPLY
    (
        SELECT  *
        FROM Table2 b
        where a.SaleID = b.SaleID
    ) b
</code>```

答:
You don't need apply for this.  A join and group by should work:

```<code>Select a.SaleID, a.Name,
       Product1Cost = max(case when b.ProductID = '1' then b.Product1Cost end),
       Product1Size = max(case when b.ProductID = '1' then b.Product1Size end),
       Product2Cost = max(case when b.ProductID = '2' then b.Product2Cost end),
       Product2Size = max(case when b.ProductID = '2' then b.Product2Size end),
       Product3Cost = max(case when b.ProductID = '3' then b.Product3Cost end),
       Product3Size = max(case when b.ProductID = '3' then b.Product3Size end)
from Table1 a join
     Table2 b
     on a.SaleID = b.SaleID
group by a.SaleID, a.Name;
</code>```

You don't need to do name = a.name.  The default alias is the column name.

Also, if ProductId is a number, then don't put single quotes around the comparison.  Instead of = '1', use = 1.

Body:
Table1

SaleID  |  Name
123     |  John Doe
456     |  Jane Doe

Table2

SaleID  |  ProductID    |  ProductCost  |  ProductSize
123     |  1            |  $200         |  Medium
123     |  2            |  $250         |  Large
123     |  3            |  $100         |  Small

Results:

SaleID     |  Name         | Product1Cost | Product1Size  | Product2Cost | Product2Size   | Product3Cost  | Product3Size
123        |  John Doe     | $200         | Medium
123        |  John Doe     |              |               | $250         | Large
123        |  John Doe     |              |               |                               | $100          | Small

Expected Results:

SaleID    |  Name        | Product1Cost  | Product1Size | Product2Cost  | Product2Size | Product3Cost  | Product3Size
123       |  John Doe    | $200          | Medium       | $250          | Large        | $100          | Small

Here is my query:

Select
    SaleID    = a.SaleID,
    Name = a.Name,
    Product1Cost = case when b.ProductID = '1'then b.Product1Cost end,
    Product1Size = case when b.ProductID = '1'then b.Product1Size end,
    Product2Cost = case when b.ProductID = '2'then b.Product2Cost end,
    Product2Size = case when b.ProductID = '2'then b.Product2Size end,
    Product3Cost = case when b.ProductID = '3'then b.Product3Cost end,
    Product3Size = case when b.ProductID = '3'then b.Product3Size end

from Table1 a

    OUTER APPLY
    (
        SELECT  *
        FROM Table2 b
        where a.SaleID = b.SaleID
    ) b

Body:
You don't need apply for this.  A join and group by should work:

Select a.SaleID, a.Name,
       Product1Cost = max(case when b.ProductID = '1' then b.Product1Cost end),
       Product1Size = max(case when b.ProductID = '1' then b.Product1Size end),
       Product2Cost = max(case when b.ProductID = '2' then b.Product2Cost end),
       Product2Size = max(case when b.ProductID = '2' then b.Product2Size end),
       Product3Cost = max(case when b.ProductID = '3' then b.Product3Cost end),
       Product3Size = max(case when b.ProductID = '3' then b.Product3Size end)
from Table1 a join
     Table2 b
     on a.SaleID = b.SaleID
group by a.SaleID, a.Name;

You don't need to do name = a.name.  The default alias is the column name.

Also, if ProductId is a number, then don't put single quotes around the comparison.  Instead of = '1', use = 1.


问:
Regex: Exact plus wildcard text
I'm looking for regex for my auto suggest key search.

String example:

```<code>universal studio japan
universal
japan
</code>```

basically if user types "universal jap" or "universal japan",
"universal studio japan" should match.

答:
To match words, you should surround them with \b (word boundary). This will check to ensure there is a "word boundary", which asserts (^\w|\w$|\W\w|\w\W) matches the position in the string.

Using something like the following will match any character between universal and japan, which may not be what you're looking for, but I'm posting it so that you (the OP) can decide which method works best for you.

See regex in use here

```<code>\buniversal\b.*\bjap(?:an)?\b
</code>```

This next method will only match word characters (a-zA-Z0-9_), hyphens -, or spaces between words (ensuring there is no other special character such as a dot/period .). Regular expressions can get complicated fast, so, assuming you now also want to match decimal points or abbreviated words, this regex will no longer be the best solution and you should use the first.

See regex in use here

```<code>\buniversal\b[ \w-]*\bjap(?:an)?\b
</code>```

Also, note that I changed japan to jap(?:an)? since your question specifies it should also match jap. Should this not be the case, simply replace the latter with the former.

Title: Regex: Exact plus wildcard text

Body:
I'm looking for regex for my auto suggest key search.

String example:

universal studio japan
universal
japan

basically if user types "universal jap" or "universal japan",
"universal studio japan" should match.

Body:
To match words, you should surround them with \b (word boundary). This will check to ensure there is a "word boundary", which asserts (^\w|\w$|\W\w|\w\W) matches the position in the string.

Using something like the following will match any character between universal and japan, which may not be what you're looking for, but I'm posting it so that you (the OP) can decide which method works best for you.

See regex in use here

\buniversal\b.*\bjap(?:an)?\b

This next method will only match word characters (a-zA-Z0-9_), hyphens -, or spaces between words (ensuring there is no other special character such as a dot/period .). Regular expressions can get complicated fast, so, assuming you now also want to match decimal points or abbreviated words, this regex will no longer be the best solution and you should use the first.

See regex in use here

\buniversal\b[ \w-]*\bjap(?:an)?\b

Also, note that I changed japan to jap(?:an)? since your question specifies it should also match jap. Should this not be the case, simply replace the latter with the former.