text:
Q: Ruby script crashes I have the following code that I am trying to learn from this Ruby book and it keeps crashing, I have spent hours trying to fix. If anyone has any clue why this is happening please let me know. I am not enjoying Ruby
# Define custom classes ---------------------------------------------------
#Define a class representing the console window
class Screen

  def cls  #Define a method that clears the display area
    puts ("\n" * 25)  #Scroll the screen 25 times
    puts "\a"  #Make a little noise to get the player's attention
  end

  def pause    #Define a method that pauses the display area
    STDIN.gets  #Execute the STDIN class's gets method to pause script
                #execution until the player presses the enter key
  end

end

#Define a class representing the Ruby Number Guessing Game
class Game

  #This method displays the game's opening screen
  def display_greeting

    Console_Screen.cls  #Clear the display area

    #Display welcome message
    print "\t\t  Welcome to the Ruby Number Guessing Game!" +
    "\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
               "continue."

  Console_Screen.pause       #Pause the game

  end

  #Define a method to be used to present game instructions
  def display_instructions

    Console_Screen.cls       #Clear the display area
    puts "INSTRUCTIONS:\n\n"  #Display a heading

    #Display the game's instructions
    puts "This game randomly generates a number from 1 to 100 and"
    puts "challenges you to identify it in as few guesses as possible."
    puts "After each guess, the game will analyze your input and provide"
    puts "you with feedback. You may take as many turns as you need in"
    puts "order to guess the game's secret number.\n\n"
    puts "Game will stop if you have guessed 10 times.\n\n\n"
    puts "Good luck!\n\n\n\n\n\n\n\n\n"
    print "Press Enter to continue."

    Console_Screen.pause       #Pause the game

  end

  #Define a method that generates the game's secret number
  def generate_number

    #Generate and return a random number between 1 and 100
    return randomNo = 1 + rand(1000)

  end

  #Define a method to be used control game play
  def play_game

    #Call on the generate_number method in order to get a random number
    number = generate_number

    #Loop until the player inputs a valid answer
    loop do

      Console_Screen.cls       #Clear the display area

        if answer == "c"

            print "Game count : #{$gameCount}"

        end
      #Prompt the player to make a guess
      print "\nEnter your guess and press the Enter key: "

      reply = STDIN.gets  #Collect the player's answer
      reply.chop!         #Remove the end of line character
      reply = reply.to_i  #Convert the player's guess to an integer

          #Validate the player's input only allowing guesses between 1 and 100
          if reply < 1 or reply > 1000 then
            redo  #Redo the current iteration of the loop
          end

          #Analyze the player's guess to determine if it is correct
          if reply == number then    #The player's guess was correct
            Console_Screen.cls        #Clear the display area
            print "You have guessed the number! Press enter to continue."
            Console_Screen.pause      #Pause the game
            break  #Exit loop
          elsif reply < number then  #The player's guess was too low
            Console_Screen.cls        #Clear the display area
            print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
            Console_Screen.pause      #Pause the game
          elsif reply > number then  #The player's guess was too high
            Console_Screen.cls        #Clear the display area
            print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
            Console_Screen.pause      #Pause the game
          end
          $noOfGuesses +=1

      break if $noOfGuesses > 10

    end

  end

  #This method displays the information about the Ruby Number Guessing Game
  def display_credits

    Console_Screen.cls  #Clear the display area

    #Thank the player and display game information
    puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
    puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
    puts "\t\t\t\t  Copyright 2010\n\n"
    puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"

  end

end

# Main Script Logic -------------------------------------------------------

Console_Screen = Screen.new  #Instantiate a new Screen object
SQ = Game.new                #Instantiate a new Game object

#Execute the Game class's display_greeting method
SQ.display_greeting

answer = ""

$gameCount = 0
$noOfGuesses = 0
$totalNoOfGuesses = 0
$avgNoOfGuesses = 0

#Loop until the player enters y or n and do not accept any other input
loop do

  Console_Screen.cls  #Clear the display area

  #Prompt the player for permission to start the game
  print "Are you ready to play the Ruby Number Guessing Game? (y/n): "

  answer = STDIN.gets  #Collect the player's response
  answer.chop!  #Remove any extra characters appended to the string

  #Terminate the loop if valid input was provided
  break if answer == "y" || answer == "n" || answer == "c"  #Exit loop

end

#Analyze the player's input
if answer == "n"  #See if the player elected not to take the game

  Console_Screen.cls  #Clear the display area

  #Invite the player to return and play the game some other time
  puts "Okay, perhaps another time.\n\n"

else  #The player wants to play the game

    #Execute the Game class's display_instructions method
    SQ.display_instructions

  loop do

    $gameCount+=1

    #Execute the Game class's play_game method
    SQ.play_game

    $totalNoOfGuesses = $noOfGuesses * $gameCount

    $avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
    print "The total number of guesses was  #{$totalNoOfGuesses}"
    print "The average number of guesses was  #{$avgNoOfGuesses}"
    Console_Screen.pause      #Pause the game
    print "Press Enter to continue"

    Console_Screen.cls  #Clear the display area

    #Prompt the player for permission start a new round of play
    print "Would you like to play again? (y/n): "

    playAgain = STDIN.gets  #Collect the player's response
    playAgain.chop!  #Remove any extra characters appended to the string

    break if playAgain == "n"  #Exit loop

  end

  #Call upon the Game class's determine_credits method in order to thank
  #the player for playing the game and to display game information
  SQ.display_credits

end

