问:
Ruby undefined method `getBakiye' for []:Array (NoMethodError)
why i cant pass getBakiye() func of Musteri class as parametre to bakiyeBilgisi() func of Banka class ? I googled it a couple time but i didnt
something to do.i did same thing python and it worked what is different between of ruby and python at this point ? Have a good day guys

and i got this problem :

rb:122:in bakiyeBilgisi': undefined methodgetBakiye' for []:Array (NoMethodError)

```<code>    class Musteri
  attr_accessor :isim,:soyisim,:idno,:parola
  def initialize(isim,soyisim,idno,parola)
    @isim = isim
    @soyisim = soyisim
    @idno = idno.to_s
    @parola = parola.to_s
    @bakiye = 0
  end
  #=====================================
  def getIsım #isim döndür
    return @isim
  end

  def getSoyIsım #soyisim al
    return @soyisim
  end

  def getIdNo #Idno al
    return getIdNo
  end

  def getParola  #parola al
    return @parola
  end

  def getBakiye  #bakiye al
    return @bakiye
  end

  def setBakiye(miktar) #bakiye değiştir
    @bakiye =miktar
    return @bakiye
  end

end #musteri sinifi bitişi

class Banka
  attr_accessor :musteriler,:isim
  def initialize(isim)
    @isim = isim
    @musteriler = []
  end #yapici

  def musteriVarmi(idno,parola)
    for musteri in musteriler
      if musteri.getIdNo == idno and musteri.getParola == parola
        return musteri

      end

    end

  end

  def aliciVarmi(idno)
    for musteri in @musteriler
      if musteri.getIdNo == idno
        return musteri
      end #if blogunun

    end #aliciVarmi for dongusu

  end #aliciVarmi fonksiyonu

  def paraAktar(gonderen,alici,miktar)
    if @musteriler.include? gonderen and @musteriler.include? alici
      if gonderen.getBakiye >= miktar
        alici.setBakiye(alici.getBakiye + miktar)
        puts "Gönderilme işlemi başarıyla gerçekleşti"
      else
        puts "Bakiye Yetersiz"
      end #paraAktar ifS
    else
      puts "Alıcı Bulunamadı"
    end #paraAktar ifS

  end #paraAktar fonk

  def musteriOl(isim,soyisim,idno,parola)
    @musteriler<<(Musteri(isim,soyisim,idno,parola))
  end #musteriOl fonk

  def paraCek(musteri,miktar)
    if miktar % 10 != 0
      puts "Bozuk para atmayiniz"
    else
      if musteri.getBakiye >= miktar
        puts "Önce paranizi\nSOnra kartinizi aliniz"
        musteri.setBakiye(musteri.getBakiye + miktar)
      else
        puts "Bakiye yetersiz"
      end #paracek elseS
    end #paracek ifS
  end #paracek fonk

  def paraYatir(musteri,miktar)
    if miktar % 5 != 0
      puts "Bozuk para atmayiniz"
    else
      musteri.setBakiye(musteri.getBakiye + miktar)
      puts "Paraniz Yatirildi"
    end #paraYatir ifS
  end #paraYatir fonk

  def bakiyeBilgisi(musteri)
    musteri.getBakiye

  end #bakiyeBİlgisi fonk
end # Banka sinifi bitisi

def main
  banka = Banka.new("UmutPalabiyik")
  while true
    system("cls")
    puts "[1] Musteri Ol : "
    puts "[2] Giriş Yap"

    puts "Lutfen yapmak istediginiz islemi seciniz"
    secim1 = gets.chomp()

    if secim1 == "1"
      puts "Lütfen isminizi giriniz  : "
      isim = gets.chomp.to_s

      puts "Lütfen soyisminizi giriniz : "
      soyisim = gets.chomp.to_s

      puts "Lütfen id numaranizi giriniz : "
      idno = gets.chomp.to_s

      puts "Lütfen parolanızı giriniz : "
      parola = gets.chomp.to_s

      puts "Ana menuye donmek icin herhangi bir tusa basiniz"
      gets.chomp()

    elsif secim1 == "2"
      puts "Lütfen id numaranizi giriniz :"
      idno = gets.chomp.to_s

      puts "Lütfen parolanizi giriniz  :"
      parola = gets.chomp.to_s

      if banka.musteriVarmi(idno,parola)
        musteri = banka.musteriVarmi(idno,parola)
        while true
          system("cls")
          puts "[1] Bakiye Goster       [2] Para Yatır"
          puts "[3] Para Çek        [4] Para Aktar"
          puts "    [Q] Cikis"

          puts "Yapmak istediginiz islemi seciniz"
          secim2 = gets.chomp()

          if secim2 == "1"
            banka.bakiyeBilgisi(musteri)
            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "2"
            puts "Lutfen yatırmak istediginz tutari seciniz : "
            miktar = gets.chomp.to_i
            banka.paraYatir(musteri,miktar)

            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "3"
            puts "Lütfen çekmek istediginiz miktarı giriniz : "
            miktar = gets.chomp.to_i
            banka.paraCek(musteri,miktar)

            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "4"
            puts "Alıcı ID :"
            idno = gets.chomp()

            puts "Aktarmak istediğiniz miktarı giriniz  :"
            miktar = gets.chomp().to_f

            if banka.aliciVarmi(idno)
              banka.paraAktar(musteri,banka.aliciVarmi(idno),miktar)
            else
              puts "Alici Bulunamadi !"

            end #3.elsif ifS

          elsif secim2 == "q" and secim2 == "Q"
            puts "Ana menüye yönlendiriliyorsunuz"
            sleep(0.5)
            puts "."
            sleep(0.5)
            puts ".."
            sleep(0.5)
            puts "..."
            break

          else
            puts "Hatalı Giriş"
            puts "Ana menüye dönmek için herhangi bir tusa basiniz : "
            gets.chomp()

          end # 2. while true ifS

        end #ikinci while true

      else
        puts "Banka kaydi bulunamadi ya da hatali giris"

      end #elsif in ifS
    else
      puts "Hatali Giris"

    end #ilk ifS
  end #while true
end #main fonk

main
</code>```

答:
I guess the error caused by musteriVarmi method. You use for loop to find a single value. When there aren't any matches the array musteriler gets returned from musteriVarmi. Ruby has a lot of nice methods to work with arrays.

```<code># This code will return a found value or `nil`
def musteriVarmi(idno, parola)
  musteriler.find do |musteri|
    musteri.getIdNo == idno and musteri.getParola == parola
  end
