问:
Increasing money when the dealer or player win the game
I am a beginner I am trying to add money if I wont to the money that I typed in the very start of the game if I won the money will be added to the input money that I had it adding but repeating its looping example I typed 500 then I won 200 price It will display 700 but if I won again and the price 300 it will show 800 and forgetting about what I won before

below is the code I will really appreciate your hep thank you

```<code>import random, sys
from random import shuffle
from _ast import Num

# define global variables for the cards

suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}

playing = True
global score
score=0

class Card:

    #When you create an instance of Card, you pass it a suit ("C", "D", "H", or "S") and a "pip" (2, 3, 4, 5, 6, 7, 8, 9, 10 J, Q, K, A).
    #These values should be stored as instance variables for the new card object.
    #I recommend you also have an instance variable "value" that stores the point value of the card.
    #It should have an __str__ method that lets you print an individual card (such as "3S" for three of spades).
    #Note that the __str__ method for Decks should take advantage of the __str__ method for Cards.

    def __init__(self, suit, pip):
        self.suit = suit
        self.pip = pip
        self.value = pipValues.get(pip)

    def __str__(self):
        return str(self.pip) + " of " + str(self.suit)

    def __repr__(self):
        return self.__str__()

class Player:

    #When you create an instance of Player, it should have an instance variable "hand" that's set to an empty list,
        #and an instance variable "handTotal" that's set to zero. These instance variables will be modified
        #by Deck's "dealOne()" method.
    #It should have an __str__ method that lets you print out a Player's hand.

    def __init__(self, isDealer):
        self.hand = []
        self.isDealer = isDealer
        self.name = "Dealer" if self.isDealer else "You"
        self.other = "Dealer" if not self.isDealer else "You"
        self.has = "has" if self.isDealer else "have"

    def __str__(self):
        return ", ".join(map(str, self.hand))

    def __repr__(self):
        return self.__str__()

    def discardHand(self):
        self.hand = []

    @property
    def handTotal(self):
      while sum(card.value for card in self.hand) > 21 and \
            any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
        for card in self.hand:
          if card.pip == 'Ace' and card.value == 11:
            card.value = 1
            break
      return sum(card.value for card in self.hand)

    def blackjack(self):
        print ("%s %s %s for a total of 21" %
          (self.name, self.has, str(self)))
        print ("%s %s a Blackjack! %s win%s!" %
          (self.name, self.has, self.name, "s" if self.isDealer else ""))

        print ("Thanks for playing. Come back again soon! ")
        #chips=chips+(bet*500)
        score+1
        return message()

    def bust(self):
        print ("%s hold%s %s for a total of %s" %
          (self.name, "s" if self.isDealer else "", str(self), str(self.handTotal)))
        print ("%s Bust%s! %s Win%s!" %
          (self.name, "s" if self.isDealer else "", self.other, "s" if not self.isDealer else ""))
        print ("Thanks for Playing! Come Back Soon!")
       # chips=chips-2
        return message()

class Deck:

    #When you create an instance of Deck, it should add 52 Card objects to an instance variable "cardList".
    #It should have a shuffle() method that rearranges the cards in cardList. You can do this easily by importing the
        #"random" package into Python, and using the random.shuffle() method. random.shuffle(myList) rearranges the
        #elements of the list "myList" into a random order.
    #It should have a dealOne() method that removes the first card from your deck's cardList, and appends it to the
        #hand of a specified player.
    #It should have an __str__ method that lets you print out the entire deck for debugging purposes.
    freshDeck = []
    for i in range(len(suits)):
            for j in range(len(pip)):
                freshDeck.append(Card(suits[i], pip[j]))

    def __init__(self):
        self.cardList = self.freshDeck[:]

    def shuffle(self):
        random. shuffle (self.cardList)

    def dealOne(self, player):
        if len(self.cardList) < 4:
          print("Out of cards... shuffling a new deck...")
          exit
          #self.cardList = self.freshDeck[:]
          #self.shuffle()
        (player.hand).append(self.cardList[0])

        del self.cardList[0]
        #print(self.cardList)
        shuffle(self.cardList)
        return self.cardList

    def __str__(self):
        printString = ""
        for i in range(len(self.cardList)):
            if i % 13 == 0:
                printString += "\n \t"
                printString += str(self.cardList[i]) + " "
            else:
                printString += str(self.cardList[i]) + " "
        printString += "\n"

        return printString

def showHands(player, opponent):
    print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
    print ('You show ' + str(player))

def turn(deck, player, other):
    #First, check scores to see if either player has a blackjack:

    if player.handTotal == 21:
      return player.blackjack()
    if other.handTotal == 21:
      return other.blackjack()

    #See if the dealer less 16

    hitOrStand = 0
    while hitOrStand != 2:
        print (player.name + ' hold%s ' % ("s" if player.isDealer else "") + str(player) + ' for a total of ' + str(player.handTotal) + '\n')
        if player.isDealer:
          if player.handTotal < 16:
            hitOrStand = 1
          if player.handTotal >= other.handTotal:
            hitOrStand = 2
        else:
          hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
          while hitOrStand != 1 and hitOrStand != 2:
              try:
                  hitOrStand = int(hitOrStand)
                  break
              except ValueError:
                  print ("Enter a valid integer \n")
              hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
          print()

        if hitOrStand == 1:
            print('Card dealt:  ' + str(deck.cardList[0]) + '\n')
            deck.dealOne(player)

        if player.handTotal == 21:
            return player.blackjack()

        if player.handTotal > 21:
            return player.bust()

        #if player.handTotal <16 :
            #return player.bust()

        if hitOrStand == 2:
          if player.isDealer:
            print ("Dealer stands at " + str(player.handTotal))
            global price
            price=bet*500*2

            print (price )
            print ("Dealer Wins!")
            return message()
          else:
            print (player.name + ' stand at: ' + str(player.handTotal))
            print()
    print ("Now Dealer's Turn\n")

def message():
    global playing
    again = raw_input("Do you want to play again? (Y/N) : ")
    if again.lower() == "n":
        print("\n\n-------Thank you for playing!--------\n\n")
        playing = False
    return True

#who won
def betValidation():
        global number
        number=input("Enter amount: ")

        number
        if (number<5000):
            print "Minimum amount is 5000!!! "
            exit()

        elif (number > 50000):
            print "You Exceeding the Maximum Amount...."
            exit()
        elif (number==5000 , number<=50000):
            if number%500==0:
                print ""

            else:
                print "Invalid"
                exit()

def main():
    cardDeck = Deck()

    global bet

    bet1=betValidation()

    while playing:
        global chips
        print "Score:",score
        chips=number/500
        print "You have", chips ,"chips!"

        betchips=chips/2
        global bet

        bet=input("How much would you like to bet: ")

        if(bet==0):
            print "Invalid"
        elif (bet>=betchips):
            if bet%1==0:

                player = Player(isDealer=False)
                opponent = Player(isDealer=True)

                player.discardHand()
                opponent.discardHand()
      #give each player 2 cards, alternating
                cardDeck.dealOne(player)
                cardDeck.dealOne(opponent)
                cardDeck.dealOne(player)
                cardDeck.dealOne(opponent)

      #show 1 faceup card for each player
                showHands(player,opponent)

      #start playing
                if turn(cardDeck,player, opponent):
                    continue

                turn(cardDeck, opponent, player)

main()
</code>```

答: I imagine your problem lies in the function blackjack() but you haven't posted that.</p>

Body:
I am a beginner I am trying to add money if I wont to the money that I typed in the very start of the game if I won the money will be added to the input money that I had it adding but repeating its looping example I typed 500 then I won 200 price It will display 700 but if I won again and the price 300 it will show 800 and forgetting about what I won before

below is the code I will really appreciate your hep thank you

import random, sys
from random import shuffle
from _ast import Num

# define global variables for the cards

suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}

playing = True
global score
score=0

class Card:

    #When you create an instance of Card, you pass it a suit ("C", "D", "H", or "S") and a "pip" (2, 3, 4, 5, 6, 7, 8, 9, 10 J, Q, K, A).
    #These values should be stored as instance variables for the new card object.
    #I recommend you also have an instance variable "value" that stores the point value of the card.
    #It should have an __str__ method that lets you print an individual card (such as "3S" for three of spades).
    #Note that the __str__ method for Decks should take advantage of the __str__ method for Cards.

    def __init__(self, suit, pip):
        self.suit = suit
        self.pip = pip
        self.value = pipValues.get(pip)

    def __str__(self):
        return str(self.pip) + " of " + str(self.suit)

    def __repr__(self):
        return self.__str__()

class Player:

    #When you create an instance of Player, it should have an instance variable "hand" that's set to an empty list,
        #and an instance variable "handTotal" that's set to zero. These instance variables will be modified
        #by Deck's "dealOne()" method.
    #It should have an __str__ method that lets you print out a Player's hand.

    def __init__(self, isDealer):
        self.hand = []
        self.isDealer = isDealer
        self.name = "Dealer" if self.isDealer else "You"
        self.other = "Dealer" if not self.isDealer else "You"
        self.has = "has" if self.isDealer else "have"

    def __str__(self):
        return ", ".join(map(str, self.hand))

    def __repr__(self):
        return self.__str__()

    def discardHand(self):
        self.hand = []

    @property
    def handTotal(self):
      while sum(card.value for card in self.hand) > 21 and \
            any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
        for card in self.hand:
          if card.pip == 'Ace' and card.value == 11:
            card.value = 1
            break
      return sum(card.value for card in self.hand)

    def blackjack(self):
        print ("%s %s %s for a total of 21" %
          (self.name, self.has, str(self)))
        print ("%s %s a Blackjack! %s win%s!" %
          (self.name, self.has, self.name, "s" if self.isDealer else ""))

        print ("Thanks for playing. Come back again soon! ")
        #chips=chips+(bet*500)
        score+1
        return message()

    def bust(self):
        print ("%s hold%s %s for a total of %s" %
          (self.name, "s" if self.isDealer else "", str(self), str(self.handTotal)))
        print ("%s Bust%s! %s Win%s!" %
          (self.name, "s" if self.isDealer else "", self.other, "s" if not self.isDealer else ""))
        print ("Thanks for Playing! Come Back Soon!")
       # chips=chips-2
        return message()

