问:
Is it possible to make a recursive SQL query - with HP Quality Center?
This question has already been asked in stackoverflow and elsewhere:

Is it possible to make a recursive SQL query ?

Requêtes récursives avec les CTE - Exemples avec SQLServer 2003

But I would like to make this work for a report query in HP Quality-Center 10.

Anybody with insights into such technicalities?

A simple check:

```<code>with t1 (parent, child) as
(select * from all_lists t where t.al_father_id = '2') select * from t1
</code>```

QC reports "Quality Center cannot run the query because it contains invalid statements".

Whereas with the following intentional typo

```<code>select * from all_lists t wher t.al_father_id = '2'
</code>```

QC reports "The SQL query ... has failed to run, with the following error: Failed SQL ... [Mercury][Oracle JDBC Driver][Oracle]ORA-00933: SQL command not properly ended."

So I guess it answers two questions:

the server is Oracle (though it does not give the version)

with is not allowed through the QC interface

答:
Ok, got it:

```<code>select      SYS_CONNECT_BY_PATH (al_description,' :: ')
from        all_lists
start with  al_father_id = '2'
connect by  prior al_item_id = al_father_id
</code>```

This is the solution to my query. Thanks to a_horse_with_a_name for comments that motivated me to search deeper.

Fab.

I'm still open to comments for improvement or further trips and tricks of the trade - such as: where can I find a reference for the CONNECT BY related functions like SYS_CONNECT_BY_PATH. I'm sure it has a few friends I'd be keen to learn about.

Body:
This question has already been asked in stackoverflow and elsewhere:

Is it possible to make a recursive SQL query ?

Requêtes récursives avec les CTE - Exemples avec SQLServer 2003

But I would like to make this work for a report query in HP Quality-Center 10.

Anybody with insights into such technicalities?

A simple check:

with t1 (parent, child) as
(select * from all_lists t where t.al_father_id = '2') select * from t1

QC reports "Quality Center cannot run the query because it contains invalid statements".

Whereas with the following intentional typo

select * from all_lists t wher t.al_father_id = '2'

QC reports "The SQL query ... has failed to run, with the following error: Failed SQL ... [Mercury][Oracle JDBC Driver][Oracle]ORA-00933: SQL command not properly ended."

So I guess it answers two questions:

the server is Oracle (though it does not give the version)

with is not allowed through the QC interface

Body:
Ok, got it:

select      SYS_CONNECT_BY_PATH (al_description,' :: ')
from        all_lists
start with  al_father_id = '2'
connect by  prior al_item_id = al_father_id

This is the solution to my query. Thanks to a_horse_with_a_name for comments that motivated me to search deeper.

Fab.

I'm still open to comments for improvement or further trips and tricks of the trade - such as: where can I find a reference for the CONNECT BY related functions like SYS_CONNECT_BY_PATH. I'm sure it has a few friends I'd be keen to learn about.


来源: stackexchange

问:
hybris populators and converters concept and their relationship
Can someone please explain the concept of converters and populators used in the Hybris? I was going through the concept of AddOns in Hybris but one of the points said "You can plug populators into existing converters without having to redefine them" after we use AddOns in Hybris commerce accelerator? So I thought it`s better to understand these concepts first.

答:
You should create object firstly for populator while converter creates target object and then populates it automatically.</p>

```<code>//converter example
Target target = targetConverter.convert(source);
List<Target> targetList = sourceList.toStream().map(s->targetConverter.convert(s));

//Populator example
Target target = new Target();
targetPopulator.populate(source, target);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should create object firstly for populator while converter creates target object and then populates it automatically.

//converter example
Target target = targetConverter.convert(source);
List<Target> targetList = sourceList.toStream().map(s->targetConverter.convert(s));

//Populator example
Target target = new Target();
targetPopulator.populate(source, target);

ContentLicense: CC BY-SA 4.0


问:
Calling a function recursively in the context of "export default"?
This may be obvious to others but I don't know the syntax for calling a function recursively in the following code:

```<code>//request.js
    export default {

      send() {
       ... do stuff ...
       this.send(); // Can't call "send" of undefined
      }
    }

//main.js
import request from './request'

export default class Main extends Component {
   init() {
      request.send();
  }
}
</code>```

In the above example, I'm calling the send function from main.js. All this is working fine but I have a condition in the send function that will recall the same function. The problem is that I have no idea how to call the function from within the function. Anybody?

答:
I don't see any reason why this.send() wouldn't work, given you are exporting an object with a method.

But if it doesn't work, you can always use a named function expression:

```<code>export default {
  send: function send() {
    … send() …
  }
};
</code>```

or a named function declaration:

```<code>function send() {
  … send() …
}
export default { send };
</code>```

or just name your exported object:

```<code>export default const request = {
  send() {
    … request.send() …
  }
};
</code>```

But I would recommend to not default-export an object at all, and use named exports instead so that you can import them separately or on a namespace object:

```<code>// request.js
export default function send() {
  … send() …
}
</code>```

```<code>// main.js
import * as request from './request'
…
request.send()
</code>```

Body:
This may be obvious to others but I don't know the syntax for calling a function recursively in the following code:

//request.js
    export default {

      send() {
       ... do stuff ...
       this.send(); // Can't call "send" of undefined
      }
    }

//main.js
import request from './request'

export default class Main extends Component {
   init() {
      request.send();
  }
}

In the above example, I'm calling the send function from main.js. All this is working fine but I have a condition in the send function that will recall the same function. The problem is that I have no idea how to call the function from within the function. Anybody?

Body:
I don't see any reason why this.send() wouldn't work, given you are exporting an object with a method.

But if it doesn't work, you can always use a named function expression:

export default {
  send: function send() {
    … send() …
  }
};

or a named function declaration:

function send() {
  … send() …
}
export default { send };

or just name your exported object:

export default const request = {
  send() {
    … request.send() …
  }
};

But I would recommend to not default-export an object at all, and use named exports instead so that you can import them separately or on a namespace object:

// request.js
export default function send() {
  … send() …
}

// main.js
import * as request from './request'
…
request.send()


问:
Save highscore in swift
I gave this code, and I want to add highscore to this project. I wa trying to do this on my own but can't get this to working. Can somebody help me with achieve that ?

I was trying to manipulate with timeInterval but with no luck, this is my learning project from GitHub, I Was trying to ask author to help me but he didn't answer.

```<code>    fileprivate extension ViewController {
  func setupPlayerView() {
    playerView.bounds.size = CGSize(width: radius * 2, height: radius * 2)
    playerView.layer.cornerRadius = radius
    playerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

    view.addSubview(playerView)
  }

  func startEnemyTimer() {
    enemyTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generateEnemy(timer:)), userInfo: nil, repeats: true)
  }

  func stopEnemyTimer() {
    guard let enemyTimer = enemyTimer,
      enemyTimer.isValid else {
        return
    }
    enemyTimer.invalidate()
  }

  func startDisplayLink() {
    displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
    displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
  }

  func stopDisplayLink() {
    displayLink?.isPaused = true
    displayLink?.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
    displayLink = nil
  }

  func getRandomColor() -> UIColor {
    let index = arc4random_uniform(UInt32(colors.count))
    return colors[Int(index)]
  }

  func getEnemyDuration(enemyView: UIView) -> TimeInterval {
    let dx = playerView.center.x - enemyView.center.x
    let dy = playerView.center.y - enemyView.center.y
    return TimeInterval(sqrt(dx * dx + dy * dy) / enemySpeed)
  }

  func gameOver() {
    stopGame()
    displayGameOverAlert()
  }

  func stopGame() {
    stopEnemyTimer()
    stopDisplayLink()
    stopAnimators()
    gameState = .gameOver

  }

  func prepareGame() {
    removeEnemies()
    centerPlayerView()
    popPlayerView()
    startLabel.isHidden = false
    clockLabel.text = "00:00.000"
    gameState = .ready
  }

  func startGame() {
    startEnemyTimer()
    startDisplayLink()
    startLabel.isHidden = true
    beginTimestamp = 0
    gameState = .playing
  }

  func removeEnemies() {
    enemyViews.forEach {
      $0.removeFromSuperview()
    }
    enemyViews = []
  }

  func stopAnimators() {
    playerAnimator?.stopAnimation(true)
    playerAnimator = nil
    enemyAnimators.forEach {
      $0.stopAnimation(true)
    }
    enemyAnimators = []
  }

  func updateCountUpTimer(timestamp: TimeInterval) {
    if beginTimestamp == 0 {
      beginTimestamp = timestamp
    }
    elapsedTime = timestamp - beginTimestamp
    clockLabel.text = format(timeInterval: elapsedTime)
  }

    func highscore(timestamp: TimeInterval) {
        if beginTimestamp == 0 {
            beginTimestamp = timestamp
        }
        elapsedTime = timestamp - beginTimestamp
        highscoreLabel.text = format(timeInterval: elapsedTime)
    }

  func format(timeInterval: TimeInterval) -> String {
    let interval = Int(timeInterval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let milliseconds = Int(timeInterval * 1000) % 1000
    return String(format: "%02d:%02d.%03d", minutes, seconds, milliseconds)
  }

  func checkCollision() {
    enemyViews.forEach {
      guard let playerFrame = playerView.layer.presentation()?.frame,
        let enemyFrame = $0.layer.presentation()?.frame,
        playerFrame.intersects(enemyFrame) else {
          return
      }
      gameOver()
    }
  }

  func movePlayer(to touchLocation: CGPoint) {
    playerAnimator = UIViewPropertyAnimator(duration: playerAnimationDuration,
                                            dampingRatio: 0.5,
                                            animations: { [weak self] in
                                              self?.playerView.center = touchLocation
                                            })
    playerAnimator?.startAnimation()
  }

  func moveEnemies(to touchLocation: CGPoint) {
    for (index, enemyView) in enemyViews.enumerated() {
      let duration = getEnemyDuration(enemyView: enemyView)
      enemyAnimators[index] = UIViewPropertyAnimator(duration: duration,
                                                     curve: .linear,
                                                     animations: {
                                                       enemyView.center = touchLocation
                                                    })
      enemyAnimators[index].startAnimation()
    }
  }

  func displayGameOverAlert() {
    let (title, message) = getGameOverTitleAndMessage()
    let alert = UIAlertController(title: "Game Over", message: message, preferredStyle: .alert)
    let action = UIAlertAction(title: title, style: .default,
                               handler: { _ in
                                self.prepareGame()
      }
    )
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)
  }

  func getGameOverTitleAndMessage() -> (String, String) {
    let elapsedSeconds = Int(elapsedTime) % 60
    switch elapsedSeconds {
    case 0..<10: return ("I try again", "You need more practice")
    case 10..<30: return ("Maybe Another try?", "No bad, just play more")
    case 30..<60: return ("Play again", "You are like Ninja")
    default:
      return ("WOW", "You are simply the best")
    }

  }
</code>```