A: When running the code it says:
script-not-working.rb:74:in `block in play_game': undefined local variable or method `answer' for #<Game:0x0000000180f9c0> (NameError)
    from script-not-working.rb:70:in `loop'
    from script-not-working.rb:70:in `play_game'
    from script-not-working.rb:181:in `block in <main>'
    from script-not-working.rb:176:in `loop'
    from script-not-working.rb:176:in `<main>'

So one solution could be make the variable answer global, adding $ before all answer variables it should look like : $answer. The code use other global variables so it could be fine for this. There are better practices than these but for this code it works fine. After that the game is running correctly. But it seems that has some other problems for evaluating the number. this should be another fix. maybe for another question. So investigate thought your code.
Here is the result of the code making answer global using $answer:
#Define a class representing the console window
class Screen

  def cls  #Define a method that clears the display area
    puts ("\n" * 25)  #Scroll the screen 25 times
    puts "\a"  #Make a little noise to get the player's attention
  end

  def pause    #Define a method that pauses the display area
    STDIN.gets  #Execute the STDIN class's gets method to pause script
                #execution until the player presses the enter key
  end

end

#Define a class representing the Ruby Number Guessing Game
class Game

  #This method displays the game's opening screen
  def display_greeting

    Console_Screen.cls  #Clear the display area

    #Display welcome message
    print "\t\t  Welcome to the Ruby Number Guessing Game!" +
    "\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
               "continue."

  Console_Screen.pause       #Pause the game

  end

  #Define a method to be used to present game instructions
  def display_instructions

    Console_Screen.cls       #Clear the display area
    puts "INSTRUCTIONS:\n\n"  #Display a heading

    #Display the game's instructions
    puts "This game randomly generates a number from 1 to 100 and"
    puts "challenges you to identify it in as few guesses as possible."
    puts "After each guess, the game will analyze your input and provide"
    puts "you with feedback. You may take as many turns as you need in"
    puts "order to guess the game's secret number.\n\n"
    puts "Game will stop if you have guessed 10 times.\n\n\n"
    puts "Good luck!\n\n\n\n\n\n\n\n\n"
    print "Press Enter to continue."

    Console_Screen.pause       #Pause the game

  end

  #Define a method that generates the game's secret number
  def generate_number

    #Generate and return a random number between 1 and 100
    return randomNo = 1 + rand(1000)

  end

  #Define a method to be used control game play
  def play_game

    #Call on the generate_number method in order to get a random number
    number = generate_number

    #Loop until the player inputs a valid answer
    loop do

      Console_Screen.cls       #Clear the display area

        if $answer == "c"

            print "Game count : #{$gameCount}"

        end
      #Prompt the player to make a guess
      print "\nEnter your guess and press the Enter key: "

      reply = STDIN.gets  #Collect the player's answer
      reply.chop!         #Remove the end of line character
      reply = reply.to_i  #Convert the player's guess to an integer

          #Validate the player's input only allowing guesses between 1 and 100
          if reply < 1 or reply > 1000 then
            redo  #Redo the current iteration of the loop
          end

          #Analyze the player's guess to determine if it is correct
          if reply == number then    #The player's guess was correct
            Console_Screen.cls        #Clear the display area
            print "You have guessed the number! Press enter to continue."
            Console_Screen.pause      #Pause the game
            break  #Exit loop
          elsif reply < number then  #The player's guess was too low
            Console_Screen.cls        #Clear the display area
            print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
            Console_Screen.pause      #Pause the game
          elsif reply > number then  #The player's guess was too high
            Console_Screen.cls        #Clear the display area
            print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
            Console_Screen.pause      #Pause the game
          end
          $noOfGuesses +=1

      break if $noOfGuesses > 10

    end

  end

  #This method displays the information about the Ruby Number Guessing Game
  def display_credits

    Console_Screen.cls  #Clear the display area

    #Thank the player and display game information
    puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
    puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
    puts "\t\t\t\t  Copyright 2010\n\n"
    puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"

  end

end

# Main Script Logic -------------------------------------------------------

Console_Screen = Screen.new  #Instantiate a new Screen object
SQ = Game.new                #Instantiate a new Game object

#Execute the Game class's display_greeting method
SQ.display_greeting

$answer = ""

$gameCount = 0
$noOfGuesses = 0
$totalNoOfGuesses = 0
$avgNoOfGuesses = 0

#Loop until the player enters y or n and do not accept any other input
loop do

  Console_Screen.cls  #Clear the display area

  #Prompt the player for permission to start the game
  print "Are you ready to play the Ruby Number Guessing Game? (y/n): "

  $answer = STDIN.gets  #Collect the player's response
  $answer.chop!  #Remove any extra characters appended to the string

  #Terminate the loop if valid input was provided
  break if $answer == "y" || $answer == "n" || $answer == "c"  #Exit loop

end

#Analyze the player's input
if $answer == "n"  #See if the player elected not to take the game

  Console_Screen.cls  #Clear the display area

  #Invite the player to return and play the game some other time
  puts "Okay, perhaps another time.\n\n"

else  #The player wants to play the game

    #Execute the Game class's display_instructions method
    SQ.display_instructions

  loop do

    $gameCount+=1

    #Execute the Game class's play_game method
    SQ.play_game

    $totalNoOfGuesses = $noOfGuesses * $gameCount

    $avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
    print "The total number of guesses was  #{$totalNoOfGuesses}"
    print "The average number of guesses was  #{$avgNoOfGuesses}"
    Console_Screen.pause      #Pause the game
    print "Press Enter to continue"

    Console_Screen.cls  #Clear the display area

    #Prompt the player for permission start a new round of play
    print "Would you like to play again? (y/n): "

    playAgain = STDIN.gets  #Collect the player's response
    playAgain.chop!  #Remove any extra characters appended to the string

    break if playAgain == "n"  #Exit loop

  end

  #Call upon the Game class's determine_credits method in order to thank
  #the player for playing the game and to display game information
  SQ.display_credits

end

A: The problem is in your play_game method within the Game class, there is no where the variable answer is defined i.e assigned to a value, even an empty value. So i edited your script such that the method takes answer as an arguement, when the the method is called later here, you pass the answer expected from the console as its argument.
  SQ.play_game answer

Here is the edited script below
  #Define a class representing the console window
   class Screen

   def cls  #Define a method that clears the display area
      puts ("\n" * 25)  #Scroll the screen 25 times
      puts "\a"  #Make a little noise to get the player's attention
   end

   def pause    #Define a method that pauses the display area
     STDIN.gets  #Execute the STDIN class's gets method to pause script
            #execution until the player presses the enter key
   end

end

#Define a class representing the Ruby Number Guessing Game
class Game

     #This method displays the game's opening screen
     def display_greeting

     Console_Screen.cls  #Clear the display area

     #Display welcome message
     print "\t\t  Welcome to the Ruby Number Guessing Game!" +
         "\n\n\n\n\n\n\n\n\n\n\n\n\n\nPress Enter to " +
           "continue."

     Console_Screen.pause       #Pause the game

  end

   #Define a method to be used to present game instructions
   def display_instructions

   Console_Screen.cls       #Clear the display area
    puts "INSTRUCTIONS:\n\n"  #Display a heading

   #Display the game's instructions
    puts "This game randomly generates a number from 1 to 100 and"
    puts "challenges you to identify it in as few guesses as possible."
    puts "After each guess, the game will analyze your input and     provide"
    puts "you with feedback. You may take as many turns as you need in"
    puts "order to guess the game's secret number.\n\n"
    puts "Game will stop if you have guessed 10 times.\n\n\n"
    puts "Good luck!\n\n\n\n\n\n\n\n\n"
    print "Press Enter to continue."

   Console_Screen.pause       #Pause the game

   end

  #Define a method that generates the game's secret number
  def generate_number

    #Generate and return a random number between 1 and 100
    return randomNo = 1 + rand(1000)

  end

   #Define a method to be used control game play
   def play_game answer

     #Call on the generate_number method in order to get a random number
     number = generate_number

#Loop until the player inputs a valid answer
loop do

  Console_Screen.cls       #Clear the display area

    if answer == "c"

        print "Game count : #{$gameCount}"

    end
  #Prompt the player to make a guess
  print "\nEnter your guess and press the Enter key: "

  reply = STDIN.gets  #Collect the player's answer
  reply.chop!         #Remove the end of line character
  reply = reply.to_i  #Convert the player's guess to an integer

      #Validate the player's input only allowing guesses between 1 and 100
      if reply < 1 or reply > 1000 then
        redo  #Redo the current iteration of the loop
      end

      #Analyze the player's guess to determine if it is correct
      if reply == number then    #The player's guess was correct
        Console_Screen.cls        #Clear the display area
        print "You have guessed the number! Press enter to continue."
        Console_Screen.pause      #Pause the game
        break  #Exit loop
      elsif reply < number then  #The player's guess was too low
        Console_Screen.cls        #Clear the display area
        print "Your guess is too low! ( valid range: 1 - 1000) Press Enter to continue."
        Console_Screen.pause      #Pause the game
      elsif reply > number then  #The player's guess was too high
        Console_Screen.cls        #Clear the display area
        print "Your guess is too high! ( valid range: 1 - 1000) Press Enter to continue."
        Console_Screen.pause      #Pause the game
      end
      $noOfGuesses +=1

  break if $noOfGuesses > 10

    end

end

     #This method displays the information about the Ruby Number Guessing Game
    def display_credits

       Console_Screen.cls  #Clear the display area

     #Thank the player and display game information
      puts "\t\tThank you playing the Ruby Number Guessing Game.\n\n\n\n"
      puts "\n\t\t\t Developed by Jerry Lee Ford, Jr.\n\n"
      puts "\t\t\t\t  Copyright 2010\n\n"
      puts "\t\t\tURL: http://www.tech-publishing.com\n\n\n\n\n\n\n\n\n\n"

    end

  end

     # Main Script Logic -------------------------------------------------------

     Console_Screen = Screen.new  #Instantiate a new Screen object
      SQ = Game.new                #Instantiate a new Game object

       #Execute the Game class's display_greeting method
      SQ.display_greeting

      answer = ""

       $gameCount = 0
      $noOfGuesses = 0
       $totalNoOfGuesses = 0
       $avgNoOfGuesses = 0

    #Loop until the player enters y or n and do not accept any other input
  loop do

     Console_Screen.cls  #Clear the display area

      #Prompt the player for permission to start the game
    print "Are you ready to play the Ruby Number Guessing Game? (y/n): "

     answer = STDIN.gets  #Collect the player's response
     answer.chop!  #Remove any extra characters appended to the string

    #Terminate the loop if valid input was provided
    break if answer == "y" || answer == "n" || answer == "c"  #Exit loop

   end

     #Analyze the player's input
     if answer == "n"  #See if the player elected not to take the game

    Console_Screen.cls  #Clear the display area

    #Invite the player to return and play the game some other time
   puts "Okay, perhaps another time.\n\n"

  else  #The player wants to play the game

  #Execute the Game class's display_instructions method
  SQ.display_instructions

    loop do

    $gameCount+=1

    #Execute the Game class's play_game method
     SQ.play_game answer

      $totalNoOfGuesses = $noOfGuesses * $gameCount

       $avgNoOfGuesses = $totalNoOfGuesses / $noOfGuesses
      print "The total number of guesses was  #{$totalNoOfGuesses}"
      print "The average number of guesses was  #{$avgNoOfGuesses}"
       Console_Screen.pause      #Pause the game
      print "Press Enter to continue"

      Console_Screen.cls  #Clear the display area

     #Prompt the player for permission start a new round of play
      print "Would you like to play again? (y/n): "

      playAgain = STDIN.gets  #Collect the player's response
      playAgain.chop!  #Remove any extra characters appended to the string

       break if playAgain == "n"  #Exit loop
     end

    #Call upon the Game class's determine_credits method in order to thank
     #the player for playing the game and to display game information
     SQ.display_credits
  end


text:
Q: How to have a jump to top link on a page that is split in half vertically no jscript or plugin just wanted to know why the following code fails when the page is split in half. The goal is that when you click on the jump to top link it would go to the top of the page. But it does not. However if the body style css is removed then it does (well kind of)

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

#split {
  height: 100%;
}

#splitr {
  overflow: scroll;
  overflow-x: hidden;
}

.right {
  float: left;
  width: 50%;
  height: 100%;
}

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Jump to top

A: The anchor that you are jumping to needs to be inside of the div that you have scrolled down.

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

#split {
  height: 100%;
}

#splitr {
  overflow: scroll;
  overflow-x: hidden;
}

.right {
  float: left;
  width: 50%;
  height: 100%;
}

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Scelerisque diam adipiscing ad justo massa torquent vehicula dictumst netus consequat parturient at a parturient augue habitasse sem nulla a tempor vestibulum parturient.Mus fermentum a a tristique dignissim ullamcorper sit fringilla sociis eget rhoncus.

Jump to top

A: I believe you need your div tag to be an  tag with the name attribute as such

redpajama_set_name: RedPajamaStackExchange


text:
Q: create an NSArray of substrings from a NSString I have a NSString that contains numbers and characters. I would like to know the best way to make an NSArray of NSStrings that contain 2 characters each from the main string.
For instance if the original NSString looked like this
AFC23S4QL0

your NSArray of substrings would look like this
ARRAY {
  AF,
  C2,
  3S,
  4Q,
  L0
}

A: You can use substringWithRange: for this.
NSString *subStr = @"";
int strLen = [yourString length];
BOOL flag = (strLen %2 == 0) ? YES : NO;
for (int index = 0; index < strLen; index+=2)
{
    if((strLen-1 == index) && !flag)
    {
       subStr = [yourString substringWithRange:NSMakeRange(index, 1)];
    }
    else
    {
        subStr = [yourString substringWithRange:NSMakeRange(index, 2)];
    }
    [yourArray addObject:subStr];
}


text:
Q: attach file uploading progress i used javamail api to send emails with attachments from java applications, and it is just simple.
File f= new File(file);
MimeBodyPart mbp2 = new MimeBodyPart();

try {
    mbp2.attachFile(f);
} catch (IOException e) {
    e.printStackTrace();
}

Multipart mp= new MimeMultipart();
mp.addBodyPart(mbp2);

message.setContent(mp);

but the thing i want is to know is how to know the uploading progress of my attachment, unlike httpclient i  can't find an outputstream to writeto!
thanks!

A: See the method implementation.
public void attachFile(File file) throws IOException, MessagingException {
    FileDataSource fds = new FileDataSource(file);
    this.setDataHandler(new DataHandler(fds));
    this.setFileName(fds.getName());
}

You need to override FileDataSource with your custom implementation that tracks file upload.
You should override getInputStream() method to return a FilterOutputStream that count the read bytes. Apache commons-io has CountingInputStream class that can do the job.
Then you simply have to compare the read bytes count with the file length to have a progression.

A: ok, i did it with overriding the DataHandler() and it works really well!
class progress extends DataHandler{
long len;
public idky(FileDataSource ds) {
    super(ds);
    len= ds.getFile().length();
    // TODO Auto-generated constructor stub
}

long transferredBytes=0;
public void writeTo(OutputStream os) throws IOException{

        InputStream instream = this.getInputStream();
        DecimalFormat dFormat = new DecimalFormat("0.00");

      byte[] tmp = new byte[4096];
      int l;
      while ((l = instream.read(tmp)) != -1)
      {
        os.write(tmp, 0, l);
        this.transferredBytes += l;
        System.out.println(dFormat.format(((double)transferredBytes/(double)this.len)*100)+"%");

      }
      os.flush();

}
}

and added it to the MimeBodyPart.


text:
Q: On the solution of a matrix optimization problem Let $A\in\mathbb{R}^{n\times n}$ be a matrix with eigenvalues $\{\lambda_i\}_{i=1}^n$ such that $\mathrm{Re}(\lambda_i)<0$. Moreover, let $\succeq$ denote the standard partial order in the cone of positive definite matrices.
Consider the following maximization problem
\begin{align}\label{eq:opt}\tag{$\ast$}
M=\sup_{P,X\in\mathbb{R}^{n\times n}} \quad & \mathrm{tr}(XP^{-1})\\
\text{s.t.} \quad & AP+(AP)^\top=-X \\
& X=X^\top \succeq 0 \\
& \mathrm{tr}(X)=1 \\
& P=P^\top \succeq 0.
\end{align}
Notice that we can rewrite \eqref{eq:opt} as
\begin{align}
M&=\sup_{\substack{X\in\mathbb{R}^{n\times n}\\ X=X^\top\succeq 0,\ \mathrm{tr}(X)=1}} -\mathrm{tr}((AP+PA^\top)P^{-1})=-2\mathrm{tr}(A).
\end{align}

My question. If the cost function $\mathrm{tr}(XP^{-1})$ in \eqref{eq:opt} is replaced by $\mathrm{tr}(X(\alpha I+ P)^{-1})$, with $\alpha>0$, is it true that
  $$
M= \frac{1}{\alpha-\frac{1}{2\mathrm{tr}(A)}} \ \ \ ?
$$

From an extensive amount of numerical simulations it seems that answer to my latter question is in the affirmative. However, after spending a lot of time thinking about this, I couldn't prove it. So, any help is really appreciated! Thank you!


text:
Q: AspNetCore, project.fragment.lock.json, and multiple configured platforms I have an AspNetCore project which references another project, which builds for both the AnyCpu and x64 platforms, and I need both platforms supported (I have legacy projects which need AnyCpu, but only the x64 platform is supported by AspNetCore).
So I need the x64 platform to be used when building my AspNetCore project.  The problem is that my AnyCpu configuration for the referenced project has OutputDirectory bin\debug, while for my x64 configuration the OutputDirectory is bin\x64\debug.  The trouble is that inside of the project.fragment.lock.json file that is generated (and I'm not even sure if its Visual Studio or something else that generates the project.fragment.lock.json), I always see the dll referenced via the path bin\debug, not bin\debug\x64.
I've worked around it by making the output directory for the referenced project the same regardless of platform, but that is a bad solution, as it often results in errors due to using dlls built for the wrong platform (and a host of other issues).  Has anyone else found away around this?
I've tried a fair amount of hacks around it, including modifying the xproj for the AspNetCore project to try to inject the platform, and modifying the csproj file for the referenced project, setting a default Platform, but I'm still trying and will hopefully add an answer if I find one.

A: Here's what I've managed to tease out, as well as the work-around for the issue I've settled upon.
Initially I thought that when building the AspNetCore project that, since there is no sign of a $(Platform) value in that project, that Visual Studio was building those projects without setting $(Platform), but that wasn't correct.  In fact, for AspNetCore projects (or any that use xproj files), $(Platform) is explicitly set to AnyCPU, and it is not possible, as far as I can tell, to alter this.  If you try to set the platform to x64 for a DotNetCore project in the Configuration Manager, it will not show any error, but it won't have any effect; the next time you open the Configuration Manager it will show it as set back to AnyCPU.
So, given that I can't control what $(Platform) gets set to, and that it is nailed down to AnyCPU, but that I require that PlatformTarget gets set to x64, and that I need a different OutputPath for x64 vs. AnyCPU, I had no choice but to start controlling this using $(Configuration) instead.
So that's the work-around: create a DebugDotNetCore configuration and a ReleaseDotNetCore configuration in the solution, and in any project used by an AspNetCore project, create PropertyGroups that look like this:
<PropertyGroup Condition="'$(Configuration)' == 'DebugDotNetCore'">
  <DebugSymbols>true</DebugSymbols>
  <OutputPath>bin\DebugDotNetCore\</OutputPath>
  <DefineConstants>DEBUG;TRACE</DefineConstants>
  <DebugType>full</DebugType>
  <PlatformTarget>x64</PlatformTarget>
  <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>

And then, in the Configuration Manager, make the DebugDotNetCore configuration use the DebugDotNetCore in each project that you've added it to.  And also add the configuration for the AspNetCore projects, and use it for those too (or else none of this won't have any effect).  Until this is fixed I use the DebugDotNetCore and ReleaseDotNetCore configurations when building my AspNetCore projects and the Debug and Release configurations when building everything else.
Oh, also notice that I don't check $(Platform) in the new PropertyGroups, so the begin tags don't look like they usually do, which is more like this:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">

That's because any difference based on $(Platform) won't make sense.
I also included an xml comment near these, basically telling the next developer with the misfortune of running into this that setting anything differently, depending on platform won't work as expected since PlatformTarget must be set to x64, while $(Platform) must be set to AnyCPU.
I can't wait to get rid of this, but it appears that Microsoft won't be fixing this until the next version of Visual Studio comes out, at which point project.json will be removed, and (I hope), DotNetCore will finally truly be integrated with Visual Studio.


text:
Q: Django: create a model with fields derived from pandas dataframe I have a pandas DataFrame from which I want to create a model whose fields are the df columns (and sets the right "Field" type for django).
Googled around but could only find bulk_create() tips, which, for my understanding, creates different Models.
My knowledge level: Django tutorial done, trying to exercise by creating this model from a big dataframe (many columns).
EDIT:
In practice, what I think I need is a way to write this part (in a model.py class):
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
run_date = models.DateTimeField('run_date')
...

in an automatic way by looking at a dataframe with 30+ columns and defining a field for each of them.
I suspect I'm probably thinking it in a wrong way, so I would like some redirection of that kind, if needed.


text:
Q: Change some checkout fields type using jQuery for a specific state in Woocommerce I am trying to implement some conditional fields on checkout in Woocommerce.
Objective: If user selects a specific state (CO) change the BILLING/SHIPPING CITY and POSTCODE text fields to select fields. Shipping needs to update according to value of POSTCODE.
I am using Jquery to update the CITY and POSTCODE fields when a specific state is selected. This works fine, however shipping is not updated when the fields are changed to select type fields -- selecting a different zip from the select field causes the spinning update graphic on the order review/shipping table but nothing is updated to reflect the selected value.
Shipping updates fine when the POSTCODE field is a standard text field and is changed with keyboard input.
What I am working with currently:
function city_to_dropdown( $fields ) {

    ?>
    <script type="text/javascript">

jQuery('#billing_state').on('change', function() {

            if (jQuery("select#billing_state option:checked").val()=='CO') {

              jQuery( document ).ready(function() {

              jQuery("#billing_city").replaceWith('<select id="billing_city" name="billing_city" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1">' +
             '<option value="" selected>- Select City -</option>' +
          '<option value="TEST1">TEST1</option>' +
          '<option value="TEST2">TEST2</option>' +
          '<option value="TEST3">TEST3</option>' +
          '<option value="TEST4">TEST4</option>' +
          '<option value="TEST5">TEST5</option>' +
        '</select>');
                            jQuery("#shipping_city").replaceWith('<select id="shipping_city" name="shipping_city" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1" >' +
          '<option value="" selected>- Select City -</option>' +
                                                                 '<option value="" selected>- Select City -</option>' +
          '<option value="TEST1">TEST1</option>' +
          '<option value="TEST2">TEST2</option>' +
          '<option value="TEST3">TEST3</option>' +
          '<option value="TEST4">TEST4</option>' +
          '<option value="TEST5">TEST5</option>' +
        '</select>');

              jQuery("#billing_postcode").replaceWith('<select id="billing_postcode" name="billing_postcode" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1" >' +
          '<option value="" selected>- Select Zip -</option>' +
                                                      '<option value="96734">96734</option>' +
          '<option value="96744">96744</option>' +
          '<option value="96795">96795</option>' +
          '<option value="96863-MCB">96863-MCB</option>' +

        '</select>');

              jQuery("#shipping_postcode").replaceWith('<select id="shipping_postcode" name="shipping_postcode" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1">' +
          '<option value="" selected>- Select Zip -</option>' +
                                                       '<option value="96734">96734</option>' +
          '<option value="96744">96744</option>' +
          '<option value="96795">96795</option>' +
          '<option value="96863-MCB">96863-MCB</option>' +

        '</select>');
              } );
            } else {

              jQuery("#billing_city").replaceWith('<input type="text" class="input-text address-field " name="billing_city" id="billing_city" placeholder="" value="" autocomplete="address-level2">');
              jQuery("#billing_postcode").replaceWith('<input type="text" class="input-text address-field " name="billing_postcode" id="billing_postcode" placeholder="" value="" autocomplete="postal-code">');
              jQuery("#shipping_city").replaceWith('<input type="text" class="input-text address-field " name="shipping_city" id="shipping_city" placeholder="" value="" autocomplete="address-level2">');
              jQuery("#shipping_postcode").replaceWith('<input type="text" class="input-text address-field " name="shipping_postcode" id="shipping_postcode" placeholder="" value="" autocomplete="postal-code">');
            }

        });

    </script>

    <?php

}
add_filter( 'woocommerce_after_checkout_billing_form', 'city_to_dropdown' );

Thanks!

A:
As the state "CO" doesn't exist by default in Woocommerce for any country, I have used "CA" (California) as state (And USA as country) for testing purpose.

So I have revisited, optimized and compacted your code (separating billing than shipping).
Try the following instead:
add_action( 'wp_footer', 'change_checkout_fields_script' );
function change_checkout_fields_script() {
    // Only checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):
    ?>
    <script type="text/javascript">
        jQuery(function($){
            var state = 'CO';

            // Utility function to convert billing or shipping city and postcode checkout fields based on state
            function cityPostcodeChange( state, type, update = false ) {
                if ($('#'+type+'_state').val() == state) {
                    $('#'+type+'_city').replaceWith('<select id="'+type+'_city" name="'+type+'_city" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1">' +
                    '<option value="" selected>- Select City -</option>' +
                    '<option value="TEST1">TEST1</option>' +
                    '<option value="TEST2">TEST2</option>' +
                    '<option value="TEST3">TEST3</option>' +
                    '<option value="TEST4">TEST4</option>' +
                    '<option value="TEST5">TEST5</option>' +
                    '</select>');
                    $('#'+type+'_postcode').replaceWith('<select id="'+type+'_postcode" name="'+type+'_postcode" class="hi_select address-field" autocomplete="address-level1" data-placeholder="" tabindex="-1" >' +
                    '<option value="" selected>- Select Zip -</option>' +
                    '<option value="96734">96734</option>' +
                    '<option value="96744">96744</option>' +
                    '<option value="96795">96795</option>' +
                    '<option value="96863-MCB">96863-MCB</option>' +
                    '</select>');
                } else {
                    $(''+type+'_city').replaceWith('<input type="text" class="input-text address-field " name="'+type+'_city" id="'+type+'_city" placeholder="" value="" autocomplete="address-level2">');
                    $('#'+type+'_postcode').replaceWith('<input type="text" class="input-text address-field " name="'+type+'_postcode" id="'+type+'_postcode" placeholder="" value="" autocomplete="postal-code">');
                }
                // Update checkout
                if( update )
                    $('body').trigger('update_checkout');
            }

            // 1. Once DOM is loaded
            cityPostcodeChange( state, 'billing' );
            cityPostcodeChange( state, 'shipping' );

            // 2. On "state" field change event
            $('#billing_state').on('change', function() {
                cityPostcodeChange( state, 'billing', true );
            });
            $('#shipping_state').on('change', function() {
                cityPostcodeChange( state, 'shipping', true );
            });
        });
    </script>
    <?php
    endif;
};

Code goes in function.php file of your active child theme (or active theme). Tested and works.

With "CA" (California) as state (And USA as country):


text:
Q: How to add an argument to pubsub callback I am using the pubsub library to publish messages to certain topics:
# init publisher
publisher = pubsub_v1.PublisherClient(credentials=credentials)

# publish iteratively and keep track of the original iter id
for iter in [0,1,2,3,4]:
   message_future = self.publisher.publish(topic_path)
   message_future.add_done_callback(callback)

# callback
def callback(message_future):
   print(message_future)
   # how can I capture here the original "iter"?

However, I would like to add some meta data like:
message_future.add_done_callback(callback(message_future, iter=iter))

While this works, I receive after the function completes the error:

TypeError: 'NoneType' object is not callable
  line 149, in add_done_callback

What is happening?
See also:
https://googleapis.dev/python/pubsub/latest/publisher/index.html

A: You are expected to pass a function in the add_done_callback.
def foo():
    print('hello')

message_future.add_done_callback(foo)

Inside the add_done_callback, the function gets executed like this
def add_done_callback(self, func):
    ...
    func(self)

The problem is that you're evaluating the callback function before passing it (message_future.add_done_callback(foo()), and your callback function returns None. So the message is trying to execute the None object and hence the error.
You can create a Callable class to store all your metadata as class members and then use it inside the callback function.
class Callable:
  def __init__(self, idx):
    self.idx = idx

  def callback(self, message_future):
    print(message_future)
    print(self.idx)

# publish iteratively and keep track of the original iter id
for iter in [0,1,2,3,4]:
  callable = Callable(iter)
  message_future = self.publisher.publish(topic_path)
  message_future.add_done_callback(callable.callback)


text:
Q: Snow Leopard Tiles Overflow Finder window I have somewhat recently noticed that when I have have the Finder mode set to Tiles, that the tiles are too wide for the window. For example, it shows 7 across (in a row), whereas that makes it to where I have to scroll sideways in order to see all the documents. It, in effect makes it very difficult to use the Finder tile display. Is there a way I can fix this?
I can increase the Finder window, and it works then, but most often I don't want a massive window. I can also shrink the size of the tiles, but that starts to defeat the purpose of using the tiles.
Any suggestions are much appreciated. This isn't something I can't live with, but it would be really nice to get fixed.

A: You could use the Keep Arranged By setting:


text:
Q: Render with other HTML This is a code basic in react
var Hello = React.createClass({
    render: function() {
        return
Hello {this.props.name}
;
    }
});

ReactDOM.render(
    <Hello name="World" />,
    document.getElementById('container')
);

My problem is that I have multiple addresses building components off. That is
+ index.html
+ component
    + hello.html
    + world.html

And I need you react charge for those templates. It will be possible to do something like this?
var Hello = React.createClass({
    render: "component/hello.html"
});

ReactDOM.render(
    <Hello name="World" />,
    document.getElementById('container')
);

A: Create React components rather than HTML files.
+ index.html
+ component
  + hello.jsx
  + world.jsx

For instance component/hello.jsx would look like this:
module.exports = React.createClass({
  render: function() {
    return
Hello {this.props.name}
;
  }
});

Then just require the components with a module bundler like webpack or browserify.
var Hello = require('./component/hello');

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);


text:
Q: Why is my bitmap drawing function plotting at an offset from the position I give it? (C VGA Mode 12h) Hello I´m working on creating a bitmap drawing function on C using VGA in mode 12h using DOSBOX to run the program. I´m getting the image on the screen, but the start of the image is being drawn on the middle on the screen instead of (0,0). Can anyone tell me why I´m getting this behavior?
My plot_pixel function works fine. I´m able to draw lines and plot pixels on the screen without getting the weird offset I´m getting now.
This shows the problem.
Original Image:

Result:

And this is my code:
Load BMP:
/**************************************************************************
 *  load_bmp                                                              *
 *    Loads a bitmap file into memory.                                    *
 **************************************************************************/

void load_bmp(char *file, BITMAP *b){

    FILE *fp;
    long index;
    byte a;
    word num_colors;
    int x;
    //SetGfxMode(0x3);

    /*Opening file */
    if((fp = fopen(file,"rb")) == NULL){

        printf("Error al abrir el archivo %s.\n",file);
        exit(1);
    }

    /*Validating if the image is a valid bitmap*/
    if(fgetc(fp) != 'B' || fgetc(fp) != 'M'){

        fclose(fp);
        printf("%s is not a bitmap file. \n", file);
        exit(1);

    }

    /*Height and width of the image
    */
    fskip(fp,16);
    fread(&b->width, sizeof(word),1 , fp);
    fskip(fp,2);
    fread(&b->height, sizeof(word),1,fp);
    fskip(fp,22);
    fread(&num_colors,sizeof(word),1,fp);
    fskip(fp,6);

    /* We are loading a 16 color image */
    if(num_colors ==0) num_colors = 16;

    /*Intentamos alojar memoria para la data del bitmap*/
    if((b->data = (byte *) malloc((b->width*b->height))) == NULL)
    {
        fclose(fp);
        printf("Error allocating memory for file %s.\n",file);
        exit(1);

    }

    /*Reading pallete info*/
    for(index=0;index<num_colors;index++){
        b->pallete[(int)(index*3+2)] = fgetc(fp) >> 2;
        b->pallete[(int)(index*3+1)] = fgetc(fp) >> 2;
        b->pallete[(int)(index*3+0)] = fgetc(fp) >> 2;
        //fskip(fp,240);
        x = fgetc(fp);

    }

    /* Leyendo el bitmap*/
    for(index=(b->height-1)*b->width;index>=0;index-=b->width){
        for(x=0;x<b->width;x++){
          b->data[index+x]=(byte)fgetc(fp);
        }
    }
    fclose(fp);

}

Draw bitmap:
/**************************************************************************
 *  draw_transparent_bitmap                                               *
 *    Draws a transparent bitmap.                                         *
 **************************************************************************/

void draw_transparent_bitmap(BITMAP *bmp,int x,int y)
{
  int i,j;
  unsigned long bitmap_offset = 0;
  byte data;
    copyMemory(double_buffer,VGA);

    printf("sum");
    getch();
  for(j=0;j<bmp->height;j++)
  {
    for(i=0;i<bmp->width;i++)
    {
      data = bmp->data[bitmap_offset];
      //if (data) double_buffer[screen_offset+x+i] = data;
      if(data) plot_pixel(x+i,y+j,data);
      bitmap_offset++;
    }
  }
}

Set Pallete
void set_pallete(byte *pallete){
    int i;
    outp(PALETTE_INDEX,0);
    for(i=0;i<16*3;i++){
        outp(PALETTE_DATA,pallete[i]);
    }
}

Main:
typedef struct

{
    word width;
    word height;
    byte pallete[256*3];
    byte *data;

} BITMAP;
BITMAP fondo_inicio;

load_bmp("home16.bmp",&fondo_inicio);
set_pallete(fondo_inicio.pallete);
draw_transparent_bitmap(&fondo_inicio,0,0);

A: I'm not persuaded you're loading the BMP correctly. Per Wikipedia, which hopefully managed to get this right as a rare all-but-objective fact, your code, after you've checked for 'BM', assuming fskip is some sort of spin on fseek, takes these steps:

*

*skip the 4 bytes telling you BMP size;

*skip the 4 reserved bytes;

*skip the 4 bytes telling you where you should load pixel data from (which you really should consume and obey);

*assume you're getting a Windows 3.1 secondary header and skip the 4 bytes tell you its length (you shouldn't);

*read the lower two bytes of width;

*skip the upper two bytes of width;

*read the lower two bytes of height;

*skip the upper two bytes of height;

*skip: number of colour planes (+ 2 bytes), bits per pixel (+ 2 bytes), compression method (+ 4 = 10), image size (+ 4 = 14), horizontal density (+ 4 = 18), vertical density (+4 = 22);

*read first two bytes of colour palette size;

*skip next two bytes of colour palette size;

*skip number of important colours;

*assume the headers have then ended (but you should instead have read the header size and skipped appropriate here);

*reads an RGBA palette, assuming it knows the image to be 16-colour, discarding the alpha and mapping from 8 bits-per-channel to VGA-style 6 bits;

*assume the image data comes straight after the palette (you shouldn't, you should have read its file offset earlier);

*read one byte per pixel of image data. Even though you've assumed 4 bits per pixel for reading the palette.

Likely your BMP file isn't 4-bit if reading a whole byte per pixel is providing the correct width of image. That means your assumptions about header size are definitely wrong. Almost certainly what you have stored as the image data is a chunk of header and then the image. Start by not skipping the header entry that tells you where image data begins — read it and use it. Otherwise if your plot_pixel automatically maps eight bits to four then it's not a big problem if you're loading a 256-colour image and assuming that only the lowest sixteen colours are used, assuming that holds true of your source imagery and storage space isn't a concern.


text:
Q: Datagridview with System.Threading.Timer This problem caused the program to run a few minutes. Before I used System.Timers.Timer and not found problem ,until I changed to System.Threading.Timer.
I would like to know that ...
What is a root cause of this problem ?
How to solve this problem ?
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
    System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Unhandled exception</Description><AppDomain>InternetCafe.vshost.exe</AppDomain><Exception><ExceptionType>System.InvalidOperationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>BindingSource cannot be its own data source. Do not set the DataSource and DataMember properties to values that refer back to BindingSource.</Message><StackTrace>   at System.Windows.Forms.BindingSource.get_Count()
       at System.Windows.Forms.CurrencyManager.get_Count()
       at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e)
       at System.Windows.Forms.BindingSource.OnListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.BindingSource.InnerList_ListChanged(Object sender, ListChangedEventArgs e)
       at System.ComponentModel.BindingList`1.OnListChanged(ListChangedEventArgs e)
       at System.ComponentModel.BindingList`1.Child_PropertyChanged(Object sender, PropertyChangedEventArgs e)
       at InternetCafe.Computer.NotifyPropertyChanged(String info) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\Computer.cs:line 163
       at InternetCafe.Computer.UsedTimeValueChanged(Object sender, PropertyChangedEventArgs e) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\Computer.cs:line 149
       at InternetCafe.TimerManager.OnTimeChanged(PropertyChangedEventArgs e) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 62
       at InternetCafe.TimerManager.set_TimeSinceStartTime(TimeSpan value) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 30
       at InternetCafe.TimerManager.tmrThreadingTimer_TimerCallback(Object state) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 50
       at System.Threading._TimerCallback.TimerCallback_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading._TimerCallback.PerformTimerCallback(Object state)</StackTrace><ExceptionString>System.InvalidOperationException: BindingSource cannot be its own data source. Do not set the DataSource and DataMember properties to values that refer back to BindingSource.
       at System.Windows.Forms.BindingSource.get_Count()
       at System.Windows.Forms.CurrencyManager.get_Count()
       at System.Windows.Forms.DataGridView.DataGridViewDataConnection.currencyManager_ListChanged(Object sender, ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.OnListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.CurrencyManager.List_ListChanged(Object sender, ListChangedEventArgs e)
       at System.Windows.Forms.BindingSource.OnListChanged(ListChangedEventArgs e)
       at System.Windows.Forms.BindingSource.InnerList_ListChanged(Object sender, ListChangedEventArgs e)
       at System.ComponentModel.BindingList`1.OnListChanged(ListChangedEventArgs e)
       at System.ComponentModel.BindingList`1.Child_PropertyChanged(Object sender, PropertyChangedEventArgs e)
       at InternetCafe.Computer.NotifyPropertyChanged(String info) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\Computer.cs:line 163
       at InternetCafe.Computer.UsedTimeValueChanged(Object sender, PropertyChangedEventArgs e) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\Computer.cs:line 149
       at InternetCafe.TimerManager.OnTimeChanged(PropertyChangedEventArgs e) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 62
       at InternetCafe.TimerManager.set_TimeSinceStartTime(TimeSpan value) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 30
       at InternetCafe.TimerManager.tmrThreadingTimer_TimerCallback(Object state) in C:\Users\at0m\Documents\Visual Studio 2010\Projects\InternetCafe\InternetCafe\TimerManager.cs:line 50
       at System.Threading._TimerCallback.TimerCallback_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading._TimerCallback.PerformTimerCallback(Object state)</ExceptionString></Exception></TraceRecord>

TimerManager Class
Property TimeSinceStartTime
public TimeSpan TimeSinceStartTime
    {
        get { return new TimeSpan(timeSinceStartTime.Hours, timeSinceStartTime.Minutes, timeSinceStartTime.Seconds); }
        set
        {
            if (timeSinceStartTime != value)
            {
                timeSinceStartTime = value;
                OnTimeChanged(new PropertyChangedEventArgs("TimeSinceStartTime"));
            }
        }
    }

TimerManager Constructor
 public TimerManager(frmMainServer main)
    {
        _timer = new System.Threading.Timer(new
                   TimerCallback(tmrThreadingTimer_TimerCallback),
                   null, System.Threading.Timeout.Infinite, 1000);
        _main = main;
    }

OnTimeChanged
private void OnTimeChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, e);
        }
    }

Timer callback
private void tmrThreadingTimer_TimerCallback(object state)
    {
        TimeSinceStartTime += TimeSpan.FromSeconds(1);
    }

Computer Class
Important Property
public decimal TotalMoney
    {
        get
        {
            return this.totalMoney;
        }

        set
        {
            if (value != this.totalMoney)
            {
                this.totalMoney = value;
                NotifyPropertyChanged("TotalMoney");
            }
        }
    }

    public TimerManager UsedTime
    {
        get
        {
            return this.usedTimeValue;

        }

        set
        {
            if (value != this.usedTimeValue)
            {
                this.usedTimeValue = value;
                NotifyPropertyChanged("UsedTimeValue");
                usedTimeValue.PropertyChanged += new PropertyChangedEventHandler(UsedTimeValueChanged);
            }
        }
    }

If time changed calculate fee, notify Usedtime and TotalMoney.
 private void UsedTimeValueChanged(object sender, PropertyChangedEventArgs e)
   {
       NotifyPropertyChanged("UsedTime");
       this.totalMoney = (decimal)(this.UsedTime.TimeSinceStartTime.Hours * this.session.Member.MemberTariff + this.UsedTime.TimeSinceStartTime.Minutes * (this.session.Member.MemberTariff / 60));
       NotifyPropertyChanged("TotalMoney");
   }

Main Form
Set CompList gridview datasource with dbBindingSource and set dbBindingSource datasource with Computers binding list.
public BindingList<Computer> computers = new BindingList<Computer>();
.
.
.
compList.DataSource = dbBindingSource;
dbBindingSource.DataSource = computers;

A: The root cause is that you're changing a data source in a non-UI thread bound to a UI control.   The easiest solution is to use a System.Windows.Forms.Timer which will always execute on the UI thread, however, it's not very high resolution or accurate.  Your next option is to make sure your PropertyChanged are raised on the UI thread using a SynchronizationContext or by using Invoke/BeginInvoke.


text:
Q: LDA vs. QDA when assumptions do not hold If the Bayes decision boundary is linear and the underlying distributional assumptions are Normal, we expect LDA to perform better than QDA on the test set. But if the Bayes decision boundary is linear and the underlying distributional assumptions are not Normal, can QDA ever perform better than LDA (I know QDA is also not appropriate if the normality assumption is not met, just trying to compare this with LDA in such a setting)?
Similarly, when the Bayes decision boundary is nonlinear (and not necessarily quadratic), can LDA ever perform better than QDA?

A: I'm pretty sure the answer is yes in both cases. You can create an example with, say, uniform distributions with linear boundaries, in which the shapes and extensions of the different classes are vastly different, which can be much better modelled by flexible covariance matrices as in QDA. On the other hand, obviously one can create situations with nonlinear boundaries that are pretty close to linear where it matters, and a low enough number of points in one of the classes so that estimating a full covariance matrix for it as required for QDA is bad.


text:
Q: Conceptualized `operator auto` in C++20 Starting from C++20 we can precede auto keyword with the name of the concept to limit possible types. And in particular this combination is possible in class conversion operator auto, e.g.
template <typename T> concept x = true;

struct S
{
    operator x auto() { return 2; }
    operator auto() { return 1; }
};

int main() { return S{}.operator x auto(); }

But Clang is the only compiler that accepts the whole program, however main() returns 1 (and not 2 as I would expected), demo: https://gcc.godbolt.org/z/b16jYGa81
GCC accepts the struct definition, but refuses to compile S{}.operator x auto().
And MSVC refuses to accept even struct S with the error:
error C2535: 'S::operator auto(void)': member function already defined or declared

Just wonder, which of the compilers is right here (if any)?

A: This conversion function:
operator auto() { return 1; }

Means exactly the same as this converison function:
operator int() { return 1; }

We're deducing the return type from 1, this isn't a function template.

This conversion function:
operator x auto() { return 2; }

Means roughly the same thing as:
operator int() { static_assert(x<int>); return 2; }

We're deducing the return type from 2 and ensuring that that type (int) satisfies a particular concept (x).

Putting both together, we have two functions (neither is a function template), both of which are named operator int(), and that's just not allowed. This should be ill-formed even at the point of declaration since the name operator int() is bound to two conflicting declarations.
Note that the second one is still named operator int(), not operator x auto().


text:
Q: EditText not displaying value on adapter call and EditText loses value when listView is Scrolled. My 1st problem is that in my Activity I'm passing an Amount in my Adapter to use it to set the Edit Text value inside my adapter but it's not showing.
My 2nd problem is that when I change the value of my Edit Text inside my adapter, the value loses when I scroll the List View.
Here my code in adapter:
public class CustomListView_InvoiceList extends BaseAdapter {

private Context mContext;
private List<InvoiceList> invoiceLists;
private float TotalPaymentAmount;

public CustomListView_InvoiceList(Context mContext, List<InvoiceList> invoiceLists, Float totalPaymentAmount) {
    this.mContext = mContext;
    this.invoiceLists = invoiceLists;
    this.TotalPaymentAmount = totalPaymentAmount;
}

public static class ViewHolder {
    CheckBox SelectInvoiceCB, PayFull, PayPartial;
    TextView SalesInvoiceNo, InvoiceDate, InvoiceAmount, AmountDue, DueDate, CreditMemoID, CreditMemoDate, CreditMemoReason;
    LinearLayout LL2, LL3;
    EditText TotalAmount;
    ImageView CaptureForm;
}

@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
    //View v = View.inflate(mContext, R.layout.sales_invoice_custom,null);
    final ViewHolder holder;

    if (view == null) {
        view = View.inflate(mContext, R.layout.sales_invoice_custom, null);
        holder = new ViewHolder();

        holder.SelectInvoiceCB = (CheckBox) view.findViewById(R.id.selectInvoiceCB);
        holder.SalesInvoiceNo = (TextView) view.findViewById(R.id.SINo);
        holder.InvoiceDate = (TextView) view.findViewById(R.id.SIDate);
        holder.InvoiceAmount = (TextView) view.findViewById(R.id.SIAmount);
        holder.AmountDue = (TextView) view.findViewById(R.id.SIAmountDue);
        holder.DueDate = (TextView) view.findViewById(R.id.SIdueDate);
        holder.PayFull = (CheckBox) view.findViewById(R.id.SIFull);
        holder.PayPartial = (CheckBox) view.findViewById(R.id.SIPartial);
        holder.TotalAmount = (EditText) view.findViewById(R.id.SITotalAmount);
        holder.CreditMemoID = (TextView) view.findViewById(R.id.creditMemoID);
        holder.CreditMemoDate = (TextView) view.findViewById(R.id.creditMemoDate);
        holder.CreditMemoReason = (TextView) view.findViewById(R.id.creditMemoReason);
        holder.LL2 = (LinearLayout) view.findViewById(R.id.ll2);
        holder.LL3 = (LinearLayout) view.findViewById(R.id.ll3);

        holder.SelectInvoiceCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setSelectInvoice(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
            }
        });

        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayFull(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                invoiceLists.get(getPosition).setPayPartial(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                }
            }
        });

        view.setTag(holder);
        view.setTag(R.id.SITotalAmount, holder.TotalAmount);
        view.setTag(R.id.selectInvoiceCB, holder.SelectInvoiceCB);
        view.setTag(R.id.SIFull, holder.PayFull);
        view.setTag(R.id.SIPartial, holder.PayPartial);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    InvoicePopulate(view,holder, position);

    return view;
}

public void InvoicePopulate(final View view, final ViewHolder holder, final int position) {
    dbHelper = new DBHelper(mContext);

    Calendar c = Calendar.getInstance();
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    final String formattedDate = df1.format(c.getTime());

    try {
        dbHelper.openDataBase();

        // LAYOUT VISIBILITY FOR CREDIT MEMOs
        try {
            if (invoiceLists.get(position).getCredit_Memo_ID().equals(null) || invoiceLists.get(position).getCredit_Memo_ID().isEmpty()
                    || invoiceLists.get(position).getCredit_Memo_ID().length() < 1
                    || invoiceLists.get(position).getCredit_Memo_ID().trim().equals("")){
                holder.CreditMemoID.setVisibility(View.GONE);
                holder.CreditMemoDate.setVisibility(View.GONE);
                holder.CreditMemoReason.setVisibility(View.GONE);
                holder.LL2.setVisibility(View.GONE);
                holder.LL3.setVisibility(View.GONE);
            } else {
                holder.LL2.setVisibility(View.VISIBLE);
                holder.LL3.setVisibility(View.VISIBLE);
                holder.CreditMemoID.setVisibility(View.VISIBLE);
                holder.CreditMemoDate.setVisibility(View.VISIBLE);
                holder.CreditMemoReason.setVisibility(View.VISIBLE);

                holder.CreditMemoID.setText(invoiceLists.get(position).getCredit_Memo_ID());
                holder.CreditMemoDate.setText(invoiceLists.get(position).getCredit_Memo_Date().substring(0,10));
                holder.CreditMemoReason.setText(invoiceLists.get(position).getCredit_Memo_Reason());
            }
        } catch (Exception e) {
            e.getMessage();
        }

        holder.SalesInvoiceNo.setText(invoiceLists.get(position).getSales_Invoice_ID());
        holder.InvoiceDate.setText(invoiceLists.get(position).getInvoice_Date());
        holder.DueDate.setText(invoiceLists.get(position).getDue_Date());

        float invAmount = 0;
        invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
        holder.InvoiceAmount.setText(String.format("%,.2f",invAmount));
        holder.AmountDue.setText(String.format("%,.2f",invAmount));
        //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());

        holder.TotalAmount.setTag(position);
        holder.SelectInvoiceCB.setTag(position); // This line is important.
        holder.PayFull.setTag(position); // This line is important.
        holder.PayPartial.setTag(position); // This line is important.

        holder.TotalAmount.setText(invoiceLists.get(position).getAmount_Paid());
        holder.SelectInvoiceCB.setChecked(invoiceLists.get(position).isSelectInvoice());
        holder.PayFull.setChecked(invoiceLists.get(position).isPayFull());
        holder.PayPartial.setChecked(invoiceLists.get(position).isPayPartial());

        try {
            if (invoiceLists.get(position).getAmount_Paid().toString().equals("") ||
                    invoiceLists.get(position).getAmount_Paid().toString().equals("0.0") ||
                    Float.parseFloat(invoiceLists.get(position).getAmount_Paid().toString()) < 1) {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = 0;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("Without AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            } else {
                invAmount = 0;
                invAmountDue = 0;
                invAmountPaid = Math.round(Float.parseFloat(invoiceLists.get(position).getAmount_Paid())*100.00)/(float)100.00;
                //invAmount = Float.parseFloat(invoiceLists.get(position).getInvoice_Amount());
                invAmount = Math.round(Float.parseFloat(invoiceLists.get(position).getInvoice_Amount())*100.00)/(float)100.00;
                invAmountDue = invAmount - invAmountPaid;
                Log.e("With AmountPaid ", "Amount Due : " + String.valueOf(invAmountDue));
            }

            holder.AmountDue.setText(String.format("%,.2f",invAmountDue));
            //holder.InvoiceAmount.setText(invoiceLists.get(position).getInvoice_Amount());
        } catch (Exception e) {
            e.getMessage();
        }

        /*final float finalInvAmount = invAmountDue;
        holder.PayFull.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayFull.isChecked()) {
                    holder.PayPartial.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_FULL";
                        holder.TotalAmount.setText(String.valueOf(Math.round(finalInvAmount*100.00)/100.00));
                        //holder.TotalAmount.setText(holder.InvoiceAmount.getText().toString());
                    }
                }
            }
        });

        holder.PayPartial.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (holder.PayPartial.isChecked()) {
                    holder.PayFull.setChecked(false);
                    if (holder.SelectInvoiceCB.isChecked()) {
                        invoiceStatusValue = "PAID_PARTIAL";
                        holder.TotalAmount.setText("0.00");
                    }
                }
            }
        });*/

        if (TotalPaymentAmount >= Float.parseFloat(String.valueOf(invAmountDue))) {
            holder.SelectInvoiceCB.setChecked(true);
            holder.PayFull.setChecked(true);
            holder.PayFull.setClickable(true);
            holder.PayPartial.setClickable(true);

            holder.TotalAmount.setText(String.valueOf(Math.round(invAmountDue * 100.00) / 100.00));

            System.out.println("TotalPaymentAmount: " + TotalPaymentAmount);
            System.out.println("invAmountDue: " + invAmountDue);

            if (Float.parseFloat(String.valueOf(invAmountDue)) < 1) {
                Log.e("Computations : ", TotalPaymentAmount + " + " + String.valueOf(Float.parseFloat(String.valueOf(invAmountDue))));
                Log.e("Equals ", "TotalPaymentAmount = " + TotalPaymentAmount);
            } else {
                TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
            }
        } else {
            if (TotalPaymentAmount < 1) {
                holder.TotalAmount.setText("0.00");
                /*holder.PayFull.setClickable(false);
                holder.PayPartial.setClickable(false);*/

            } else {
                holder.SelectInvoiceCB.setChecked(true);
                holder.PayPartial.setChecked(true);
                holder.PayFull.setClickable(true);
                holder.PayPartial.setClickable(true);
                holder.TotalAmount.setText(String.valueOf(Math.round(TotalPaymentAmount * 100.00) / 100.00));

                if ((TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue))) < 0) {
                    TotalPaymentAmount = (float) 0.0;
                } else {
                    TotalPaymentAmount = TotalPaymentAmount - Float.parseFloat(String.valueOf(invAmountDue));
                }
            }
        }

    } catch (Exception e) {
        e.getMessage();
        System.out.println("Custom Invoice List: " + e);
    } finally {
        dbHelper.close();
    }

}

A: First, I recommend using RecyclerView instead of ListView, a simple implementation will avoid the problem of scrolling.
I recommend these links:
https://developer.android.com/training/material/lists-cards.html
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
Second, the method invoicePopulate * opens the SQLite database every time a view is created, this gives a serious performance problem because with the scroll the views are recreated and you generate multiple instances in the end you will end up with an error and you will not be able to access to the database. For this I recommend that you calculate the data previously and pass it to the adapter already ready.
It is best to use the adapters to only show information, if you need to calculate try to do it before.


text:
Q: Conditional merge on 2 huge pandas datasets I have 2 dataframes as below:
A = pd.DataFrame({'UserId':['U1','U1','U1','U2','U2','U3'],'End_Week':['1/6/2020','15/6/2020','6/7/2020','4/5/2020','18/5/2020','20/4/2020'],'Start_Week':['1/6/2019','15/6/2019','6/7/2019','4/5/2019','18/5/2019','20/4/2019']})

B = pd.DataFrame({'UserId':['U1','U1','U1','U1','U2','U2','U3'],'Action':['U','V','U','U','V','V','U'],'Date':['5/3/2019','4/6/2019','1/7/2019','12/6/2020','4/4/2019','12/5/2019','19/3/2019'],'V1':[2,3,1,2,4,1,1],'V2':[0,1,0,0,1,2,1]})

I want to do the below steps:
For each row of 'A', find all corresponding rows from dataframe 'B' that fall between columns Start_Week and End_Week given in A. For example - 1st row of 'A' -> Start_Week is '1/6/2019' and End_Week is '1/6/2020'. All rows from dataframe 'B' that fall between these dates are 2nd and 3rd rows i.e. dates 4/06/2019 and 1/7/2019 (for User U1). Similar operation has to be done for all rows of dataframe A.
I have the below solution which works fine with small data but fails to allocate memory on the entire data I am using.
a = A.Date.values
a1 = A.UserId.values
b1 = B.UserId.values
bh = B.End_Week.values
bl = B.Start_Week.values

i, j = np.where((a1[:, None]==b1) & (a[:, None] >= bl) & (a[:, None] <= bh))
final_df = pd.DataFrame(np.column_stack([A.values[i], B.values[j]]),columns=A.columns.append(B.columns))

I get the following error message:
MemoryError: Unable to allocate 514. GiB for an array with shape (662195, 834051) and data type bool

A contains 662195 rows and B contains 834051 in my dataset.
Can someone help with a more optimal solution for this problem.

A: First convert the dates to datetime (Ignore this block if dates are already a datetime dtype)
A[['End_Week','Start_Week']] = A[['End_Week','Start_Week']].apply(pd.to_datetime,
                                                                dayfirst=True)
B['Date']  = pd.to_datetime(B['Date'],dayfirst=True)

Then merge and use series.between
out = B.merge(A,on='UserId',how='left')
out = out[out['Date'].between(u['Start_Week'],u['End_Week'])]

print(out)

   UserId Action       Date  V1  V2   End_Week Start_Week
3      U1      V 2019-06-04   3   1 2020-06-01 2019-06-01
6      U1      U 2019-07-01   1   0 2020-06-01 2019-06-01
7      U1      U 2019-07-01   1   0 2020-06-15 2019-06-15
10     U1      U 2020-06-12   2   0 2020-06-15 2019-06-15
11     U1      U 2020-06-12   2   0 2020-07-06 2019-07-06
14     U2      V 2019-05-12   1   2 2020-05-04 2019-05-04

If you want only columns from B, you can filter the output to retain just columns from B;
out = out[out['Date'].between(u['Start_Week'],u['End_Week'])].loc[:,B.columns]
print(out)

   UserId Action       Date  V1  V2
3      U1      V 2019-06-04   3   1
6      U1      U 2019-07-01   1   0
7      U1      U 2019-07-01   1   0
10     U1      U 2020-06-12   2   0
11     U1      U 2020-06-12   2   0
14     U2      V 2019-05-12   1   2


text:
Q: Using Riemann-Roch to guarantee a pole at $P$? As an easy consequence of Riemann-Roch, for a point $P$ on a curve $X$, we can show that there is some function regular everywhere but $P$. We can start by choosing $n$ large enough such that $h^0(X, \mathcal{L}(nP)) > 1$, and so we get a non constant rational function $f \in K(X)$, but this alone just gives us that $\text{ord}_P(f) > -n$. How do we proceed from here to show that in fact $f$ must have $\text{ord}_P(f)<0$?

A: I think the idea is that there cannot be a (non constant) function with no poles, since the only possible pole for $f$ is $P$, it must really be a pole.


text:
Q: How to store UTF-8 email addresses in a unique MySQL column using PHP? I'm trying to support UTF-8 characters into email addresses. If I understand correctly, email addresses are limited to 254 usable (ASCII) characters. Based on this, I would like to store email address in a VARCHAR(254) ASCII MySQL InnoDB column. One of the problems I'm encountering is to validate such scenarios. I'm trying to convert UTF-8 to ASCII but getting mixed results as shown below (I know the example is not a valid email but I could have used other characters - this is just to explain the problem):
<?php
$string = '@.';
echo 'UTF-8 Value: ' . $string . '
';
echo 'ASCII Length (from UTF-8 string):' . mb_strlen($string, 'ASCII') . '
';
$stringAscii =  mb_convert_encoding($string, 'ASCII', 'UTF-8');
echo 'ASCII Length:' . strlen($stringAscii) . '
';
echo 'ASCII Value:' . $stringAscii . '
';

The output is:

UTF-8 Value: @.
ASCII Length (from UTF-8 string)::14
ASCII Length:5
ASCII Value:?@?.

I would expect the length to be 14 characters in the ASCII string once it's converted? How can I convert the UTF-8 string to ASCII without losing its original length and value? Basically I'm looking for a way to store a UTF-8 string into its ASCII format while being able to convert it back to its original UTF-8 format.
I also tried other type of encoding output (e.g. byte outputs) but was unable to find any output matching the 14 characters length. I also tried iconv which is returning exceptions for there characters. The idea to convert in ASCII is that I can support this value as a primary key of a table in MySQL within my VARCHAR(254). I could always try to convert to HTML-ENTITIES but it will be hard to predict the maximum size of the string to reflect it in the DB schema.
An other option is to use a UTF-8MB4 encoded VARCHAR(256) column in MySQL but when used as a primary key, this will go above the 767 bytes index limit and require to enable large index in InnoDB which I would prefer to avoid.
Is there a way to achieve what I'm trying to do without using innodb_large_prefix=on in MySQL?

A: Nicholas you seem to have some fundamental confusions with Ascii Vs UTF-8 Character sets in your Question and your comments to answer(s).

UTF-8 Value: @.
ASCII Length (from UTF-8 string):14
ASCII Length:5
ASCII Value:?@?.

I would expect the length to be 14 characters in the ASCII string once it's converted?

No, If the Panda Face UTF-8 character was represented in Ascii how would it be represented? At best this would be subjective such as with a <3 or a B-) etc.
There is no translation of the Pandaface, hence it is substituted with the placeholder ? in the output character set. It is somewhat like trying to spell king but only with vowels. There are simply less ascii options than UTF8.
So please take away that Ascii is a practical sub-set of UTF-8, not vice versa.
MySQL Unique Storage Solution
MYSQL Unique indexes have a limit of 767 bytes in total. You can chain these indexes together and for any table MySQL can provide a total unique index of 3072 bytes. For the purposes of using a single index column of collation UTF8mb4_unicode_ci (ie, the one you should be using) then the unique index column would be:
<max index size in bytes> / <max bytes per character in collation>
          767             /            4                    = 191 characters.

Therefore MySQL will only unqiuely index the first 191 characters of any UTF-8 string.
To sidestep this limiter, you would make a new table, with two columns, an Auto_increment integer column, and a varchar column:
CREATE TABLE `emails` (
 `id` int(8) NOT NULL AUTO_INCREMENT,
 `email` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`),
 KEY `email` (`email`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

Then each time a new email address is added, you search this table if it already exists (the column is indexed but is not unique) and if not, then the email address is inserted and referenced by the id column.
The email column is always UTF8mb4 because this is full UTF8 unlike the MySQL standard utf8_ collation. MySQL can't uniquely qualify data larger than 767 bytes as you have said, but if your various other tables reference the id row for the email, that column on the other tables can be unique.
Some Further thoughts
1 htmlentities is not an effective solution because for any character the size of it's entity is always bigger, take the > character, which is > this is already 4 characters in length at best case, even if each of these could be stored in "1 byte", this would still be a larger storage than with > which as a general UTF-8 character at worst case would be 4-bytes.
htmlentities will only effect characters that have a specified HTML alternative, and I'm unsure if things like <PandaFace> or <shitpoo> have htmlentities(?).
2 What is the longest email address you have ever seen or even ever used, that is a real genuine address? While the maximum size of email addresses is 254 ascii characters, that is:
thisisaverylongandtediousemailaddresswhichisprettyimpractical.
andonlyreallyworth.jacksquitintheamount.ofspacethiscantakeupinyourdatabase
@home.somewhere.overtherainbow.ornear.somepot.of.irishgold.thinkaboutthis.
thisemailisthemaximumlengthallowed.co.uk.com

Now look at that code, that is the longest allowed ascii email address by definition. That' pretty long and while not impossible, the number of users who have email addresses (in ascii) of this length will be an extreme edgecase.
Taking this a step futher down this line, say that you have an email address that is 64 UTF-8 4-byte characters as you've set as the upper utf-8 limit,
So as ascii something of this length:
  horsesandgoastandcatsanddogsandfleas@some.petting.zoo.org.uk.com

But as UTF-8 4byte characters and say this above email was translated into certain UTF-8 Chinese character sets, this email address length is still the upper range of what is practical for humans to actually use and have as their addresses. But it is not quite out the park, it's unlikely unless you're aiming for a specific market audience.
The MySQL Unique Indexing of 767 bytes would limit you to approximately 191 4-byte UTF-8 characters, then you'd be limited to 47 fully UTF-8 characters in an email address featuring 2 (well, max 3) non UTF-8 4byte character (such as @ and .).
Example:
thisIsAnEmailOfUTF8CharasandA@IntheRightPlace.com

Now remember that this email doesn't look that long, it's of a more realistic size than others, but each and every character (except . and @) would need to be at the 4byte UTF-8 encoding for this to hit the MySQL unique index limit, so for example if each of the characters in the email was of a certain non-latin language such as Ethiopian or certain UTF-8 Chinese sets.
3
It is also worth noting that Chinese (and I think Japanese) characters are each words or syllabales in their own right (therefore bigger than simply letters), so (I hazard) few Chinese would have excessive email addresses instead you'd have:
猫@空间农场.com

This is donkey@spacefarm.com*, taking up 10 character spaces in Chinese, whereas the ascii latin takes up 20 character spaces.
Further to this there are some (sub)sets of Chinese and Japanese characters that are still not present in the UTF-8 standard. (annoyingly, the example above is one of these).
*^ Google translation, so may be wrong!
Some Conclusion Options

*

*Store your Email in plaintext UTF-8 in a specific table with a unique AI column (as outlined above). reference/cross-reference the column AI id number to discover if the email text is unique on any other field/column in the database. Do not Unique the email column, simply index it, but unique the index reference to that column.

*Store the Email address as a hash and check if the hash is unique such as with sha1 in PHP . SHA1 is better than MD5 because it is a longer hash so can accept more values without collisions (although collisions are still possible). Sha hashes are always 160 bit or 40 characters long and therefore comfortably fit into the MySQL unique column constraints.

*Store your email address to a VARCHAR(190) length and expect that to cover 98%+ of your database usership.

*MySQL unique index limit is not as likely to effect your emails as the criteria for valid email length.

*You may be able to get away with using email addresses that are technically questionably valid but weather these are accepted by routers and DNS servers is pretty much up to each server.

*Email is an old and anachronistic way of transporting data. Consider the future will be more like SnapChat [example] and other database based authenticated communications which have few of the curtailing limits that email inherits. Email is also very tedious to code with and prone to a wide variety of issues errors and problems as well as extremely poor security overheads.

MySQL Storing The Email Address
Option 1 ) Hash the email address and store the hash in a unique column.