end
</code>```

Also, please install and check your code via Rubocop. Your code style is not conventional. And better to name classes, methods and variables in English.

Body:
why i cant pass getBakiye() func of Musteri class as parametre to bakiyeBilgisi() func of Banka class ? I googled it a couple time but i didnt
something to do.i did same thing python and it worked what is different between of ruby and python at this point ? Have a good day guys

and i got this problem :

rb:122:in bakiyeBilgisi': undefined methodgetBakiye' for []:Array (NoMethodError)

    class Musteri
  attr_accessor :isim,:soyisim,:idno,:parola
  def initialize(isim,soyisim,idno,parola)
    @isim = isim
    @soyisim = soyisim
    @idno = idno.to_s
    @parola = parola.to_s
    @bakiye = 0
  end
  #=====================================
  def getIsım #isim döndür
    return @isim
  end

  def getSoyIsım #soyisim al
    return @soyisim
  end

  def getIdNo #Idno al
    return getIdNo
  end

  def getParola  #parola al
    return @parola
  end

  def getBakiye  #bakiye al
    return @bakiye
  end

  def setBakiye(miktar) #bakiye değiştir
    @bakiye =miktar
    return @bakiye
  end

end #musteri sinifi bitişi

class Banka
  attr_accessor :musteriler,:isim
  def initialize(isim)
    @isim = isim
    @musteriler = []
  end #yapici

  def musteriVarmi(idno,parola)
    for musteri in musteriler
      if musteri.getIdNo == idno and musteri.getParola == parola
        return musteri

      end

    end

  end

  def aliciVarmi(idno)
    for musteri in @musteriler
      if musteri.getIdNo == idno
        return musteri
      end #if blogunun

    end #aliciVarmi for dongusu

  end #aliciVarmi fonksiyonu

  def paraAktar(gonderen,alici,miktar)
    if @musteriler.include? gonderen and @musteriler.include? alici
      if gonderen.getBakiye >= miktar
        alici.setBakiye(alici.getBakiye + miktar)
        puts "Gönderilme işlemi başarıyla gerçekleşti"
      else
        puts "Bakiye Yetersiz"
      end #paraAktar ifS
    else
      puts "Alıcı Bulunamadı"
    end #paraAktar ifS

  end #paraAktar fonk

  def musteriOl(isim,soyisim,idno,parola)
    @musteriler<<(Musteri(isim,soyisim,idno,parola))
  end #musteriOl fonk

  def paraCek(musteri,miktar)
    if miktar % 10 != 0
      puts "Bozuk para atmayiniz"
    else
      if musteri.getBakiye >= miktar
        puts "Önce paranizi\nSOnra kartinizi aliniz"
        musteri.setBakiye(musteri.getBakiye + miktar)
      else
        puts "Bakiye yetersiz"
      end #paracek elseS
    end #paracek ifS
  end #paracek fonk

  def paraYatir(musteri,miktar)
    if miktar % 5 != 0
      puts "Bozuk para atmayiniz"
    else
      musteri.setBakiye(musteri.getBakiye + miktar)
      puts "Paraniz Yatirildi"
    end #paraYatir ifS
  end #paraYatir fonk

  def bakiyeBilgisi(musteri)
    musteri.getBakiye

  end #bakiyeBİlgisi fonk
end # Banka sinifi bitisi

def main
  banka = Banka.new("UmutPalabiyik")
  while true
    system("cls")
    puts "[1] Musteri Ol : "
    puts "[2] Giriş Yap"

    puts "Lutfen yapmak istediginiz islemi seciniz"
    secim1 = gets.chomp()

    if secim1 == "1"
      puts "Lütfen isminizi giriniz  : "
      isim = gets.chomp.to_s

      puts "Lütfen soyisminizi giriniz : "
      soyisim = gets.chomp.to_s

      puts "Lütfen id numaranizi giriniz : "
      idno = gets.chomp.to_s

      puts "Lütfen parolanızı giriniz : "
      parola = gets.chomp.to_s

      puts "Ana menuye donmek icin herhangi bir tusa basiniz"
      gets.chomp()

    elsif secim1 == "2"
      puts "Lütfen id numaranizi giriniz :"
      idno = gets.chomp.to_s

      puts "Lütfen parolanizi giriniz  :"
      parola = gets.chomp.to_s

      if banka.musteriVarmi(idno,parola)
        musteri = banka.musteriVarmi(idno,parola)
        while true
          system("cls")
          puts "[1] Bakiye Goster       [2] Para Yatır"
          puts "[3] Para Çek        [4] Para Aktar"
          puts "    [Q] Cikis"

          puts "Yapmak istediginiz islemi seciniz"
          secim2 = gets.chomp()

          if secim2 == "1"
            banka.bakiyeBilgisi(musteri)
            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "2"
            puts "Lutfen yatırmak istediginz tutari seciniz : "
            miktar = gets.chomp.to_i
            banka.paraYatir(musteri,miktar)

            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "3"
            puts "Lütfen çekmek istediginiz miktarı giriniz : "
            miktar = gets.chomp.to_i
            banka.paraCek(musteri,miktar)

            puts "Ana menüye dönmek için 'enter' a basiniz !"
            gets.chomp()

          elsif secim2 == "4"
            puts "Alıcı ID :"
            idno = gets.chomp()

            puts "Aktarmak istediğiniz miktarı giriniz  :"
            miktar = gets.chomp().to_f

            if banka.aliciVarmi(idno)
              banka.paraAktar(musteri,banka.aliciVarmi(idno),miktar)
            else
              puts "Alici Bulunamadi !"

            end #3.elsif ifS

          elsif secim2 == "q" and secim2 == "Q"
            puts "Ana menüye yönlendiriliyorsunuz"
            sleep(0.5)
            puts "."
            sleep(0.5)
            puts ".."
            sleep(0.5)
            puts "..."
            break

          else
            puts "Hatalı Giriş"
            puts "Ana menüye dönmek için herhangi bir tusa basiniz : "
            gets.chomp()

          end # 2. while true ifS

        end #ikinci while true

      else
        puts "Banka kaydi bulunamadi ya da hatali giris"

      end #elsif in ifS
    else
      puts "Hatali Giris"

    end #ilk ifS
  end #while true
end #main fonk

main

Body:
I guess the error caused by musteriVarmi method. You use for loop to find a single value. When there aren't any matches the array musteriler gets returned from musteriVarmi. Ruby has a lot of nice methods to work with arrays.

# This code will return a found value or `nil`
def musteriVarmi(idno, parola)
  musteriler.find do |musteri|
    musteri.getIdNo == idno and musteri.getParola == parola
  end
end

Also, please install and check your code via Rubocop. Your code style is not conventional. And better to name classes, methods and variables in English.


来源: stackexchange

问:
Python Nested conditional? double condition followed by another condition
Im trying to learn python but struggling on this problem.

Imagine this situations:

1- user press button1 and button2 =
program need to "do some"

2 - user press button1 and button2 then press button3 =
Its ok to me "do some 2"

3 - user press button2 and button1 then press button3 =
Its ok to me "do some 2"

but

4 - if user press button3 before button1 and button2 =
Its not ok to me "do some2", I need just to "do some"

so the sequence of which button is pressed first matters to my purpose

```<code>def button1_pressed():  # Returns true if the left mouse button is pressed
    button1_state = win32api.GetKeyState(0x01)
    return button1_state < 0

def button2_pressed():  # Returns true if the right mouse button is pressed
    button2_state = win32api.GetKeyState(0x02)
    return  button2_state < 0

def button3_pressed():  # Returns true if the M button is pressed
    button3_state = win32api.GetKeyState(0x4D)
    return button3_state < 0

while True:
    while button1_pressed() and button2_pressed(): # No matter which one is pressed first to me
        print("do some")
        while button3_pressed(): # Only if it is pressed after button1 and button2 are pressed
            print("do some2")
            if button2_pressed() == 0:
                break # this only breaks the inner while loop
        break # added an extra break else it would just be stuck in an endless loop
</code>```

I will be thankfull if anyone give me some help.

答:
What you want here is what's called a "state machine".  The situations you describe are called "states", and they persist after the button presses have stopped (e.g. you can be in the state "the user has pressed button 2", which is different from "the user is pressing button 2").

```<code>pressed = [True, False, False, False]
while True:
  if button1_pressed() and not pressed[1]:
      pressed[1] = True
      if pressed[2]:
          print("do some")
          continue
  if button2_pressed() and not pressed[2]:
      pressed[2] = True
      if pressed[1]:
          print("do some")
          continue
  if button3_pressed() and not pressed[3]:
      pressed[3] = True
      if pressed[1] and pressed[2]:
          print("do some 2")
  if all(pressed):
      # All the buttons have been pressed (in some order).  Done!
      break
</code>```

You could potentially encode this in a data structure, something like this:

```<code>buttons = [lambda: False, button1_pressed, button2_pressed, button3_pressed]
pressed = [False, False, False, False]
actions = {
    # For each button press, what action happens
    # based on button(s) previously pressed.
    1: ([2], "do some")
    2: ([1], "do some")
    3: ([1, 2], "do some 2")
}
while True:
    for num in (1, 2, 3):
        if not buttons[num]() or pressed[num]:
            continue
        pressed[num] = True
        prev, action = actions[num]
        if all(pressed[p] for p in prev):
            print(action)
    if any(
        not pressed_now() and was_pressed
        for pressed_now, was_pressed in zip(buttons, pressed)
    ):
        # Break condition: previously pressed button was released
        break
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying to learn python but struggling on this problem.

Imagine this situations:

1- user press button1 and button2 =
program need to "do some"

2 - user press button1 and button2 then press button3 =
Its ok to me "do some 2"

3 - user press button2 and button1 then press button3 =
Its ok to me "do some 2"

but

4 - if user press button3 before button1 and button2 =
Its not ok to me "do some2", I need just to "do some"

so the sequence of which button is pressed first matters to my purpose

def button1_pressed():  # Returns true if the left mouse button is pressed
    button1_state = win32api.GetKeyState(0x01)
    return button1_state < 0

def button2_pressed():  # Returns true if the right mouse button is pressed
    button2_state = win32api.GetKeyState(0x02)
    return  button2_state < 0

def button3_pressed():  # Returns true if the M button is pressed
    button3_state = win32api.GetKeyState(0x4D)
    return button3_state < 0

while True:
    while button1_pressed() and button2_pressed(): # No matter which one is pressed first to me
        print("do some")
        while button3_pressed(): # Only if it is pressed after button1 and button2 are pressed
            print("do some2")
            if button2_pressed() == 0:
                break # this only breaks the inner while loop
        break # added an extra break else it would just be stuck in an endless loop

I will be thankfull if anyone give me some help.

Body:
What you want here is what's called a "state machine".  The situations you describe are called "states", and they persist after the button presses have stopped (e.g. you can be in the state "the user has pressed button 2", which is different from "the user is pressing button 2").

pressed = [True, False, False, False]
while True:
  if button1_pressed() and not pressed[1]:
      pressed[1] = True
      if pressed[2]:
          print("do some")
          continue
  if button2_pressed() and not pressed[2]:
      pressed[2] = True
      if pressed[1]:
          print("do some")
          continue
  if button3_pressed() and not pressed[3]:
      pressed[3] = True
      if pressed[1] and pressed[2]:
          print("do some 2")
  if all(pressed):
      # All the buttons have been pressed (in some order).  Done!
      break

You could potentially encode this in a data structure, something like this:

buttons = [lambda: False, button1_pressed, button2_pressed, button3_pressed]
pressed = [False, False, False, False]
actions = {
    # For each button press, what action happens
    # based on button(s) previously pressed.
    1: ([2], "do some")
    2: ([1], "do some")
    3: ([1, 2], "do some 2")
}
while True:
    for num in (1, 2, 3):
        if not buttons[num]() or pressed[num]:
            continue
        pressed[num] = True
        prev, action = actions[num]
        if all(pressed[p] for p in prev):
            print(action)
    if any(
        not pressed_now() and was_pressed
        for pressed_now, was_pressed in zip(buttons, pressed)
    ):
        # Break condition: previously pressed button was released
        break


问:
Javascript Websocket fails to receive TCP data
I'm trying to receive json data from an ESP32 via TCP to a website hosted thru WAMP (localhost -> ESP32 IP address on local network is 10.11.125:23). Below is my javascript function. My browser (Firefox Developer) generates a "SecurityError: The operation is insecure" when executing the line var connection = new webSocket('ws://10.11.13.125:23'). What am I missing??

```<code>function openWebsocket() {
    console.log("open Websocket.....");
    var connection = new WebSocket('ws://10.11.13.125:23');

    connection.onerror = function(error) {
        $("#Connection").html("Connection Error");

        console.log("Websocket Error: " + error);
    }

    connection.onopen = function(evt) {
        $("#Connection").html("Connected");
    }

    connection.binaryType = 'arraybuffer';
    connection.onmessage = function(evt) {
        console.log("Server: " + evt.data.byteLength);
    }

    console.log("ReadyState: "+connection.readyState);
}
</code>```

答:
I found the problem. The Chromium browser yields a more descriptive error message. Port 23 is not available. Switched over to
var connection = new WebSocket('ws://10.11.13.125:80');
and voila, everything works as expected.

Sorry for posting about an issue that in the end I found the solution for myself.

Body:
I'm trying to receive json data from an ESP32 via TCP to a website hosted thru WAMP (localhost -> ESP32 IP address on local network is 10.11.125:23). Below is my javascript function. My browser (Firefox Developer) generates a "SecurityError: The operation is insecure" when executing the line var connection = new webSocket('ws://10.11.13.125:23'). What am I missing??