class Deck:

    #When you create an instance of Deck, it should add 52 Card objects to an instance variable "cardList".
    #It should have a shuffle() method that rearranges the cards in cardList. You can do this easily by importing the
        #"random" package into Python, and using the random.shuffle() method. random.shuffle(myList) rearranges the
        #elements of the list "myList" into a random order.
    #It should have a dealOne() method that removes the first card from your deck's cardList, and appends it to the
        #hand of a specified player.
    #It should have an __str__ method that lets you print out the entire deck for debugging purposes.
    freshDeck = []
    for i in range(len(suits)):
            for j in range(len(pip)):
                freshDeck.append(Card(suits[i], pip[j]))

    def __init__(self):
        self.cardList = self.freshDeck[:]

    def shuffle(self):
        random. shuffle (self.cardList)

    def dealOne(self, player):
        if len(self.cardList) < 4:
          print("Out of cards... shuffling a new deck...")
          exit
          #self.cardList = self.freshDeck[:]
          #self.shuffle()
        (player.hand).append(self.cardList[0])

        del self.cardList[0]
        #print(self.cardList)
        shuffle(self.cardList)
        return self.cardList

    def __str__(self):
        printString = ""
        for i in range(len(self.cardList)):
            if i % 13 == 0:
                printString += "\n \t"
                printString += str(self.cardList[i]) + " "
            else:
                printString += str(self.cardList[i]) + " "
        printString += "\n"

        return printString

def showHands(player, opponent):
    print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
    print ('You show ' + str(player))

def turn(deck, player, other):
    #First, check scores to see if either player has a blackjack:

    if player.handTotal == 21:
      return player.blackjack()
    if other.handTotal == 21:
      return other.blackjack()

    #See if the dealer less 16

    hitOrStand = 0
    while hitOrStand != 2:
        print (player.name + ' hold%s ' % ("s" if player.isDealer else "") + str(player) + ' for a total of ' + str(player.handTotal) + '\n')
        if player.isDealer:
          if player.handTotal < 16:
            hitOrStand = 1
          if player.handTotal >= other.handTotal:
            hitOrStand = 2
        else:
          hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
          while hitOrStand != 1 and hitOrStand != 2:
              try:
                  hitOrStand = int(hitOrStand)
                  break
              except ValueError:
                  print ("Enter a valid integer \n")
              hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
          print()

        if hitOrStand == 1:
            print('Card dealt:  ' + str(deck.cardList[0]) + '\n')
            deck.dealOne(player)

        if player.handTotal == 21:
            return player.blackjack()

        if player.handTotal > 21:
            return player.bust()

        #if player.handTotal <16 :
            #return player.bust()

        if hitOrStand == 2:
          if player.isDealer:
            print ("Dealer stands at " + str(player.handTotal))
            global price
            price=bet*500*2

            print (price )
            print ("Dealer Wins!")
            return message()
          else:
            print (player.name + ' stand at: ' + str(player.handTotal))
            print()
    print ("Now Dealer's Turn\n")

def message():
    global playing
    again = raw_input("Do you want to play again? (Y/N) : ")
    if again.lower() == "n":
        print("\n\n-------Thank you for playing!--------\n\n")
        playing = False
    return True

#who won
def betValidation():
        global number
        number=input("Enter amount: ")

        number
        if (number<5000):
            print "Minimum amount is 5000!!! "
            exit()

        elif (number > 50000):
            print "You Exceeding the Maximum Amount...."
            exit()
        elif (number==5000 , number<=50000):
            if number%500==0:
                print ""

            else:
                print "Invalid"
                exit()

def main():
    cardDeck = Deck()

    global bet

    bet1=betValidation()

    while playing:
        global chips
        print "Score:",score
        chips=number/500
        print "You have", chips ,"chips!"

        betchips=chips/2
        global bet

        bet=input("How much would you like to bet: ")

        if(bet==0):
            print "Invalid"
        elif (bet>=betchips):
            if bet%1==0:

                player = Player(isDealer=False)
                opponent = Player(isDealer=True)

                player.discardHand()
                opponent.discardHand()
      #give each player 2 cards, alternating
                cardDeck.dealOne(player)
                cardDeck.dealOne(opponent)
                cardDeck.dealOne(player)
                cardDeck.dealOne(opponent)

      #show 1 faceup card for each player
                showHands(player,opponent)

      #start playing
                if turn(cardDeck,player, opponent):
                    continue

                turn(cardDeck, opponent, player)

main()


来源: stackexchange

问:
Calculating the difference between dates not working and giving an huge error
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

```<code>if ($date1B > $date2B) {
   echo "<script>alert('Expired coupon!!');</script>";
}
</code>```

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

```<code>$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
</code>```

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

```<code><?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "<br>" ;
   echo "Datum 1: " . $date1B . "<br><br>";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "<br>";
   echo "Datum 2: " . $date2B . "<br>";

   if ($date1B > $date2B) {
      echo "<script>alert('Klaar!!');</script>";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>
</code>```

答:
Updated .PHP file

I fixed the errors.. This is the updated .PHP page:

```<code><?php

    date_default_timezone_set("America/Curacao");
    $date1A = date("d-m-Y H:i:s");
    $date1 = date_create($date1A);
    echo date_format($date1,"d-m-Y H:i:s");

    echo "<br>";

    $date2B = "31032017042100";
    $date2A = date_create_from_format('dmYHis', $date2B);
    $final = date_format($date2A, 'd-m-Y H:i:s');
    $date2 = date_create($final);
    echo date_format($date2,"d-m-Y H:i:s");

    echo "<br>";

    $diff = date_diff($date1, $date2);
    echo $diff->format("%R %a days %h Hours %i Minute %s Seconds");

    if ($date1 > $date2) {
       echo "<script>alert('Coupon Expired!!');</script>";
    }

?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

if ($date1B > $date2B) {
   echo "";
}

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

<?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "
" ;
   echo "Datum 1: " . $date1B . "

";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "
";
   echo "Datum 2: " . $date2B . "
";

   if ($date1B > $date2B) {
      echo "";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>

Body:
Updated .PHP file

I fixed the errors.. This is the updated .PHP page:

<?php

    date_default_timezone_set("America/Curacao");
    $date1A = date("d-m-Y H:i:s");
    $date1 = date_create($date1A);
    echo date_format($date1,"d-m-Y H:i:s");

    echo "<br>";

    $date2B = "31032017042100";
    $date2A = date_create_from_format('dmYHis', $date2B);
    $final = date_format($date2A, 'd-m-Y H:i:s');
    $date2 = date_create($final);
    echo date_format($date2,"d-m-Y H:i:s");

    echo "<br>";

    $diff = date_diff($date1, $date2);
    echo $diff->format("%R %a days %h Hours %i Minute %s Seconds");

    if ($date1 > $date2) {
       echo "<script>alert('Coupon Expired!!');</script>";
    }

?>


问:
Displaying a Play button on Multiple videos on the same page
I'm a complete novice when it comes to Javascript (& copy and paste kind of guy ;)... so I'm having a bit of a problem trying to figure out how to do the following:

I've got a slideshow gallery that has 2 mp4 videos in the same set

I've found some javascript that overlays a play button on the mp4 video

However... the code work fine when I have one video - but when I place the 2nd video, I'm failing to get the overlaid arrows working on both...

There's an obvious problem with clashing classes / variables (or something to that effect) - but I can't figure it out...

HTML:

```<code><div class="swiper-slide">
    <div class="video-wrapper">
        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>
    </div>
</div>

<div class="swiper-slide">
    <div class="video-wrapper-two">
        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>
    </div>
</div>
</code>```

Javascript:

```<code><script>

var videoPlayButton,
videoWrapper = document.getElementsByClassName('video-wrapper')[0],
video = document.getElementsByTagName('video')[0],
videoMethods = {
    renderVideoPlayButton: function() {
        if (videoWrapper.contains(video)) {
            this.formatVideoPlayButton()
            video.classList.add('has-media-controls-hidden')
            videoPlayButton = document.getElementsByClassName('video-overlay-play-button')[0]
            videoPlayButton.addEventListener('click', this.hideVideoPlayButton)
        }
    },

    formatVideoPlayButton: function() {
        videoWrapper.insertAdjacentHTML('beforeend', '\
            <svg class="video-overlay-play-button" viewBox="0 0 200 200" alt="Play video">\
                <circle cx="100" cy="100" r="90" fill="#000" stroke-width="5" stroke="#fff"/>\
                <polygon points="70, 55 70, 145 145, 100" fill="#fff"/>\
            </svg>\
        ')
    },

    hideVideoPlayButton: function() {
        video.play()
        videoPlayButton.classList.add('is-hidden')
        video.classList.remove('has-media-controls-hidden')
        video.setAttribute('controls', 'controls')
    }
}

videoMethods.renderVideoPlayButton()