right know I managed to have state of score but I can't to save high score whats wrong with that

```<code>    func updateBest(){

    var defaults=UserDefaults()
    var highscore=defaults.integer(forKey: "highscore")

    if(Int(elapsedTime)) > highscore
    {
        defaults.set(Int(self.elapsedTime), forKey: "highscore")
    }
    var highscoreshow=defaults.integer(forKey: "highscore")

    highscoreLabel.text = "\(highscoreshow)"
    print("hhScore reported: \(highscoreLabel.text)")
  //  clockLabel.text = "\(elapsedTime)"
  //  print("play reported: \(clockLabel.text)")

}
</code>```

答:
For saving highscore to userdefaults :

```<code>let highscore : String = "\(Int(self.elapsedTime))"
UserDefaults.standard.set(highscore, forKey: "highscore")
</code>```

For retrieving highscore from userdefaults :

```<code>highscoreLabel.text = (UserDefaults.standard.value(forKey: "highscore") as? String)
</code>```

I hope it helps. Cheers. :]

Title: Save highscore in swift

Body:
I gave this code, and I want to add highscore to this project. I wa trying to do this on my own but can't get this to working. Can somebody help me with achieve that ?

I was trying to manipulate with timeInterval but with no luck, this is my learning project from GitHub, I Was trying to ask author to help me but he didn't answer.

    fileprivate extension ViewController {
  func setupPlayerView() {
    playerView.bounds.size = CGSize(width: radius * 2, height: radius * 2)
    playerView.layer.cornerRadius = radius
    playerView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)

    view.addSubview(playerView)
  }

  func startEnemyTimer() {
    enemyTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(generateEnemy(timer:)), userInfo: nil, repeats: true)
  }

  func stopEnemyTimer() {
    guard let enemyTimer = enemyTimer,
      enemyTimer.isValid else {
        return
    }
    enemyTimer.invalidate()
  }

  func startDisplayLink() {
    displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
    displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
  }

  func stopDisplayLink() {
    displayLink?.isPaused = true
    displayLink?.remove(from: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
    displayLink = nil
  }

  func getRandomColor() -> UIColor {
    let index = arc4random_uniform(UInt32(colors.count))
    return colors[Int(index)]
  }

  func getEnemyDuration(enemyView: UIView) -> TimeInterval {
    let dx = playerView.center.x - enemyView.center.x
    let dy = playerView.center.y - enemyView.center.y
    return TimeInterval(sqrt(dx * dx + dy * dy) / enemySpeed)
  }

  func gameOver() {
    stopGame()
    displayGameOverAlert()
  }

  func stopGame() {
    stopEnemyTimer()
    stopDisplayLink()
    stopAnimators()
    gameState = .gameOver

  }

  func prepareGame() {
    removeEnemies()
    centerPlayerView()
    popPlayerView()
    startLabel.isHidden = false
    clockLabel.text = "00:00.000"
    gameState = .ready
  }

  func startGame() {
    startEnemyTimer()
    startDisplayLink()
    startLabel.isHidden = true
    beginTimestamp = 0
    gameState = .playing
  }

  func removeEnemies() {
    enemyViews.forEach {
      $0.removeFromSuperview()
    }
    enemyViews = []
  }

  func stopAnimators() {
    playerAnimator?.stopAnimation(true)
    playerAnimator = nil
    enemyAnimators.forEach {
      $0.stopAnimation(true)
    }
    enemyAnimators = []
  }

  func updateCountUpTimer(timestamp: TimeInterval) {
    if beginTimestamp == 0 {
      beginTimestamp = timestamp
    }
    elapsedTime = timestamp - beginTimestamp
    clockLabel.text = format(timeInterval: elapsedTime)
  }

    func highscore(timestamp: TimeInterval) {
        if beginTimestamp == 0 {
            beginTimestamp = timestamp
        }
        elapsedTime = timestamp - beginTimestamp
        highscoreLabel.text = format(timeInterval: elapsedTime)
    }

  func format(timeInterval: TimeInterval) -> String {
    let interval = Int(timeInterval)
    let seconds = interval % 60
    let minutes = (interval / 60) % 60
    let milliseconds = Int(timeInterval * 1000) % 1000
    return String(format: "%02d:%02d.%03d", minutes, seconds, milliseconds)
  }

  func checkCollision() {
    enemyViews.forEach {
      guard let playerFrame = playerView.layer.presentation()?.frame,
        let enemyFrame = $0.layer.presentation()?.frame,
        playerFrame.intersects(enemyFrame) else {
          return
      }
      gameOver()
    }
  }

  func movePlayer(to touchLocation: CGPoint) {
    playerAnimator = UIViewPropertyAnimator(duration: playerAnimationDuration,
                                            dampingRatio: 0.5,
                                            animations: { [weak self] in
                                              self?.playerView.center = touchLocation
                                            })
    playerAnimator?.startAnimation()
  }

  func moveEnemies(to touchLocation: CGPoint) {
    for (index, enemyView) in enemyViews.enumerated() {
      let duration = getEnemyDuration(enemyView: enemyView)
      enemyAnimators[index] = UIViewPropertyAnimator(duration: duration,
                                                     curve: .linear,
                                                     animations: {
                                                       enemyView.center = touchLocation
                                                    })
      enemyAnimators[index].startAnimation()
    }
  }

  func displayGameOverAlert() {
    let (title, message) = getGameOverTitleAndMessage()
    let alert = UIAlertController(title: "Game Over", message: message, preferredStyle: .alert)
    let action = UIAlertAction(title: title, style: .default,
                               handler: { _ in
                                self.prepareGame()
      }
    )
    alert.addAction(action)
    self.present(alert, animated: true, completion: nil)
  }

  func getGameOverTitleAndMessage() -> (String, String) {
    let elapsedSeconds = Int(elapsedTime) % 60
    switch elapsedSeconds {
    case 0..<10: return ("I try again", "You need more practice")
    case 10..<30: return ("Maybe Another try?", "No bad, just play more")
    case 30..<60: return ("Play again", "You are like Ninja")
    default:
      return ("WOW", "You are simply the best")
    }

  }

right know I managed to have state of score but I can't to save high score whats wrong with that

    func updateBest(){

    var defaults=UserDefaults()
    var highscore=defaults.integer(forKey: "highscore")

    if(Int(elapsedTime)) > highscore
    {
        defaults.set(Int(self.elapsedTime), forKey: "highscore")
    }
    var highscoreshow=defaults.integer(forKey: "highscore")

    highscoreLabel.text = "\(highscoreshow)"
    print("hhScore reported: \(highscoreLabel.text)")
  //  clockLabel.text = "\(elapsedTime)"
  //  print("play reported: \(clockLabel.text)")

}

Body:
For saving highscore to userdefaults :

let highscore : String = "\(Int(self.elapsedTime))"
UserDefaults.standard.set(highscore, forKey: "highscore")

For retrieving highscore from userdefaults :

highscoreLabel.text = (UserDefaults.standard.value(forKey: "highscore") as? String)

I hope it helps. Cheers. :]


问:
Can't save hashed password to database using bcrypt and bookshelf
Still quite new to nodejs, so I frequently get tripped up by the whole asynchronous thing. I am attempting to hash a password before storing it in the database, using bcrypt and bookshelf. Pretty straight forward right...

I am calling the save action like so,

```<code>create(data) {
    this.logger.info(`creating account`);
    return bookshelf.transaction(trx => {
        return new Account().save(data, { method: 'insert', transacting: trx });
    });
}
</code>```

and in the account model, I intercept the save action

```<code>initialize: function() {
    let _this = this;
    const saltRounds = 10;
    _this.on('creating', function () {
        bcrypt.genSaltSync(saltRounds, function(err, salt) {
            bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
                if (err) throw err;

                _this.set('password', hash);
            });
        });
    });
}
</code>```

Everything i've looked up so far says this should work, but the plain text password is still getting saved into the database instead of the hashed password. What am I doing wrong?