function openWebsocket() {
    console.log("open Websocket.....");
    var connection = new WebSocket('ws://10.11.13.125:23');

    connection.onerror = function(error) {
        $("#Connection").html("Connection Error");

        console.log("Websocket Error: " + error);
    }

    connection.onopen = function(evt) {
        $("#Connection").html("Connected");
    }

    connection.binaryType = 'arraybuffer';
    connection.onmessage = function(evt) {
        console.log("Server: " + evt.data.byteLength);
    }

    console.log("ReadyState: "+connection.readyState);
}


问:
Count half of rest of a partition by from position
I'm trying to achieve the following results:

now, the group comes from

```<code> SUM(CASE WHEN seqnum <= (0.5 * seqnum_rev) THEN i.[P&L] END) OVER(PARTITION BY i.bracket_label ORDER BY i.event_id) AS [P&L 50%],
</code>```

I need that in each iteration it counts the total of rows from the end till position (seq_inv) and sum the amounts in P&L only for the half of it from that position.

for example, when

```<code>seq = 2
</code>```

seq_inv will be = 13, half of it is 6 so I need to sum the following 6 positions from seq = 2.

when seq = 4  there are 11 positions till the end (seq_inv = 11), so half is 5, so I want to count 5 positions from seq = 4.

I hope this makes sense, I'm trying to come up with a rule that will be able to adapt to the case I have, since the partition by is what gives me the numbers that need to be summed.

I was also thinking if there was something to do with a partition by top 50% or something like that, but I guess that doesn't exist.

答:
I don't think that window functions can do what you want. You could use a correlated subquery instead, with the following logic:</p>

```<code>select
    t.*,
    (
        select  sum(t1.P&L]
        from mytable t1
        where t1.seq - t.seq between 0 and t.seq_inv/2
    ) [P&L 50%]
from mytable t
</code>```

Body:
I'm trying to achieve the following results:

now, the group comes from

 SUM(CASE WHEN seqnum <= (0.5 * seqnum_rev) THEN i.[P&L] END) OVER(PARTITION BY i.bracket_label ORDER BY i.event_id) AS [P&L 50%],

I need that in each iteration it counts the total of rows from the end till position (seq_inv) and sum the amounts in P&L only for the half of it from that position.

for example, when

seq = 2

seq_inv will be = 13, half of it is 6 so I need to sum the following 6 positions from seq = 2.

when seq = 4  there are 11 positions till the end (seq_inv = 11), so half is 5, so I want to count 5 positions from seq = 4.

I hope this makes sense, I'm trying to come up with a rule that will be able to adapt to the case I have, since the partition by is what gives me the numbers that need to be summed.

I was also thinking if there was something to do with a partition by top 50% or something like that, but I guess that doesn't exist.

Body:
I don't think that window functions can do what you want. You could use a correlated subquery instead, with the following logic:

select
    t.*,
    (
        select  sum(t1.P&L]
        from mytable t1
        where t1.seq - t.seq between 0 and t.seq_inv/2
    ) [P&L 50%]
from mytable t


问:
Create a table matrix with 2d arrays C#
I am trying to create a program where you ask the user for a number, Create an array that is as close to square as you can and fill it with 1 to the user's specified number. You have to use a 2d array. Here is an example of what it would look like:

user input: 16

output:  1  2  3  4
        5  6  7  8
        9  10 11 12
        13 14 15 16

I have tried to do it by running it trough loops but it has not worked, I hope someone can guide me on how to do this

答:
First let's get the user input:

```<code>int num;
while(!int.TryParse(Console.ReadLine(), out num) || num < 1)
{
    Console.WriteLine("Invalid number!");
}
</code>```

after this calculate the side of the square:

```<code>var sideLength = (int)Math.Ceiling(Math.Sqrt(num));
</code>```

then create the 2D array:

```<code>var array = new int[sideLength, sideLength];
</code>```

and write the numbers into it:

```<code>for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
            break;
        array[row, column] = value;
    }
}
</code>```

but don't write anything higher then the user input, this will leave them 0, which is great because you want to display it from 1 so you can use the 0 to detect the end in case the user input is not a square number.

Now let's prepare a string to format the numbers. If you want all numbers to be the exact same length you can format it with int.ToString("0") where the number of 0s will set the length. Let's create a string which will make all number the same length. The user input is the longest possible number so you can use that to create the string:

```<code>var format = new string('0', num.ToString().Length);
</code>```

Now print the array:

```<code>for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = array[row, column];
        if (value == 0)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:
</code>```

This will put the same number of numbers in a line and there will the same amount of rows unless it finds a 0, then it will stop and the last line won't be a full line, this happens if the input wasn't a square number.

Let's look at the outputs:

Input: 16

Output:

```<code>01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16
</code>```

Input: 14

Output:

```<code>01 02 03 04
05 06 07 08
09 10 11 12
13 14
</code>```

If you want to display the 0s if it's not a full line you can remove the 0 check from the print part.

Can this be optimized?

Yes! The array is useless, it just contains incrementing numbers. If 2d arrays are not a requirement you can completely remove it and make some modifications to the print function.

```<code>int num;
while(!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Invalid number!");
}

var sideLength = (int)Math.Ceiling(Math.Sqrt(num));
var format = new string('0', num.ToString().Length);
for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:
</code>```

This code does the same thing but without 2d arrays.

Title: Create a table matrix with 2d arrays C#

Body:
First let's get the user input:

int num;
while(!int.TryParse(Console.ReadLine(), out num) || num < 1)
{
    Console.WriteLine("Invalid number!");
}

after this calculate the side of the square:

var sideLength = (int)Math.Ceiling(Math.Sqrt(num));

then create the 2D array:

var array = new int[sideLength, sideLength];

and write the numbers into it:

for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
            break;
        array[row, column] = value;
    }
}

but don't write anything higher then the user input, this will leave them 0, which is great because you want to display it from 1 so you can use the 0 to detect the end in case the user input is not a square number.

Now let's prepare a string to format the numbers. If you want all numbers to be the exact same length you can format it with int.ToString("0") where the number of 0s will set the length. Let's create a string which will make all number the same length. The user input is the longest possible number so you can use that to create the string:

var format = new string('0', num.ToString().Length);

Now print the array:

for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = array[row, column];
        if (value == 0)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:

This will put the same number of numbers in a line and there will the same amount of rows unless it finds a 0, then it will stop and the last line won't be a full line, this happens if the input wasn't a square number.

Let's look at the outputs:

Input: 16

Output:

01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16

Input: 14

Output:

01 02 03 04
05 06 07 08
09 10 11 12
13 14

If you want to display the 0s if it's not a full line you can remove the 0 check from the print part.

Can this be optimized?

Yes! The array is useless, it just contains incrementing numbers. If 2d arrays are not a requirement you can completely remove it and make some modifications to the print function.

int num;
while(!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Invalid number!");
}

var sideLength = (int)Math.Ceiling(Math.Sqrt(num));
var format = new string('0', num.ToString().Length);
for (int row = 0; row < sideLength; row++)
{
    for (int column = 0; column < sideLength; column++)
    {
        var value = row * sideLength + (column + 1);
        if (value > num)
        {
            Console.WriteLine("");
            goto breakBoth;
        }
        Console.Write($"{value.ToString(format)} ");
    }
    Console.WriteLine("");
}
breakBoth:

This code does the same thing but without 2d arrays.


问:
Create a function generateString(char, val) that returns a string with val number of char characters concatenated together
I have been working this for days and I can only come up with:</p>

```<code>def generateString(char, val):
</code>```

答:
If you just print(character * count) of course you will get the right output but the goal is to create an operational function and then output by using the function</p>

```<code>import sys
character= sys.argv[1]
count= int(sys.argv[2])

def generateString(char, val):
   string = char * val
   return string

print(generateString(character, count))
</code>```

Body:
I have been working this for days and I can only come up with:

def generateString(char, val):

Body:
If you just print(character * count) of course you will get the right output but the goal is to create an operational function and then output by using the function

import sys
character= sys.argv[1]
count= int(sys.argv[2])

def generateString(char, val):
   string = char * val
   return string

print(generateString(character, count))


问:
Unable to get select button click in unit testing using Jasmine and Angular
Hi here i am using Angular and trying to create a unit test for the Reactive form but unable to succeed

what i required : How to execute button click after the form is filled both with false and truthy values using jasmine in angular.

what i did : I created a logic but it is not working

```<code> it('Form check is valid or not if no values entered', () => {

    expect(component.userCreationForm.valid).toBeFalsy();
  });

  it('Form check is valid or not when values entered', () => {

    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('123456');
    expect(component.userCreationForm.valid).toBeTruthy();
  });

  it('Form Submitted should check from is submitted', () => {
    // check form is invalid
    expect(component.userCreationForm.invalid).toBeTruthy();
    let btn = fixture.debugElement.query(By.css('button[type=submit]'));
    // Check button is disabled
    expect(btn.nativeElement.disabled).toBeTruthy();
    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('testpassword');
    fixture.detectChanges();
    // check button is enabled
    expect(btn.nativeElement.disabled).toBeFalsy();

    component.onUserCreation();
    fixture.detectChanges();

    let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
    expect(success.textContent).toBe('Bubba');

 });
</code>```

html logic

```<code><div class="inv-buttons">
          <button mat-raised-button color="primary" [disabled]="userCreationForm.invalid" type="submit">Create User</button>
        </div>
</code>```

Below is my stackblitz : https://stackblitz.com/edit/angular-9-material-starter-q9wxvq

答:
Where ever you want to click that btn you have created. Use it like below :-

```<code> btn.nativeElement.click();
</code>```

I changed your test case below :-

```<code>it('Form Submitted should check from is submitted',async () => {
    // check form is invalid
    expect(component.userCreationForm.invalid).toBeTruthy();
    let btn = fixture.debugElement.query(By.css('button[type=submit]'));
    // Check button is disabled
    expect(btn.nativeElement.disabled).toBeTruthy();
    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('testpassword');
    fixture.detectChanges();
    // check button is enabled
    expect(btn.nativeElement.disabled).toBeFalsy();
    await fixture.whenStable();
    console.clear();
    btn.nativeElement.click();
    fixture.detectChanges();
    //component.onUserCreation();
    //fixture.detectChanges();

    //let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
    //expect(success.textContent).toBe('Bubba');

 });
</code>```