</script>
</code>```

The javascript handles the 1st wrapper fine, I'm just having difficulty getting the 2nd wrapper to display the Play button correctly...

Any help appreciated.

答:
The issue is

```<code>videoWrapper = document.getElementsByClassName('video-wrapper')[0],
video = document.getElementsByTagName('video')[0],
</code>```

It specify first set only

You should make it as a function and invoke twice.

var videoPlayButton;
function addMethod(video,videoWrapper){
 return {
    renderVideoPlayButton: function() {
      if (videoWrapper.contains(video)) {
        this.formatVideoPlayButton()
        video.classList.add('has-media-controls-hidden')
        videoPlayButton = document.getElementsByClassName('video-overlay-play-button')[0]
        videoPlayButton.addEventListener('click', this.hideVideoPlayButton)
      }
    },

    formatVideoPlayButton: function() {
      videoWrapper.insertAdjacentHTML('beforeend', '\
            <svg class="video-overlay-play-button" viewBox="0 0 200 200" alt="Play video">\
                <circle cx="100" cy="100" r="90" fill="#000" stroke-width="5" stroke="#fff"/>\
                <polygon points="70, 55 70, 145 145, 100" fill="#fff"/>\
            </svg>\
        ')
    },

    hideVideoPlayButton: function() {
      video.play()
      videoPlayButton.classList.add('is-hidden')
      video.classList.remove('has-media-controls-hidden')
      video.setAttribute('controls', 'controls')
    }
  }
}

addMethod(document.getElementsByTagName('video')[0],document.getElementsByClassName('video-wrapper')[0]).renderVideoPlayButton();
addMethod(document.getElementsByTagName('video')[1],document.getElementsByClassName('video-wrapper-two')[0]).renderVideoPlayButton();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="swiper-slide">
  <div class="video-wrapper">
    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>
  </div>
</div>

<div class="swiper-slide">
  <div class="video-wrapper-two">
    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>
  </div>
</div></code>```

Body:
I'm a complete novice when it comes to Javascript (& copy and paste kind of guy ;)... so I'm having a bit of a problem trying to figure out how to do the following:

I've got a slideshow gallery that has 2 mp4 videos in the same set

I've found some javascript that overlays a play button on the mp4 video

However... the code work fine when I have one video - but when I place the 2nd video, I'm failing to get the overlaid arrows working on both...

There's an obvious problem with clashing classes / variables (or something to that effect) - but I can't figure it out...

HTML:

        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>

        <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
            <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
        </video>

Javascript:

The javascript handles the 1st wrapper fine, I'm just having difficulty getting the 2nd wrapper to display the Play button correctly...

Any help appreciated.

Body:
The issue is

videoWrapper = document.getElementsByClassName('video-wrapper')[0],
video = document.getElementsByTagName('video')[0],

It specify first set only

You should make it as a function and invoke twice.

var videoPlayButton;
function addMethod(video,videoWrapper){
 return {
    renderVideoPlayButton: function() {
      if (videoWrapper.contains(video)) {
        this.formatVideoPlayButton()
        video.classList.add('has-media-controls-hidden')
        videoPlayButton = document.getElementsByClassName('video-overlay-play-button')[0]
        videoPlayButton.addEventListener('click', this.hideVideoPlayButton)
      }
    },

    formatVideoPlayButton: function() {
      videoWrapper.insertAdjacentHTML('beforeend', '\
            <svg class="video-overlay-play-button" viewBox="0 0 200 200" alt="Play video">\
                <circle cx="100" cy="100" r="90" fill="#000" stroke-width="5" stroke="#fff"/>\
                <polygon points="70, 55 70, 145 145, 100" fill="#fff"/>\
            </svg>\
        ')
    },

    hideVideoPlayButton: function() {
      video.play()
      videoPlayButton.classList.add('is-hidden')
      video.classList.remove('has-media-controls-hidden')
      video.setAttribute('controls', 'controls')
    }
  }
}

addMethod(document.getElementsByTagName('video')[0],document.getElementsByClassName('video-wrapper')[0]).renderVideoPlayButton();
addMethod(document.getElementsByTagName('video')[1],document.getElementsByClassName('video-wrapper-two')[0]).renderVideoPlayButton();

<div class="swiper-slide">
  <div class="video-wrapper">
    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>
  </div>
</div>

<div class="swiper-slide">
  <div class="video-wrapper-two">
    <video controls preload="metadata" class="pure-img video" poster="assets/posters/poster_adele-BBC.jpg">
                        <source src="http://d1wv6pnepp7p5s.cloudfront.net/AA_BBC_ALL_CUTDOWN_02.mp4" type="video/mp4"></source>
                    </video>
  </div>
</div>


问:
File Locking (Read/Write) in ASP.NET Application
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

```<code>public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}
</code>```

And here's my code for the Reader :

```<code>private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}
</code>```

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

答: No it won't. First, you're creating a brand new mutex with every call so multiple threads are going to access the writing critical section. Second, you don't even use the mutex in the reading critical section so one thread could be attempting to read the file while another is attempting to write. Also, you're not closing the stream in the ReadLog method so once the first read request comes through your app won't be able to write any log entries anyway until garbage collection comes along and closes the stream for you... which could take awhile.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have two ASP.NET web application. One is responsible for processing some info and writing to a log file, and the other application is reponsible for reading the log file and displays the information based on user request.

Here's my code for the Writer

public static void WriteLog(String PathToLogFile, String Message)
{
    Mutex FileLock = new Mutex(false, "LogFileMutex");
    try
    {
        FileLock.WaitOne();
        using (StreamWriter sw = File.AppendText(FilePath))
        {
            sw.WriteLine(Message);
            sw.Close();
        }
    }
    catch (Exception ex)
    {
        LogUtil.WriteToSystemLog(ex);
    }
    finally
    {
        FileLock.ReleaseMutex();
    }
}

And here's my code for the Reader :

private String ReadLog(String PathToLogFile)
{
    FileStream fs = new FileStream(
          PathToLogFile, FileMode.Open,
          FileAccess.Read, FileShare.ReadWrite);
    StreamReader Reader = new StreamReader(fs);
    return Reader.ReadToEnd();
}

My question, is the above code enough to prevent locking in a web garden environemnt?

EDIT 1 : Dirty read is okay.
EDIT 2 : Creating Mutex with new Mutex(false, "LogFileMutex"), closing StreamWriter

OwnerDisplayName: Spencer Ruport


问:
how to take addition in json data
I need Addition of qty in + (sum of qty) +. What do I need to do?

```<code>[{"qty": "34"},{"qty": "5"}]
</code>```