答:
You're using synchronous functions, but passing them callbacks, which won't get called (and therefore, the password won't be replaced).

Try this:

```<code>initialize: function() {
  const saltRounds = 10;
  this.on('creating', () => {
    let salt = bcrypt.genSaltSync(saltRounds);
    let hash = bcrypt.hashSync(this.get('password'), salt);
    this.set('password', hash);
  });
}
</code>```

Or replacing the synchronous functions with async ones, using promises (which are supported by both bcrypt and bookshelf):

```<code>initialize: function() {
  const saltRounds = 10;
  this.on('creating', () => {
    return bcrypt.genSalt(saltRounds).then(salt => {
      return bcrypt.hash(this.get('password'), salt);
    }).then(hash => {
      this.set('password', hash);
    });
  });
}
</code>```

Body:
Still quite new to nodejs, so I frequently get tripped up by the whole asynchronous thing. I am attempting to hash a password before storing it in the database, using bcrypt and bookshelf. Pretty straight forward right...

I am calling the save action like so,

create(data) {
    this.logger.info(`creating account`);
    return bookshelf.transaction(trx => {
        return new Account().save(data, { method: 'insert', transacting: trx });
    });
}

and in the account model, I intercept the save action

initialize: function() {
    let _this = this;
    const saltRounds = 10;
    _this.on('creating', function () {
        bcrypt.genSaltSync(saltRounds, function(err, salt) {
            bcrypt.hashSync(_this.get('password'), salt, function (err, hash) {
                if (err) throw err;

                _this.set('password', hash);
            });
        });
    });
}

Everything i've looked up so far says this should work, but the plain text password is still getting saved into the database instead of the hashed password. What am I doing wrong?

Body:
You're using synchronous functions, but passing them callbacks, which won't get called (and therefore, the password won't be replaced).

Try this:

initialize: function() {
  const saltRounds = 10;
  this.on('creating', () => {
    let salt = bcrypt.genSaltSync(saltRounds);
    let hash = bcrypt.hashSync(this.get('password'), salt);
    this.set('password', hash);
  });
}

Or replacing the synchronous functions with async ones, using promises (which are supported by both bcrypt and bookshelf):

initialize: function() {
  const saltRounds = 10;
  this.on('creating', () => {
    return bcrypt.genSalt(saltRounds).then(salt => {
      return bcrypt.hash(this.get('password'), salt);
    }).then(hash => {
      this.set('password', hash);
    });
  });
}


问:
Anagram with JavaScript
```<code>const myAnagram = (arr1, arr2) => {
  let str1 = arr1;
  let str2 = arr2;
  let temp1 = [];
  let temp2 = [];
  let flag = 0;

  if (str1.length !== str2.length) return "Not Anagram statement A";

  for (var i = 0; i < str1.length - 1; i++) {
    temp1[i] = str1[i];
  }

  for (var j = 0; j < str2.length - 1; j++) {
    temp2[i] = str2[i];
  }

  temp1.sort();
  temp2.sort();

  for (var k = 0; k < str1.length - 1; k++) {
    if (temp1[j] !== temp2[j]) return "Not Anagram statement C";
    return "Anagram! statement D";
  }
}
</code>```

答:
Your loops always skip the last elements since you use < together with str1.length - 1. You should either use
for (var i = 0; i < str1.length; ++i) {...} or
for (var i = 0; i <= str.length-1; ++i) {...}

Furthermore in your comparison loop you already return when the first characters match (or when they don't). Therefore the loop will never compare the second (or nth) characters. The loop should further compare the characters until you are sure the arrays differ at some point.

You can shrink the function like

```<code>function isAnagram(str1, str2) {
    if (str1.length !== str2.length) return false

    var arr1 = arr2 = []
    for (var i = 0; i < str1.length; ++i) {
        arr1[i] = str1[i]
        arr2[i] = str2[i]
    }

    arr1.sort()
    arr2.sort()

    for (var i = 0; i < arr1.length; ++i)
        if (arr1[i] !== arr2[i]) return false
    return true
}
</code>```

And then

```<code>if (isAnagram("frog","rg0f")) {
    console.log("Anagram!")
} else {
    console.log("Not Anagram.")
}
</code>```

Title: Anagram with JavaScript

Body:
Your loops always skip the last elements since you use < together with str1.length - 1. You should either use
for (var i = 0; i < str1.length; ++i) {...} or
for (var i = 0; i <= str.length-1; ++i) {...}

Furthermore in your comparison loop you already return when the first characters match (or when they don't). Therefore the loop will never compare the second (or nth) characters. The loop should further compare the characters until you are sure the arrays differ at some point.

You can shrink the function like

function isAnagram(str1, str2) {
    if (str1.length !== str2.length) return false

    var arr1 = arr2 = []
    for (var i = 0; i < str1.length; ++i) {
        arr1[i] = str1[i]
        arr2[i] = str2[i]
    }

    arr1.sort()
    arr2.sort()

    for (var i = 0; i < arr1.length; ++i)
        if (arr1[i] !== arr2[i]) return false
    return true
}

And then

if (isAnagram("frog","rg0f")) {
    console.log("Anagram!")
} else {
    console.log("Not Anagram.")
}


问:
Laravel only retrieve Model Records if they belong to authenticated user
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

```<code>/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}
</code>```

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

```<code>/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}
</code>```

And I've registered it in the AuthServiceProvider.php:

```<code>protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];
</code>```

I can still check the Order for another user.

答:
Another way would be to use the defined relationship and tell it to only retrieve the one with id $id. Like this:

```<code>$customerOrder = auth()->user()->orders()->with('products')->find($id);
</code>```

Body:
I'm using Laravel 5.4 and have a Model called Order.
To test things I've created two users and two Orders, each user having one Order.

I've just seen that I'm able to retrieve the order of someone who is not my current user. I'm retrieving a list of user's own orders using Auth::user()->orders. But in order to show the details of a specific order I do this:

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    $order = CustomerOrder::findOrFail($id)->with('products')->get();
    return view('order.show')
        ->with('order', $order);
}

What am I missing out here? Is there a middleware or something to tell the application to only allow access to orders associated with the authenticated user?

Edit: So I've tried to do it using a Policy OrderPolicy (CRUD).

The view() fucntion of the Policy:

/**
 * Determine whether the user can view the customerOrder.
 *
 * @param  \App\User  $user
 * @param  \App\CustomerOrder  $customerOrder
 * @return mixed
 */
public function view(User $user, CustomerOrder $customerOrder)
{
    return $user->id === $customerOrder->user_id;
}

And I've registered it in the AuthServiceProvider.php:

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    Adress::class => AdressPolicy::class, //Doesn't work either
    Order::class => OrderPolicy::class
];

I can still check the Order for another user.

Body:
Another way would be to use the defined relationship and tell it to only retrieve the one with id $id. Like this:

$customerOrder = auth()->user()->orders()->with('products')->find($id);


问:
Installed, just not linked
Note: I'm not so good at using shell.

I was trying to install Valgrind using brew on Yosemite.

brew install --HEAD valgrind

Towards the end, I got an error having to do with linking so when I tried to reinstall, I got:

Warning: valgrind-HEAD already installed, it's just not linked

So apparently I've already installed it. Then based on other SO questions and answers, I tried:

brew link valgrind

This seemed to solve other people's problems with linking an already installed software but this gave me an error:

```<code>Linking /usr/local/Cellar/valgrind/HEAD...
Error: Could not symlink lib/pkgconfig/valgrind.pc
/usr/local/lib/pkgconfig is not writable.
</code>```

I also tried to update brew but it didn't solve the issue. If it is not writable, maybe sudo would give me permission but I don't want to use sudo without knowing exactly what I am doing.

What is happening and how to I fix it?

答:
I got a similar problem,

$ brew install sqlite
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
No changes to formulae.

Warning: sqlite-3.17.0 already installed, it's just not linked.

I tried to link it,

$ brew link sqlite
Warning: sqlite is keg-only and must be linked with --force
Note that doing so can interfere with building software.

Then do it by force,

$ brew link --force sqlite
Linking /usr/local/Cellar/sqlite/3.17.0... 8 symlinks created

Title: Installed, just not linked

Body:
Note: I'm not so good at using shell.

I was trying to install Valgrind using brew on Yosemite.

brew install --HEAD valgrind

Towards the end, I got an error having to do with linking so when I tried to reinstall, I got:

Warning: valgrind-HEAD already installed, it's just not linked

So apparently I've already installed it. Then based on other SO questions and answers, I tried:

brew link valgrind

This seemed to solve other people's problems with linking an already installed software but this gave me an error:

Linking /usr/local/Cellar/valgrind/HEAD...
Error: Could not symlink lib/pkgconfig/valgrind.pc
/usr/local/lib/pkgconfig is not writable.

I also tried to update brew but it didn't solve the issue. If it is not writable, maybe sudo would give me permission but I don't want to use sudo without knowing exactly what I am doing.

What is happening and how to I fix it?


问:
Autofill an HTML form
What applications exist that can take a series of fields from my db (or csv output from my db) and insert them into a web-based form and then submit that form?

Big Picture Use Case:

I maintain an in-house registration management system for webinars that we produce/present. Currently we use GoToWebinar.com to host our events but they haven't always been (and may not always continue to be) our vendor.

GoToWebinars.com does not provide me an API for creating registrations for 3rd party individuals. So when someone decides to attend one of our events they have to fill out 2 registrations forms, mine and GoToWebinars.com. I'd like to automate the task of filling in GoToWebinar's registration form.

答:
I am looking into the same thing. I found some bits and pieces here and there and was able to decipher the URL to post to GTW:

https://www.gotowebinar.com/en_US/island/webinar/registration.flow?Template=island/webinar/registration.tmpl&Form=webinarRegistrationForm&WebinarKey=XXX_YOUR_WEBINAR_ID_XXX&Name_First=ViewersFirstName&Name_Last=ViewersLastName&Email=ViewersEmailAddress

If you are using cURL, then be sure to use CURLOPT_FOLLOWLOCATION because there are some redirections on the GTW side and cURL needs to follow them.

So far this seems to work for us.

Good luck!

ContentLicense: CC BY-SA 2.5

Title: Autofill an HTML form


问:
Iron form with polymer 2.0
I'm having a bug, I replicate the bug in jsbin: https://jsbin.com/micinalacu/1/edit?html,console,output

The iron form, when submit the serialize method return always undefined, and it's called two times.

```<code> <dom-module id="my-form">
  <template>

    <iron-form id="myForm">
      <form method="get" action="cenfdsas">
        <input type="text" name="cenas">
        <button on-click="cenas">Submit</button>
      </form>
    </iron-form>

  </template>

  <script>
   class MyForm extends Polymer.Element {

      static get is() {
        return 'my-form';
      }

      connectedCallback() {
        super.connectedCallback();
        const form = this.$.myForm;
        form.addEventListener('iron-form-presubmit', function (event) {
          event.preventDefault();
          console.log("here")
          console.log(form.serialize());
        });
      }

      cenas() {
        this.$.myForm.submit();
      }

    }

    window.customElements.define(MyForm.is, MyForm);

  </script>
</dom-module>
</code>```

Update

Polymer team needed to change the name of the method to serializeForm, because they had a bug. Source: https://github.com/PolymerElements/iron-form/issues/174

But I continue with the issue that the submit event It's called two times
Bug --> https://jsbin.com/koyelafeze/1/edit?html,console,output

答:
According to the documentation, the use of a standard <button> element in the form will submit it automatically.

You should then use a <paper-button> as suggested in the link, or comment the content of your cenas() method.

JS Bin example

Title: Iron form with polymer 2.0

Body:
I'm having a bug, I replicate the bug in jsbin: https://jsbin.com/micinalacu/1/edit?html,console,output

The iron form, when submit the serialize method return always undefined, and it's called two times.

 <dom-module id="my-form">
  <template>

    <iron-form id="myForm">
      <form method="get" action="cenfdsas">
        <input type="text" name="cenas">
        <button on-click="cenas">Submit</button>
      </form>
    </iron-form>

  </template>

</dom-module>

Update

Polymer team needed to change the name of the method to serializeForm, because they had a bug. Source: https://github.com/PolymerElements/iron-form/issues/174

But I continue with the issue that the submit event It's called two times
Bug --> https://jsbin.com/koyelafeze/1/edit?html,console,output


问:
Most efficient way to get the highest number from a collection of integers
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

```<code>int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }
</code>```

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?

答:
If the Collection is already sorted, you can find the largest element in O(1) (assuming the Collection supports random access or O(1) access to the end of the Collection holding the largest element - if the largest element is first, any Collections would give you an O(1) access to it via its Iterator). In that case you don't have to sort it, though.

Any sorting would take at least O(n) when the input is sorted (and at least O(nlog(n)) when it's not), since you can't verify that the input is sorted without going over all the elements. Therefore sorting algorithms cannot beat your O(n) solution.

Body:
Question:Most efficient way to get the highest number from a collection of integers

I was recently discussing this question, I had 2 solutions in mind.
1) Iterating over the collection and find the highest number (code below)
2) Use a sorting algorithm.

The first method will have O(n) efficiency

int getHighestNumber(ArrayList<Integer> list)
    {
        if(list != null && list.size() > 0)
        {
            if(list.size() == 1)
                return list.get(0);

            int maxNum = list.get(0);
            for(int item:list)
            {
                if(item > maxNum)
                    maxNum = item;
            }
            return maxNum;
        }
        return null;
    }

My question is "Can any sorting algorithm beat it (on time scale) on any given input for eg. if the collection is already sorted or not?"
Is there any other way better than this ?


问:
Protractor 2.28 - headless Chrome 57 - linux - tests failed
I am trying to run protractor tests with jenkins, but I couldn't get it working.
The tests are started but all fails with one of the following exceptions:

from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
      (Session info: content shell=)
      (Driver info: chromedriver=2.28.455506 (18f6627e265f442aeec9b6661a49fe819aeeea1f),platform=Linux 4.4.0-22-generic x86_64)

or

Failed: Error while waiting for Protractor to sync with the page: "window.angular is undefined.  This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping.  See http://git.io/v4gXM for details"

The mentioned git issue doesn't help me.
All of them are running well local on a windows 10 machine.

The used versions local and on with jenkins are:

protractor: 5.1.1

chrome: 57.*

chromedriver: 2.28

I have found some issues that chrome should be downgraded to version 55.* but the all didn't solve my problem.

Thank you in advance

答:
It says window.angular is undefined.
I assume it is not an angular site.
Have you tried entering
Browser.ignoreSynchronization = true
Before you get the browser. </p>


问:
C# 7 tuples and lambdas
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

```<code>var list = new List<(int,int)>();
</code>```

normal way to use a tuple in lambda:

```<code>list.Select(value => value.Item1*2 + value.Item2/2);
</code>```

i expected some new sugar to avoid .Item1 .Item2, like:

```<code>list.Select((x,y) => x*2 + y/2);
</code>```

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

```<code>list.Add((1,2));
</code>```

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

```<code>void Foo((int,int)(x,y)) { x+y; }
</code>```

Instead of this:

```<code>void Foo((int x,int y) value) { value.x+value.y }
</code>```

答:
As you have observed, for:

```<code>var list = new List<(int,int)>();
</code>```

One would at least expect to be able to do the following:

```<code>list.Select((x,y) => x*2 + y/2);
</code>```

But the C# 7 compiler doesn't (yet) support this. It is also reasonable to desire sugar that would allow the following:

```<code>void Foo(int x, int y) => ...

Foo(list[0]);
</code>```

with the compiler converting Foo(list[0]); to Foo(list[0].Item1, list[0].Item2); automatically.

Neither of these is currently possible. However, the issue, Proposal: Tuple deconstruction in lambda argument list, exists on the dotnet/csharplang repo on GitHub, requesting that the language team consider these features for a future version of C#. Please do add your voices to that thread if you too would like to see support for this.

Title: C# 7 tuples and lambdas

Body:
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

var list = new List<(int,int)>();

normal way to use a tuple in lambda:

list.Select(value => value.Item1*2 + value.Item2/2);

i expected some new sugar to avoid .Item1 .Item2, like:

list.Select((x,y) => x*2 + y/2);

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

list.Add((1,2));

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

void Foo((int,int)(x,y)) { x+y; }

Instead of this:

void Foo((int x,int y) value) { value.x+value.y }

Body:
As you have observed, for:

var list = new List<(int,int)>();

One would at least expect to be able to do the following:

list.Select((x,y) => x*2 + y/2);

But the C# 7 compiler doesn't (yet) support this. It is also reasonable to desire sugar that would allow the following:

void Foo(int x, int y) => ...

Foo(list[0]);

with the compiler converting Foo(list[0]); to Foo(list[0].Item1, list[0].Item2); automatically.

Neither of these is currently possible. However, the issue, Proposal: Tuple deconstruction in lambda argument list, exists on the dotnet/csharplang repo on GitHub, requesting that the language team consider these features for a future version of C#. Please do add your voices to that thread if you too would like to see support for this.


问:
Can't find named elements
Something is not clicking for me with this code:

```<code>var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}
</code>```

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>
```

<p><strong>2nd try</strong></p>

```var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}
```

答:
Are you sure you're loading the file/xml? Check your _cfgFile value. Your 2nd try works for me:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace XElementMadness
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = "<session-factory xmlns=\"urn:nhibernate-configuration-2.2\"><property name=\"connection.release_mode\">on_close</property><property name=\"show_sql\">true</property></session-factory>";

            var cfgDoc = XElement.Load(new StringReader(xml));
            XNamespace ns = "urn:nhibernate-configuration-2.2";
            var properties = cfgDoc.Elements(ns + "property");

            foreach (var x in cfgDoc.Elements(ns + "property"))
            {
                Console.WriteLine(x);
            }

            Console.ReadLine();
        }
    }
}
</code>```