Body:
Hi here i am using Angular and trying to create a unit test for the Reactive form but unable to succeed

what i required : How to execute button click after the form is filled both with false and truthy values using jasmine in angular.

what i did : I created a logic but it is not working

 it('Form check is valid or not if no values entered', () => {

    expect(component.userCreationForm.valid).toBeFalsy();
  });

  it('Form check is valid or not when values entered', () => {

    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('123456');
    expect(component.userCreationForm.valid).toBeTruthy();
  });

  it('Form Submitted should check from is submitted', () => {
    // check form is invalid
    expect(component.userCreationForm.invalid).toBeTruthy();
    let btn = fixture.debugElement.query(By.css('button[type=submit]'));
    // Check button is disabled
    expect(btn.nativeElement.disabled).toBeTruthy();
    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('testpassword');
    fixture.detectChanges();
    // check button is enabled
    expect(btn.nativeElement.disabled).toBeFalsy();

    component.onUserCreation();
    fixture.detectChanges();

    let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
    expect(success.textContent).toBe('Bubba');

 });

html logic

          <button mat-raised-button color="primary" [disabled]="userCreationForm.invalid" type="submit">Create User</button>

Below is my stackblitz : https://stackblitz.com/edit/angular-9-material-starter-q9wxvq

Body:
Where ever you want to click that btn you have created. Use it like below :-

 btn.nativeElement.click();

I changed your test case below :-

it('Form Submitted should check from is submitted',async () => {
    // check form is invalid
    expect(component.userCreationForm.invalid).toBeTruthy();
    let btn = fixture.debugElement.query(By.css('button[type=submit]'));
    // Check button is disabled
    expect(btn.nativeElement.disabled).toBeTruthy();
    component.userCreationForm.controls['firstname'].setValue('luther');
    component.userCreationForm.controls['lastname'].setValue('adams');
    component.userCreationForm.controls['email'].setValue('test@gmail.com');
    component.userCreationForm.controls['password'].setValue('testpassword');
    fixture.detectChanges();
    // check button is enabled
    expect(btn.nativeElement.disabled).toBeFalsy();
    await fixture.whenStable();
    console.clear();
    btn.nativeElement.click();
    fixture.detectChanges();
    //component.onUserCreation();
    //fixture.detectChanges();

    //let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
    //expect(success.textContent).toBe('Bubba');

 });


问:
A new property value stored thru a setter takes affect before execution
I'm creating 4 instances of the class Coordinates. Next I'm changing one of the values thru the setter.

```<code>class Coordinates {
    constructor(lat, lng) {
        this._lat = lat;
        this._lng = lng;
    }
    get lat() { return this._lat; }
    get lng() { return this._lng; }
    set lat(newLat) { this._lat = newLat; }
    set lng(newLng) { this._lng = newLng; }
}

let points = [];
for (let p = 0; p < 4; p++) {
    const point = new Coordinates(p, p);
    points.push(point);
}
console.log(points);  // Shows the 55, although the setter wasn't executed
points[1].lat = 55;
console.log(points); // Shows the 55 (as expected)
</code>```

The first console.log shows 0/0, 55/1, 2/2, 3/3. I actually expected 0/0, 1/1, 2/2, 3/3, because I didn't executed the setter. The 2nd log shows 0/0, 55/1, 2/2, 3/3, as expected.
Can somebody help me to understand, pls?

答:
As I cannot reproduce this in Node.js, but can reproduce in Chrome console, I suppose this is because the points variable is displayed in the console lazily, i.e. it has a live reevaluation when you click on it to see the elements in details. If you try this, you can see the issue is gone as now you have string primitives instead of live objects.

console.log(JSON.stringify(points));
points[1].lat = 55;
console.log(JSON.stringify(points));
```

Body:
I'm creating 4 instances of the class Coordinates. Next I'm changing one of the values thru the setter.

class Coordinates {
    constructor(lat, lng) {
        this._lat = lat;
        this._lng = lng;
    }
    get lat() { return this._lat; }
    get lng() { return this._lng; }
    set lat(newLat) { this._lat = newLat; }
    set lng(newLng) { this._lng = newLng; }
}

let points = [];
for (let p = 0; p < 4; p++) {
    const point = new Coordinates(p, p);
    points.push(point);
}
console.log(points);  // Shows the 55, although the setter wasn't executed
points[1].lat = 55;
console.log(points); // Shows the 55 (as expected)

The first console.log shows 0/0, 55/1, 2/2, 3/3. I actually expected 0/0, 1/1, 2/2, 3/3, because I didn't executed the setter. The 2nd log shows 0/0, 55/1, 2/2, 3/3, as expected.
Can somebody help me to understand, pls?


问:
Relation between generics type in Java
Please, consider my code:

```<code>interface AInterface {}

interface BInterface extends AInterface {}

class AClass implements AInterface { }

class BClass extends AClass implements BInterface {}

class Descriptor<S extends AClass, T extends AInterface> {

    private Class<S> classClass;

    private Class<T> interfaceClass;

    public Descriptor(Class<S> classClass, Class<T> interfaceClass) {
        this.classClass = classClass;
        this.interfaceClass = interfaceClass;
    }
}

class Foo {

    public void test() {
        Descriptor<AClass, BInterface> descriptor =
               new Descriptor<>(AClass.class, BInterface.class);//LINE X
    }
}
</code>```

So, I have two interfaces and two classes that implement them. And I have a descriptor to which I must add two classes - the class of the interface and class of the implementation. The question is how to add relation restrict between them. I mean, that at LINE X I must get compilation error, because AClass doesn't implement BInterface. How to do it?

答:
I do not think this is possible. Enforcing multiple type bounds is possible when all of them but the first one (optionally) are interfaces, but I'm unaware of any trick allowing to do it for multiple classes. Here's how it works for interfaces:

```<code>public class Bar {}
public class Baz extends Bar {}
public class Foo1<T extends Bar & Serializable> {}                   // compiles
public class Foo2<T extends Serializable & Bar> {}                   // doesn't compile
public class Foo2<T extends Bar & Baz> {}                            // doesn't compile
public class Foo3<T extends Serializable & Closeable> {}             // compiles
public class Foo4<T extends Serializable & Closeable & Runnable> {}  // compiles
</code>```

What's your real use case? Perhaps there's a way to approach the problem differently.

Title: Relation between generics type in Java

Body:
Please, consider my code:

interface AInterface {}

interface BInterface extends AInterface {}

class AClass implements AInterface { }

class BClass extends AClass implements BInterface {}

class Descriptor<S extends AClass, T extends AInterface> {

    private Class<S> classClass;

    private Class<T> interfaceClass;

    public Descriptor(Class<S> classClass, Class<T> interfaceClass) {
        this.classClass = classClass;
        this.interfaceClass = interfaceClass;
    }
}

class Foo {

    public void test() {
        Descriptor<AClass, BInterface> descriptor =
               new Descriptor<>(AClass.class, BInterface.class);//LINE X
    }
}

So, I have two interfaces and two classes that implement them. And I have a descriptor to which I must add two classes - the class of the interface and class of the implementation. The question is how to add relation restrict between them. I mean, that at LINE X I must get compilation error, because AClass doesn't implement BInterface. How to do it?

Body:
I do not think this is possible. Enforcing multiple type bounds is possible when all of them but the first one (optionally) are interfaces, but I'm unaware of any trick allowing to do it for multiple classes. Here's how it works for interfaces:

public class Bar {}
public class Baz extends Bar {}
public class Foo1<T extends Bar & Serializable> {}                   // compiles
public class Foo2<T extends Serializable & Bar> {}                   // doesn't compile
public class Foo2<T extends Bar & Baz> {}                            // doesn't compile
public class Foo3<T extends Serializable & Closeable> {}             // compiles
public class Foo4<T extends Serializable & Closeable & Runnable> {}  // compiles

What's your real use case? Perhaps there's a way to approach the problem differently.


问:
Converting more columns into different types
I have a dataset that looks like as follows:

```<code>date           time_h     Checked     Verified
2018-03-10    21:10     TRUE         TRUE
2018-03-19    03:20     FALSE        TRUE
2018-04-04    12:03     TBC          FALSE
...
</code>```

I have been trying to convert the strings to the following formats:

date and time_h to date and time objects;

Checked and Verified to boolean values.

After putting all text in lower case, I have tried as follows:

```<code>bool = {'true': True, 'false': False}

df['Checked']=df['Checked'].map(bool)
df['Verified']=df['Verified'].map(bool)