$.ajax({
    url: "localhost/sp/text.json", //json link
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push("
");
            items.push("" + val.qty + 	");
            items.push("" + (sum of qty) + 	"); //need sum of qty here
            items.push("
");
        });
    }
});
```

答:
The "sum of qty" will have the same value in each node?

If so...

```<code>$.ajax({
    url: 'localhost/sp/text.json', //json link
    dataType:'json',
    success: function(data) {
        var items = [],
            sum = 0;
        $.each(data, function(k, obj) {
            sum += parseInt(obj.qty, 10);
        });
        $.each(data, function(key, val) {
            items.push('<tr>');
            items.push('<td id="' + key + '">' + val.qty + '</td>');
            items.push('<td id="' + key + '">' + sum + '</td>');
            items.push('</tr>');
        });
    }
});
</code>```

Was missing a few quotes.

Edit
Not NaN anymore.

Title: how to take addition in json data

Body:
I need Addition of qty in + (sum of qty) +. What do I need to do?

[{"qty": "34"},{"qty": "5"}]

$.ajax({
    url: "localhost/sp/text.json", //json link
    dataType: 'json',
    success: function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push("
");
            items.push("" + val.qty + 	");
            items.push("" + (sum of qty) + 	"); //need sum of qty here
            items.push("
");
        });
    }
});

Body:
The "sum of qty" will have the same value in each node?

If so...

$.ajax({
    url: 'localhost/sp/text.json', //json link
    dataType:'json',
    success: function(data) {
        var items = [],
            sum = 0;
        $.each(data, function(k, obj) {
            sum += parseInt(obj.qty, 10);
        });
        $.each(data, function(key, val) {
            items.push('<tr>');
            items.push('<td id="' + key + '">' + val.qty + '</td>');
            items.push('<td id="' + key + '">' + sum + '</td>');
            items.push('</tr>');
        });
    }
});

Was missing a few quotes.

Edit
Not NaN anymore.


问:
"Single Sign on" using OKTA in an MVC Application
I need to implement the "Single Sign on" using OKTA in an MVC Application. I have created an account on Okta and created an application.

I can able to get the details such as Identity Provider Single Sign-On URL,Identity Provider Issuer and X.509 Certificate from OKTA.

But I am not able to configure it in to the MVC site.

Does any body know how can I configure "Single Sign on" using OKTA in an MVC Application?

答:
We're currently adopting Okta, and chose to use SAML. I found the info at Okta Blog very helpful. In this Blog they reference a module by Kentor IT, which makes implementing SAML really easy.

Keep in mind, the currentversion is 0.20, so you might have to tweak a little.

.Net version should be 4.6.2, or you have to go to SHA1 encryption instead of SHA256

We had to handle the way Okta gives back groups, where we needed roles (hint: Within 'Group Attribute Statements' set Name to 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' and Name format to URI. This way groups will be added as Role claim to the SAML token

Happy Okta'ing

Gerwin


问:
Requirejs error - Load timeout for modules: jquery
I have the following folder structure

```<code>index.html
scripts/
- app.js
- app/
-- main.js
-- page.js
- lib/
-- require.js
-- jquery.min.js
</code>```

index.html :

```<code><head>
    <script data-main="scripts/app" src="scripts/lib/require.js"></script>
</head>
</code>```

app.js :

```<code>requirejs.config({
    baseUrl: 'scripts/lib',
    paths: {
        app : '../app',
        jquery : 'jquery.min'
    },
    shim : {
        'jquery': {
            deps : ['app/page'],
            exports: '$'
        }
    }
});

requirejs(['app/main']);
</code>```

main.js :

```<code>require(["app/page"], function(page){
    page.renderPage();
});
</code>```

page.js :

```<code>define(['jquery'], function($) {
    return {
        renderPage : function() {
            //some code
        }
    }
});
</code>```

When index.html is loaded I get the following error in the console:

Uncaught Error: Load timeout for modules: jquery
  http://requirejs.org/docs/errors.html#timeout
  at makeError (require.js:168) at checkLoaded (require.js:698) at require.js:719

I have checked a lot of related questions and tried various options but couldn't make jquery work with requirejs. What am I doing wrong?

答:
You should not have a shim for jquery. The shim configuration option is only for scripts that are not actual AMD modules. An AMD module registers itself with the module loader by calling define. jQuery has added support to register itself as an AMD module a long time ago, so it calls define itself. You can see it here in its source code:

```<code>if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    } );
}
</code>```

jQuery calls define so you must not set a shim for it.

There is no defined meaning to using shim with AMD modules. In other words, RequireJS does not have to conform to any specific behavior when you try to specify a shim configuration for an AMD module. RequireJS may just ignore it, or it may behave badly.

Body:
I have the following folder structure

index.html
scripts/
- app.js
- app/
-- main.js
-- page.js
- lib/
-- require.js
-- jquery.min.js

index.html :

app.js :

requirejs.config({
    baseUrl: 'scripts/lib',
    paths: {
        app : '../app',
        jquery : 'jquery.min'
    },
    shim : {
        'jquery': {
            deps : ['app/page'],
            exports: '$'
        }
    }
});

requirejs(['app/main']);

main.js :

require(["app/page"], function(page){
    page.renderPage();
});

page.js :

define(['jquery'], function($) {
    return {
        renderPage : function() {
            //some code
        }
    }
});

When index.html is loaded I get the following error in the console:

Uncaught Error: Load timeout for modules: jquery
  http://requirejs.org/docs/errors.html#timeout
  at makeError (require.js:168) at checkLoaded (require.js:698) at require.js:719

I have checked a lot of related questions and tried various options but couldn't make jquery work with requirejs. What am I doing wrong?

Body:
You should not have a shim for jquery. The shim configuration option is only for scripts that are not actual AMD modules. An AMD module registers itself with the module loader by calling define. jQuery has added support to register itself as an AMD module a long time ago, so it calls define itself. You can see it here in its source code:

if ( typeof define === "function" && define.amd ) {
    define( "jquery", [], function() {
        return jQuery;
    } );
}

jQuery calls define so you must not set a shim for it.

There is no defined meaning to using shim with AMD modules. In other words, RequireJS does not have to conform to any specific behavior when you try to specify a shim configuration for an AMD module. RequireJS may just ignore it, or it may behave badly.


问:
Where is the JobManager on embedded Flink instances?
I am developing an application with multiple (micro)services.

I am using Flink (over Kafka) to stream messages between the services. Flink is embedded in the Java applications, each running in a separate docker container.
This is the first time I'm trying Flink and after reading the docs I still have a feeling I'm missing something basic.

Who is managing the jobs?

Where is the JobManager running?

How do  I monitor the processing?

Thanks,

Moshe

答:
I would recommend this talk by Stephan Ewen at Flink Forward 2016. It explains the current Apache Flink architecture (10:45) for different deployments as well as future goals.

In general, the JobManager is managing Flink jobs and TaskManagers execute your job consisting of multiple tasks. How the components are orchestrated depends on your deployment (local, Flink cluster, YARN, Mesos etc.).

The best tool for monitor your processing is the Flink Web UI at port 8081 by default, it offers different metrics for debugging and monitoring (e.g. monitoring checkpointing or back-pressure).


问:
free-jqGrid change shrinkToFit dynamically
I'm using free-jqGrid and I'd like to set the shrinkToFit option dynamically depending on the size of the window.
Is there a way to do it?
and another question while I'm a it,
What is the event, like  onSelectRow: function (){}, for the click on the inline edit button?
Thanks,</p>

答: If you call the method setGridWidth explicitly, then you can use the last parameter (shrink) independent from the value of shrinkToFit. It should solve your problem.


问:
Silverlight Date Formats
I'm getting some very strange date formatting issues in my Silverlight application. My local culture is set to UK, yet I am consistently seeing US dates popping up all over the place. I can easily hardcode these to UK format in specific loactions using:

```<code><UserControl ... Language="en-GB"...>
</code>```

But as I'm sure you'd all agree this is a terrible thing to do.

I have tried setting the Lanaguage to en-GB in the main application and this has partial success. I have also tried Justin Angels suggestion (posted here: How to change date format in Silverlight DatePicker control?), again only partial success.

An example of the issue can be seen here:

http://lh3.ggpht.com/%5FL9TmtwXFtew/Sw5aVZJfG1I/AAAAAAAAGkI/6jYnsB91HjI/image%5Fthumb%5B1%5D.png http://lh3.ggpht.com/%5FL9TmtwXFtew/Sw5aVZJfG1I/AAAAAAAAGkI/6jYnsB91HjI/image%5Fthumb%5B1%5D.png

The datagrid on the parent page shows UK formatting, whilst the information in the ChildWindow shows US formatting ...grrrr

Anyone have a definitive solution for solving this across a whole application?

Thanks,
Mark

答:
You can data bind Language property of the root visual element. Take a look at my question here:

How to switch UI Culture of data binding on the fly in Silverlight

Title: Silverlight Date Formats

Body:
I'm getting some very strange date formatting issues in my Silverlight application. My local culture is set to UK, yet I am consistently seeing US dates popping up all over the place. I can easily hardcode these to UK format in specific loactions using:

<UserControl ... Language="en-GB"...>

But as I'm sure you'd all agree this is a terrible thing to do.

I have tried setting the Lanaguage to en-GB in the main application and this has partial success. I have also tried Justin Angels suggestion (posted here: How to change date format in Silverlight DatePicker control?), again only partial success.

An example of the issue can be seen here:

http://lh3.ggpht.com/%5FL9TmtwXFtew/Sw5aVZJfG1I/AAAAAAAAGkI/6jYnsB91HjI/image%5Fthumb%5B1%5D.png http://lh3.ggpht.com/%5FL9TmtwXFtew/Sw5aVZJfG1I/AAAAAAAAGkI/6jYnsB91HjI/image%5Fthumb%5B1%5D.png

The datagrid on the parent page shows UK formatting, whilst the information in the ChildWindow shows US formatting ...grrrr

Anyone have a definitive solution for solving this across a whole application?

Thanks,
Mark


问:
How to add anchor links when links as well sections are populated using PageableListView? How will I get the "id" to which my link should point to?
Editing the question to provide the code.

HTML:-

```<code><a href=""><div wicket:id="awardLink_"></div></a>
</code>```

JAVA:

final   PageableListView awardLinksList = new PageableListView("awardLinksList_",
                AwardList, 10) {

```<code>        private static final long serialVersionUID = 1L;

        @SuppressWarnings({ "serial", "unchecked", "unchecked" })
        @Override
        protected void populateItem(ListItem item) {
            final BLL_Docs StkList = (BLL_Docs) item
                    .getModelObject();
            item.add(new Label("awardLink_",StkList.getAwardName()==null?"NA":StkList.getAwardName()));
            }

    };
</code>```

The above code will provide 4-5 list of awards which will be generated using pageablelistview
Ex:Bharat Ratna, Padma Bhushan, Padma Vibhushan.

Description of each award will be generated through

HTML:-

```<code><div wicket:id="lblFarmerBio" class="control-label2"></div>
</code>```

JAVA:

final
        PageableListView awdDisplay = new PageableListView("listView_",
                ImgList, 10) {

```<code>        private static final long serialVersionUID = 1L;

        @SuppressWarnings({ "serial", "unchecked", "unchecked" })
        @Override
        protected void populateItem(ListItem item) {
            final BLL_Docs StkList = (BLL_Docs) item
                    .getModelObject();

            item.add(new Label("lblFarmerBio",StkList.getFarmerBio()==null?"NA":StkList.getFarmerBio()));

            }

    };
</code>```

When I click on link Bharat Ratna, it should focus on the part which provided description of Bharat Ratna.

答:
Since You need more information I have added one more answer:

```<code>//I guess you model like this
public class BLL_Docs implements Serializable{
    private Integer id;
    private String awardName;
    private String awardinfo;