*

*Postives:
This will mean you can store the email in the same column as you'd originally intended. Email should be fixed length sha hash. MySQL Unique column contstraint would be valid.

*Negatives
Hash collisions would be possible, email address itself would not be searchable or "de-codable".
Option 2 ) Store the email address plaintext in the UTF-8 column and simply limit the email VARCHAR field size to 190 characters.

*

*Positives:
This would probably cover all likely valid email addresses.

*Negatives:
Longer email addresses would be invalid and truncated, meaning they would be saved without error but would not be the same text strings (due to truncation).
Option 3 ) Store the Email in a new MySQL table with an indexed VARCHAR column and an auto_increment numerical reference column as detailed above.
This would then mean that any occurance of the email text would be replaced by a numerical reference for that row in the database. The column that features the original email text can then be a unique index.

*

*Positives:
This means you can store emails as unique entities and can carry out SQL checks for if they already appear.

*Negatives:
This would mean changing your current coding and SQL commands slightly to accommodate this new table as a reference table.
Example
Email Reference Table:
CREATE TABLE `email_reference` (
 `id` int(8) NOT NULL AUTO_INCREMENT,
 `email` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`id`),
 KEY `email` (`email`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

Users (example) table:
CREATE TABLE `userdata` (
 `user_id` int(8) NOT NULL AUTO_INCREMENT,
 `name` varchar(90) COLLATE utf8mb4_unicode_ci NOT NULL,
 `email_ref` int(11) DEFAULT NULL,
 `details` text COLLATE utf8mb4_unicode_ci NOT NULL,
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `email_ref` (`email_ref`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

The above userdata table will have a unique column for email ref which will reference the email table. This unique column means no two userdata rows can reference the same row in the email_reference table.
Because it is a UNIQUE column it is a good idea to allow NULL values for if anyone for any reason doesn't have an email or other such "uniqueness escape" situations.

The long and the short of my long post is that I think your concerns appear to be mostly edge cases or due to imperfect Database structural design, rather than due to issues with character sets or unique keys themselves. If what you're envisaging with your system are not edge cases then using the MySQL AI int reference system I have outlined above should, with a little bit of foresight on your part, cover your needs.

A: I'm adding the missing details in my own answer (special thanks for Ignacio, andig, Martin and Markus Laire for helping me to put the pieces of this puzzle together).
There are two problems to this question :

*

*Encoding conversion from UTF-8 to ASCII

*MySQL index limit to 767 bytes without enabling innodb_large_prefix for MySQL < 5.7.7 (looks like this is now enabled by default).

Answer for "Encoding conversion from UTF-8 to ASCII"
ASCII is a subset of UTF-8 so not all characters can be converted. ASCII only uses 128 characters (the first 128) per byte while UTF-8 bytes can use more. The ideal solution would be to use an encoding that support all 256 possibilities per 8-bits bytes. Some encoding like cp1252 supports most characters but even if this is true, some characters are invisible which could end up causing issues.
For a true byte by byte conversion the only reliable option is to use binary. for our user case given we use MySQL, the best option would be to have a VARBINARY(254) (binary fields don't have encoding). After that it would be easy to simply:
INSERT into user_table set email_address='@.';
SELECT * FROM user_table where email_address = '@.';

To be safe, values can also be HEX('') on the client of application side if needed. This is truly the most efficient solution for this problem given that you will only store email address in a 254 bytes column which is by RFC standard the maximum length with any encoding.
Answer for "MySQL index limit to 767 bytes"
It looks like InnoDB large prefixes is now the default configuration on MySQL >= 5.7.7 since it was mostly a backward compatible setting. While one could implement this complex UTF-8 to HTML-ENTITIES conversion, it probably make more sense to just upgrade MySQL when using a UTF-8 email address as a primary key. Or one could also simply enable large prefixes in the MySQL configuration for MySQL <= 5.7.7:
innodb_large_prefix=on
innodb_file_format=barracuda

Conslusion
Keep in mind that while some providers supports UTF-8 in email addresses, it is still not mainstream in 2016. In the meantime there are a few options to store the information but less to make sure it will make it to its destination.

A: You cannot "convert" a UTF8 string to ASCII at the same length if the characters do not have an ASCII representation as in your example.
What you could do is to create some kind of representation of the bytecodes that make up the UTF8 characters. I doubt that would be useful as email address though.
UPDATE
In UTF8 each character can consume multiple bytes. how many varies by character. If ASCII one character is one byte. So you can use each byte of the UTF8 character and see chat character that byte represents in ASCII. However- this will have absolutely nothing to to with the original UTF8 character except for those UTF8 characters that are represented by a single byte. IMHO those will match their ASCII representation.


text:
Q: Specifying sets where/with/for My main interest is in the mathematical context, where one denotes a set of objects with indices. I can imagine 3 cases :

*

*Let xₙ for n=1,2,... denote all objects ...

*Let xₙ with n=1,2,... denote all objects ...

*Let xₙ where n=1,2,... denote all objects ...

I would tend to use 2 but I was told this sounds strange.

A: I would say that "with" is not a likely choice, but in fact it is possibly used more often than "where", and "for" is chosen most often: ngram.
In this ngram are included all cases in which n is fixed and equal to 1, but I think it doesn't matter.


text:
Q: wp_nav_menu list children if on parent page but sibling if on sibling page For example:
About Page (Parent)

*

*History

*Mission & Vision

*Location

If I'm on the About Page, I need the wp_nav_menu to show the three children pages. But if I'm on the History page, I need it to show History (with current class), Mission & Vision and Location.
Is there a way to do this? Thank you.


text:
Q: Firebase functions GET request with query params returns 400 error I have a function called base which runs and returns a 200 status fine with the expected payload when I do a GET via postman to: http://localhost:5001/api-name/region/base.
But when I add a get parameter to the URL, the request fails, i.e. http://localhost:5001/api-name/region/base?origin=localhost. I get a 400 Bad Request error. The interesting thing is while postman reports the 400 Bad Request almost immediately, the firebase emulator acts like it is still running the function and times out after 60s.
I have function runtime options to set the request at 300s (because it's a big query and takes a while, this works as expected too without the params), so it seems like it's not even being routed to the correct function or anywhere at all.

A: I had the same issue. The solution was to update to the latest version of firebase-tools.
If using npm:
npm install -g firebase-tools@latest
This was a bug fixed in v9.2.1. More info here: https://github.com/firebase/firebase-tools/releases/tag/v9.2.1