df['date']= pd.to_datetime(df['date']).dt.date
df['time_h']= pd.to_datetime(df['time_h']).dt.strftime('%H:%M')
</code>```

However, when I check using dtypes, the outputs show all the columns as objects (so no change has been applied).
Where am I doing wrong? How could I also include the TBC in the TRUE boolean value (saying TBC = TRUE)?

Edit:

An example of nan in my code within column time_h is NaN (string format, as it comes from a csv file).
After replacing 'NaN' value using

```<code>df['time_h'] = df['time_h'].replace('NaN', np.nan)
</code>```

I get:

```<code><bound method Series.isnull of 0      nan
1      nan
2      nan
3      nan
</code>```

but when I use

```<code>t = df['time_h'].str.split(':', expand=True).astype(int)
df['time_h'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')
</code>```

I get the following error:

```<code>ValueError: invalid literal for int() with base 10: 'nan'
</code>```

答:
You have the correct idea, but you need to use astype instead for the boolean type

```<code>df['Checked'] = df['Checked'].astype(bool)
df['Verified'] = df['Verified'].astype(bool)
</code>```

As for the datetime you can use the to_datetime to do that

```<code>df['date'] = pd.to_datetime(df['date'])
df['time_h'] = pd.to_datetime(df['time_h'], format='%H:%M')
</code>```

And then you can manually convert the time_h to time

```<code>df['time_h'] = df['time_h'].map(lambda x: x.time())
</code>```

which will convert the type into a datetime.time object

Edit: if you have missing/invalid elements, that will cause the to_datetime to generate a pd.NaT object, you can handle it like this

```<code>df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else np.nan)
</code>```

here I'm converting it to an np.nan object (need to import numpy as np before) or you can leave it as is if you want using

```<code>df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else x)
</code>```

The full time_h part would be

```<code>df['time_h'] = pd.to_datetime(df['time_h'], format='%H:%M')
df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else np.nan)
</code>```

Body:
I have a dataset that looks like as follows:

date           time_h     Checked     Verified
2018-03-10    21:10     TRUE         TRUE
2018-03-19    03:20     FALSE        TRUE
2018-04-04    12:03     TBC          FALSE
...

I have been trying to convert the strings to the following formats:

date and time_h to date and time objects;

Checked and Verified to boolean values.

After putting all text in lower case, I have tried as follows:

bool = {'true': True, 'false': False}

df['Checked']=df['Checked'].map(bool)
df['Verified']=df['Verified'].map(bool)

df['date']= pd.to_datetime(df['date']).dt.date
df['time_h']= pd.to_datetime(df['time_h']).dt.strftime('%H:%M')

However, when I check using dtypes, the outputs show all the columns as objects (so no change has been applied).
Where am I doing wrong? How could I also include the TBC in the TRUE boolean value (saying TBC = TRUE)?

Edit:

An example of nan in my code within column time_h is NaN (string format, as it comes from a csv file).
After replacing 'NaN' value using

df['time_h'] = df['time_h'].replace('NaN', np.nan)

I get:

<bound method Series.isnull of 0      nan
1      nan
2      nan
3      nan

but when I use

t = df['time_h'].str.split(':', expand=True).astype(int)
df['time_h'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')

I get the following error:

ValueError: invalid literal for int() with base 10: 'nan'

Body:
You have the correct idea, but you need to use astype instead for the boolean type

df['Checked'] = df['Checked'].astype(bool)
df['Verified'] = df['Verified'].astype(bool)

As for the datetime you can use the to_datetime to do that

df['date'] = pd.to_datetime(df['date'])
df['time_h'] = pd.to_datetime(df['time_h'], format='%H:%M')

And then you can manually convert the time_h to time

df['time_h'] = df['time_h'].map(lambda x: x.time())

which will convert the type into a datetime.time object

Edit: if you have missing/invalid elements, that will cause the to_datetime to generate a pd.NaT object, you can handle it like this

df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else np.nan)

here I'm converting it to an np.nan object (need to import numpy as np before) or you can leave it as is if you want using

df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else x)

The full time_h part would be

df['time_h'] = pd.to_datetime(df['time_h'], format='%H:%M')
df['time_h'] = df['time_h'].map(lambda x: x.time() if pd.notna(x) else np.nan)


问:
Android Firebase ML-Kit real time Barcode Detection through Camera
I have a situation where i have to detect barcode from camera on fly without taking picture using Firebase ML-Kit Vision API.help appreciated.</p>

答: Use cameraview library to pass frames in realtime to firebase ml kit</p>


问:
Let a container use the OpenJDK and libraries of an existing container
I am doing some experiments with my thesis involving the cold start problem that occurs with containers. My test application is a spring boot application that is build on the openjdk image. The first thing I want to try to resolve the problem of cold start, is the following:

Have a container ready, in the container is the openjdk and the libraries that the springboot app uses. I start my other container, using the ipc and networknamespace of the already existing container, and then be able to use the openjdk and the libraries of this container to run the jar file.

I am not exactly sure on how to achieve this? Can i achieve this by using volumes or should i be looking for a completely different approach?

On a another note, if i want x containers to run, i will make sure there are x pre-existing containers running. This is to make sure that every container has its own specific librarycontainer to work with. Would this be okay ?

In short, any way that I can speed up the spring boot application by using a second containers that is connected through ipc/net; would be helpfull to my problem.

答:
Spring boot is a purely "runtime" framework.

If I've got your question right, you describe the following situation:

So, say you have a container A with JDK and some jars. This alone doesn't mean that you have a running process though. So its more like a volume with files ready to be reused (or maybe a layer in terms of docker images).

In addition you have another container B with a spring boot application that should be started somehow (probably with the open jdk from container A or its dedicated JDK).

Now what exactly would like like to "speed up"? The size of image (smaller image means faster deployment in CI/CD pipeline for example)? The spring boot application startup time (the time interval between the point of spawning the JVM till the Spring boot application is up and running)? Or maybe you're trying to load less classes in runtime?

The techniques that solve the arised issues are different. But all in all I think you might need to check out the Graal VM integration that among other things might create native images and speed up the startup time. This stuff is fairly new, I by myself haven't tried this yet. I believe its work-in-progress and spring will put an effort on pushing this forward (this is only my speculation so take it with a grain of salt).

Anyway, you may be interested in reading this article

However, I doubt it has something to do with your research as you've described it.

Update 1

Based on your comments - let me give some additional information that might help. This update contains information from the "real-life" working experience and I post it because it might help to find directions in your thesis.

So, we have a spring boot application on the first place.

By default its a JAR and its Pivotal's recommendation there is also an option of WARs(as Josh Long, their developer advocate says: "Make JAR not WAR")

This spring boot application usually includes some web server - Tomcat for traditional Spring Web MVC applications by default, but you can switch it to Jetty, or undertow. If you're running a "reactive applcation" (Spring WebFlux Supported since spring boot 2) your default choice is Netty.

One side note that not all the spring boot driven applications have to include some kind of embedded web server, but I'll put aside this subtle point since you seem to target the case with web servers (you mention tomcat, a quicker ability to serve requests etc, hence my assumption).

Ok, now lets try to analyze what happens when you start a spring boot application JAR.

First of all the JVM itself starts - the process is started, the heap is allocated, the internal classes are loaded and so on and so forth. This can take some time (around a second or even slightly more depending on server, parameters, the speed of your disk etc).
This thread address the question whether the JVM is really slow to start I probably won't be able to add more to that.

Ok, So now, its time to load the tomcat internal classes. This is again can take a couple of seconds on modern servers. Netty seems to be faster, but you can try to download a stanalone distribution of tomcat and start it up on your machine, or create a sample application wihout spring boot but with Embedded Tomcat to see what I'm talking about.

So far so good, not comes our application. As I said in the beginning, spring boot is purely runtime framework. So The classes of spring/spring boot itself must be loaded, and then the classes of the application itself. If The application uses some libraries - they'll be also loaded and sometimes even custom code will be executed during the application startup: Hibernate may check schema and/or scan db schema definitions and even update the underlying schema, Flyway/Liquidbase can execute schema migrations and what not, Swagger might scan controllers and generate documentation and what not.

Now this process in "real life" can even take a minute and even more, but its not because of the spring boot itself, but rather from the beans created in the application that have some code in "constructor"/"post-construct" - something that happens during the spring boot application context initialization. Another side note, I won't really dive into the internals of spring boot application startup process, spring boot is an extremely power framework that has a lot of things happening under the hood, I assume you've worked with spring boot in one way or another - if not, feel free to ask concrete questions about it - I/my colleagues will try to address.

If you go to start.spring.io can create a sample demo application - it will load pretty fast. So it all depends on your application beans.

In this light, what exactly should be optimized?

You've mentioned in comments that there might be a tomcat running with some JARs so that they won't be loaded upon the spring boot application starts.

Well, like our colleagues mentioned, this indeed more resembles a "traditional" web servlet container/application server model that we, people in the industry, "used for ages" (for around 20 years more or less).

This kind of deployment indeed has an "always up-and-running" a JVM process that is "always" ready to accept WAR files - a package archive of your application.
Once it detects the WAR thrown into some folder - it will "deploy" the application by means of creating the Hierarchical class-loader and loading up the application JARs/classes. Whats interesting in your context is that it was possible to "share" the libraries between multiple wars so that were loaded only once. For example, if your tomcat hosts, say, 3 applications (read 3 WARs) and all are using, oracle database driver, you can put this driver's jar to some shared libs folder and it will be loaded only once by the class loader which is a "parent" for the class loaders created per "WAR". This class loader hierarchy thing is crucial, but I believe its outside the scope of the question.

I used to work with both models (spring boot driven with embedded server, an application without spring boot with embedded Jetty server and "old-school" tomcat/jboss deployments ).

From my experience, and, as time proves, many of our colleagues agree on this point, spring boot applications are much more convenient operational wise for many reasons (again, these reasons are out of scope for the question IMO, let me know if you need to know more on this), that's why its a current "trend" and "traditional" deployments are still in the industry because or many non pure technical reasons (historical, the system is "defined to be" in the maintenance mode, you already have a deployment infrastructure, a team of "sysadmins" that "know" how to deploy, you name it, but bottom line nothing purely technical).

Now with all this information you probably understand better why did I suggest to take a look at Graal VM that will allow a faster application startup by means of native images.

One more point that might be relevant. If you're choosing the technology that will allow a fast startup, probably you're into Amazon Lambda or the alternative offered by other cloud providers these days.

This model allows virtually infinite scalability of the "computational" power (CPU) and under the hood they "start" containers and "kill" them immediately once they detect that the container does actually nothing. For this kind of application spring boot simple is not a good fit, but so is basically Java, again, because the JVM process is relatively slow-to-start, so once they start the container like this it will take too long till the time it becomes operational.

You can read Here about what spring ecosystem has to offer at this field, but its not really relevant to your question (I'm trying to provide directions).

Spring boot shines when you need an application that might take some time to start, but once it starts it can do its job pretty fast. And yes, its possible to stop the application (we use the term scale out/scale in) if its not "occupied" by doing an actual work, this approach is also kind of new (~3-4 years) and works best in "managed" deployment environments like kubernetes, amazon ECS, etc.


问:
Lock as a member of entity vs synchronized (best practice)
Let's say I have an EntityPool. After I get an entity from the pool, I need to modify the entity in a thread-safe way. So I see 2 choices:

1) Using synchronized:

```<code>Entity e = pool.getById(id);
synchronized (e) {
    // modifying e
}
</code>```

2) Add a lock to the Entity class and use it:

```<code>Entity e = pool.getById(id);
Lock l = e.getLock();
try {
    l.lock();
    // modifying e
} finally {
    l.unlock();
}
</code>```

I've heard that I should avoid using "synchronized" keyword. Should I use lock instead? But it seems weird to me that the Entity class should know anything about synchronization.

答:
There are different use cases to justify both approaches.

1 is common. It uses the object itself as a lock, so any synchronized methods on the entity as well as any other synchronized access are serialized. It also does not require making the Entity class lock-aware.

2 requires that you embed a lock into the entity class. This allows you to control synchronization in a more fine-grained manner. You can, for instance, use the lock to control access to a subset of the object state while keeping methods accessing other parts of the object lock-free.

If you know what you're doing, there's no need to avoid the synchronized keyword. That can be said for locks as well.

Body:
Let's say I have an EntityPool. After I get an entity from the pool, I need to modify the entity in a thread-safe way. So I see 2 choices:

1) Using synchronized:

Entity e = pool.getById(id);
synchronized (e) {
    // modifying e
}

2) Add a lock to the Entity class and use it:

Entity e = pool.getById(id);
Lock l = e.getLock();
try {
    l.lock();
    // modifying e
} finally {
    l.unlock();
}

I've heard that I should avoid using "synchronized" keyword. Should I use lock instead? But it seems weird to me that the Entity class should know anything about synchronization.


问:
App Engine ConfigFilter: failed to load service
I am trying to build a GAE java8 app with Cloud Endpoints Framework. I followed this guide. I have set ENDPOINTS_SERVICE_NAME and ENDPOINTS_SERVICE_VERSION in app.yaml and appengine-web.xml. I have also given my App Engine service account Editor AND Service Controller role.

Here are the logs from Logs Viewer:

```<code>com.google.api.control.ConfigFilter init: Failed to load service (ConfigFilter.java:94)
endpoints.repackaged.com.google.api.config.ServiceConfigException: Failed to fetch service config (status code 403):
This may occur if the App Engine service account has been deleted or does not have correct permissions. Visit https://console.cloud.google.com/iam-admin/iam/project and verify that the App Engine default service account has either the Editor or Service Controller role.
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.fetch(ServiceConfigSupplier.java:167)
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.get(ServiceConfigSupplier.java:131)
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.get(ServiceConfigSupplier.java:50)
    at endpoints.repackaged.com.google.common.base.Suppliers$ExpiringMemoizingSupplier.get(Suppliers.java:241)
    at endpoints.repackaged.com.google.api.config.ServiceConfigFetcher.fetch(ServiceConfigFetcher.java:41)
    at com.google.api.control.ServiceManagementConfigFilter$1.load(ServiceManagementConfigFilter.java:33)
    at com.google.api.control.ConfigFilter.init(ConfigFilter.java:90)
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:139)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:873)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:349)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1406)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:175)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1368)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:778)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:262)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:522)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:240)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:178)
    at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:120)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest(JavaRuntime.java:757)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest(JavaRuntime.java:720)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:690)
    at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run(JavaRuntime.java:882)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:270)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I have also tried following many other posts that recommended running gcloud auth application-default login. It did not fix the issue as well. Any help will be appreciated!