which outputs:

```<code><property name="connection.release_mode" xmlns="urn:nhibernate-configuration-2.2 ">on_close</property> <property name="show_sql" xmlns="urn:nhibernate-configuration-2.2">true</property>
</code>```

Title: Can't find named elements

Body:
Something is not clicking for me with this code:

var cfgDoc = XElement.Load(_cfgFile);
foreach (var x in cfgDoc.Elements("property"))
{
    Console.WriteLine(x);
}

I am expecting to be able to output only nodes that are named property, but getting zilch. If I leave the XName parameter out, I get the document (below), which shows at least it is being loaded correctly.

What am I missing?

<session-factory xmlns="urn:nhibernate-configuration-2.2">
    <property name="connection.release_mode">on_close</property>
    <property name="show_sql">true</property>
</session-factory>

2nd try

var cfgDoc = XElement.Load(_cfgFile);
XNamespace ns = "urn:nhibernate-configuration-2.2";
var properties = cfgDoc.Elements(ns + "property");
Assert.That(properties.Count() > 0);
foreach (var x in cfgDoc.Elements(ns + "property"))
{
    Console.WriteLine(x);
}

Body:
Are you sure you're loading the file/xml? Check your _cfgFile value. Your 2nd try works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.IO;

namespace XElementMadness
{
    class Program
    {
        static void Main(string[] args)
        {
            var xml = "<session-factory xmlns=\"urn:nhibernate-configuration-2.2\"><property name=\"connection.release_mode\">on_close</property><property name=\"show_sql\">true</property></session-factory>";

            var cfgDoc = XElement.Load(new StringReader(xml));
            XNamespace ns = "urn:nhibernate-configuration-2.2";
            var properties = cfgDoc.Elements(ns + "property");

            foreach (var x in cfgDoc.Elements(ns + "property"))
            {
                Console.WriteLine(x);
            }

            Console.ReadLine();
        }
    }
}