    public BLL_Docs(Integer id, String awardName, String awardinfo) {
        this.id = id;
        this.awardName = awardName;
        this.awardinfo = awardinfo;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAwardName() {
        return awardName;
    }

    public void setAwardName(String awardName) {
        this.awardName = awardName;
    }

    public String getAwardinfo() {
        return awardinfo;
    }

    public void setAwardinfo(String awardinfo) {
        this.awardinfo = awardinfo;
    }
}
</code>```

Html page

```<code><html xmlns:wicket="http://wicket.apache.org">
<head>
    <meta charset="utf-8"/>
    <title>Apache Wicket Quickstart</title>
    <link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:regular,bold' rel='stylesheet'
          type='text/css'/>
</head>
<body>

<wicket:container wicket:id="awardList">
<a  wicket:id="awardNameLink"><label wicket:id="awardName"></label></a><br>
</wicket:container>

<wicket:container wicket:id="awardDescriptionList">
<p wicket:id="description"></p>
</wicket:container>

</body>
</html>
</code>```

Java Page:

```<code>//Im considering your object like this
        List<BLL_Docs> awardList = new ArrayList<>();
        BLL_Docs bll_docs1 = new BLL_Docs(1, "Bharat Ratna", "The Bharat Ratna is the highest civilian award of the Republic of India.");
        BLL_Docs bll_docs2 = new BLL_Docs(2, "Padma Bhushan", "The Padma Bhushan is the highest civilian award of the Republic of India.");
        BLL_Docs bll_docs3 = new BLL_Docs(3, "Padma Vibhushan", "The Padma Vibhushan is the highest civilian award of the Republic of India.");

        awardList.add(bll_docs1);
        awardList.add(bll_docs2);
        awardList.add(bll_docs3);

        PageableListView<BLL_Docs> awardLinksList = new PageableListView("awardList", awardList, 10) {

            @Override
            protected void populateItem(ListItem item) {
                BLL_Docs bll_docs = (BLL_Docs) item.getModelObject();
                Link awardNameLink = new Link("awardNameLink") {
                    @Override
                    public void onClick() {
                    }
                };
                awardNameLink.add(new AttributeModifier("href","#"+bll_docs.getAwardName()));
                 Label awardName = new Label("awardName" ,bll_docs.getAwardName());
                awardNameLink.add(awardName);
                item.add(awardNameLink);
            }
        };

        PageableListView<BLL_Docs> describtionList = new PageableListView("awardDescriptionList", awardList, 10) {

            @Override
            protected void populateItem(ListItem item) {
                BLL_Docs bll_docs = (BLL_Docs) item.getModelObject();
                Label description = new Label("description",bll_docs.getAwardinfo());
                description.add(new AttributeModifier("id",bll_docs.getAwardName()));
                item.add(description);
            }
        };
         add(describtionList);
        add(awardLinksList);
    }
</code>```

I have successfully tested this working fine.While testing add more description and test .

Body:
Editing the question to provide the code.

HTML:-

JAVA:

final   PageableListView awardLinksList = new PageableListView("awardLinksList_",
                AwardList, 10) {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings({ "serial", "unchecked", "unchecked" })
        @Override
        protected void populateItem(ListItem item) {
            final BLL_Docs StkList = (BLL_Docs) item
                    .getModelObject();
            item.add(new Label("awardLink_",StkList.getAwardName()==null?"NA":StkList.getAwardName()));
            }

    };

The above code will provide 4-5 list of awards which will be generated using pageablelistview
Ex:Bharat Ratna, Padma Bhushan, Padma Vibhushan.

Description of each award will be generated through

HTML:-

JAVA:

final
        PageableListView awdDisplay = new PageableListView("listView_",
                ImgList, 10) {

        private static final long serialVersionUID = 1L;

        @SuppressWarnings({ "serial", "unchecked", "unchecked" })
        @Override
        protected void populateItem(ListItem item) {
            final BLL_Docs StkList = (BLL_Docs) item
                    .getModelObject();

            item.add(new Label("lblFarmerBio",StkList.getFarmerBio()==null?"NA":StkList.getFarmerBio()));

            }

    };

When I click on link Bharat Ratna, it should focus on the part which provided description of Bharat Ratna.

Body:
Since You need more information I have added one more answer:

//I guess you model like this
public class BLL_Docs implements Serializable{
    private Integer id;
    private String awardName;
    private String awardinfo;

    public BLL_Docs(Integer id, String awardName, String awardinfo) {
        this.id = id;
        this.awardName = awardName;
        this.awardinfo = awardinfo;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAwardName() {
        return awardName;
    }

    public void setAwardName(String awardName) {
        this.awardName = awardName;
    }

    public String getAwardinfo() {
        return awardinfo;
    }

    public void setAwardinfo(String awardinfo) {
        this.awardinfo = awardinfo;
    }
}

Html page

<html xmlns:wicket="http://wicket.apache.org">
<head>
    <meta charset="utf-8"/>
    <title>Apache Wicket Quickstart</title>
    <link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:regular,bold' rel='stylesheet'
          type='text/css'/>
</head>
<body>

<wicket:container wicket:id="awardList">
<a  wicket:id="awardNameLink"><label wicket:id="awardName"></label></a><br>
</wicket:container>

<wicket:container wicket:id="awardDescriptionList">
<p wicket:id="description"></p>
</wicket:container>

</body>
</html>

Java Page:

//Im considering your object like this
        List<BLL_Docs> awardList = new ArrayList<>();
        BLL_Docs bll_docs1 = new BLL_Docs(1, "Bharat Ratna", "The Bharat Ratna is the highest civilian award of the Republic of India.");
        BLL_Docs bll_docs2 = new BLL_Docs(2, "Padma Bhushan", "The Padma Bhushan is the highest civilian award of the Republic of India.");
        BLL_Docs bll_docs3 = new BLL_Docs(3, "Padma Vibhushan", "The Padma Vibhushan is the highest civilian award of the Republic of India.");

        awardList.add(bll_docs1);
        awardList.add(bll_docs2);
        awardList.add(bll_docs3);

        PageableListView<BLL_Docs> awardLinksList = new PageableListView("awardList", awardList, 10) {

            @Override
            protected void populateItem(ListItem item) {
                BLL_Docs bll_docs = (BLL_Docs) item.getModelObject();
                Link awardNameLink = new Link("awardNameLink") {
                    @Override
                    public void onClick() {
                    }
                };
                awardNameLink.add(new AttributeModifier("href","#"+bll_docs.getAwardName()));
                 Label awardName = new Label("awardName" ,bll_docs.getAwardName());
                awardNameLink.add(awardName);
                item.add(awardNameLink);
            }
        };

        PageableListView<BLL_Docs> describtionList = new PageableListView("awardDescriptionList", awardList, 10) {

            @Override
            protected void populateItem(ListItem item) {
                BLL_Docs bll_docs = (BLL_Docs) item.getModelObject();
                Label description = new Label("description",bll_docs.getAwardinfo());
                description.add(new AttributeModifier("id",bll_docs.getAwardName()));
                item.add(description);
            }
        };
         add(describtionList);
        add(awardLinksList);
    }

I have successfully tested this working fine.While testing add more description and test .


问:
Jquery function optimalize (slick slider)
I made a slick slider with some filter functions.

Everything works, but my functions for the filters are not as efficient as I want them to be.
Does anyone know of a way to make it efficient?

```<code>// init Isotope
var slickoptions = {
      rows: 2,
      dots: true,
      appendDots: $('.slick-nav'),
      appendArrows: $('.slick-nav'),
      accessibility: true,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      infinite: false,
}

$(document).ready(function () {
  $('.slider2').slick(slickoptions);

  var slider = $('.slider2');
  var allSlides = $('.slick-slide > div > *').clone();
  var trigger = $('js-filter');

  $('.filter-all').on('click', function () {
        $('.active').removeClass('active');
        $('.filter-all').addClass('active');
        var filterSlides = allSlides.filter('*');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
  });

    $('.js-filter[data-filter=".category-website"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-website"]').addClass('active');
        var filterSlides = allSlides.filter('.category-website');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-webshop"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-webshop"]').addClass('active');
        var filterSlides = allSlides.filter('.category-webshop');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-drukwerk"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-drukwerk"]').addClass('active');
        var filterSlides = allSlides.filter('.category-drukwerk');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-videos"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-videos"]').addClass('active');
        var filterSlides = allSlides.filter('.category-videos');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-bestaat-niet"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-bestaat-niet"]').addClass('active');
        var filterSlides = allSlides.filter('.category-bestaat-niet');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

});
</code>```

http://codepen.io/Pondake/pen/vxVQam

答:
Just in case you don't need every filter to be used in the logic and only need particular defined ones (as seen in the switch).</p>

```<code> $('.js-filter').on('click', function () {
   $('.active').removeClass('active');
   var filterSlides;

   switch($(this).data("filter")) {
      case ".category-website":
          filterSlides = runSlideLogic(".category-website");
          break;
       // rest of them here
   }

   slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
});