答:
I fixed it by enabling the following services:</p>

```<code>gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com
gcloud services enable endpoints.googleapis.com
</code>```

Body:
I am trying to build a GAE java8 app with Cloud Endpoints Framework. I followed this guide. I have set ENDPOINTS_SERVICE_NAME and ENDPOINTS_SERVICE_VERSION in app.yaml and appengine-web.xml. I have also given my App Engine service account Editor AND Service Controller role.

Here are the logs from Logs Viewer:

com.google.api.control.ConfigFilter init: Failed to load service (ConfigFilter.java:94)
endpoints.repackaged.com.google.api.config.ServiceConfigException: Failed to fetch service config (status code 403):
This may occur if the App Engine service account has been deleted or does not have correct permissions. Visit https://console.cloud.google.com/iam-admin/iam/project and verify that the App Engine default service account has either the Editor or Service Controller role.
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.fetch(ServiceConfigSupplier.java:167)
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.get(ServiceConfigSupplier.java:131)
    at endpoints.repackaged.com.google.api.config.ServiceConfigSupplier.get(ServiceConfigSupplier.java:50)
    at endpoints.repackaged.com.google.common.base.Suppliers$ExpiringMemoizingSupplier.get(Suppliers.java:241)
    at endpoints.repackaged.com.google.api.config.ServiceConfigFetcher.fetch(ServiceConfigFetcher.java:41)
    at com.google.api.control.ServiceManagementConfigFilter$1.load(ServiceManagementConfigFilter.java:33)
    at com.google.api.control.ConfigFilter.init(ConfigFilter.java:90)
    at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:139)
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:873)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:349)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1406)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.startWebapp(AppEngineWebAppContext.java:175)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1368)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:778)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:262)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:522)
    at com.google.apphosting.runtime.jetty9.AppEngineWebAppContext.doStart(AppEngineWebAppContext.java:120)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:240)
    at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:178)
    at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:120)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest(JavaRuntime.java:757)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest(JavaRuntime.java:720)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:690)
    at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run(JavaRuntime.java:882)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:270)
    at java.lang.Thread.run(Thread.java:748)

I have also tried following many other posts that recommended running gcloud auth application-default login. It did not fix the issue as well. Any help will be appreciated!

Body:
I fixed it by enabling the following services:

gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com
gcloud services enable endpoints.googleapis.com


问:
CSS: navbar items on top of each other?
in my page the navbar menu items show on top of each other.

Why?

Codepen:

https://codepen.io/ogonzales/pen/mdeNNLB

Code:

```<code><nav class="navbar navbar-expand-md navbar-light fixed-top" style="height: 70px;" id="top-navbar">
    <img src="" alt="Ministerios Elim" width="2%" height="50%"/>
    <a class="navbar-brand" href="" style="margin-right: 5%;"><span style="margin-left: 3%;">Ministerios Elim</span></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
        aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
        <ul>
            <li>
                <a href="/">Home</a>
            </li>
            {% for item in navigation.menu_items.all %}
                <li>
                    <a href="{{ item.link }}" class="nav-link" {% if item.open_in_new_tab %} target="_blank" {% endif %}>{{ item.title }}</a>
                </li>
            {% endfor %}
        </ul>
        <form class="form-inline ml-auto">
            <a href="" class="btn btn-outline-secondary">Ingresar</a>
            <a href="" class="btn btn-primary ml-2">Registro</a>
        </form>
    </div>
</nav>
</code>```

Title: CSS: navbar items on top of each other?

Body:
in my page the navbar menu items show on top of each other.

Why?

Codepen:

https://codepen.io/ogonzales/pen/mdeNNLB

Code:

    Ministerios Elim
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse"
        aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

            {% for item in navigation.menu_items.all %}

                    {{ item.title }}

            {% endfor %}

        <form class="form-inline ml-auto">
            Ingresar
            Registro
        </form>

Body: You can add "display: inline-block" to your <li>


问:
NSString with \0
What is the best way to initiate NSString that contains @"\0"?

```<code>NSString* foo = @"bar\0";
</code>```

causes 'CFString literal contains NUL character' warning.

答: NSString objects are for text. Consider using an NSData or NSMutableData object if you wish to have non-text data in amongst textual data (for example, when it is to be written to a socket or saved to a file).

ContentLicense: CC BY-SA 3.0

Title: NSString with \0

Body:
What is the best way to initiate NSString that contains @"\0"?

NSString* foo = @"bar\0";

causes 'CFString literal contains NUL character' warning.


问:
How to normalize a url in C?
A developer recently wrote a function for me to normalise URLs given a base URL and a URL to normalise. See function below:

```<code>int
starts_with(const char *str, const char *pre)
{
        size_t lenstr;
        size_t lenpre;

        if (str == NULL || pre == NULL)
                return (-1);

        lenstr = strlen(str);
        lenpre = strlen(pre);

        if (lenstr < lenpre)
                return (-1);

    return (memcmp(pre, str, lenpre));
}

char *
url_sanitize(char *base_url, char *url, int size)
{
        char *newurl;
        int base_url_len = strlen(base_url);

        if (starts_with(url, "http") == 0) {
                newurl = malloc(size+1);
                if (newurl == NULL) {
                        fprintf(stderr, "1 malloc() of %d bytes, failed\n", size);
                        exit(1);
                }

                strncpy(newurl, url, size);
                newurl[size] = '\0';

        } else {
                if (starts_with(url, "//") == 0) {
                        newurl = malloc(size+7);
                        if (newurl == NULL) {
                                fprintf(stderr, "2 malloc() of %d bytes, failed\n", size);
                                exit(1);
                        }

                        strncpy(newurl, "https:", 6);
                        strncpy(newurl+6, url, size);
                        newurl[size+6] = '\0';
                } else {
                        newurl = malloc(base_url_len + size + 2);
                        if (newurl == NULL) {
                                fprintf(stderr, "3 malloc() of %d bytes, failed\n", size);
                                exit(1);
                        }

                        strncpy(newurl, base_url, base_url_len);
                        strncpy(newurl + base_url_len, url, size);
                        newurl[size + base_url_len] = '\0';
                }
        }

        return (newurl);
}
</code>```

The problem is this function doesn't remove ./ or ../. Also it doesn't lowercase the host and scheme. It doesn't normalise properly. How can the above function be modified to properly normalise a URL?

答: The uriparser C library at https://uriparser.github.io/ allows not only parsing a URL but also recomposing, so maybe if you use that library to parse and the recompose you may get the desired result.</p>

Title: How to normalize a url in C?

Body:
A developer recently wrote a function for me to normalise URLs given a base URL and a URL to normalise. See function below:

int
starts_with(const char *str, const char *pre)
{
        size_t lenstr;
        size_t lenpre;

        if (str == NULL || pre == NULL)
                return (-1);

        lenstr = strlen(str);
        lenpre = strlen(pre);

        if (lenstr < lenpre)
                return (-1);

    return (memcmp(pre, str, lenpre));
}

char *
url_sanitize(char *base_url, char *url, int size)
{
        char *newurl;
        int base_url_len = strlen(base_url);

        if (starts_with(url, "http") == 0) {
                newurl = malloc(size+1);
                if (newurl == NULL) {
                        fprintf(stderr, "1 malloc() of %d bytes, failed\n", size);
                        exit(1);
                }

                strncpy(newurl, url, size);
                newurl[size] = '\0';

        } else {
                if (starts_with(url, "//") == 0) {
                        newurl = malloc(size+7);
                        if (newurl == NULL) {
                                fprintf(stderr, "2 malloc() of %d bytes, failed\n", size);
                                exit(1);
                        }

                        strncpy(newurl, "https:", 6);
                        strncpy(newurl+6, url, size);
                        newurl[size+6] = '\0';
                } else {
                        newurl = malloc(base_url_len + size + 2);
                        if (newurl == NULL) {
                                fprintf(stderr, "3 malloc() of %d bytes, failed\n", size);
                                exit(1);
                        }

                        strncpy(newurl, base_url, base_url_len);
                        strncpy(newurl + base_url_len, url, size);
                        newurl[size + base_url_len] = '\0';
                }
        }

        return (newurl);
}

The problem is this function doesn't remove ./ or ../. Also it doesn't lowercase the host and scheme. It doesn't normalise properly. How can the above function be modified to properly normalise a URL?


问:
How to insert data in a Graph Tree dynamically?
I am trying to insert different kinds of parameters in a Graph method using a loop. Statically I would write the code like this

```<code>    graph.connect('Station', 'Place1', 6)
    graph.connect('Place1', 'Extension12', 2)
    graph.connect('Place1', 'Extension14', 4)
    graph.connect('Place1', 'Extension17', 6)
    graph.connect('Station', 'Place2', 2)
    graph.connect('Place2', 'Extension13', 6)
    graph.connect('Place2', 'Extension16', 4)
    graph.connect('Place2', 'Extension21', 2)
</code>```

But I want to use a loop to get this data from dictionary and insert it into a graph method.