which outputs:

<property name="connection.release_mode" xmlns="urn:nhibernate-configuration-2.2 ">on_close</property> <property name="show_sql" xmlns="urn:nhibernate-configuration-2.2">true</property>


问:
Remove duplicate values from JS array
I have a very simple JavaScript array that may or may not contain duplicates.

```<code>var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
</code>```

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

答:
A simple but effective technique, is to use the filter method in combination with the filter function(value, index){ return this.indexOf(value) == index }.

Code example :

var data = [2,3,4,5,5,4];
var filter = function(value, index){ return this.indexOf(value) == index };
var filteredData = data.filter(filter, data );

document.body.innerHTML = '```' + JSON.stringify(filteredData, null, '\t') +  '```';```

See also this Fiddle.

Title: Remove duplicate values from JS array

Body:
I have a very simple JavaScript array that may or may not contain duplicates.

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

I need to remove the duplicates and put the unique values in a new array.

I could point to all the code that I've tried but I think it's useless because they don't work. I accept jQuery solutions too.

Similar question:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Body:
A simple but effective technique, is to use the filter method in combination with the filter function(value, index){ return this.indexOf(value) == index }.

Code example :

var data = [2,3,4,5,5,4];
var filter = function(value, index){ return this.indexOf(value) == index };
var filteredData = data.filter(filter, data );

document.body.innerHTML = '<pre>' + JSON.stringify(filteredData, null, '\t') +  '</pre>';

See also this Fiddle.


问:
My Android device does not appear in the list of adb devices
I have a HP Slate 21 that is connected to my Windows box using a USB cable.

USB debugging is enabled on the device.

After adding the proper %SingleAdbInterface% and %CompositeAdbInterface% entries to the android_winusb.inf file, I now see "Android ADB Interface" in my Device Manager.
However, running adb devices at the command-line does not show the device.

I have another HP slate 7 that shows up just fine under adb devices.

The only difference I see from Device Manager is that the one that works is named "Android Composite ADB Interface" and the other one is named "Android ADB Interface."

There is yet another subtle difference. In the winusb.inf file, for Slate 7 I have two %CompositeAdbInterface% entries defined but for Slate 21, there is just one %CompositeAdbInterface% entry defined.

How can I see my device by running the command adb devices?

答:
Remove battery from phone, wait 10s, re-add it and try it again (alongside developer options etc.. in other questions)

I tried all other answers, but that was required in addition to the other suggestions for me.


问:
Friend funcitons of template classes
I want to return a nested class object using a friend function

```<code>template <typename T>
class X{
public:
    class Y{
    public:
        int y;
    }test;
public:
    X(){
        test.y=10;
    }

    template <typename U>
    friend Y fun(X<U>);
};

template <typename T>
X<T>::Y fun(X<T> x){
    return x.test;
}
</code>```

But I get an error saying

need 'typename' before 'X::Y' because 'X' is a dependent scope

What is wrong?

答:
You have to write

```<code>template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}
</code>```

becouse compliler can't resolve if Y is filed or type.

Title: Friend funcitons of template classes

Body:
I want to return a nested class object using a friend function

template <typename T>
class X{
public:
    class Y{
    public:
        int y;
    }test;
public:
    X(){
        test.y=10;
    }

    template <typename U>
    friend Y fun(X);
};

template <typename T>
X<T>::Y fun(X<T> x){
    return x.test;
}

But I get an error saying

need 'typename' before 'X::Y' because 'X' is a dependent scope

What is wrong?

Body:
You have to write

template <typename T>
typename X<T>::Y fun(X<T> x){
    return x.test;
}

becouse compliler can't resolve if Y is filed or type.


问:
Prevent window on scroll function occurring on mobile
I have a function that runs on window scroll, I only want it to work however on screensizes of 768 and above. This is working fine if i loaded it on mobile size, but if the initial page load is on a widescreen of 768px + and then i shrink the viewport down it doesn't prevent the function?

```<code>(function($) {

    var s,
    clippy = {
    settings: {
      heading: $('.js-clippy'),
    },
    init: function() {
      s = this.settings;
      this.bindEvents();
    },
    bindEvents: function(){
        if ($(window).width() > 768) {
            $(window).on("load resize scroll", $.proxy(this.getClippy, this));
        }
    },

    getClippy: function(){
      s.heading.each(function() {
        var layerOffset = $(this).closest('a').offset(),
          containerOffset = layerOffset.top - $(window).scrollTop(),
          clippy = containerOffset - $(this).css("top").replace(/[^-\d\.]/g, '') - $(this).css("margin-top").replace(/[^-\d\.]/g, '');
        $(this).css('clip', 'rect('+ clippy +'px, auto, auto, auto)');
      });
    },
    };
    clippy.init();

  })(jQuery);
</code>```

I've tried adding a conditional statement to my binded event with no luck...

```<code>bindEvents: function(){
        if ($(window).width() > 768) {
            $(window).on("load resize scroll", $.proxy(this.getClippy, this));
        }
});
</code>```

to the event only it doesn't seem to work?

答:
You should consider checking the width inside the getClippy function. That will work if you load the page with a large viewport and shrink it and vice versa.

```<code>    (function($) {

    var s,
    clippy = {
    settings: {
      heading: $('.js-clippy'),
    },
    init: function() {
      s = this.settings;
      this.bindEvents();
    },
    bindEvents: function(){
        $(window).on("load resize scroll", $.proxy(this.getClippy, this));
    },

    getClippy: function(){
        if ($(window).width() > 768) {
            s.heading.each(function() {
                var layerOffset = $(this).closest('a').offset(),
                containerOffset = layerOffset.top - $(window).scrollTop(),
                clippy = containerOffset - $(this).css("top").replace(/[^-\d\.]/g, '') - $(this).css("margin-top").replace(/[^-\d\.]/g, '');
                $(this).css('clip', 'rect('+ clippy +'px, auto, auto, auto)');
            });
        }
    },
    };
    clippy.init();

  })(jQuery);
</code>```

Body:
I have a function that runs on window scroll, I only want it to work however on screensizes of 768 and above. This is working fine if i loaded it on mobile size, but if the initial page load is on a widescreen of 768px + and then i shrink the viewport down it doesn't prevent the function?

(function($) {

    var s,
    clippy = {
    settings: {
      heading: $('.js-clippy'),
    },
    init: function() {
      s = this.settings;
      this.bindEvents();
    },
    bindEvents: function(){
        if ($(window).width() > 768) {
            $(window).on("load resize scroll", $.proxy(this.getClippy, this));
        }
    },

    getClippy: function(){
      s.heading.each(function() {
        var layerOffset = $(this).closest('a').offset(),
          containerOffset = layerOffset.top - $(window).scrollTop(),
          clippy = containerOffset - $(this).css("top").replace(/[^-\d\.]/g, '') - $(this).css("margin-top").replace(/[^-\d\.]/g, '');
        $(this).css('clip', 'rect('+ clippy +'px, auto, auto, auto)');
      });
    },
    };
    clippy.init();

  })(jQuery);

I've tried adding a conditional statement to my binded event with no luck...

bindEvents: function(){
        if ($(window).width() > 768) {
            $(window).on("load resize scroll", $.proxy(this.getClippy, this));
        }
});

to the event only it doesn't seem to work?

Body:
You should consider checking the width inside the getClippy function. That will work if you load the page with a large viewport and shrink it and vice versa.

    (function($) {

    var s,
    clippy = {
    settings: {
      heading: $('.js-clippy'),
    },
    init: function() {
      s = this.settings;
      this.bindEvents();
    },
    bindEvents: function(){
        $(window).on("load resize scroll", $.proxy(this.getClippy, this));
    },

    getClippy: function(){
        if ($(window).width() > 768) {
            s.heading.each(function() {
                var layerOffset = $(this).closest('a').offset(),
                containerOffset = layerOffset.top - $(window).scrollTop(),
                clippy = containerOffset - $(this).css("top").replace(/[^-\d\.]/g, '') - $(this).css("margin-top").replace(/[^-\d\.]/g, '');
                $(this).css('clip', 'rect('+ clippy +'px, auto, auto, auto)');
            });
        }
    },
    };
    clippy.init();

  })(jQuery);


问:
How to center a "position: absolute" element
I'm having a problem centering an element that has the attribute position set to absolute.
Does anyone know why the images are not centered?

body {
  text-align: center;
}

#slideshowWrapper {
  margin-top: 50px;
  text-align: center;
}

ul#slideshow {
  list-style: none;
  position: relative;
  margin: auto;
}

ul#slideshow li {
  position: absolute;
}

ul#slideshow li img {
  border: 1px solid #ccc;
  padding: 4px;
  height: 450px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="slideshowWrapper">
    <ul id="slideshow">
      <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li>
      <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li>
    </ul>
  </div>
</body></code>```

答:
Here is easy and best solution for center element with “position: absolute”

 body,html{
  min-height:100%;
 }

 div.center{
 width:200px;
 left:50%;
 margin-left:-100px;/*this is 50% value for width of the element*/
 position:absolute;
 background:#ddd;
 border:1px solid #999;
 height:100px;
 text-align:center
 }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>