function runSlideLogic(className) {
   $('.js-filter[data-filter="' + className + '"]').addClass('active');
   return allSlides.filter(className);
}
</code>```

Body:
I made a slick slider with some filter functions.

Everything works, but my functions for the filters are not as efficient as I want them to be.
Does anyone know of a way to make it efficient?

// init Isotope
var slickoptions = {
      rows: 2,
      dots: true,
      appendDots: $('.slick-nav'),
      appendArrows: $('.slick-nav'),
      accessibility: true,
      speed: 300,
      slidesToShow: 3,
      slidesToScroll: 3,
      infinite: false,
}

$(document).ready(function () {
  $('.slider2').slick(slickoptions);

  var slider = $('.slider2');
  var allSlides = $('.slick-slide > div > *').clone();
  var trigger = $('js-filter');

  $('.filter-all').on('click', function () {
        $('.active').removeClass('active');
        $('.filter-all').addClass('active');
        var filterSlides = allSlides.filter('*');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
  });

    $('.js-filter[data-filter=".category-website"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-website"]').addClass('active');
        var filterSlides = allSlides.filter('.category-website');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-webshop"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-webshop"]').addClass('active');
        var filterSlides = allSlides.filter('.category-webshop');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-drukwerk"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-drukwerk"]').addClass('active');
        var filterSlides = allSlides.filter('.category-drukwerk');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-videos"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-videos"]').addClass('active');
        var filterSlides = allSlides.filter('.category-videos');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

    $('.js-filter[data-filter=".category-bestaat-niet"]').on('click', function () {
        $('.active').removeClass('active');
        $('.js-filter[data-filter=".category-bestaat-niet"]').addClass('active');
        var filterSlides = allSlides.filter('.category-bestaat-niet');
        slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
    });

});

http://codepen.io/Pondake/pen/vxVQam

Body:
Just in case you don't need every filter to be used in the logic and only need particular defined ones (as seen in the switch).

 $('.js-filter').on('click', function () {
   $('.active').removeClass('active');
   var filterSlides;

   switch($(this).data("filter")) {
      case ".category-website":
          filterSlides = runSlideLogic(".category-website");
          break;
       // rest of them here
   }

   slider.slick('unslick').empty().append(filterSlides).slick(slickoptions);
});

function runSlideLogic(className) {
   $('.js-filter[data-filter="' + className + '"]').addClass('active');
   return allSlides.filter(className);
}


问:
Is html title attribute a toolip?
I have question to know the truth. can some one tell me is HTML title attribute a tool tip.
Someone told me it is not a tooltip.
Can anybody describe what is a tool tip?
and HTML title is it or not?
I need the truth pleas.

答:
Html title attribute is not tool-tip but on hover of the element we can see the title the element

For Eg:

ABCD INFO

so we will get output as

enter image description here

Title: Is html title attribute a toolip?


问:
Using knockout js with jquery ui sliders
I'm trying to figure out if knockout js would work nicely for the following problem:

I have multiple sliders that I want to link to textboxes.

When the textbox is changed the corresponding slider must update to the new value and vice versa.

On changing the slider value or textbox a function needs to be called that uses the input from all textboxes to calculate a result.

I have my quick and dirty jQuery solution here.

Would it be easy to achieve the same result in a more elegant way using knockout js?

I guess I would need to create a custom binding handler like its done in jQuery UI datepicker change event not caught by KnockoutJS

答:
Thanks so much for the help, I needed to use a range slider in my scenario so here is an extension to @John Earles and @Michael Kire Hansen

```<code>ko.bindingHandlers.sliderRange = {
init: function (element, valueAccessor, allBindingsAccessor) {
    var options = allBindingsAccessor().sliderOptions || {};
    $(element).slider(options);
    ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
        var observable = valueAccessor();
        observable.Min(ui.values[0]);
        observable.Max(ui.values[1]);
    });
    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
        $(element).slider("destroy");
    });
    ko.utils.registerEventHandler(element, "slide", function (event, ui) {
        var observable = valueAccessor();
        observable.Min(ui.values[0]);
        observable.Max(ui.values[1]);
    });
},
update: function (element, valueAccessor, allBindingsAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    if (isNaN(value.Min())) value.Min(0);
    if (isNaN(value.Max())) value.Max(0);

    $(element).slider("option", allBindingsAccessor().sliderOptions);
    $(element).slider("values", 0, value.Min());
    $(element).slider("values", 1, value.Max());
}
};
</code>```

and then the HTML to accompany it

```<code><div id="slider-range"
             data-bind="sliderRange: { Min: 0, Max: 100 },
                                sliderOptions: {
                                    range: true,
                                    min: 0,
                                    max: 100,
                                    step: 10,
                                    values: [0, 100]
                                }"></div>
</code>```

Body:
Thanks so much for the help, I needed to use a range slider in my scenario so here is an extension to @John Earles and @Michael Kire Hansen

ko.bindingHandlers.sliderRange = {
init: function (element, valueAccessor, allBindingsAccessor) {
    var options = allBindingsAccessor().sliderOptions || {};
    $(element).slider(options);
    ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
        var observable = valueAccessor();
        observable.Min(ui.values[0]);
        observable.Max(ui.values[1]);
    });
    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
        $(element).slider("destroy");
    });
    ko.utils.registerEventHandler(element, "slide", function (event, ui) {
        var observable = valueAccessor();
        observable.Min(ui.values[0]);
        observable.Max(ui.values[1]);
    });
},
update: function (element, valueAccessor, allBindingsAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    if (isNaN(value.Min())) value.Min(0);
    if (isNaN(value.Max())) value.Max(0);

    $(element).slider("option", allBindingsAccessor().sliderOptions);
    $(element).slider("values", 0, value.Min());
    $(element).slider("values", 1, value.Max());
}
};

and then the HTML to accompany it

<div id="slider-range"
             data-bind="sliderRange: { Min: 0, Max: 100 },
                                sliderOptions: {
                                    range: true,
                                    min: 0,
                                    max: 100,
                                    step: 10,
                                    values: [0, 100]
                                }"></div>


问:
Load selected/active tab content in view pager
I'm having a view pager in an application which is dynamically populated based on content available on server i.e tabs in view pager is variable. To do this I have created a single fragment which is binds to each tabs inside view pager.

I have populated viewpager like this:

```<code>
    List lstFragments = lstFragments = new ArrayList();
    lstFragments.add(DetailsFragment.newInstance(cat.getId(), subcategoryId, cat.getName(), subcategoryName, subcategoryIconUrl));
    DetailsTabsAdapter pageAdapter = new DetailsTabsAdapter(getChildFragmentManager(), lstFragments);

    viewPager.setAdapter(pageAdapter);

</code>```

By default viewpager has property that its load content for one previous and one next fragment, but I don't want this.

What I want to achieve:

Load content of only selected/active tab.

At the same time once content is loaded for that tab I don't want to
load it again from server if user comes back.

How to achieve above functionality?

What I have did to achieve this:

I have loaded content from server in fragment's public View
onCreateView() lifecycle event. Content is loading fine but it
loads content for other tab as well.

Then I tried viewPager.setOffscreenPageLimit(0). But it also not working.

Please help me out to resolve this.
Thanks

答:
There is a method called setUserVisibleHint() you can override it in your Frament. Which is called when the Fragment is visible. Now you can call the service to load data inside that method. And at the same time in the same method check for data if it is already loaded (saved in db) then call the service otherwise load the data from saved once.

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    // check if fragment is visible
    if (isVisibleToUser) {

    if(mdata == null){
    callService();
    } else{
    loadFromSavedDB();
    }
 }
}
</code>```

Body:
I'm having a view pager in an application which is dynamically populated based on content available on server i.e tabs in view pager is variable. To do this I have created a single fragment which is binds to each tabs inside view pager.

I have populated viewpager like this:

    List lstFragments = lstFragments = new ArrayList();
    lstFragments.add(DetailsFragment.newInstance(cat.getId(), subcategoryId, cat.getName(), subcategoryName, subcategoryIconUrl));
    DetailsTabsAdapter pageAdapter = new DetailsTabsAdapter(getChildFragmentManager(), lstFragments);

    viewPager.setAdapter(pageAdapter);

By default viewpager has property that its load content for one previous and one next fragment, but I don't want this.

What I want to achieve:

Load content of only selected/active tab.

At the same time once content is loaded for that tab I don't want to
load it again from server if user comes back.

How to achieve above functionality?

What I have did to achieve this:

I have loaded content from server in fragment's public View
onCreateView() lifecycle event. Content is loading fine but it
loads content for other tab as well.

Then I tried viewPager.setOffscreenPageLimit(0). But it also not working.

Please help me out to resolve this.
Thanks

Body:
There is a method called setUserVisibleHint() you can override it in your Frament. Which is called when the Fragment is visible. Now you can call the service to load data inside that method. And at the same time in the same method check for data if it is already loaded (saved in db) then call the service otherwise load the data from saved once.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    // check if fragment is visible
    if (isVisibleToUser) {

    if(mdata == null){
    callService();
    } else{
    loadFromSavedDB();
    }
 }
}


问:
Best approach to store and retrieve files?
I'm developing an application using C# 4.0 and SQL Server 2008 R2 Express, my application needs to store and retrieve files (docx, pdf, png) locally and remotely, which approach would be the best?

Store the files in separate database (problem: restricted to 10 GB)

Use a windows shared folder (who to do?)

Use an FTP server (which server and library and how to do?)

答:
SQL Server supports FILESTREAM, so if you have enough control over the SQL Server install to enable that feature then it seems like a good fit for you.

FILESTREAM integrates the SQL Server Database Engine with an NTFS file system by storing varbinary(max) binary large object (BLOB) data as files on the file system. Transact-SQL statements can insert, update, query, search, and back up FILESTREAM data. Win32 file system interfaces provide streaming access to the data.

Files stored directly in the file system with FILESTREAM don't count towards the database size because they aren't stored in the DB.

To confirm with an official source: https://learn.microsoft.com/en-us/sql/relational-databases/blob/filestream-compatibility-with-other-sql-server-features

SQL Server Express supports FILESTREAM. The 10-GB database size limit does not include the FILESTREAM data container.


问:
replace multiple spaces by non breaking spaces
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

```<code>"This is     my text."
</code>```

Should be converted into

```<code>"This is     my text."
</code>```

答:
What you need to do is use Regex Lookahead & Lookbehind like so:

Like so:

```<code><?php
echo preg_replace("/\s(?=\s+)|(?<=\s)\s/", " ", "Welcome to stack       overflow");
</code>```

Outputs

```<code>Welcome to stack       overflow
</code>```

Test it here: https://regex101.com/r/DGraSS/1 - provides good explications :)

Body:
How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

"This is     my text."

Should be converted into