location = {'Station': 0, Place2': 2, 'Place1': 6}

sublocation = {'Extension12': 2, 'Extension14': 4, 'Extension17': 6, 'Extension13': 6, 'Extension16': 4, 'Extension21': 2}

答:
If I'm understanding correctly, you want to organize data per group. You can do this simply using a nested dictionary with lists. Example:

```<code>data = {
  "Place1": [
    ["Extension12", 2],
    ["Extension14", 4],
  ],
  "Place2": [...]
}

for place in data.keys():
    for ext in data[place]:
        graph.connect(place, ext[0], ext[1])
</code>```

This should dynamically add them to the graph. Although I am concerned about the discrepancies in your parameters (Station) but it seems straightforward to deal with.

Body:
I am trying to insert different kinds of parameters in a Graph method using a loop. Statically I would write the code like this

    graph.connect('Station', 'Place1', 6)
    graph.connect('Place1', 'Extension12', 2)
    graph.connect('Place1', 'Extension14', 4)
    graph.connect('Place1', 'Extension17', 6)
    graph.connect('Station', 'Place2', 2)
    graph.connect('Place2', 'Extension13', 6)
    graph.connect('Place2', 'Extension16', 4)
    graph.connect('Place2', 'Extension21', 2)

But I want to use a loop to get this data from dictionary and insert it into a graph method.

location = {'Station': 0, Place2': 2, 'Place1': 6}

sublocation = {'Extension12': 2, 'Extension14': 4, 'Extension17': 6, 'Extension13': 6, 'Extension16': 4, 'Extension21': 2}

Body:
If I'm understanding correctly, you want to organize data per group. You can do this simply using a nested dictionary with lists. Example:

data = {
  "Place1": [
    ["Extension12", 2],
    ["Extension14", 4],
  ],
  "Place2": [...]
}

for place in data.keys():
    for ext in data[place]:
        graph.connect(place, ext[0], ext[1])

This should dynamically add them to the graph. Although I am concerned about the discrepancies in your parameters (Station) but it seems straightforward to deal with.


问:
JS window.onload why don't wait loaded
Why it works without waiting for the page to be full loaded. Also, how can I run a function when the whole page is full loaded on Javascript?

答:
change your onload function syntax to any one of the following and try

```<code>window.addEventListener('load', (event) => {
 console.log('page is fully loaded');
});
</code>```

with onload

```<code>window.onload = (event) => {
 console.log('page is fully loaded');
};
</code>```

Title: JS window.onload why don't wait loaded

Body:
change your onload function syntax to any one of the following and try

window.addEventListener('load', (event) => {
 console.log('page is fully loaded');
});

with onload

window.onload = (event) => {
 console.log('page is fully loaded');
};


问:
How to make a discord bot send a message in a channel when a video is uploaded by a specific youtuber
I need my discord bot to send a message whenever a specific youtube channel uploads a video.  How would I do this in python?  I just want examples of the different ways it can be done.</p>

答: For this you need to use the Google data api, aka the youtube api, and combine it with the discord api. the discord api is pretty easy to understand, but the youtube one is pretty hard. so i sugesst you dig deep in how apis work and how the youtube data api functions</p>


问:
Populate values in a dataframe based on matching row and column of another dataframe
I have two data-frames and I want to populate new column values in data-frame1 based on matching Zipcode and date from another data-frame2.
The sample input and desired output are given below. The date formats are not the same. Dataframe 1 has more than 100k records and data-frame2 has columns for every month.

Any suggestions would be of great help since I am a newbie to python.

答:
you are looking for pd.merge. Here is an example which shows how you can use it.

```<code>df1 = pd.DataFrame({'x1': [1, 2, 3, 4, 5, 6],
                'y': ['a', 'b', 'c', 'd', 'e', 'f']})

df2 = pd.DataFrame({'x2': [1, 2, 3, 4, 5, 6],
                    'y': ['h', 'i', 'j', 'k', 'l', 'm']})

pd.merge(df1, df2, left_on='x1', right_on='x2')
</code>```

Body:
you are looking for pd.merge. Here is an example which shows how you can use it.

df1 = pd.DataFrame({'x1': [1, 2, 3, 4, 5, 6],
                'y': ['a', 'b', 'c', 'd', 'e', 'f']})

df2 = pd.DataFrame({'x2': [1, 2, 3, 4, 5, 6],
                    'y': ['h', 'i', 'j', 'k', 'l', 'm']})

pd.merge(df1, df2, left_on='x1', right_on='x2')


问:
Implementing a cache
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

```<code>loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []
</code>```

but I'm getting a

```
Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)
```

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

```<code>findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType
</code>```

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

答: Why not just memoize findObj?</p>

OwnerDisplayName: viraptor

ContentLicense: CC BY-SA 2.5

Title: Implementing a cache

Body:
I'm trying to implement a transparent cache that can load a specific object when it's not available, or return an already existing object indexed by (name).

I've tried running this:

loader' objs name = case findObj objs name of
  Nothing →  (new_obj, loader' new_objs)
  Just obj →  (obj, loader' objs)
  where
    new_objs = [(name, new_obj)] ++ objs
    new_obj = readObj name
loader = loader' []

but I'm getting a

Occurs check: cannot construct the infinite type:
  t = (ObjType, String -> t)

which looks exactly like something I want :)

How can I fix the function so that it compiles?

Clarifications:

As requested, signatures (findObj either returns a known value found via a key, or Nothing, readObj creates a new obj for a key):

findObj :: [(String, ObjType)] -> String -> Maybe ObjType
readObj :: String -> ObjType

And yes - I need a cache, because the keys are filenames and I don't want to read+parse the file each time some object is needed.

LastEditorDisplayName: David Segonds

Body: Why not just memoize findObj?

OwnerDisplayName: Craig Stuntz


问:
implementing simple Document management
My qustion is: How would you go on implementing simple DMS(document management) based on following requirements?

DMS shouls be distributed web application.

Support for document versioning.

Support for document locking.

Document search.

Im already clear on what technologies I want to use. I will use Sring MVC, Hibernate and relational (most likely MYSQL) database.

One thing Im not very clear on is if I need to use webdav, since I could just upload or download documets. I thing I have to because I need to acomplish point 2. and especially point 3. somehow. Is this the right way to go?

Any examples or experience with this would come very handy :). May be Milton is not the best library to pick for webdav?

答:
Option 1:

I am not sure about webdav, no real experience on it. But I would highly recommend you using a Document database like MongoDB.

With mongodb, you can:

1. Handle document versions

2. MongoDB has atomic operations, you can add your logic of document locking.

This will give you some awesome added benefits of search your documents store.

Option 2:

Apache Jackrabbit: A Content repository

A content repository is a hierarchical
  content store with support for
  structured and unstructured content,
  full text search, versioning,
  transactions, observation, and more.

Title: implementing simple Document management


问:
How to download/find the Saxon samples/cs for .NET
This page: https://www.saxonica.com/html/documentation/samples/dotnetsamples.html refers to a samples/cs directory.   Where can that be found or downloaded?

The samples/cs directory contains some sample applications written in
  C#, designed to illustrate use of the Saxon API available in the
  Saxon.Api namespace.

I downloaded the Saxonica open source from SourceForge (filename=saxon9-9-1-7source.zip) and don't see it in there. I think it contains the "trans-compiled" code from Java.

答:
It's in the latest saxon-resourcesx-x.zip (example saxon-resources9-9.zip).

I finally figured this out by reading the readme99.txt that is also available on SourceForge.

https://sourceforge.net/projects/saxon/files/Saxon-HE/9.9/

After unzipping it, it also a local html copy of the documentation, for example: C:/Saxonica/Resources/doc/dotnetdoc/index.html


答:
It depends on your definition of "loaded".

The load event will fire...

[...]once a web page has completely loaded all content (including images, script files, CSS files, etc.). (Source)

This is the case here. All the images and script files and CSS files in the original HTML document have been loaded! However, the "loaded" state in case of Twitter is a state in which a script will later initiate the loading of new elements. That is outside the scope of the original page load.

If you want to wait for what you call "loaded", you'd have to ask yourself technically what point that is. I guess the answer would be something like "when element X is visible". In that case you can install a MutationObserver to listen on that element getting added/modified, after identifying what element you want to wait for by checking the DOM in your browser console. (The worse solution would be an interval that checks if that element exists yet.)

For Twitter, this works for me for example (watching for the first story to be loaded):

const observer = new MutationObserver(mutations => {
  if (mutations.some(mutation => {
    return Array.from(mutation.addedNodes).some(node => node.querySelector('article'))
  })) {
    setTimeout(() => { // Wait for all the updates of this frame to go through
      console.log('Page fully loaded!')
    }, 0)
    observer.disconnect()
  }
})

observer.observe(document, {
  attributes: false,
  childList: true,
  characterData: false,
  subtree: true
})
```

Title: JS window.onload why don't wait loaded

Body: Why it works without waiting for the page to be full loaded. Also, how can I run a function when the whole page is full loaded on Javascript?


问:
Renaming multiple JSON based on its content using Batch file
This is more sort of a continuation to this question, I referred to the answer section and its fine but it doesn't seem to work for JSON files. The below is my JSON

```<code>{
    "id": "ee308826-5aa6-412b-ba65-fd647d9cc8e8",
    "name": "Stub",
    "request": {
        "url": "/World/Wilfred",
        "method": "GET"
    }
}
</code>```

I need the file to be renamed with "Stub_GET_World_Wilfred.json" which is of the syntax name_method_url ( without the / )

Script from the Original Question :

```<code>@echo off

for %%i in (%1) do (
  for /f "tokens=2 delims==" %%j in ('findstr /B /I "Description=" "%%i"') do (
    ren "%%i" "%%j.temp_txt"
  )
)

ren *.temp_txt *.txt
</code>```

答:
The following commented batch file could be used for this task:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ErrorCount=0"
set "FileCount=0"

rem Was the batch file called with an argument string to process one file?
if not "%~1" == "" (
    rem Is there no file (or directory) with the name passed to the batch file?
    if not exist "%~1" (
        set "ErrorCount=1"
        echo ERROR: File "%~1" does not exist.
    ) else call :ProcessFile "%~1"
    goto EndBatch
)

rem Process all files with the file extension .json in current directory.
for /F "eol=| delims=" %%I in ('dir *.json /A-D /B 2^>nul') do call :ProcessFile "%%I"
goto EndBatch

rem Rund FINDSTR on the file (or wrong on directory) in a background command
rem process started by FOR to find lines with the literal string "url" or the
rem literal string "method" in any case and process this line by splitting it
rem into substrings using comma, colon, horizontal tab and normal space as
rem string delimiters with using first substring without the surrounding quotes
rem as environment variable name and assigning the second substring without the
rem surrounding quotes to the environment variable. Please note that this code
rem does not work for a url with a colon or comma inside.

:ProcessFile
set /A FileCount+=1
set "method="
set "url="
for /F "tokens=1,2 delims=,:     " %%J in ('%SystemRoot%\System32\findstr.exe /I /L /C:"\"url\"" /C:"\"method\"" "%~1"') do set "%%~J=%%~K"

if not defined url (
    rem There was no string "url" found in the file (or the passed string
    rem was a folder name) or the line with "url" has not a string value.
    set /A ErrorCount+=1
    echo ERROR: Could not find a url in "%~1".
    goto :EOF
)
if not defined method (
    rem There was no string "method" found in the file (or the passed string
    rem was a folder name) or the line with "method" has not a string value.
    set /A ErrorCount+=1
    echo ERROR: Could not find a method in "%~1".
    goto :EOF
)

rem Create the new file name by concatenating Stub_ with the method string
rem and with the url string read from the file with each slash replaced by
rem an underscore in url and file extension .json appended. There is not
rem replaced any percent encoded character in the url by the appropriate
rem character.
set "FileName=Stub_%method%%url:/=_%.json"

rem There is nothing done on name of processed file has case-insensitive
rem compared already the right name.
if /I "%~nx1" == "%FileName%" goto :EOF

rem Next is checked if a file with new name exists already in directory of the
rem file passed to the batch file which makes it impossible to rename the file.
if exist "%~dp1%FileName%" (
    set /A ErrorCount+=1
    echo ERROR: A file with name "%FileName%" exits already in "%~dp1".
    goto :EOF
)

rem Otherwise the file is renamed which can still fail for various reasons.
ren "%~1" "%FileName%"
if errorlevel 1 (
    set /A ErrorCount+=1
    echo ERROR: File "%~1" could not be renamed to "%FileName%".
    goto :EOF
)
echo Renamed file "%~1" to "%FileName%".
goto :EOF

:EndBatch
set "Plural_S_Files="
if not %FileCount% == 1 set "Plural_S_Files=s"
set "Plural_S_Errors="
if not %ErrorCount% == 1 set "Plural_S_Errors=s"
echo/
echo Proccessed %FileCount% file%Plural_S_Files% with %ErrorCount% error%Plural_S_Errors%.
if not %ErrorCount% == 0 echo/& pause
endlocal
</code>```

ATTENTION: There must be a horizontal tab and a space after delims=,: left to " in the batch file. Please make sure to have only these two characters and not multiple spaces in the batch file after copying and pasting the batch file code.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?

dir /?

echo /?

endlocal /?

findstr /?

for /?

goto /?

if /?

pause /?

rem /?

ren /?

set /?

setlocal /?

See single line with multiple commands using Windows batch file for an explanation of operator &.

Body:
This is more sort of a continuation to this question, I referred to the answer section and its fine but it doesn't seem to work for JSON files. The below is my JSON

{
    "id": "ee308826-5aa6-412b-ba65-fd647d9cc8e8",
    "name": "Stub",
    "request": {
        "url": "/World/Wilfred",
        "method": "GET"
    }
}

I need the file to be renamed with "Stub_GET_World_Wilfred.json" which is of the syntax name_method_url ( without the / )

Script from the Original Question :

@echo off

for %%i in (%1) do (
  for /f "tokens=2 delims==" %%j in ('findstr /B /I "Description=" "%%i"') do (
    ren "%%i" "%%j.temp_txt"
  )
)

ren *.temp_txt *.txt

Body:
The following commented batch file could be used for this task:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "ErrorCount=0"
set "FileCount=0"

rem Was the batch file called with an argument string to process one file?
if not "%~1" == "" (
    rem Is there no file (or directory) with the name passed to the batch file?
    if not exist "%~1" (
        set "ErrorCount=1"
        echo ERROR: File "%~1" does not exist.
    ) else call :ProcessFile "%~1"
    goto EndBatch
)

rem Process all files with the file extension .json in current directory.
for /F "eol=| delims=" %%I in ('dir *.json /A-D /B 2^>nul') do call :ProcessFile "%%I"
goto EndBatch

rem Rund FINDSTR on the file (or wrong on directory) in a background command
rem process started by FOR to find lines with the literal string "url" or the
rem literal string "method" in any case and process this line by splitting it
rem into substrings using comma, colon, horizontal tab and normal space as
rem string delimiters with using first substring without the surrounding quotes
rem as environment variable name and assigning the second substring without the
rem surrounding quotes to the environment variable. Please note that this code
rem does not work for a url with a colon or comma inside.

:ProcessFile
set /A FileCount+=1
set "method="
set "url="
for /F "tokens=1,2 delims=,:     " %%J in ('%SystemRoot%\System32\findstr.exe /I /L /C:"\"url\"" /C:"\"method\"" "%~1"') do set "%%~J=%%~K"

if not defined url (
    rem There was no string "url" found in the file (or the passed string
    rem was a folder name) or the line with "url" has not a string value.
    set /A ErrorCount+=1
    echo ERROR: Could not find a url in "%~1".
    goto :EOF
)
if not defined method (
    rem There was no string "method" found in the file (or the passed string
    rem was a folder name) or the line with "method" has not a string value.
    set /A ErrorCount+=1
    echo ERROR: Could not find a method in "%~1".
    goto :EOF
)

rem Create the new file name by concatenating Stub_ with the method string
rem and with the url string read from the file with each slash replaced by
rem an underscore in url and file extension .json appended. There is not
rem replaced any percent encoded character in the url by the appropriate
rem character.
set "FileName=Stub_%method%%url:/=_%.json"

rem There is nothing done on name of processed file has case-insensitive
rem compared already the right name.
if /I "%~nx1" == "%FileName%" goto :EOF

rem Next is checked if a file with new name exists already in directory of the
rem file passed to the batch file which makes it impossible to rename the file.
if exist "%~dp1%FileName%" (
    set /A ErrorCount+=1
    echo ERROR: A file with name "%FileName%" exits already in "%~dp1".
    goto :EOF
)

rem Otherwise the file is renamed which can still fail for various reasons.
ren "%~1" "%FileName%"
if errorlevel 1 (
    set /A ErrorCount+=1
    echo ERROR: File "%~1" could not be renamed to "%FileName%".
    goto :EOF
)
echo Renamed file "%~1" to "%FileName%".
goto :EOF

:EndBatch
set "Plural_S_Files="
if not %FileCount% == 1 set "Plural_S_Files=s"
set "Plural_S_Errors="
if not %ErrorCount% == 1 set "Plural_S_Errors=s"
echo/
echo Proccessed %FileCount% file%Plural_S_Files% with %ErrorCount% error%Plural_S_Errors%.
if not %ErrorCount% == 0 echo/& pause
endlocal

ATTENTION: There must be a horizontal tab and a space after delims=,: left to " in the batch file. Please make sure to have only these two characters and not multiple spaces in the batch file after copying and pasting the batch file code.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

call /?

dir /?

echo /?

endlocal /?

findstr /?

for /?

goto /?

if /?

pause /?

rem /?

ren /?

set /?

setlocal /?

See single line with multiple commands using Windows batch file for an explanation of operator &.