</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body></code>```

Body:
Here is easy and best solution for center element with “position: absolute”

 body,html{
  min-height:100%;
 }

 div.center{
 width:200px;
 left:50%;
 margin-left:-100px;/*this is 50% value for width of the element*/
 position:absolute;
 background:#ddd;
 border:1px solid #999;
 height:100px;
 text-align:center
 }

<style>

</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body>


问:
My program won't print my results
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this

```<code>#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
       if (argv[1] == "777")
       {
          printf("rwxrwxrwx");
       }

       else if (argv[1] == "755")
       {
            printf("rwxr-xr-x");
       }

       else if (argv[1] == "750")
       {
            printf("rwxr-x---");
       }
       else if (argv[1] == "700")
       {
            printf("rwxr-x---");
       }
       else if (argv[1] == "666")
       {
            printf("rw-rw-rw");
       }
       else if (argv[1] == "664")
       {
            printf("rw-rw-r--");
       }
       else if (argv[1] == "640")
       {
            printf("rw-r-----");
       }
       else if (argv[1] == "600")
       {
            printf("rw-------");
       }
       else if (argv[1] == "400")
       {
            printf("r--------");
       }
return (0);

}
</code>```

答:
Comparing strings in C doesn't work like this, you have to use strcmp

Instead of doing if (argv[1] == "XXX"), you should do if (strcmp(argv[1], "XXX") == 0)

Read on here

Title: My program won't print my results

Body:
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this

#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
       if (argv[1] == "777")
       {
          printf("rwxrwxrwx");
       }

       else if (argv[1] == "755")
       {
            printf("rwxr-xr-x");
       }

       else if (argv[1] == "750")
       {
            printf("rwxr-x---");
       }
       else if (argv[1] == "700")
       {
            printf("rwxr-x---");
       }
       else if (argv[1] == "666")
       {
            printf("rw-rw-rw");
       }
       else if (argv[1] == "664")
       {
            printf("rw-rw-r--");
       }
       else if (argv[1] == "640")
       {
            printf("rw-r-----");
       }
       else if (argv[1] == "600")
       {
            printf("rw-------");
       }
       else if (argv[1] == "400")
       {
            printf("r--------");
       }
return (0);

}


问:
PHP/Javascript: Javascript not sending data to PHP
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

```<code><script type="text/javascript">
function search(str)
{
if (str=="")
  {
  document.getElementById("search").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {//IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {//IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("search").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","leaderboard.php?q="+str,true);
xmlhttp.send();
}
</script>
</code>```

Text input:

```<code><form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>
</code>```

PHP:

```<code><?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
  $i++;
 }
 }
?>
</code>```

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

```<code><table border="0" cellspacing="15" padding="0" width="200">

<th><font color="#00FF00">Rank</font></th>
<th><font color="#00FF00">Username</font></th>
<th><font color="#00FF00">Score</font></th>
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '<tr><td>' .$a. '</td><td>'.$row['username'].'</td><td>'.$row['count'].'</td></tr>';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '<tr><td>' .$a. '</td><td>'.$User[$i].'</td><td>'.$Count[$i].'</td></tr>';
    $i++;
}
}
?>
</table>
</code>```

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.

答:
Wow. Hard to know where to begin.

I think you're going to get more help if you give us more of an idea of what you're trying to accomplish. I'm thinking you're trying to build an inline search?

If your URL is changing then the form is getting submitted somehow. Since you're using AJAX that's probably not what you want. Add onSubmit="return false;" to the form element. That may solve your immediate problem. (though I'm not sure that onChange will work right cross browser. See #2)

Look at jQuery for AJAX and for DOM manipulation. It's a lot easier than what you're trying to build it using the native tools.

Your query won't work and it's a security problem. Right now anyone can send SQL commands in your q parameter and depending on permissions probably do whatever they want with your database.  Look at mysql_real_escape_string() or better yet look at a database framework that uses place holders such as PDO.  As for the query itself you're only going to find people with the exact match. You probably want to use LIKE rather than equals.

Body:
I'm making a search system whereby the user enters data into a text area and when he presses 'enter', the search text is sent to the php search query via javascript so that the page doesn't have to reload.

Javascript:

Text input:

<form>
<input type="text" value="search for user" onfocus="if
(this.value==this.defaultValue) this.value='';" onblur="if (this.value!==this.defaultValue) this.value='search for user';" id="search" name="search" style="background-color: white; color: black; border: 1px solid black; font-family: verdana; font-size: 9px; height: 20px; text-align: center;" onchange="search(this.value)">
</form>

PHP:

<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=mysql_num_rows($sql);
 }

  echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

  $User = array(); $Count = array(); $t=0; $i=0;
 while($row = mysql_fetch_array($result)){
  $User[] = $row['username']; $Count[] = $row['count'];
  $t=13;
 }
   $User[] = $row['username']; $Count[] = $row['count'];
 while($i<$t) {
  $a = $i + 1;
  echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
  $i++;
 }
 }
?>

The javascript definitely works up to the penultimate line, because the url changes to 'http://localhost/%5bclickphilia%5d/leaderboard.php?search=whatever was searched' but then nothing happens.

I'm very new to this so I might have made a blindingly obvious mistake so don't rule out that possibility :D

Thanks

EDIT:

Here is the full code for the table including the php:

Rank
Username
Score
<?php
$con = mysql_connect('localhost', 'refrigerator', 'XXXX');
mysql_select_db('refrigerator');
if($q=$_GET["q"]){
$sql="SELECT * FROM users WHERE username = '".$q."'";
$result = mysql_query($sql);
$result=mysql_real_escape_string($result);
$User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
}

    echo '
' .$a. '	'.$row['username'].'	'.$row['count'].'
';

mysql_close($con);
}

if ($q=!$_GET["q"]){

    $User = array(); $Count = array(); $t=0; $i=0;
while($row = mysql_fetch_array($result)){
    $User[] = $row['username']; $Count[] = $row['count'];
    $t=13;
}
    $User[] = $row['username']; $Count[] = $row['count'];
while($i<$t) {
    $a = $i + 1;
    echo '
' .$a. '	'.$User[$i].'	'.$Count[$i].'
';
    $i++;
}
}
?>

I'm sure the inserting the php echo into the table works, because the event for if ($q=!$_GET["q"]) works fine. The data is entered into the table okay.


问:
Setting a BBSectionInfo using BBSettingsGateway fails for unclear reason
I’m attempting to create a solution for an end-to-end testing suite to set user permissions (contacts, photos, notifications, etc.) on the simulator. The reason for doing this is because permission alerts are displayed by SpringBoard, and they interfere with the testing suite.

I’ve tried using the XCUITest suite, but it does not work as expected regarding SpringBoard alerts, and is inconvenient to use in general.

So my idea was to modify system files in order to set permissions on-demand. I found the TCC database, and it seems to be pretty straightforward. I then noticed that notification permissions are saved under a different file, /Library/BulletinBoard/SectionInfo.plist. This file is cached by a BBServer object in the SpringBoard process. I managed to change this file, and if SpringBoard is terminated, changes to the file are accepted. But I want this change to happen during the tested app’s process runtime.

After some digging, I noticed that when the Settings app (Preferences) makes a change to notification settings, it uses an XPC connection to notify it has made a change.

I am trying to accomplish the same thing in the tested process. I create a BBSectionInfo object which contains all the settings for the notifications, and try to notify the BulletinBoard server of this change using a BBSettingsGateway, which internally uses an XPC connection. This does not work, and I am not sure why not, because I do not get any error.

Perhaps it’s an entitlement issue? What annoys me is that no error is given by the system, just nothing happens.

In debugger, bringing the XPC connection, I get this:

```<code> (lldb) po [inv.target valueForKey:@“connection”]
 <NSXPCConnection: 0x60000011bcf0> connection to service named com.apple.bulletinboard.settingsconnection
</code>```

The internal connection also does not disclose any issues:

```<code> (lldb) po [[inv.target valueForKey:@"connection"] valueForKey:@"xpcConnection"]
 <OS_xpc_connection: connection[0x6000001a6200]: { refcnt = 2, xrefcnt = 1, name = com.apple.bulletinboard.settingsconnection, type =  named, state = init-done, error = 0x0 mach = true, privileged = false, bssend = 0x6f07, recv = 0x6d0b, send = 0x7003, pid = 0, euid = 4294967295, egid = 4294967295, asid = 4294967295 } <connection: 0x6000001a6200> { name = com.apple.bulletinboard.settingsconnection, listener = false, pid = 0, euid = 4294967295, egid = 4294967295, asid = 4294967295 }>
</code>```

So all seems good. The only difference I can find between the connections is that in my process, the state is init-done, while in the Preferences process, the state is checked in:

```<code>(lldb) po [[[QuietHoursStateController sharedController] bbGateway] valueForKey:@"connection"]
<NSXPCConnection: 0x6180001160b0> connection to service named com.apple.bulletinboard.settingsconnection