"This is     my text."

Body:
What you need to do is use Regex Lookahead & Lookbehind like so:

Like so:

<?php
echo preg_replace("/\s(?=\s+)|(?<=\s)\s/", "&nbsp;", "Welcome to stack       overflow");

Outputs

Welcome to stack&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;overflow

Test it here: https://regex101.com/r/DGraSS/1 - provides good explications :)


问:
Microsoft JDBC and Datetime2 - rounding issue
From our application we create a java.sql.Timestamp like this:

```<code>Timestamp currentTimeStamp = new Timestamp(System.currentTimeMillis());
currentTimeStamp.setNanos((int) (System.nanoTime() % 1000000000));
</code>```

And then use this as column value in a distributed transaction against a DB2 and MSSQL.

DB2 strips off the digits it cannot use and stores the remaining.

MSSQL rounds the digits and stores the value.

The problem then becomes that the timestamp value is different in the two databases even though they both have the same fraction digits of 6.

Example reproduced using pure T-SQL:

```<code>DECLARE @t TABLE(x DATETIME2(6))
INSERT @t SELECT '2017-03-28 14:00:59.4106489'
SELECT x FROM @t
</code>```

Result:
2017-03-28 14:00:59.410649

Expected:
2017-03-28 14:00:59.410648

答:
The issue that MSSQL Character length is 19 positions minimum to 23 maximum
because of that it rounded it to be at maximum 23 Character
This is the case</p>

Body:
From our application we create a java.sql.Timestamp like this:

Timestamp currentTimeStamp = new Timestamp(System.currentTimeMillis());
currentTimeStamp.setNanos((int) (System.nanoTime() % 1000000000));

And then use this as column value in a distributed transaction against a DB2 and MSSQL.

DB2 strips off the digits it cannot use and stores the remaining.

MSSQL rounds the digits and stores the value.

The problem then becomes that the timestamp value is different in the two databases even though they both have the same fraction digits of 6.

Example reproduced using pure T-SQL:

DECLARE @t TABLE(x DATETIME2(6))
INSERT @t SELECT '2017-03-28 14:00:59.4106489'
SELECT x FROM @t

Result:
2017-03-28 14:00:59.410649

Expected:
2017-03-28 14:00:59.410648


答:
In you fragment call this</p>

```<code> @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //Do what you want here`enter code here`

        }
    }
</code>```

Title: Load selected/active tab content in view pager

Body:
In you fragment call this

 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //Do what you want here`enter code here`

        }
    }


问:
UIImage as Representation but no file extension
I want to convert an image to either

```<code>UIImagePNGRepresentation
UIImageJPEGRepresentation
</code>```

however I do not know the file type. I've just got a URL with no extension. Is there anyway to save the image from the URL to the filesystem?

```<code>// got the data from the URL

let imageData = UIImage(data: data!)

// now I want to write to the filesystem but only way was with a representation as UIImage has no write

if let saveImageData = UIImageXXXXXXRepresentation(imageData!) {
try saveImageData.write(to: URL(fileURLWithPath: localFilename), options: [.atomic])
}
</code>```

答:
Get the imageData from URL and then check the image type as below from that data object

Swift 3

```<code>let data: Data = UIImagePNGRepresentation(yourImage)!

extension Data {
    var format: String {
        let array = [UInt8](self)
        let ext: String
        switch (array[0]) {
        case 0xFF:
            ext = "jpg"
        case 0x89:
            ext = "png"
        case 0x47:
            ext = "gif"
        case 0x49, 0x4D :
            ext = "tiff"
        default:
            ext = "unknown"
        }
        return ext
    }
}
</code>```

Objective C

```<code>+ (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];

    switch (c) {
    case 0xFF:
        return @"image/jpeg";
    case 0x89:
        return @"image/png";
    case 0x47:
        return @"image/gif";
    case 0x49:
    case 0x4D:
        return @"image/tiff";
    }
    return nil;
}
</code>```

After checking above you can store the image with selected extension

For getting extension from data you can check from here also

Body:
I want to convert an image to either

UIImagePNGRepresentation
UIImageJPEGRepresentation

however I do not know the file type. I've just got a URL with no extension. Is there anyway to save the image from the URL to the filesystem?

// got the data from the URL

let imageData = UIImage(data: data!)

// now I want to write to the filesystem but only way was with a representation as UIImage has no write

if let saveImageData = UIImageXXXXXXRepresentation(imageData!) {
try saveImageData.write(to: URL(fileURLWithPath: localFilename), options: [.atomic])
}

Body:
Get the imageData from URL and then check the image type as below from that data object

Swift 3

let data: Data = UIImagePNGRepresentation(yourImage)!

extension Data {
    var format: String {
        let array = [UInt8](self)
        let ext: String
        switch (array[0]) {
        case 0xFF:
            ext = "jpg"
        case 0x89:
            ext = "png"
        case 0x47:
            ext = "gif"
        case 0x49, 0x4D :
            ext = "tiff"
        default:
            ext = "unknown"
        }
        return ext
    }
}

Objective C

+ (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];

    switch (c) {
    case 0xFF:
        return @"image/jpeg";
    case 0x89:
        return @"image/png";
    case 0x47:
        return @"image/gif";
    case 0x49:
    case 0x4D:
        return @"image/tiff";
    }
    return nil;
}

After checking above you can store the image with selected extension

For getting extension from data you can check from here also


问:
OpenCV / Python : Fast way to match a picture with a database
I would like to match a picture with a database which contains more than 2500 pictures at the moment, but I need to find a way to get good results with at least 10k pictures.

I already read a lot of posts on stackoverflow but I couldn't find a proper solution to my problem.
I thought about using histograms, but if I understand well, it is useful to find similarities, however I need a 'perfect' match.

I currently have some code working to do the task, but it is too slow (about 6 seconds to find a match with 2500 images)

I'm using ORB detector cv2.ORB() to find keypoints and descriptors, FlannBasedMatcher and findHomography function with RANSAC as you can see below.

```<code>FLANN_INDEX_LSH = 6
flann_params = dict(algorithm = FLANN_INDEX_LSH, table_number = 6, key_size = 12, multi_probe_level = 1)
...
self.matcher = cv2.FlannBasedMatcher(params, {})
...
(_, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, 4.0)
</code>```