(lldb) po [[[[QuietHoursStateController sharedController] bbGateway] valueForKey:@"connection"] valueForKey:@"xpcConnection"]
<OS_xpc_connection: connection[0x6180001a3fe0]: { refcnt = 2, xrefcnt = 1, name = com.apple.bulletinboard.settingsconnection, type = named, state = checked in, error = 0x0 mach = true, privileged = false, bssend = 0x9d03, recv = 0x9817, send = 0x9e03, pid = 17877, euid = 26053515, egid = 20, asid = 100046 } <connection: 0x6180001a3fe0> { name = com.apple.bulletinboard.settingsconnection, listener = false, pid = 17877, euid = 26053515, egid = 20, asid = 100046 }>
</code>```

I don’t have enough experience with XPC connections, so maybe I am missing something? BBSettingsGateway seems to manage its own connection, and it does not expose any methods for managing the connection.

I don’t mind other creative solutions, as this solution is only for the simulator. I have added the jailbreak tag for discoverability, but I am looking for simulator-only solutions.

答:
Turns out it is security related. BBServer implements a listener:shouldAcceptNewConnection: method (which is defined in NSXPCListenerDelegate), which has a whitelist of entitlements that are accepted. Otherwise, the connection is not accepted, but not terminated either. Since this is for the simulator, I added the com.apple.bulletinboard.settings entitlement to my app, and that indeed solved the issues, and I was able to set the section info using BBSettingsGateway.

I ended up editing the plist directly for a specified simulator. This functionality is implemented in AppleSimulatorUtils, a collection of command-line utils for Apple simulators.

Body:
I’m attempting to create a solution for an end-to-end testing suite to set user permissions (contacts, photos, notifications, etc.) on the simulator. The reason for doing this is because permission alerts are displayed by SpringBoard, and they interfere with the testing suite.

I’ve tried using the XCUITest suite, but it does not work as expected regarding SpringBoard alerts, and is inconvenient to use in general.

So my idea was to modify system files in order to set permissions on-demand. I found the TCC database, and it seems to be pretty straightforward. I then noticed that notification permissions are saved under a different file, /Library/BulletinBoard/SectionInfo.plist. This file is cached by a BBServer object in the SpringBoard process. I managed to change this file, and if SpringBoard is terminated, changes to the file are accepted. But I want this change to happen during the tested app’s process runtime.

After some digging, I noticed that when the Settings app (Preferences) makes a change to notification settings, it uses an XPC connection to notify it has made a change.

I am trying to accomplish the same thing in the tested process. I create a BBSectionInfo object which contains all the settings for the notifications, and try to notify the BulletinBoard server of this change using a BBSettingsGateway, which internally uses an XPC connection. This does not work, and I am not sure why not, because I do not get any error.

Perhaps it’s an entitlement issue? What annoys me is that no error is given by the system, just nothing happens.

In debugger, bringing the XPC connection, I get this:

 (lldb) po [inv.target valueForKey:@“connection”]
 <NSXPCConnection: 0x60000011bcf0> connection to service named com.apple.bulletinboard.settingsconnection

The internal connection also does not disclose any issues:

 (lldb) po [[inv.target valueForKey:@"connection"] valueForKey:@"xpcConnection"]
 <OS_xpc_connection: connection[0x6000001a6200]: { refcnt = 2, xrefcnt = 1, name = com.apple.bulletinboard.settingsconnection, type =  named, state = init-done, error = 0x0 mach = true, privileged = false, bssend = 0x6f07, recv = 0x6d0b, send = 0x7003, pid = 0, euid = 4294967295, egid = 4294967295, asid = 4294967295 } <connection: 0x6000001a6200> { name = com.apple.bulletinboard.settingsconnection, listener = false, pid = 0, euid = 4294967295, egid = 4294967295, asid = 4294967295 }>

So all seems good. The only difference I can find between the connections is that in my process, the state is init-done, while in the Preferences process, the state is checked in:

(lldb) po [[[QuietHoursStateController sharedController] bbGateway] valueForKey:@"connection"]
<NSXPCConnection: 0x6180001160b0> connection to service named com.apple.bulletinboard.settingsconnection

(lldb) po [[[[QuietHoursStateController sharedController] bbGateway] valueForKey:@"connection"] valueForKey:@"xpcConnection"]
<OS_xpc_connection: connection[0x6180001a3fe0]: { refcnt = 2, xrefcnt = 1, name = com.apple.bulletinboard.settingsconnection, type = named, state = checked in, error = 0x0 mach = true, privileged = false, bssend = 0x9d03, recv = 0x9817, send = 0x9e03, pid = 17877, euid = 26053515, egid = 20, asid = 100046 } <connection: 0x6180001a3fe0> { name = com.apple.bulletinboard.settingsconnection, listener = false, pid = 17877, euid = 26053515, egid = 20, asid = 100046 }>

I don’t have enough experience with XPC connections, so maybe I am missing something? BBSettingsGateway seems to manage its own connection, and it does not expose any methods for managing the connection.

I don’t mind other creative solutions, as this solution is only for the simulator. I have added the jailbreak tag for discoverability, but I am looking for simulator-only solutions.


问:
SQL Server 2014, trigger : how to iterate over deleted rows?
ATTENTION! Using trigger is necessary for me! The only way needed for me to perform following task - is to use trigger!

The question is - I need a trigger, which would be called on rowS deletion in a certain table. The thing trigger must do - iterate over every deleted
row, and perform some code - depending on current iterated row values.

for example, I made this trigger, which works when I delete one row
by command

```<code>DELETE FROM books WHERE id=5
</code>```

the trigger is here:

```<code>GO
CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
DECLARE @book_id int
BEGIN

    SET NOCOUNT ON;

    SELECT id FROM deleted
    SET @book_id = (SELECT id FROM deleted)
    PRINT @book_id
    BEGIN
         DELETE FROM "books-topics" WHERE book_id=@book_id
         DELETE FROM "books-genres" WHERE book_id=@book_id
         DELETE FROM books WHERE id=@book_id
    END
END;
</code>```

So, what I want to achieve - is to create trigger with same task,
but it must work when I delete many rows at one time, for example

```<code> DELETE FROM books WHERE id=5 OR id=3 OR id=8
</code>```

by same task I mean, for example, calling the following code on each deleted row

```<code>DELETE FROM "books-topics" WHERE id=DELETEDROW.book_id
DELETE FROM "books-genres" WHERE id=DELETEDROW.book_id
DELETE FROM books WHERE id=DELETEDROW.book_id
</code>```

答:
Your teacher should have thought about a better example for an instead of delete trigger. This problem is what on delete cascade is there for in the first place.

However, since your assignment is to use a trigger, I would suggest something like this instead:

```<code>CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
BEGIN

    SET NOCOUNT ON;

    BEGIN TRASACTION
    BEGIN TRY
        DELETE bt
        FROM "books-topics" bt
        INNER JOIN deleted d ON bt.book_id= d.book_id

        DELETE bg
        FROM "books-genres" bg
        INNER JOIN deleted d ON bg.book_id= d.book_id

        DELETE b
        FROM books b
        INNER JOIN deleted d ON b.book_id= d.book_id

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    END CATCH
END;
</code>```

Body:
ATTENTION! Using trigger is necessary for me! The only way needed for me to perform following task - is to use trigger!

The question is - I need a trigger, which would be called on rowS deletion in a certain table. The thing trigger must do - iterate over every deleted
row, and perform some code - depending on current iterated row values.

for example, I made this trigger, which works when I delete one row
by command

DELETE FROM books WHERE id=5

the trigger is here:

GO
CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
DECLARE @book_id int
BEGIN

    SET NOCOUNT ON;

    SELECT id FROM deleted
    SET @book_id = (SELECT id FROM deleted)
    PRINT @book_id
    BEGIN
         DELETE FROM "books-topics" WHERE book_id=@book_id
         DELETE FROM "books-genres" WHERE book_id=@book_id
         DELETE FROM books WHERE id=@book_id
    END
END;

So, what I want to achieve - is to create trigger with same task,
but it must work when I delete many rows at one time, for example

 DELETE FROM books WHERE id=5 OR id=3 OR id=8

by same task I mean, for example, calling the following code on each deleted row

DELETE FROM "books-topics" WHERE id=DELETEDROW.book_id
DELETE FROM "books-genres" WHERE id=DELETEDROW.book_id
DELETE FROM books WHERE id=DELETEDROW.book_id

Body:
Your teacher should have thought about a better example for an instead of delete trigger. This problem is what on delete cascade is there for in the first place.

However, since your assignment is to use a trigger, I would suggest something like this instead:

CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
BEGIN

    SET NOCOUNT ON;

    BEGIN TRASACTION
    BEGIN TRY
        DELETE bt
        FROM "books-topics" bt
        INNER JOIN deleted d ON bt.book_id= d.book_id

        DELETE bg
        FROM "books-genres" bg
        INNER JOIN deleted d ON bg.book_id= d.book_id

        DELETE b
        FROM books b
        INNER JOIN deleted d ON b.book_id= d.book_id

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    END CATCH
END;


问:
Dart serializing immutable objects
I would like serialize this immutable class

```<code>class CatalogueItem {
  final Uri source;
  final DateTime analyis;
  final Period fromTo;

  CatalogueItem.create(this.source, this.analyis, this.fromTo);
}
</code>```

But I cannot as it is not a simple class. From the web site https://www.dartlang.org/articles/serialization/

Simple: All of the objects to be serialized are data transfer objects
  (DTOs) with a default constructor.

So I have to add a default constructor - which means I have to drop the final keywords and my class is no longer immutable.

```<code>class CatalogueItem {
  Uri source;
  DateTime analyis;
  Period fromTo;

  CatalogueItem.create(this.source, this.analyis, this.fromTo);
  CatalogueItem(){}
}
</code>```

Is there any way around this one?

答:
https://github.com/google/built_value.dart may do what you want -- it is specifically for creating immutable classes and serializing them.

Note that this requires a slightly different form for the class. This is to allow built_value to generate an implementation for you, and serializers.

```<code>abstract class CatalogueItem
    implements Built<CatalogueItem, CatalogueItemBuilder> {
  static Serializer<CatalogueItem> get serializer
      => _$catalogueItemSerializer;

  Uri get source;
  DateTime get analyis;
  Period get fromTo;

  factory CatalogueItem([updates(CatalogueItemBuilder b)]) =
      _$CatalogueItem;
  CatalogueItem._();
}
</code>```

The generated implementation is immutable (uses final), and also provides operator==, hashCode and toString.

More detailed example: https://github.com/google/built_value.dart/blob/master/example/lib/example.dart

Title: Dart serializing immutable objects

Body:
I would like serialize this immutable class

class CatalogueItem {
  final Uri source;
  final DateTime analyis;
  final Period fromTo;

  CatalogueItem.create(this.source, this.analyis, this.fromTo);
}

But I cannot as it is not a simple class. From the web site https://www.dartlang.org/articles/serialization/

Simple: All of the objects to be serialized are data transfer objects
  (DTOs) with a default constructor.

So I have to add a default constructor - which means I have to drop the final keywords and my class is no longer immutable.

class CatalogueItem {
  Uri source;
  DateTime analyis;
  Period fromTo;

  CatalogueItem.create(this.source, this.analyis, this.fromTo);
  CatalogueItem(){}
}

Is there any way around this one?

Body:
https://github.com/google/built_value.dart may do what you want -- it is specifically for creating immutable classes and serializing them.

Note that this requires a slightly different form for the class. This is to allow built_value to generate an implementation for you, and serializers.

abstract class CatalogueItem
    implements Built<CatalogueItem, CatalogueItemBuilder> {
  static Serializer<CatalogueItem> get serializer
      => _$catalogueItemSerializer;

  Uri get source;
  DateTime get analyis;
  Period get fromTo;

  factory CatalogueItem([updates(CatalogueItemBuilder b)]) =
      _$CatalogueItem;
  CatalogueItem._();
}

The generated implementation is immutable (uses final), and also provides operator==, hashCode and toString.

More detailed example: https://github.com/google/built_value.dart/blob/master/example/lib/example.dart


答:
```<code>argv[1] == "755"
</code>```

is not how you compare strings in C, you need to use:

```<code>strcmp (argv[1], "755") == 0
</code>```

In any case, this "brute force" method is both totally unnecessary and unreliable (missing possibilities, only nine of the 512 possibilities are handled, even without taking into account setuid and setgid bits and so on).

You would be better off having a function to evaluate one octal digit, such as:

```<code>static const char * permXlat (char octal) {
    switch (octal) {
        case '0' : return "---";
        case '1' : return "--x";
        case '2' : return "-w-";
        case '3' : return "-wx";
        case '4' : return "r--";
        case '5' : return "r-x";
        case '6' : return "rw-";
    }
    return "rwx";
}
</code>```

and then processing the argument one character at a time:

```<code>printf ("%s%s%s\n",
    permXlat (argv[1][0]),
    permXlat (argv[1][1]),
    permXlat (argv[1][2]));