I want to know if there is a better, and more important, a faster way to match with my database, and maybe a different way to store pictures in a database (I'm currently saving keypoints and descriptors).

I hope I was clear enough, if you need more details, post in comments.

答:
The point of what I am doing is to recognize a page from a book on a video capture, that's why I needed my code to be fast, and accurate.

I found a faster way to do the job, I built a FLANN index with the whole database at startup (which is not that slow with 3k pictures), I got help from this link.
Also, and that's the most important part, I changed my flann_params to this :

```<code>flann_params = dict(algorithm = FLANN_INDEX_LSH, table_number = 10, key_size = 20, multi_probe_level = 0)
</code>```

In order to not lose accuracy with these parameters, I changed the number of feature points I extract with ORB detector from 400 to 700.

It fixed my problem, before the match was done between 2 and 3 seconds (6 seconds without FLANN index), now it is around 25/30ms

But even after this solution, I'm still open to new suggestions to improve accuracy without losing much speed.

Body:
I would like to match a picture with a database which contains more than 2500 pictures at the moment, but I need to find a way to get good results with at least 10k pictures.

I already read a lot of posts on stackoverflow but I couldn't find a proper solution to my problem.
I thought about using histograms, but if I understand well, it is useful to find similarities, however I need a 'perfect' match.

I currently have some code working to do the task, but it is too slow (about 6 seconds to find a match with 2500 images)

I'm using ORB detector cv2.ORB() to find keypoints and descriptors, FlannBasedMatcher and findHomography function with RANSAC as you can see below.

FLANN_INDEX_LSH = 6
flann_params = dict(algorithm = FLANN_INDEX_LSH, table_number = 6, key_size = 12, multi_probe_level = 1)
...
self.matcher = cv2.FlannBasedMatcher(params, {})
...
(_, status) = cv2.findHomography(ptsA, ptsB, cv2.RANSAC, 4.0)

I want to know if there is a better, and more important, a faster way to match with my database, and maybe a different way to store pictures in a database (I'm currently saving keypoints and descriptors).

I hope I was clear enough, if you need more details, post in comments.

Body:
The point of what I am doing is to recognize a page from a book on a video capture, that's why I needed my code to be fast, and accurate.

I found a faster way to do the job, I built a FLANN index with the whole database at startup (which is not that slow with 3k pictures), I got help from this link.
Also, and that's the most important part, I changed my flann_params to this :

flann_params = dict(algorithm = FLANN_INDEX_LSH, table_number = 10, key_size = 20, multi_probe_level = 0)

In order to not lose accuracy with these parameters, I changed the number of feature points I extract with ORB detector from 400 to 700.

It fixed my problem, before the match was done between 2 and 3 seconds (6 seconds without FLANN index), now it is around 25/30ms

But even after this solution, I'm still open to new suggestions to improve accuracy without losing much speed.


问:
How to create inshorts like notifications for android
How to create inshorts like push notifications for andriod. The notifications include full image with text at the bottom of the notification.

The small notification is just the text but while u expand it, it shows the image in background with text at bottom.

Can some one please help me with this. Below are the screenshots

答:
PFB the screenshot of the notification having padding at top and bottom.
Test 62 is the notification message, it is coming in the white space. I want it to come on top of image at the bottom.

ContentLicense: CC BY-SA 4.0


问:
Finding the address range of the data segment
As a programming exercise, I am writing a mark-and-sweep garbage collector in C. I wish to scan the data segment (globals, etc.) for pointers to allocated memory, but I don't know how to get the range of the addresses of this segment. How could I do this?</p>

答: Load the file that the executable came from and parse the PE headers, for Win32. I've no idea about on other OSes. Remember that if your program consists of multiple files (e.g. DLLs) you may have multiple data segments.</p>


问:
OpenERP 7 disable manual entry on date control
I understand that OpenERP 7 is outdated and no longer has any support

but as this question is important I need to ask it here
I am new to OpenERP 7 and we hired a freelancer to do some work for us

we needed the date of the entry to be limited to today, yesterday and the day before it

The freelancer did limit it though the selection but if the user types the date manually, it will still accept the entry

I mentioned to him this loophole and how it would make problems for us, but he claims that he would need to change a js file and it would be hard to accomplish

I took his word but my manager wants to confirm that I have not been tricked hence, this question

So, how possible is it to accomplish the mentioned above?

答:
What you are looking for is absolutely possible.
You can use onchange or _constraints for this :

If you want to check a condition  on the fly you can use onchange or if you want to check a condition at the time of save you can use _constraints .

Examples:

```<code>    def _check_duration(self, cr, uid, ids, context=None):
    for obj_ac in self.browse(cr, uid, ids, context=context):
        if obj_ac.date_stop < obj_ac.date_start:
            return False
    return True

_constraints = [
    (_check_duration, _('Error! The duration of the academic year is invalid.'), ['date_stop']),
]

    def onchange_date(self, cr, uid, ids, date, context=None):
    if date:
        if Condition Here:
            warning = "Your text"
            return {'value':{'date': None}, 'warning':warning}
        else:
            return {}
</code>```

Hope this helps.

Body:
What you are looking for is absolutely possible.
You can use onchange or _constraints for this :

If you want to check a condition  on the fly you can use onchange or if you want to check a condition at the time of save you can use _constraints .

Examples:

    def _check_duration(self, cr, uid, ids, context=None):
    for obj_ac in self.browse(cr, uid, ids, context=context):
        if obj_ac.date_stop < obj_ac.date_start:
            return False
    return True

_constraints = [
    (_check_duration, _('Error! The duration of the academic year is invalid.'), ['date_stop']),
]

    def onchange_date(self, cr, uid, ids, date, context=None):
    if date:
        if Condition Here:
            warning = "Your text"
            return {'value':{'date': None}, 'warning':warning}
        else:
            return {}

Hope this helps.


问:
Wrong symfony configuration
I have a problem with configuration of my project and I can't see where is the mistake...

AppKernel.php
    ...

```<code>class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            ...
            new CMS\CoreBundle\CMSCoreBundle(),
        ];
</code>```

app/config/routing.yml

```<code>cms_core:
    resource: "@CMSCoreBundle/Resources/config/routing.yml"
    prefix:   /
</code>```

src/CMS/CoreBundle/Resourcers/config/routing.yml

```<code>cms_core_homepage:
    path:     /
    defaults: { _controller: CMSCoreBundle:Default:index }
</code>```

src/CMS/CoreBundle/Resources/views/index.html.twig

```<code>{% extends "@CMSCoreBundle/template.html.twig" %}

{% block content %}
test
{% endblock %}
</code>```

src/CMS/CoreBundle/Resources/views/template.html.twig

```<code>{% block content %}
Template block
{% endblock %}
</code>```

And I'm getting this message

There are no registered paths for namespace "CMSCoreBundle" in CMSCoreBundle::index.html.twig at line 1.

Where is the mistake please ?
Thank you guys.

答:
I think you have 2 ways to fix it.

you can add your bundle to the path

```<code>#app/config/config.yml
twig:
    paths:
        "%kernel.root_dir%/../src/CMS/CoreBundle/Resources/views/": CMSCoreBundle
</code>```

Or try to extend your template like that

```<code>{% extends "CMSCoreBundle:template.html.twig" %}
</code>```

I'm not 100% sure for the 2nd solution.

Hope it may helps you

Title: Wrong symfony configuration

Body:
I have a problem with configuration of my project and I can't see where is the mistake...

AppKernel.php
    ...

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            ...
            new CMS\CoreBundle\CMSCoreBundle(),
        ];

app/config/routing.yml

cms_core:
    resource: "@CMSCoreBundle/Resources/config/routing.yml"
    prefix:   /

src/CMS/CoreBundle/Resourcers/config/routing.yml

cms_core_homepage:
    path:     /
    defaults: { _controller: CMSCoreBundle:Default:index }

src/CMS/CoreBundle/Resources/views/index.html.twig

{% extends "@CMSCoreBundle/template.html.twig" %}

{% block content %}
test
{% endblock %}

src/CMS/CoreBundle/Resources/views/template.html.twig

{% block content %}
Template block
{% endblock %}

And I'm getting this message

There are no registered paths for namespace "CMSCoreBundle" in CMSCoreBundle::index.html.twig at line 1.

Where is the mistake please ?
Thank you guys.

Body:
I think you have 2 ways to fix it.

you can add your bundle to the path

#app/config/config.yml
twig:
    paths:
        "%kernel.root_dir%/../src/CMS/CoreBundle/Resources/views/": CMSCoreBundle

Or try to extend your template like that

{% extends "CMSCoreBundle:template.html.twig" %}

I'm not 100% sure for the 2nd solution.

Hope it may helps you


问:
Spock interaction does not work if defined with 'as'
I've written the following specification:

```<code>class Spec extends Specification {

    def 'does not work if interaction declared as Set without parens'() {
        given:
        def holder = Mock(Holder)
        def expected = [1, 2, 3, 3]

        when:
        def output = holder.value()

        then:
        output == [1, 2, 3] as Set
//        1 * holder.value() >> expected.toSet()      // 1
        1 * holder.value() >> expected as Set       // 2
//        1 * holder.value() >> (expected as Set)     // 3
    }

    class Holder {
        def value() {
        }
    }
}
</code>```

The problem lies in the fact that it works only if holder.value() interaction is defined as in line 1 or 3. When it's defined like in the line 2 it fails with the following error:

```<code>Condition not satisfied:

output == [1, 2, 3] as Set
|      |
null   false
</code>```

Why? It seems that there might be some parser error.

答:
There is no parser error but you made a programming error. According to the rules of Groovy operator precedence >> has a higher precedence than as, which effectively makes your faulty code equivalent to

((1 * holder.value()) >> expected) as Set
```

Spock implements a DSL for testing, but the code is still Groovy. ;-)

Body:
I've written the following specification:

class Spec extends Specification {

    def 'does not work if interaction declared as Set without parens'() {
        given:
        def holder = Mock(Holder)
        def expected = [1, 2, 3, 3]

        when:
        def output = holder.value()

        then:
        output == [1, 2, 3] as Set
//        1 * holder.value() >> expected.toSet()      // 1
        1 * holder.value() >> expected as Set       // 2
//        1 * holder.value() >> (expected as Set)     // 3
    }

    class Holder {
        def value() {
        }
    }
}

The problem lies in the fact that it works only if holder.value() interaction is defined as in line 1 or 3. When it's defined like in the line 2 it fails with the following error:

Condition not satisfied:

output == [1, 2, 3] as Set
|      |
null   false

Why? It seems that there might be some parser error.

Body:
There is no parser error but you made a programming error. According to the rules of Groovy operator precedence >> has a higher precedence than as, which effectively makes your faulty code equivalent to

((1 * holder.value()) >> expected) as Set

Spock implements a DSL for testing, but the code is still Groovy. ;-)


问:
Sum up every N elements of a list?
I have a list of numbers like this:

```<code>[ 0, 1, 2, 3, 4, 5, 6, 7 ]
</code>```

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

```<code>[ 1, 5, 9, 13 ]
</code>```

edit:
I came up with the following solution:

```<code>    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);
</code>```

It works, but I'm still looking for a more readable and simple one.

答:
How about this? (I've edited to take nTh)

```<code> int nTh = 2;

    List<Integer> list = List.of(0, 1, 2, 3, 4, 5, 6, 7);

    int[] result = IntStream.iterate(0, i -> i + nTh)
            .limit(list.size() / nTh)
            .map(x -> {
                return IntStream.range(0, nTh).map(i -> list.get(i + x)).sum();
            })
            .toArray();

    System.out.println(Arrays.toString(result));
</code>```

Title: Sum up every N elements of a list?

Body:
I have a list of numbers like this:

[ 0, 1, 2, 3, 4, 5, 6, 7 ]

How to sum up every N (let's assume 2) elements in an elegant way and transform the list into:

[ 1, 5, 9, 13 ]

edit:
I came up with the following solution:

    List<Double> input = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0);
    List<Double> output = new ArrayList<>();

    int N = 2;
    IntStream.range(0, (input.size() + N - 1) / N)
            .mapToObj(i -> input.subList(i * N, Math.min(N * (i + 1), input.size())))
            .mapToDouble(l -> l.stream().mapToDouble(Double::doubleValue).sum())
            .forEach(output::add);

    System.out.println(output);

It works, but I'm still looking for a more readable and simple one.

Body:
How about this? (I've edited to take nTh)

 int nTh = 2;

    List<Integer> list = List.of(0, 1, 2, 3, 4, 5, 6, 7);

    int[] result = IntStream.iterate(0, i -> i + nTh)
            .limit(list.size() / nTh)
            .map(x -> {
                return IntStream.range(0, nTh).map(i -> list.get(i + x)).sum();
            })
            .toArray();

    System.out.println(Arrays.toString(result));