</code>```

adding whatever sanity checking you think is necessary (argument list size, character values and so on).

Title: My program won't print my results

Body:
argv[1] == "755"

is not how you compare strings in C, you need to use:

strcmp (argv[1], "755") == 0

In any case, this "brute force" method is both totally unnecessary and unreliable (missing possibilities, only nine of the 512 possibilities are handled, even without taking into account setuid and setgid bits and so on).

You would be better off having a function to evaluate one octal digit, such as:

static const char * permXlat (char octal) {
    switch (octal) {
        case '0' : return "---";
        case '1' : return "--x";
        case '2' : return "-w-";
        case '3' : return "-wx";
        case '4' : return "r--";
        case '5' : return "r-x";
        case '6' : return "rw-";
    }
    return "rwx";
}

and then processing the argument one character at a time:

printf ("%s%s%s\n",
    permXlat (argv[1][0]),
    permXlat (argv[1][1]),
    permXlat (argv[1][2]));

adding whatever sanity checking you think is necessary (argument list size, character values and so on).


问:
Local install or remote install of a MySQL database?
Could someone explain the advantages and disadvantages of installing a MySQL database on a local machine compared to a remote machine (on a server)?

Thanks.
L.

答:
Well, it depends on what you are going to use the MySQL database for.

Basically the MySQL Server is communicating over TCP/IP even on a local machine (unless you enable the PIPE option).

If the Server needs to be reached 24/7, yes a dedicated server machine would be the solution.

If it is for your own pleasure well, no harm in installing it locally. Only if you have a huge amount of data you would probably want a dedicated Server.

By installing it locally, you can block access to MySQL from your LAN through your Firewall. A server solution needs to open up the firewall to access MySQL.

I had one locally for years when I developed, but now when I have a dedicated web server I put the SQL server there as well.


问:
Dialog box not displaying upon clicking button
I have a site which has the button 'Currency Converter'. When clicked on it, it should open the dialog box and conversion should happen. Following is the code:

currency_converter.php

<!DOCTYPE HTML>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

    <button id="opener">Currency Converter</button>

    ```

The problem is: dialog box is not getting opened in my browser.

Can anyone please help. Thanks in advance

答:
You have listen for document ready twice, other then that it should work just fine.

<!DOCTYPE HTML>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

<button id="opener">Currency Converter</button>

```

Body:
I have a site which has the button 'Currency Converter'. When clicked on it, it should open the dialog box and conversion should happen. Following is the code:

currency_converter.php

<!DOCTYPE HTML>

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

    <button id="opener">Currency Converter</button>

The problem is: dialog box is not getting opened in my browser.

Can anyone please help. Thanks in advance

Body:
You have listen for document ready twice, other then that it should work just fine.

<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" media="all" />

    <script>
        $(document).ready(function() {
            $('#openwindow').each(function() {
                var $link = $(this);
                var $dialog = $('<div></div>')
                    .load($link.attr('href'))
                    .dialog({
                        autoOpen: false,
                        title: $link.attr('title'),
                        width: 500,
                        height: 300
                    });

                $link.click(function() {
                    $dialog.dialog('open');

                    return false;
                });
            });

            $('#wrapper').dialog({
                autoOpen: false,
                title: 'Basic Dialog'
            });
            $('#opener').click(function() {
                var page = "https://www.google.com/finance/converter";

                var $dialog = $('<div></div>')
                    .html('<iframe style="border: 0px; " src="' + page + '" width="100%" height="100%"></iframe>')
                    .dialog({
                        autoOpen: false,
                        modal: true,
                        height: 250,
                        width: 350,
                        title: "Currency Converter"
                    });
                $dialog.dialog('open');
                return false;
            });
        });
    </script>
</head>
<body>

<button id="opener">Currency Converter</button>
<div id="wrapper">

</div>
</body>
</html>


问:
Google Maps API V3 same event lister to multiple arrays of markers
So basically I have something like this

```<code>var arrayOfMarker1 = [...], arrayOfMarker2 = [...], ... arrayOfMarkerN = [...];
</code>```

and I want to use a eventListener able to close the current open infoPanel to show the last clicked one, even if it is a marker of another array to be clicked.

Example:

I open a marker of arrayOfMarker1 infoPanel (let's call it marker1)

I click on a arrayOfMarker2 marker (marker2)

marker1's infoPanel is closed and marker2's in opened

The only thing that I have found is this

```<code>marker.addListener('click', function () {
    infowindow.setContent(this.html);
    infowindow.open(map, this);
});
</code>```

But it just works for markers of the same array. Is there any way to do it?

答:
You would need a global variable to track the last opened infoPanel.</p>

```<code>var openedInfoWindow = null;
marker.addListener('click', function () {
    if(openedInfoWindow != null)
    {
        openedInfoWindow.close();
    }
    openedInfoWindow = infowindow;
    infowindow.setContent(this.html);
    infowindow.open(map, this);
});
</code>```

Body:
So basically I have something like this

var arrayOfMarker1 = [...], arrayOfMarker2 = [...], ... arrayOfMarkerN = [...];

and I want to use a eventListener able to close the current open infoPanel to show the last clicked one, even if it is a marker of another array to be clicked.

Example:

I open a marker of arrayOfMarker1 infoPanel (let's call it marker1)

I click on a arrayOfMarker2 marker (marker2)

marker1's infoPanel is closed and marker2's in opened

The only thing that I have found is this

marker.addListener('click', function () {
    infowindow.setContent(this.html);
    infowindow.open(map, this);
});

But it just works for markers of the same array. Is there any way to do it?

Body:
You would need a global variable to track the last opened infoPanel.

var openedInfoWindow = null;
marker.addListener('click', function () {
    if(openedInfoWindow != null)
    {
        openedInfoWindow.close();
    }
    openedInfoWindow = infowindow;
    infowindow.setContent(this.html);
    infowindow.open(map, this);
});


问:
How to avoid having 2 times | async in this situation (4.0.0)?
I would like to avoid to use .subscribe() in this component.
I tried *ngIf="user$ | async as user" but it did not work.

How can I make a local variable with user$ | async un order to use it at different places in this view?

<app-xpbar *ngIf="user$ | async"></app-xpbar>

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user$ | async"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

```

答:
After thinking of pros and cons of differents propositions, I'll go with a ParentComponent event if it's here only for getting user stream.
Thanks everyone.


问:
Android: what happens to background process when a new version is installed from the Market Place?
I have developed an Android health app which launches a process running in the background and monitoring user activities such as steps. If the app is closed by the user, the core sensors monitor keeps running in the background.
I am about to upload a new version of the app to the marketplace. What will happen to the background service when the app is updated? Will it be killed?
Tests on the beta channel seem to indicate that the background process is somehow left in a semi-dead status (i.e. the process is there but is not working).
Shall I make sure that the background process stops when a new version is installed? If so, how?
Thanks</p>

答: While updating to new version, the app is killed by Android. It means that Android stops all the background services as well, but once the app update is done, then the services are restarted.</p>