问:
PostgreSQL ERROR: canceling statement due to conflict with recovery
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

```<code>ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed
</code>```

Any suggestions on how to resolve? Thanks

答:
It might be too late for the answer but we face the same kind of issue on the production.
Earlier we have only one RDS and as the number of users increases on the app side, we decided to add Read Replica for it. Read replica works properly on the staging but once we moved to the production we start getting the same error.

So we solve this by enabling hot_standby_feedback property in the Postgres properties.
We referred the following link

https://aws.amazon.com/blogs/database/best-practices-for-amazon-rds-postgresql-replication/

I hope it will help.

Body:
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed

Any suggestions on how to resolve? Thanks


来源: stackexchange

问:
How to display images using PyQt5 on a widget?
I am making Wafer contour map program by PyQt5. I have some problems.

```<code>import pandas as pd
test = pd.DataFrame(index=range(0,101), columns=range(0,101)) # empty dataframe

for i in range(0,101):  #
    for j in range(0,101):
        if ((50-i)**2 + (50-j)**2) < 50**2:
            test.loc[i,j] = i*2+i+j
        else:
            test.loc[i,j] = 0

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
test[test == 0] = np.nan
plt.figure(1)
plt.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')
plt.colorbar()
</code>```

I got a below image

and I would like to display this image instead of graph on PyQt5 window

My window is below like

```<code>from PyQt5.uic import loadUiType
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar)

Ui_MainWindow, QMainWindow = loadUiType(r'C:\Users\wtjang\.spyder-py3\window.ui')

import numpy as np
from PyQt5 import QtWidgets

class Main(QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()

if __name__ == '__main__':
    import sys
    from PyQt5 import QtWidgets

    fig1 = Figure()
    ax1f1 = fig1.add_subplot(111)
    ax1f1.plot(np.random.rand(5))

    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.addmpl(fig1)
    main.show()
    sys.exit(app.exec_())
</code>```

how to change graph to wafer image?

I tried to

```<code> if __name__ == '__main__':
        import sys
        from PyQt5 import QtWidgets

        fig1 = plt.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')

        app = QtWidgets.QApplication(sys.argv)
        main = Main()
        main.addmpl(fig1)
        main.show()
        sys.exit(app.exec_())
</code>```

but I failed.

答:
I got a answer. Thank your helping :)</p>

```<code>ax1f1.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making Wafer contour map program by PyQt5. I have some problems.

import pandas as pd
test = pd.DataFrame(index=range(0,101), columns=range(0,101)) # empty dataframe

for i in range(0,101):  #
    for j in range(0,101):
        if ((50-i)**2 + (50-j)**2) < 50**2:
            test.loc[i,j] = i*2+i+j
        else:
            test.loc[i,j] = 0

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
test[test == 0] = np.nan
plt.figure(1)
plt.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')
plt.colorbar()

I got a below image

and I would like to display this image instead of graph on PyQt5 window

My window is below like

from PyQt5.uic import loadUiType
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QT as NavigationToolbar)

Ui_MainWindow, QMainWindow = loadUiType(r'C:\Users\wtjang\.spyder-py3\window.ui')

import numpy as np
from PyQt5 import QtWidgets

class Main(QMainWindow, Ui_MainWindow):
    def __init__(self, ):
        super(Main, self).__init__()
        self.setupUi(self)

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()

if __name__ == '__main__':
    import sys
    from PyQt5 import QtWidgets

    fig1 = Figure()
    ax1f1 = fig1.add_subplot(111)
    ax1f1.plot(np.random.rand(5))

    app = QtWidgets.QApplication(sys.argv)
    main = Main()
    main.addmpl(fig1)
    main.show()
    sys.exit(app.exec_())

how to change graph to wafer image?

I tried to

 if __name__ == '__main__':
        import sys
        from PyQt5 import QtWidgets

        fig1 = plt.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')

        app = QtWidgets.QApplication(sys.argv)
        main = Main()
        main.addmpl(fig1)
        main.show()
        sys.exit(app.exec_())

but I failed.

Body:
I got a answer. Thank your helping :)

ax1f1.imshow(test, interpolation = 'hanning', vmin = 0, cmap = 'gist_rainbow_r')


问:
Need help transferring multiple strings from one .XIB file to a view controller
My goal is to try and pass multiple names from one input in an XIB view to a view controller file. It's a very simple issue, but I haven't found a solution online.

This is what I'm using to try and transfer the string input currently.

```<code>    let nameOne = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameOne.swimmerOneName = swimmerOneTextField.text!

    let nameTwo = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameTwo.swimmerTwoName = swimmerTwoTextField.text!

    let nameThree = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameThree.swimmerThreeName = swimmerThreeTextField.text!

    let nameFour = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameFour.swimmerFourName = swimmerFourTextField.text!

    navigationController?.pushViewController(nameOne, animated: true)
    navigationController?.pushViewController(nameTwo, animated: true)
    navigationController?.pushViewController(nameThree, animated: true)
    navigationController?.pushViewController(nameFour, animated: true)
</code>```

My issue is that it only transfers one name at a time with an animation each time also. I have tried setting the "animated: true" to false however it still only transfers each name one at a time.

To make it more clear this is what I'm trying to accomplish. This was done using segues and the storyboard, not an XIB: Images 1 and 2

This is what is happening to me when I want to transfer all the names: Images 3 and 4. It cycles through each one and doesn't keep them all at once like in image 2.

答: you can define a global array of String and transfer your text with this array but better way is using one of pass data methods.</p>

Body:
My goal is to try and pass multiple names from one input in an XIB view to a view controller file. It's a very simple issue, but I haven't found a solution online.

This is what I'm using to try and transfer the string input currently.

    let nameOne = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameOne.swimmerOneName = swimmerOneTextField.text!

    let nameTwo = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameTwo.swimmerTwoName = swimmerTwoTextField.text!

    let nameThree = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameThree.swimmerThreeName = swimmerThreeTextField.text!

    let nameFour = TwoMedleyStopwatch(nibName: "TwoMedleyStopwatch", bundle: nil)
    nameFour.swimmerFourName = swimmerFourTextField.text!

    navigationController?.pushViewController(nameOne, animated: true)
    navigationController?.pushViewController(nameTwo, animated: true)
    navigationController?.pushViewController(nameThree, animated: true)
    navigationController?.pushViewController(nameFour, animated: true)

My issue is that it only transfers one name at a time with an animation each time also. I have tried setting the "animated: true" to false however it still only transfers each name one at a time.

To make it more clear this is what I'm trying to accomplish. This was done using segues and the storyboard, not an XIB: Images 1 and 2

This is what is happening to me when I want to transfer all the names: Images 3 and 4. It cycles through each one and doesn't keep them all at once like in image 2.


问:
Prevent download of MP3 files in wordpress
I know many people asks the opposite of what I am asking. I am trying to make browsers play the file instead of downloading when opening the mp3 files´ link. I do not care if the users download the file after that, but I need the browsers to play the file at first, instead of automatically downloading. It happens in computers and smarthphones.
, b
I don´t know if it is something I have to change in .htaccess file or somewhere else. The link to the site is this: https://cefadchurch.com/sermones/predicas-dominicales/
Try the download button. If you see, it directly sends you to the file´s link, but it starts downloading instead playing. I know a "Download" button function is obviously to make the browser download the file, but that will not be the case for me, because however, if the button sends me to the file´s link, I rather the browser play instead download, and the company has asked me for that function.</p>

答:
In your response headers, you're actively forcing the download in two ways:

```<code>Content-Disposition: attachment
Content-Type: application/octet-stream
</code>```

Firstly, the Content-Disposition header value of attachment forces a download to occur.  You must get rid of it if you want to not have a forced download.

Next, the content type of application/octet-stream is the generic binary type, and thus the browser doesn't know how to render it so just downloads it as a file to let the system handle it.  If you're sending MP3s, use audio/mpeg for the Content-Type response header.

Finally, not all browsers can/will play media in a tab when you link to the media directly.  If you want the file to play in-browser, you need to embed it into a web page with the <audio> tag.

Body:
In your response headers, you're actively forcing the download in two ways:

Content-Disposition: attachment
Content-Type: application/octet-stream

Firstly, the Content-Disposition header value of attachment forces a download to occur.  You must get rid of it if you want to not have a forced download.

Next, the content type of application/octet-stream is the generic binary type, and thus the browser doesn't know how to render it so just downloads it as a file to let the system handle it.  If you're sending MP3s, use audio/mpeg for the Content-Type response header.

Finally, not all browsers can/will play media in a tab when you link to the media directly.  If you want the file to play in-browser, you need to embed it into a web page with the <audio> tag.


问:
if statement, boolean value
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

```<code>        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }
</code>```

My question is about this if statement and boolean value:

```<code>            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
</code>```

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

答:
A bool value on its own is the same as value == true

If you have

```<code>bool trueThing = true;
</code>```

then the following are all equivalent (and true)

```<code>trueThing;
trueThing == true;
(trueThing == true) == true;
((trueThing == true) == true) == true;
</code>```

and so on.  The simplest, least verbose form is the first: trueThing.  It's not a 0 or 1, it's a true or false.

ContentLicense: CC BY-SA 3.0

Title: if statement, boolean value

Body:
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }

My question is about this if statement and boolean value:

            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

Body:
A bool value on its own is the same as value == true

If you have

bool trueThing = true;

then the following are all equivalent (and true)

trueThing;
trueThing == true;
(trueThing == true) == true;
((trueThing == true) == true) == true;

and so on.  The simplest, least verbose form is the first: trueThing.  It's not a 0 or 1, it's a true or false.


问:
Unable to add NuGet packages
I have started a new sample .NET Core 3.1 project to use Gremlin.NET to connect to CosmosDB Graph API and can't seem to get the Gremlin.NET package installed. The problem is when I run dotnet add package Gremlin.NET, I get the following output:

```<code>  Writing C:\Users\xxx\AppData\Local\Temp\tmp343B.tmp
info : Adding PackageReference for package 'Gremlin.NET' into project 'C:\opt\Source\...\gremlin-spike\gremlin-spike.csproj'.
info : Restoring packages for C:\opt\Source\...\gremlin-spike\gremlin-spike.csproj...
error: The local source 'C:\Program Files\Microsoft SDKs\Service Fabric\packages\' doesn't exist.
</code>```

The problem is the last line where it is attempting save package into the Service Fabric packages directory, but I no longer have Service Fabric installed and the directory no longer exists. I have looked at all the nuget.config files I can find and none of them have a package source pointing to that directory. How do I reset .NET Core to use the default packages folder location instead of this value?

答:
Create an empty folder here:

C:\Program Files\Microsoft SDKs\Service Fabric\packages

Title: Unable to add NuGet packages

Body:
I have started a new sample .NET Core 3.1 project to use Gremlin.NET to connect to CosmosDB Graph API and can't seem to get the Gremlin.NET package installed. The problem is when I run dotnet add package Gremlin.NET, I get the following output:

  Writing C:\Users\xxx\AppData\Local\Temp\tmp343B.tmp
info : Adding PackageReference for package 'Gremlin.NET' into project 'C:\opt\Source\...\gremlin-spike\gremlin-spike.csproj'.
info : Restoring packages for C:\opt\Source\...\gremlin-spike\gremlin-spike.csproj...
error: The local source 'C:\Program Files\Microsoft SDKs\Service Fabric\packages\' doesn't exist.

The problem is the last line where it is attempting save package into the Service Fabric packages directory, but I no longer have Service Fabric installed and the directory no longer exists. I have looked at all the nuget.config files I can find and none of them have a package source pointing to that directory. How do I reset .NET Core to use the default packages folder location instead of this value?


问:
How to prompt the user that they already made an election in this condition
At the end of this code, I'm trying to prevent the user from inputting another entry for menuID 2. I need to prompt that they've already made an election and then redisplay my table.

I'm aware my else statement is incorrect.

```<code>menuID = -1
totalPrice = 0
while (menuID != 0)
  puts ("Menu ID \tMenu Item")
  puts ("-------\t\t----------")
  puts ("1\t\tAdd Item Charge")
  puts ("2\t\tAdd Labor Charge")
  puts ("3\t\tApply Discount")
  puts ("4\t\tApply Gift Card")
  puts ("5\t\tTotal")
  puts ("9\t\tNew Transaction")
  puts ("0\t\tExit Application")

  print ("Enter Menu ID: ")
  menuID = gets().to_i()
  if (menuID == 1)
    print ("Enter item's charge amount: $")
    chargeAmount = gets().to_f()
    chargeAmount = chargeAmount.round(2)
    totalPrice += chargeAmount
    if (chargeAmount <= 0)
      puts ("Item charge amount must be greater than 0. You entered $#{chargeAmount}")
    end

  elsif (menuID == 2)
    print ("Enter labor charge amount: $")
    laborCharge = gets().to_f()
    laborCharge = laborCharge.round(2)
    if (laborCharge <= 0)
      puts ("Labor charge amount must be greater than 0. You entered $#{laborCharge}")
    else
      puts ("Labor charge has already been applied")
    end
  end

end
</code>```

答:
Here's a basic structure you could use.

Menu

First let's create a helper method to display the menu. Doing so speeds testing and makes it easier to change the menu in future.

```<code>MENU = [{ label: "Add Item Charge",  text: 'item',  type: :item },
        { label: "Add Labor Charge", text: 'labor', type: :labor}]
</code>```

```<code>def display_menu
  puts "Menu ID \tMenu Item"
  puts "-------\t\t----------"
  MENU.each.with_index(1) { |h,i| puts "#{i}\t\t#{h[:label]}" }
  puts "0\t\tExit application"
end
</code>```

Let's try it.

```<code>display_menu
Menu ID         Menu Item
-------         ----------
1               Add Item Charge
2               Add Labor Charge
0               Exit application
</code>```

Note that to make changes to the menu items only MENU needs to be altered.

For now, disregard the keys :text and :type in MENU.

Adding charges

If the user wishes to add an item charge the following method will be called with an argument that is a label for the charge type and will return a valid dollar amount:

```<code>def item_charge(charge_type)
  loop do
    print "Enter #{charge_type} amount: $"
    case (amt = Float(gets, exception: false))
    when nil
      puts "  Entry must be in dollars or dollars and cents"
    when -Float::INFINITY...0
      puts "  Entry cannot be negative"
    else
      break amt
    end
  end
end
</code>```

See Kernel::Float. This method was given the :exception option in Ruby v2.7. Earlier versions raised an exception if the string could not be converted to a float. That exception would have to be rescued and nil returned.

Here's a possible dialogue:

```<code>item_charge('labor')
Enter labor amount: $213.46x
  Entry must be in dollars or dollars and cents
Enter labor amount: $-76
  Entry cannot be negative
Enter labor amount: $154.73
  #=> 154.73
</code>```

Save charges

Now let's create a hash to hold the total cost of items and the cost of labor, with values initialized to nil.

```<code>costs = MENU.each_with_object({}) { |g,h| h[g[:type]] = nil }
  #=> {:item=>nil, :labor=>nil}
</code>```

This will be the first line of the method enter_costs below.

OK to exit?

Let's assume we don't want to allow the user to exit the application before they have entered a labor charge and at least one item charge. We might write a separate method to see if they meet that requirement:

```<code>def ok_to_exit?(costs)
  h = MENU.find { |h| costs[h[:type]].nil? }
  puts "  You have not yet entered a #{h[:text]} cost" unless h.nil?
  h.nil?
end
</code>```

See Enumerable#find.

Is menu selection valid?

We need to see if numerical value entered for the menu id selection (other than zero, which we have already checked for) is valid:

```<code>def menu_selection_valid?(menu_id)
  valid = (1..MENU.size).cover?(menu_id)
  puts "  That is not a valid menu id" unless valid
  valid
end
</code>```

```<code>menu_selection_valid?(4)
That is not a valid menu id
  #=> false
menu_selection_valid?(-3)
That is not a valid menu id
  #=> false
menu_selection_valid?(2)
  #=> true
</code>```

Body

We can now put everything together.

```<code>def enter_costs
  costs = MENU.each_with_object({}) { |g,h| h[g[:type]] = nil }
  loop do
    display_menu
    print ("Enter Menu ID: ")
    menu_id = gets().to_i

    if menu_id.zero?
      ok_to_exit?(costs) ? break : next
    end

    next unless menu_selection_valid?(menu_id)

    h = MENU[menu_id-1]
    case h[:type]
    when :labor
      if costs[h[:type]].nil?
        costs[h[:type]] = item_charge(h[:text])
      else
        puts "  You have already entered the labor charge"
        next
      end
    when :item
      costs[h[:type]] = (costs[h[:type]] ||= 0) + item_charge(h[:text])
    end
  end
  costs
end
</code>```

Here is a possible dialog.

```<code>def display_menu
  puts "Menu ID \tMenu Item"
  puts "-------\t\t----------"
  MENU.each.with_index(1) { |h,i| puts "#{i}\t\t#{h[:label]}" }
  puts "0\t\tExit application"
end
</code>```0

```<code>def display_menu
  puts "Menu ID \tMenu Item"
  puts "-------\t\t----------"
  MENU.each.with_index(1) { |h,i| puts "#{i}\t\t#{h[:label]}" }
  puts "0\t\tExit application"
end
</code>```1

Notice that the numbering of items in the menu is done in code, so that changes to MENU will not necessitate changes to those menu item numbers elsewhere in the code.

I suggest using Kernel#loop, together with keyword break, for all loops, in preference to while, until and (especially) for loops.

Body:
At the end of this code, I'm trying to prevent the user from inputting another entry for menuID 2. I need to prompt that they've already made an election and then redisplay my table.

I'm aware my else statement is incorrect.

menuID = -1
totalPrice = 0
while (menuID != 0)
  puts ("Menu ID \tMenu Item")
  puts ("-------\t\t----------")
  puts ("1\t\tAdd Item Charge")
  puts ("2\t\tAdd Labor Charge")
  puts ("3\t\tApply Discount")
  puts ("4\t\tApply Gift Card")
  puts ("5\t\tTotal")
  puts ("9\t\tNew Transaction")
  puts ("0\t\tExit Application")

  print ("Enter Menu ID: ")
  menuID = gets().to_i()
  if (menuID == 1)
    print ("Enter item's charge amount: $")
    chargeAmount = gets().to_f()
    chargeAmount = chargeAmount.round(2)
    totalPrice += chargeAmount
    if (chargeAmount <= 0)
      puts ("Item charge amount must be greater than 0. You entered $#{chargeAmount}")
    end

  elsif (menuID == 2)
    print ("Enter labor charge amount: $")
    laborCharge = gets().to_f()
    laborCharge = laborCharge.round(2)
    if (laborCharge <= 0)
      puts ("Labor charge amount must be greater than 0. You entered $#{laborCharge}")
    else
      puts ("Labor charge has already been applied")
    end
  end

end

Body:
Here's a basic structure you could use.

Menu

First let's create a helper method to display the menu. Doing so speeds testing and makes it easier to change the menu in future.

MENU = [{ label: "Add Item Charge",  text: 'item',  type: :item },
        { label: "Add Labor Charge", text: 'labor', type: :labor}]

def display_menu
  puts "Menu ID \tMenu Item"
  puts "-------\t\t----------"
  MENU.each.with_index(1) { |h,i| puts "#{i}\t\t#{h[:label]}" }
  puts "0\t\tExit application"
end

Let's try it.

display_menu
Menu ID         Menu Item
-------         ----------
1               Add Item Charge
2               Add Labor Charge
0               Exit application

Note that to make changes to the menu items only MENU needs to be altered.

For now, disregard the keys :text and :type in MENU.

Adding charges

If the user wishes to add an item charge the following method will be called with an argument that is a label for the charge type and will return a valid dollar amount:

def item_charge(charge_type)
  loop do
    print "Enter #{charge_type} amount: $"
    case (amt = Float(gets, exception: false))
    when nil
      puts "  Entry must be in dollars or dollars and cents"
    when -Float::INFINITY...0
      puts "  Entry cannot be negative"
    else
      break amt
    end
  end
end

See Kernel::Float. This method was given the :exception option in Ruby v2.7. Earlier versions raised an exception if the string could not be converted to a float. That exception would have to be rescued and nil returned.

Here's a possible dialogue:

item_charge('labor')
Enter labor amount: $213.46x
  Entry must be in dollars or dollars and cents
Enter labor amount: $-76
  Entry cannot be negative
Enter labor amount: $154.73
  #=> 154.73

Save charges

Now let's create a hash to hold the total cost of items and the cost of labor, with values initialized to nil.

costs = MENU.each_with_object({}) { |g,h| h[g[:type]] = nil }
  #=> {:item=>nil, :labor=>nil}

This will be the first line of the method enter_costs below.

OK to exit?

Let's assume we don't want to allow the user to exit the application before they have entered a labor charge and at least one item charge. We might write a separate method to see if they meet that requirement:

def ok_to_exit?(costs)
  h = MENU.find { |h| costs[h[:type]].nil? }
  puts "  You have not yet entered a #{h[:text]} cost" unless h.nil?
  h.nil?
end

See Enumerable#find.

Is menu selection valid?

We need to see if numerical value entered for the menu id selection (other than zero, which we have already checked for) is valid:

def menu_selection_valid?(menu_id)
  valid = (1..MENU.size).cover?(menu_id)
  puts "  That is not a valid menu id" unless valid
  valid
end

menu_selection_valid?(4)
That is not a valid menu id
  #=> false
menu_selection_valid?(-3)
That is not a valid menu id
  #=> false
menu_selection_valid?(2)
  #=> true

Body

We can now put everything together.

def enter_costs
  costs = MENU.each_with_object({}) { |g,h| h[g[:type]] = nil }
  loop do
    display_menu
    print ("Enter Menu ID: ")
    menu_id = gets().to_i

    if menu_id.zero?
      ok_to_exit?(costs) ? break : next
    end

    next unless menu_selection_valid?(menu_id)

    h = MENU[menu_id-1]
    case h[:type]
    when :labor
      if costs[h[:type]].nil?
        costs[h[:type]] = item_charge(h[:text])
      else
        puts "  You have already entered the labor charge"
        next
      end
    when :item
      costs[h[:type]] = (costs[h[:type]] ||= 0) + item_charge(h[:text])
    end
  end
  costs
end

Here is a possible dialog.

enter_costs
Menu ID         Menu Item
-------         ----------
1               Add Item Charge
2               Add Labor Charge
0               Exit application
Enter Menu ID: 0
  You have not yet entered a item cost

< menu redisplayed >
Enter Menu ID: 1
Enter item amount: $2.50

< menu redisplayed >
Enter Menu ID: 0
  You have not yet entered a labor cost

< menu redisplayed >
Enter Menu ID: 9
  That is not a valid menu id

< menu redisplayed >
Enter Menu ID: 2
Enter labor amount: $1345.61

< menu redisplayed >
Enter Menu ID: 1
Enter item amount: $3.12

< menu redisplayed >
Enter Menu ID: 2
  You have already entered the labour charge

< menu redisplayed >
Enter Menu ID: 0
  #=> {:item=>5.62, :labor=>1345.61}

Notice that the numbering of items in the menu is done in code, so that changes to MENU will not necessitate changes to those menu item numbers elsewhere in the code.

I suggest using Kernel#loop, together with keyword break, for all loops, in preference to while, until and (especially) for loops.


问:
Temporarily disable showing autofill values in input fields while recording screen capture video
I am screen recording a "How to video" and would like to temporarily disable autofill values being shown in input fields while I am doing the recording. They keep popping up when I click a input field during recording and it spoils the video because I don't want to show them.</p>

答:
make your input autocomplete off like below:

<input type"text" autocomplete="off">```


问:
Unique int _id for MongoDB
I am trying to assign unique int for _id. I know that ObjectID is a great option, but I need to use int as an ID in my case. I am using Random to generate random int to assign it the new object.

Here is the error:

```<code>Exception in thread "main" com.mongodb.MongoWriteException: E11000 duplicate key error
collection: TOP100SongsUK.artists index: _id_ dup key: { _id: 484624875 }
</code>```

Though, it is not true. For now, my collection has a few records and that's impossible. What may be a trigger this issue?

Here is the method that writes into the DB and last method assigns an ID.

```<code> public boolean add(Artist artist) {
    Document artistToInsert = new Document();
    artistToInsert.append(ARTIST_ID, assignArtistID()).append(ARTIST_NAME, artist.getName());
    boolean validOperation = false;
    int attempts = 0;
    do {
        try {
            addArtist(artistToInsert);
            validOperation = true;
        } catch (DuplicateKeyException e) {
            attempts++;
            System.out.println("Incorrect ID for Artist");
        }
    } while (!validOperation || attempts < 3);
    if (attempts == 3) {
        throw new RuntimeException("Unable to add Artist - Mongo");
    }
    return true;
}

private boolean addArtist(Document artistToInsert) {
    artistCollection.insertOne(artistToInsert);
    return true;
}

private static Random intGenerator = new Random();
 private int assignArtistID() {
        return Math.abs(intGenerator.nextInt());
}
</code>```

UPDATED: getNextSequence Function:

```<code>static final String ID_PARAM = "idParam";
static final String ID_SEQ = "seq";

static int getNextSequence(MongoCollection<Document> collection){
    Document findRequest = new Document();
    findRequest.append("_id", ID_PARAM);
    Document updateRequest =  new Document();
    updateRequest.append("$inc", new Document(ID_SEQ,1));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
    options.upsert(true);
    options.returnDocument(ReturnDocument.AFTER);
    Document returnDoc =  collection.findOneAndUpdate(findRequest,updateRequest,options);
    return (int) returnDoc.get(ID_SEQ);
}
</code>```

答:
It's not a good idea to use a random int to generate your _id mongo.
You should use an auto increment sequence using Mongo.

You have to create a collection for your sequence, with a sequenceName and your sequenceNumber.
Then for each insert, get your sequence, and increment it.

Here are some links to help you with that :

Auto increment sequence in mongodb using java

https://mkyong.com/mongodb/spring-data-mongodb-auto-sequence-id-example/

https://dzone.com/articles/mongodb-java-api-using-a-sequence-collection-with

Title: Unique int _id for MongoDB

Body:
I am trying to assign unique int for _id. I know that ObjectID is a great option, but I need to use int as an ID in my case. I am using Random to generate random int to assign it the new object.

Here is the error:

Exception in thread "main" com.mongodb.MongoWriteException: E11000 duplicate key error
collection: TOP100SongsUK.artists index: _id_ dup key: { _id: 484624875 }

Though, it is not true. For now, my collection has a few records and that's impossible. What may be a trigger this issue?

Here is the method that writes into the DB and last method assigns an ID.

 public boolean add(Artist artist) {
    Document artistToInsert = new Document();
    artistToInsert.append(ARTIST_ID, assignArtistID()).append(ARTIST_NAME, artist.getName());
    boolean validOperation = false;
    int attempts = 0;
    do {
        try {
            addArtist(artistToInsert);
            validOperation = true;
        } catch (DuplicateKeyException e) {
            attempts++;
            System.out.println("Incorrect ID for Artist");
        }
    } while (!validOperation || attempts < 3);
    if (attempts == 3) {
        throw new RuntimeException("Unable to add Artist - Mongo");
    }
    return true;
}

private boolean addArtist(Document artistToInsert) {
    artistCollection.insertOne(artistToInsert);
    return true;
}

private static Random intGenerator = new Random();
 private int assignArtistID() {
        return Math.abs(intGenerator.nextInt());
}

UPDATED: getNextSequence Function:

static final String ID_PARAM = "idParam";
static final String ID_SEQ = "seq";

static int getNextSequence(MongoCollection<Document> collection){
    Document findRequest = new Document();
    findRequest.append("_id", ID_PARAM);
    Document updateRequest =  new Document();
    updateRequest.append("$inc", new Document(ID_SEQ,1));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
    options.upsert(true);
    options.returnDocument(ReturnDocument.AFTER);
    Document returnDoc =  collection.findOneAndUpdate(findRequest,updateRequest,options);
    return (int) returnDoc.get(ID_SEQ);
}


问:
SQL query to find Primary Key of a table?
How can I find which column is the primary key of a table by using a query?

答:
LEFT joining table_constraints seems to take more time on mine.
i use Information_schema.COLUMNS

```<code>SELECT TABLE_SCHEMA , TABLE_NAME , COLUMN_NAME
FROM Information_schema.Columns
WHERE COLUMN_KEY = "PRI" AND TABLE_SCHEMA = DATABASE()
</code>```

Body:
LEFT joining table_constraints seems to take more time on mine.
i use Information_schema.COLUMNS

SELECT TABLE_SCHEMA , TABLE_NAME , COLUMN_NAME
FROM Information_schema.Columns
WHERE COLUMN_KEY = "PRI" AND TABLE_SCHEMA = DATABASE()


问:
php how to add php code in the twitter callback url?
I am trying to start a new app on dev.twitter.com, and in the callback URL I want to pass a link like: www.text.com?number=<?= $var?> but it won't let me.

Any ideas? Thanks.

Edit: my link will eventually look like this: www.text.com?number=123456

But it will depend on who is logged in, so the number could be any 6 numbers, so I'm thinking the callback URL has to have that var inside it.

答:
Why do you assume twitter is even running php? Even so they certainly wouldn't let you execute arbitrary php code in a callback they make.

Please explain what you really want to do. What you are asking isn't clear.


问:
What's the simplest way to schedule a function to be called at midnight everyday with Clojure?
While one can use threads and set a timeout to run a function at set intervals from the time a new Thread has been started, how to make it so that the function runs at 00:00:00 starting from the next midnight? </p>

答:
You can interop to any Java library like Quartz, cron4j or Java Timer itself.  To make it more idiomatic to Clojure, you can also write a macro (or couple functions) to simplify things. For example, using a roll-your-own macro:

(deftask my-midnight-task
  "0 0 * * 2-6"
  (println "start to work")
  (do-something))
```

<p>where "0 0 * * 2-6" is a cron like pattern used in cron4j.  Implementation in here is using mount to take care of scheduling and descheduling:</p>

<pre class="lang-clj prettyprint-override"><code>(defonce ^Scheduler scheduler (doto (Scheduler.)
                                (.setDaemon true)
                                (.start)))

(defmacro deftask [name cron & body]
  `(defstate ~name
     :start (.schedule scheduler ~cron (fn [] ~@body))
     :stop  (.deschedule scheduler ~name)))
</code>```

Body:
You can interop to any Java library like Quartz, cron4j or Java Timer itself.  To make it more idiomatic to Clojure, you can also write a macro (or couple functions) to simplify things. For example, using a roll-your-own macro:

(deftask my-midnight-task
  "0 0 * * 2-6"
  (println "start to work")
  (do-something))

where "0 0 * * 2-6" is a cron like pattern used in cron4j.  Implementation in here is using mount to take care of scheduling and descheduling:

(defonce ^Scheduler scheduler (doto (Scheduler.)
                                (.setDaemon true)
                                (.start)))

(defmacro deftask [name cron & body]
  `(defstate ~name
     :start (.schedule scheduler ~cron (fn [] ~@body))
     :stop  (.deschedule scheduler ~name)))


问:
who is the best theme load time speed in WordPress site?
friend i have junior developer and i have create site but site home page is load time is 15 second. how can use i use best theme in my site plz ask best theme...</p>

答: you can use wp rocket plugin.this plugin working any theme  </p>


问:
Is there any way to call a specific variable based on user input?
I want to be able to call a certain variable based off which variable the user asked for.
I'm aware I can use if/else statements but I feel like there's a better way. In the last line of my code, I want the input variables in the curly braces to complete the variable call.
Sorry if this was a poor explanation as it's hard to explain.</p>

```<code>class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def bed_size(self):
        print('This bed is {}'.format(self.size))

    def bed_color(self):
        print('This bed is {}'.format(self.color))

    def bed_price(self):
        print('This bed is {}'.format(self.price))

king_bed = Bed('very big', 'turquoise', '$1000')
queen_bed = Bed("medium size", 'magenta', '$700')
twin_bed = Bed('quite small', 'azure', '$400')

bed = input('Which of our fine beds would you like to gain more knowledge of? The king, queen or twin bed?')
attribute = input("Would you like to know the price, size or color?")

{bed}_bed.bed_{attribute}()
</code>```

答:
One way to do it is by defining a dictionary and using the built-in getattr() function:

```<code>class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def print_size(self):
        print('This bed is {}'.format(self.size))

    def print_color(self):
        print('This bed is {}'.format(self.color))

    def print_price(self):
        print('This bed is {}'.format(self.price))

beds = {
    'king': Bed('very big', 'turquoise', '$1000'),
    'queen':  Bed("medium size", 'magenta', '$700'),
    'twin': Bed('quite small', 'azure', '$400'),
}

which = input('Which of our fine beds would you like to gain more knowledge of,\n'
              'the king, queen or twin bed? ')
attribute = input("Would you like to know the price, size or color? ")

getattr(beds[which], 'print_' + attribute)()
</code>```

Body:
I want to be able to call a certain variable based off which variable the user asked for.
I'm aware I can use if/else statements but I feel like there's a better way. In the last line of my code, I want the input variables in the curly braces to complete the variable call.
Sorry if this was a poor explanation as it's hard to explain.

class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def bed_size(self):
        print('This bed is {}'.format(self.size))

    def bed_color(self):
        print('This bed is {}'.format(self.color))

    def bed_price(self):
        print('This bed is {}'.format(self.price))

king_bed = Bed('very big', 'turquoise', '$1000')
queen_bed = Bed("medium size", 'magenta', '$700')
twin_bed = Bed('quite small', 'azure', '$400')

bed = input('Which of our fine beds would you like to gain more knowledge of? The king, queen or twin bed?')
attribute = input("Would you like to know the price, size or color?")

{bed}_bed.bed_{attribute}()

Body:
One way to do it is by defining a dictionary and using the built-in getattr() function:

class Bed:
    def __init__(self, size, color, price):
        self.size = size
        self.color = color
        self.price = price

    def print_size(self):
        print('This bed is {}'.format(self.size))

    def print_color(self):
        print('This bed is {}'.format(self.color))

    def print_price(self):
        print('This bed is {}'.format(self.price))

beds = {
    'king': Bed('very big', 'turquoise', '$1000'),
    'queen':  Bed("medium size", 'magenta', '$700'),
    'twin': Bed('quite small', 'azure', '$400'),
}

which = input('Which of our fine beds would you like to gain more knowledge of,\n'
              'the king, queen or twin bed? ')
attribute = input("Would you like to know the price, size or color? ")

getattr(beds[which], 'print_' + attribute)()


问:
Responding to touchesBegan in UIPickerView instead of UIView
I have a UIPickerView that gets faded out to 20% alpha when not in use. I want the user to be able to touch the picker and have it fade back in.

I can get it to work if I put a touchesBegan method on the main View, but this only works when the user touches the View. I tried sub-classing UIPickerView and having a touchesBegan in there, but it didn't work.

I'm guessing it's something to do with the Responder chain, but can't seem to work it out.

答: Couldn't find a recent, easier solution to this so I rigged something to solve my problem. Created an invisible button that stretches over the picker view. Connected that button with a "Touch Down" recognizer to my parent UIView.  Now any functionality can be added, I happened to need a random selection timer to be invalidated when someone touches the picker view. Not elegant but it works.</p>

OwnerDisplayName: KiwiBastard

ContentLicense: CC BY-SA 2.5


问:
How to config networks in docker-compose?
In the host, I have created docker network using below command:

```<code>docker network create -d macvlan \
    --subnet=192.168.2.0/24 \
    --gateway=192.168.2.1  \
    -o parent=eth0 pub_net
</code>```

docker network shows below:

```<code>[root@192-168-2-70 shell]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
935ae8b52eb2        bridge              bridge              local
81577f72f606        host                host                local
846d54a2c7da        none                null                local
158428b19c4d        pub_net             macvlan             local
[root@192-168-2-70 shell]#
</code>```

and docker container with specified IP can be started by command:

docker run --net=pub_net --ip=192.168.2.10 --name hadoop0 --hostname
  hadoop0 -d -P  hadoop-cluster-hadoop0:v1.1

but when I convert the above command to docker-compose file like below:

```<code>version: '3'
services:
    hadoop-cluster-hadoop0:
        container_name: hadoop0
        restart: always
        networks:
            pub_net:
                ipv4_address: 192.168.2.10
        volumes:
            - /tmp/hadoop0/logs:/tmp
        extra_hosts:
            - "hadoop0:192.168.1.10"
            - "hadoop1:192.168.1.11"
            - "hadoop2:192.168.1.12"
            - "dbus-n1:192.168.2.81"
        image: 'hadoop-cluster-hadoop0:v1.1'
networks:
    put_net:
      external: true
</code>```

the following error occured.

```<code>[root@192-168-2-70 shell]# docker-compose up -d
WARNING: Some networks were defined but are not used by any service: put_net
ERROR: Service "hadoop-cluster-hadoop0" uses an undefined network "pub_net"
[root@192-168-2-70 shell]#
</code>```

Can anybody please help me on how to correct the docker-compose file?
How docker network can be created in docker-compose file, instead created beforehand?

Appreciate your help very much!!!

答:
Look closely, you named your network put_net but instead referenced it as pub_net in your service definition.

Moreover, when you define the network as external it means that it should already be created. If you want docker-compose to do that for you, you can do this instead.

```<code>networks:
    put_net:
        driver: bridge
        ipam:
            driver: default
            config:
                -
                  subnet: 192.168.2.0/24
</code>```

If you would like to exactly re-create the network you specified in the question then you would have to downgrade the version from '3' to '2'; This is because some functionality was removed in version '3' and one of these options was the ability to specify gateway (at least to the best of my knowledge).

Here is how your docker-compose file would look like. (Notice the change in version from '3' to '2')

```<code>version: '2'
services:
    hadoop-cluster-hadoop0:
        container_name: hadoop0
        restart: always
        networks:
            put_net:
                ipv4_address: 192.168.2.10
        volumes:
            - /tmp/hadoop0/logs:/tmp
        extra_hosts:
            - "hadoop0:192.168.1.10"
            - "hadoop1:192.168.1.11"
            - "hadoop2:192.168.1.12"
            - "dbus-n1:192.168.2.81"
        image: 'hadoop-cluster-hadoop0:v1.1'
networks:
    put_net:
        driver: macvlan
        driver_opts:
            parent: eth0
        ipam:
            config:
                -
                  subnet: 192.168.2.0/24
                  gateway: 192.168.2.1
</code>```

Body:
In the host, I have created docker network using below command:

docker network create -d macvlan \
    --subnet=192.168.2.0/24 \
    --gateway=192.168.2.1  \
    -o parent=eth0 pub_net

docker network shows below:

[root@192-168-2-70 shell]# docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
935ae8b52eb2        bridge              bridge              local
81577f72f606        host                host                local
846d54a2c7da        none                null                local
158428b19c4d        pub_net             macvlan             local
[root@192-168-2-70 shell]#

and docker container with specified IP can be started by command:

docker run --net=pub_net --ip=192.168.2.10 --name hadoop0 --hostname
  hadoop0 -d -P  hadoop-cluster-hadoop0:v1.1

but when I convert the above command to docker-compose file like below:

version: '3'
services:
    hadoop-cluster-hadoop0:
        container_name: hadoop0
        restart: always
        networks:
            pub_net:
                ipv4_address: 192.168.2.10
        volumes:
            - /tmp/hadoop0/logs:/tmp
        extra_hosts:
            - "hadoop0:192.168.1.10"
            - "hadoop1:192.168.1.11"
            - "hadoop2:192.168.1.12"
            - "dbus-n1:192.168.2.81"
        image: 'hadoop-cluster-hadoop0:v1.1'
networks:
    put_net:
      external: true

the following error occured.

[root@192-168-2-70 shell]# docker-compose up -d
WARNING: Some networks were defined but are not used by any service: put_net
ERROR: Service "hadoop-cluster-hadoop0" uses an undefined network "pub_net"
[root@192-168-2-70 shell]#

Can anybody please help me on how to correct the docker-compose file?
How docker network can be created in docker-compose file, instead created beforehand?

Appreciate your help very much!!!

Body:
Look closely, you named your network put_net but instead referenced it as pub_net in your service definition.

Moreover, when you define the network as external it means that it should already be created. If you want docker-compose to do that for you, you can do this instead.

networks:
    put_net:
        driver: bridge
        ipam:
            driver: default
            config:
                -
                  subnet: 192.168.2.0/24

If you would like to exactly re-create the network you specified in the question then you would have to downgrade the version from '3' to '2'; This is because some functionality was removed in version '3' and one of these options was the ability to specify gateway (at least to the best of my knowledge).

Here is how your docker-compose file would look like. (Notice the change in version from '3' to '2')

version: '2'
services:
    hadoop-cluster-hadoop0:
        container_name: hadoop0
        restart: always
        networks:
            put_net:
                ipv4_address: 192.168.2.10
        volumes:
            - /tmp/hadoop0/logs:/tmp
        extra_hosts:
            - "hadoop0:192.168.1.10"
            - "hadoop1:192.168.1.11"
            - "hadoop2:192.168.1.12"
            - "dbus-n1:192.168.2.81"
        image: 'hadoop-cluster-hadoop0:v1.1'
networks:
    put_net:
        driver: macvlan
        driver_opts:
            parent: eth0
        ipam:
            config:
                -
                  subnet: 192.168.2.0/24
                  gateway: 192.168.2.1


问:
Can I display lists (<ol>, <ul>) as inline items?
I know they are block elements, but I'm sure there is a way, maybe with CSS? I tried to use the span tag but it doesn't work. What did I do wrong? I would like to put the second element next to the first one on the website. Not under it, but next.</p>

```<code>  <span>
        <section>
        <h3>Favourite quotes</h3>
         <ul>
          <li>
              “Pizza is good" ―Me
          </li>
         </ul>
        </section>
  </span>

  <span>
        <section>
        <h3>Favourite series</h3>
         <ul>
          <li> X </li>
          <li> Y </li>
          <li> Z </li>
         </ul>
        </section>
  </span>
</code>```

答:
make the two "span" "inline-block" display and that's it!

.first,.second{
  display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <span class="first">
        <section>
        <h3>Favourite quotes</h3>
         <ul>
          <li>
              “Pizza is good" ―Me
          </li>
         </ul>
        </section>
  </span>

  <span class="second">
        <section>
        <h3>Favourite series</h3>
         <ul>
          <li> X </li>
          <li> Y </li>
          <li> Z </li>
         </ul>
        </section>
  </span></code>```

Body:
I know they are block elements, but I'm sure there is a way, maybe with CSS? I tried to use the span tag but it doesn't work. What did I do wrong? I would like to put the second element next to the first one on the website. Not under it, but next.

Favourite quotes

              “Pizza is good" ―Me

Favourite series

 X

 Y

 Z

Body:
make the two "span" "inline-block" display and that's it!

.first,.second{
  display:inline-block;
}

  <span class="first">
        <section>
        <h3>Favourite quotes</h3>
         <ul>
          <li>
              “Pizza is good" ―Me
          </li>
         </ul>
        </section>
  </span>

  <span class="second">
        <section>
        <h3>Favourite series</h3>
         <ul>
          <li> X </li>
          <li> Y </li>
          <li> Z </li>
         </ul>
        </section>
  </span>


问:
Having problems plotting Lineplot in seaborn library
I would please like to request some help here. I am using seaborn in Python to plot multiple line plots but unfortunately, I keep getting errors. However, when I used the preloaded datasets in seaborn like fMRI datasets, it went well.

Below is the code I used:

import seaborn as sns; sns.set()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("ucc.csv")
df

df = sns.load_dataset("ucc")
ax = sns.lineplot(x="hours", y="viability", data=ucc)
```

<p>This is the error that I get whenever I run the above code: </p>

<pre class="lang-sh prettyprint-override"><code>HTTPError                                 Traceback (most recent call last)
<ipython-input-3-07a022f8777e> in <module>
----> 1 df = sns.load_dataset("ucc")
      2 ax = sns.lineplot(x="hours", y="viability", data=ucc)

~/miniconda3/lib/python3.7/site-packages/seaborn/utils.py in load_dataset(name, cache, data_home, **kws)
    434                                   os.path.basename(full_path))
    435         if not os.path.exists(cache_path):
--> 436             urlretrieve(full_path, cache_path)
    437         full_path = cache_path
    438

~/miniconda3/lib/python3.7/urllib/request.py in urlretrieve(url, filename, reporthook, data)
    245     url_type, path = splittype(url)
    246
--> 247     with contextlib.closing(urlopen(url, data)) as fp:
    248         headers = fp.info()
    249

~/miniconda3/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

~/miniconda3/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
    529         for processor in self.process_response.get(protocol, []):
    530             meth = getattr(processor, meth_name)
--> 531             response = meth(req, response)
    532
    533         return response

~/miniconda3/lib/python3.7/urllib/request.py in http_response(self, request, response)
    639         if not (200 <= code < 300):
    640             response = self.parent.error(
--> 641                 'http', request, response, code, msg, hdrs)
    642
    643         return response

~/miniconda3/lib/python3.7/urllib/request.py in error(self, proto, *args)
    567         if http_err:
    568             args = (dict, 'default', 'http_error_default') + orig_args
--> 569             return self._call_chain(*args)
    570
    571 # XXX probably also want an abstract factory that knows when it makes

~/miniconda3/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    501         for handler in handlers:
    502             func = getattr(handler, meth_name)
--> 503             result = func(*args)
    504             if result is not None:
    505                 return result

~/miniconda3/lib/python3.7/urllib/request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 404: Not Found
</code>```

答:
Let me break down what you have done so that perhaps you can understand better what is going on; See the comments inline with your code.

import seaborn as sns; sns.set()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("ucc.csv"). # Loads the csv file locally into a pandas dataframe
df  # Prints the head of that dataframe

# This command specifically loads datasets from [github](https://github.com/mwaskom/seaborn-data) by name; It's for testing. You are getting the 404 error because there is no ucc dataset in the github repository.
df = sns.load_dataset("ucc")

# This is the command that actually creates the plot. You are referencing a variable 'ucc' that you have not declared and you would get an error if you had not already excepted from the prior 404.
ax = sns.lineplot(x="hours", y="viability", data=ucc)
```

<p>I don't have your dataset so I can not give you an exact example, however, using the mpg dataset downloaded locally I can give you at least a working example of what I believe you are trying to accomplish.</p>

<pre class="lang-py prettyprint-override"><code>import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv('mpg.csv')
ax = sns.lineplot(x=df['model_year'], y=df['mpg'])
</code>```

Body:
I would please like to request some help here. I am using seaborn in Python to plot multiple line plots but unfortunately, I keep getting errors. However, when I used the preloaded datasets in seaborn like fMRI datasets, it went well.

Below is the code I used:

import seaborn as sns; sns.set()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("ucc.csv")
df

df = sns.load_dataset("ucc")
ax = sns.lineplot(x="hours", y="viability", data=ucc)

This is the error that I get whenever I run the above code:

HTTPError                                 Traceback (most recent call last)
<ipython-input-3-07a022f8777e> in <module>
----> 1 df = sns.load_dataset("ucc")
      2 ax = sns.lineplot(x="hours", y="viability", data=ucc)

~/miniconda3/lib/python3.7/site-packages/seaborn/utils.py in load_dataset(name, cache, data_home, **kws)
    434                                   os.path.basename(full_path))
    435         if not os.path.exists(cache_path):
--> 436             urlretrieve(full_path, cache_path)
    437         full_path = cache_path
    438

~/miniconda3/lib/python3.7/urllib/request.py in urlretrieve(url, filename, reporthook, data)
    245     url_type, path = splittype(url)
    246
--> 247     with contextlib.closing(urlopen(url, data)) as fp:
    248         headers = fp.info()
    249

~/miniconda3/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

~/miniconda3/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
    529         for processor in self.process_response.get(protocol, []):
    530             meth = getattr(processor, meth_name)
--> 531             response = meth(req, response)
    532
    533         return response

~/miniconda3/lib/python3.7/urllib/request.py in http_response(self, request, response)
    639         if not (200 <= code < 300):
    640             response = self.parent.error(
--> 641                 'http', request, response, code, msg, hdrs)
    642
    643         return response

~/miniconda3/lib/python3.7/urllib/request.py in error(self, proto, *args)
    567         if http_err:
    568             args = (dict, 'default', 'http_error_default') + orig_args
--> 569             return self._call_chain(*args)
    570
    571 # XXX probably also want an abstract factory that knows when it makes

~/miniconda3/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    501         for handler in handlers:
    502             func = getattr(handler, meth_name)
--> 503             result = func(*args)
    504             if result is not None:
    505                 return result

~/miniconda3/lib/python3.7/urllib/request.py in http_error_default(self, req, fp, code, msg, hdrs)
    647 class HTTPDefaultErrorHandler(BaseHandler):
    648     def http_error_default(self, req, fp, code, msg, hdrs):
--> 649         raise HTTPError(req.full_url, code, msg, hdrs, fp)
    650
    651 class HTTPRedirectHandler(BaseHandler):

HTTPError: HTTP Error 404: Not Found

Body:
Let me break down what you have done so that perhaps you can understand better what is going on; See the comments inline with your code.

import seaborn as sns; sns.set()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("ucc.csv"). # Loads the csv file locally into a pandas dataframe
df  # Prints the head of that dataframe

# This command specifically loads datasets from [github](https://github.com/mwaskom/seaborn-data) by name; It's for testing. You are getting the 404 error because there is no ucc dataset in the github repository.
df = sns.load_dataset("ucc")

# This is the command that actually creates the plot. You are referencing a variable 'ucc' that you have not declared and you would get an error if you had not already excepted from the prior 404.
ax = sns.lineplot(x="hours", y="viability", data=ucc)

I don't have your dataset so I can not give you an exact example, however, using the mpg dataset downloaded locally I can give you at least a working example of what I believe you are trying to accomplish.

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv('mpg.csv')
ax = sns.lineplot(x=df['model_year'], y=df['mpg'])


问:
Binary Tree Not Showing Nodes Present Python
I'm trying to implement a binary tree with insert and preorder methods.

After adding elements to the tree, only one element is displayed.

Can someone let me know where I'm wrong.

Below is code:

```<code>class Node(object):

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = None
        self.right = None

    def __repr__(self):
        return '{}'.format(self.value)

class BinaryTree(object):

    def __init__(self, root=None):
        self.root = root

    def add(self, value):
        val = self.root
        if not val:
            self.root = value
            val = value

        elif not val.left:
            val = value
        elif not val.right:
            val = value
        else:
            self.left = val.left.add(value)
        return val

    def preorder(self):
        val = self.root
        if not val: # this will handle the case when root node is None.
            return
        print(val)
        if val.left:
            val.left.preorder()
        if val.right:
            val.right.preorder()

def main():

    binary_tree = BinaryTree()

    print("Adding nodes to the tree")
    for i in range(1, 11):
        node = Node(i)
        binary_tree.add(node)

    print("Printing preorder...")
    binary_tree.preorder()

if __name__ == '__main__':
    main()

</code>```

Output

```<code>Adding nodes to the tree
Printing preorder...
1
</code>```

答:
Your code has a few different errors. Some relate to how you modify self.root (or fail to), others have to do with attempts at recursion on the wrong types.

The first issue, which is why your code fails silently, has to do with your BinaryTree.add method, which does nothing when the tree is empty. The problem is that you initialize a local variable val to be equal to your root node (if you have one), and then later rebind it to some other value. But that never changes the root value at all, only the local val variable.

I suggest you get rid of val all together, and instead read and write self.root directly. Then you'll actually make some progress, and see the other issues.

Here's a start:

```<code>def add(self, value):
    if self.root is None:
        self.root = value
    elif self.root.left.left is None:
        self.root.left = value
    ...
</code>```

The other issues I mention are both similar, though one occurs in BinaryTree.add and the other in BinaryTree.preorder. The issue is that you try to call the same method (add or preorder) on one of the children of your root node. But the nodes are Node instances, and don't have the methods that you've defined in the BinaryTree class.

This issue doesn't have as obvious a solution as the previous one. One idea might be to move the logic for the methods into the Node class (where you can recurse easily), and leave only the empty-tree handling code in the BinaryTree methods (everything else gets delegated to the root node).

Body:
I'm trying to implement a binary tree with insert and preorder methods.

After adding elements to the tree, only one element is displayed.

Can someone let me know where I'm wrong.

Below is code:

class Node(object):

    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = None
        self.right = None

    def __repr__(self):
        return '{}'.format(self.value)

class BinaryTree(object):

    def __init__(self, root=None):
        self.root = root

    def add(self, value):
        val = self.root
        if not val:
            self.root = value
            val = value

        elif not val.left:
            val = value
        elif not val.right:
            val = value
        else:
            self.left = val.left.add(value)
        return val

    def preorder(self):
        val = self.root
        if not val: # this will handle the case when root node is None.
            return
        print(val)
        if val.left:
            val.left.preorder()
        if val.right:
            val.right.preorder()

def main():

    binary_tree = BinaryTree()

    print("Adding nodes to the tree")
    for i in range(1, 11):
        node = Node(i)
        binary_tree.add(node)

    print("Printing preorder...")
    binary_tree.preorder()

if __name__ == '__main__':
    main()

Output

Adding nodes to the tree
Printing preorder...
1

Body:
Your code has a few different errors. Some relate to how you modify self.root (or fail to), others have to do with attempts at recursion on the wrong types.

The first issue, which is why your code fails silently, has to do with your BinaryTree.add method, which does nothing when the tree is empty. The problem is that you initialize a local variable val to be equal to your root node (if you have one), and then later rebind it to some other value. But that never changes the root value at all, only the local val variable.

I suggest you get rid of val all together, and instead read and write self.root directly. Then you'll actually make some progress, and see the other issues.

Here's a start:

def add(self, value):
    if self.root is None:
        self.root = value
    elif self.root.left.left is None:
        self.root.left = value
    ...

The other issues I mention are both similar, though one occurs in BinaryTree.add and the other in BinaryTree.preorder. The issue is that you try to call the same method (add or preorder) on one of the children of your root node. But the nodes are Node instances, and don't have the methods that you've defined in the BinaryTree class.

This issue doesn't have as obvious a solution as the previous one. One idea might be to move the logic for the methods into the Node class (where you can recurse easily), and leave only the empty-tree handling code in the BinaryTree methods (everything else gets delegated to the root node).


问:
Validate e-mail address when pressing a button
I'm trying to make a basic login screen. However, I'm struggling with the e-mail validation.

Every time I press a button, I want to make sure that the user inputs the correct e-mail format, or give them a small alert under the e-mail TextInput if they write something other than a valid e-mail (this alert will be hidden by default.). However, when I try, it always gives me this error (regardless of the user input):

```<code>undefined is not an object (evaluating 'this.state.username')
</code>```

This is my code so far

```<code>class HomeScreen extends Component {
 state = { username: null, password: null }
 show = false;

 _validar = (text) => {
  let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;

  if(reg.test(text) === false) {
    return false;
  } else {
    return true;
  }
 }

 _onSubmit() {
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }

 render() {
  return (
   <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
   enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
    <View style={styles.logo}>
     <Image source = {logo} style={styles.img}/>
     <Text style={styles.textLogoPrimary}>Neuron App</Text>
     <Text style={styles.textLogoSecondary}>Test</Text>
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Correo Electrónico</Text>
     <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
     style={styles.formInput} />
     {this.state.show ? (
       <Text style={styles.textAlert}>Correo Electrónico no valido.</Text>
     ) : null}
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Contraseña</Text>
     <TextInput style={styles.formInput} onChangeText={value => this.setState({ password: value })} secureTextEntry={true}/>
    </View>

    <View style={styles.buttonView}>
     <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
      <Text style={styles.buttonText}>Iniciar</Text>
     </TouchableOpacity>
    </View>
  </KeyboardAwareScrollView>
 );
}}
</code>```

答:
Just change your onSubmit funciton to "

```<code> _onSubmit = () =>{
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }
</code>```

ES^ binds this automatically. Hope it solves the error

Body:
I'm trying to make a basic login screen. However, I'm struggling with the e-mail validation.

Every time I press a button, I want to make sure that the user inputs the correct e-mail format, or give them a small alert under the e-mail TextInput if they write something other than a valid e-mail (this alert will be hidden by default.). However, when I try, it always gives me this error (regardless of the user input):

undefined is not an object (evaluating 'this.state.username')

This is my code so far

class HomeScreen extends Component {
 state = { username: null, password: null }
 show = false;

 _validar = (text) => {
  let reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;

  if(reg.test(text) === false) {
    return false;
  } else {
    return true;
  }
 }

 _onSubmit() {
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }

 render() {
  return (
   <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled
   enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}>
    <View style={styles.logo}>
     <Image source = {logo} style={styles.img}/>
     <Text style={styles.textLogoPrimary}>Neuron App</Text>
     <Text style={styles.textLogoSecondary}>Test</Text>
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Correo Electrónico</Text>
     <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })}
     style={styles.formInput} />
     {this.state.show ? (
       <Text style={styles.textAlert}>Correo Electrónico no valido.</Text>
     ) : null}
    </View>

    <View style={styles.formElement}>
     <Text style={styles.formText}>Contraseña</Text>
     <TextInput style={styles.formInput} onChangeText={value => this.setState({ password: value })} secureTextEntry={true}/>
    </View>

    <View style={styles.buttonView}>
     <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
      <Text style={styles.buttonText}>Iniciar</Text>
     </TouchableOpacity>
    </View>
  </KeyboardAwareScrollView>
 );
}}

Body:
Just change your onSubmit funciton to "

 _onSubmit = () =>{
  if(this._validar(this.state.username) == true) {
    const { username, password } = this.state;
  } else {
    this.show = true;
  }
 }

ES^ binds this automatically. Hope it solves the error


问:
How to track the percentage of the video watched using Komito Analytics?
Komito Analytics allow to track media events like "play", "pause" and "ended" of embedded HTML5, Vimeo and YouTube videos. (https://komito.net/integration/)

But does it support tracking the percentage of the videos watched?
I am particularly interested in HTML5 video.

答:
Good question, currently Komito Analytics cannot track the percentage of the videos watched due to lot of reasons.

But you can use this simple script to track the percentage of watched HTML5 videos:
https://gist.github.com/vpodk/7306f657995985bf27de5a858c909ca4

This script also supports dynamic content, steps, and examples for analytics.js and gtag.js.


问:
How to limit cross correlation window width in Numpy?
I am learning numpy/scipy, coming from a MATLAB background.  The xcorr function in Matlab has an optional argument "maxlag" that limits the lag range from –maxlag to maxlag.  This is very useful if you are looking at the cross-correlation between two very long time series but are only interested in the correlation within a certain time range.  The performance increases are enormous considering that cross-correlation is incredibly expensive to compute.

In numpy/scipy it seems there are several options for computing cross-correlation.  numpy.correlate, numpy.convolve, scipy.signal.fftconvolve.  If someone wishes to explain the difference between these, I'd be happy to hear, but mainly what is troubling me is that none of them have a maxlag feature.  This means that even if I only want to see correlations between two time series with lags between -100 and +100 ms, for example, it will still calculate the correlation for every lag between -20000 and +20000 ms (which is the length of the time series).  This gives a 200x performance hit!  Do I have to recode the cross-correlation function by hand to include this feature?

答:
I encountered the same problem some time ago, I paid more attention to the efficiency of calculation.Refer to the source code of MATLAB's  function xcorr.m, I made a simple one.

```<code>import numpy as np
from scipy import signal, fftpack
import math
import time

def nextpow2(x):
    if x == 0:
        y = 0
    else:
        y = math.ceil(math.log2(x))
    return y

def xcorr(x, y, maxlag):
    m = max(len(x), len(y))
    mx1 = min(maxlag, m - 1)
    ceilLog2 = nextpow2(2 * m - 1)
    m2 = 2 ** ceilLog2

    X = fftpack.fft(x, m2)
    Y = fftpack.fft(y, m2)
    c1 = np.real(fftpack.ifft(X * np.conj(Y)))
    index1 = np.arange(1, mx1+1, 1) + (m2 - mx1 -1)
    index2 = np.arange(1, mx1+2, 1) - 1
    c = np.hstack((c1[index1], c1[index2]))
    return c

if __name__ == "__main__":
    s = time.clock()
    a = [1, 2, 3, 4, 5]
    b = [6, 7, 8, 9, 10]
    c = xcorr(a, b, 3)
    e = time.clock()
    print(c)
    print(e-c)
</code>```

Take the results of a certain run as an exmple:

```<code>[ 29.  56.  90. 130. 110.  86.  59.]
0.0001745000000001884
</code>```

comparing with MATLAB code:

```<code>clear;close all;clc
tic
a = [1, 2, 3, 4, 5];
b = [6, 7, 8, 9, 10];
c = xcorr(a, b, 3)
toc
</code>```

```<code>
   29.0000   56.0000   90.0000  130.0000  110.0000   86.0000   59.0000

时间已过 0.000279 秒。
</code>```

If anyone can give a strict mathematical derivation about this,that would be very helpful.

Body:
I encountered the same problem some time ago, I paid more attention to the efficiency of calculation.Refer to the source code of MATLAB's  function xcorr.m, I made a simple one.

import numpy as np
from scipy import signal, fftpack
import math
import time

def nextpow2(x):
    if x == 0:
        y = 0
    else:
        y = math.ceil(math.log2(x))
    return y

def xcorr(x, y, maxlag):
    m = max(len(x), len(y))
    mx1 = min(maxlag, m - 1)
    ceilLog2 = nextpow2(2 * m - 1)
    m2 = 2 ** ceilLog2

    X = fftpack.fft(x, m2)
    Y = fftpack.fft(y, m2)
    c1 = np.real(fftpack.ifft(X * np.conj(Y)))
    index1 = np.arange(1, mx1+1, 1) + (m2 - mx1 -1)
    index2 = np.arange(1, mx1+2, 1) - 1
    c = np.hstack((c1[index1], c1[index2]))
    return c

if __name__ == "__main__":
    s = time.clock()
    a = [1, 2, 3, 4, 5]
    b = [6, 7, 8, 9, 10]
    c = xcorr(a, b, 3)
    e = time.clock()
    print(c)
    print(e-c)

Take the results of a certain run as an exmple:

[ 29.  56.  90. 130. 110.  86.  59.]
0.0001745000000001884

comparing with MATLAB code:

clear;close all;clc
tic
a = [1, 2, 3, 4, 5];
b = [6, 7, 8, 9, 10];
c = xcorr(a, b, 3)
toc

   29.0000   56.0000   90.0000  130.0000  110.0000   86.0000   59.0000

时间已过 0.000279 秒。

If anyone can give a strict mathematical derivation about this,that would be very helpful.


问:
How to render string as custom React component?
So I have this code

```<code>ReactDom.render(<Home />, document.getElementById("main"));
</code>```

This works perfectly and it renders Home component.
I want to make this code dynamic
instead Home component, it can be any component like Apartment or Building component.

I have tried to do this by the following code.

```<code>const tag = `<${main} />`;
ReactDom.render(tag, document.getElementById("main"));
</code>```

This doesn't work.

I would like to know if it is possible. I would prefer to do this without any third party library.

答:
You can create a component to render each name you pass set in state, This will render all the components as you might expect based on your props.

for example you can write this component : Render.js

```<code>import React, { useState } from 'react';
// import other components

export default (props) => {
  const [current, setCurrent] = useState('home');
  const App= {
    home: Home,
    apartment: Apartment ,
    building: Building,
    ...
  };

  let Render = App[current] || Home;

  return <Render {...props}   />;
};
</code>```

The index.js would be like the following:

```<code>ReactDOM.render(<Render/>, document.getElementById('root'));
</code>```

Body:
So I have this code

ReactDom.render(<Home />, document.getElementById("main"));

This works perfectly and it renders Home component.
I want to make this code dynamic
instead Home component, it can be any component like Apartment or Building component.

I have tried to do this by the following code.

const tag = `<${main} />`;
ReactDom.render(tag, document.getElementById("main"));

This doesn't work.

I would like to know if it is possible. I would prefer to do this without any third party library.

Body:
You can create a component to render each name you pass set in state, This will render all the components as you might expect based on your props.

for example you can write this component : Render.js

import React, { useState } from 'react';
// import other components

export default (props) => {
  const [current, setCurrent] = useState('home');
  const App= {
    home: Home,
    apartment: Apartment ,
    building: Building,
    ...
  };

  let Render = App[current] || Home;

  return <Render {...props}   />;
};

The index.js would be like the following:

ReactDOM.render(<Render/>, document.getElementById('root'));


问:
Dynamically initializing a static value in C vs C++
```<code>#include <stdio.h>

int b(){
 return 5;
}

int main(){
 static int a = b();
 return 0;
}
</code>```

Above code doesn't compile in C with this error:

error: initializer element is not a compile-time constant

but compiles fine in C++. What are the differences between initializing static values in C and C++?

答:
From cppreference:

Variables declared at block scope with the specifier static or thread_local (since C++11) have static or thread (since C++11) storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

So, in C static is initialized at startup, while in C++ during the first time the code passes through this section of code.
This will allow assignment of a return from a function in C++ which would be impossible in C since C would need to know the value before the program starts to run...

I hope this helps
Lior

Body:
#include <stdio.h>

int b(){
 return 5;
}

int main(){
 static int a = b();
 return 0;
}

Above code doesn't compile in C with this error:

error: initializer element is not a compile-time constant

but compiles fine in C++. What are the differences between initializing static values in C and C++?


问:
How to print process name in StartUp.cs for .net core 3.1
From yesterday I have started learning .netcore. I have installed .netcore 2.2 & .netcore 3.1 in my machine.

In .netcore 2.2, I am able to print the process name on the website.
i.e.
I had written this below code in Startup.cs in an empty .netcore web application:

```<code>app.Run(async (context) =>
{
    await context.Response
    .WriteAsync(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
});
</code>```

But now in .netcore 3.1, by default, it is calling the razor pages. So, I tried to replace that code with the above code, but I am getting this below error:

'HttpResponse' does not contain a definition for 'WriteAsync' and no
  accessible extension method 'WriteAsync' accepting a first argument of
  type 'HttpResponse' could be found (are you missing a using directive
  or an assembly reference?

It seems the extension method 'WriteAsync' has been removed in .netcore 3.1.

So, how do I display that now?

答:
Add this using</p>

```<code>using Microsoft.AspNetCore.Http;
</code>```

Body:
From yesterday I have started learning .netcore. I have installed .netcore 2.2 & .netcore 3.1 in my machine.

In .netcore 2.2, I am able to print the process name on the website.
i.e.
I had written this below code in Startup.cs in an empty .netcore web application:

app.Run(async (context) =>
{
    await context.Response
    .WriteAsync(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
});

But now in .netcore 3.1, by default, it is calling the razor pages. So, I tried to replace that code with the above code, but I am getting this below error:

'HttpResponse' does not contain a definition for 'WriteAsync' and no
  accessible extension method 'WriteAsync' accepting a first argument of
  type 'HttpResponse' could be found (are you missing a using directive
  or an assembly reference?

It seems the extension method 'WriteAsync' has been removed in .netcore 3.1.

So, how do I display that now?

Body:
Add this using

using Microsoft.AspNetCore.Http;


问:
My Darkcode is showing error "the value of the local variable 'choice' isn't used"
I just started learning dart for flutter and wrote this code for a simple calculator but there is an error associated with a variable "choice".It is declared inside the while loop but when I use it for condition checking, it's showing "The value of the local variable 'choice' isn't used". Please help me.

```<code>import 'dart:io';

void main() {
  do {
    print(
        "Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
    int ch = int.parse(stdin.readLineSync());

    print("Enter two numbers");

    int num1 = int.parse(stdin.readLineSync());
    int num2 = int.parse(stdin.readLineSync());

    switch (ch) {
      case 1:
        print("Addition of $num1 and $num2 is ");
        print(add(num1, num2));
        break;
      case 2:
        print("Subtraction of $num1 and $num2 is ");
        print(sub(num1, num2));
        break;
      case 3:
        print("Division of $num1 and $num2 is ");
        print(div(num1, num2));
        break;
      case 4:
        print("Multiplication of $num1 and $num2 is ");
        print(mul(num1, num2));
        break;
      default:
        print("Invalid choice...");
    }

    String choice = stdin.readLineSync();
  } while (choice == "Yes" || choice == "yes");
}

int add(int x, int y) => (x + y);
int sub(int x, int y) => (x - y);
double div(int x, int y) => (x / y);
int mul(int x, int y) => (x * y);
</code>```

Shown errors:

The value of the local variable 'choice' isn't used - line 30

Undefined name 'choice' - line 30

Undefined name 'choice' - line 30

答:
As you declared choice inside the do-while, its scope is only inside the block of the do-while, so is not visible in the condition. Try declaring choice before the do keyword:

```<code>void main() {
    String choice;
    do {
        print("Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
        int ch= int.parse(stdin.readLineSync());
        print("Enter two numbers");
        int num1=int.parse(stdin.readLineSync());
        int num2=int.parse(stdin.readLineSync());
        switch(ch)
        {
            case 1:
               print("Addition of $num1 and $num2 is ");
               print(add(num1,num2));
               break;
            case 2:
               print("Subtraction of $num1 and $num2 is ");
               print(sub(num1,num2));
               break;
            case 3:
               print("Division of $num1 and $num2 is ");
               print(div(num1,num2));
               break;
            case 4:
               print("Multiplication of $num1 and $num2 is ");
               print(mul(num1,num2));
               break;
            default:
                print("Invalid choice...");
        }
        choice = stdin.readLineSync();
    } while (choice=="Yes" || choice=="yes");
}
</code>```

Body:
I just started learning dart for flutter and wrote this code for a simple calculator but there is an error associated with a variable "choice".It is declared inside the while loop but when I use it for condition checking, it's showing "The value of the local variable 'choice' isn't used". Please help me.

import 'dart:io';

void main() {
  do {
    print(
        "Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
    int ch = int.parse(stdin.readLineSync());

    print("Enter two numbers");

    int num1 = int.parse(stdin.readLineSync());
    int num2 = int.parse(stdin.readLineSync());

    switch (ch) {
      case 1:
        print("Addition of $num1 and $num2 is ");
        print(add(num1, num2));
        break;
      case 2:
        print("Subtraction of $num1 and $num2 is ");
        print(sub(num1, num2));
        break;
      case 3:
        print("Division of $num1 and $num2 is ");
        print(div(num1, num2));
        break;
      case 4:
        print("Multiplication of $num1 and $num2 is ");
        print(mul(num1, num2));
        break;
      default:
        print("Invalid choice...");
    }

    String choice = stdin.readLineSync();
  } while (choice == "Yes" || choice == "yes");
}

int add(int x, int y) => (x + y);
int sub(int x, int y) => (x - y);
double div(int x, int y) => (x / y);
int mul(int x, int y) => (x * y);

Shown errors:

The value of the local variable 'choice' isn't used - line 30

Undefined name 'choice' - line 30

Undefined name 'choice' - line 30

Body:
As you declared choice inside the do-while, its scope is only inside the block of the do-while, so is not visible in the condition. Try declaring choice before the do keyword:

void main() {
    String choice;
    do {
        print("Choose operation:\n1.Addition\n2.Subtraction\n3.Division\n4.Multiplication\nChoice:");
        int ch= int.parse(stdin.readLineSync());
        print("Enter two numbers");
        int num1=int.parse(stdin.readLineSync());
        int num2=int.parse(stdin.readLineSync());
        switch(ch)
        {
            case 1:
               print("Addition of $num1 and $num2 is ");
               print(add(num1,num2));
               break;
            case 2:
               print("Subtraction of $num1 and $num2 is ");
               print(sub(num1,num2));
               break;
            case 3:
               print("Division of $num1 and $num2 is ");
               print(div(num1,num2));
               break;
            case 4:
               print("Multiplication of $num1 and $num2 is ");
               print(mul(num1,num2));
               break;
            default:
                print("Invalid choice...");
        }
        choice = stdin.readLineSync();
    } while (choice=="Yes" || choice=="yes");
}


问:
How to get unix style prompt in windows (batch)
I am trying to make dos shell which displayes a unix/linux promt. The code is:

```<code>@echo off
:hi
set tmpdrv=%cd:~0,2%

if %homedrive% == %tmpdrv% (
  set drvmatch=1
) else (
  set drvmatch=0
)
set "MYSTRING=abcdef!%%^^()^!"
set MYSTRING=%homepath%
:strlen
(echo "%MYSTRING%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%-5
set tmppath1=%cd:~2%
CALL set tmppath2=%%tmppath1:~0,%STRLENGTH%%%
if %homepath% == %tmppath2% (
  set homematch=1
) else (
  set homematch=0
)

set homepathmatch=0
if %homepath% == %tmppath2% (
    if %homedrive% == %tmpdrv% (
    set homepathmatch=1
    )
)

if %homepathmatch%==1 (
    REM set /a STRLENGTH=%STRLENGTH%+2
        CALL set newpath=%%tmppath1:~%STRLENGTH%%%
    set newpath1=~%newpath%
)
set newpath2=%newpath1:\=/%
:check_Permissions

 net session >nul 2>&1
 if %errorLevel% == 0 (
 set "username2=root"
 ) else (
 set username2=%username%
 )
set /p %command%="%username2%@%computername%:%newpath2%$ "
%command%
goto :hi
</code>```

I want it to display directory name like in unix/linux but it displays a ~. What is wrong in my code? Can you please help me improve it?

答:
Probably not quite on the ball with the prompts specific situational substring modification, but the Method of setting the Prompt is.

```<code>@ECHO OFF & Setlocal EnableDelayedExpansion & TITLE %~n0
cls & MODE 1000 & CD %userprofile%\desktop

    For /F "tokens=* Delims=\" %%A In ("%userprofile%") Do (
        Set "C_Prompt=%%A"
        Set "C_Prompt=!C_Prompt:\=!"
        Set "C_Prompt=!C_Prompt:Users=!"
    For %%A in (a,b,c,d,e,f,g,h,i) Do (Set "C_Prompt=!C_Prompt:%%A:=!")
    )
    Set DirPath=:!CD:\=/!
    For %%A in (a,b,c,d,e,f,g,h,i) Do (Set "DirPath=!DirPath:%%A:=!")
    Set "C_Prompt=!C_Prompt!@!computername!!DirPath! $$ "

prompt !C_Prompt!

Start /B cmd.exe
</code>```

The above does not refresh the command prompt with the working directory, however will result in commands behaving as expected without expansion issues.

This linked Macro will refresh the Prompt when the working Directory changes, however the act of expanding commands within a user defined variable can result in unexpected results.

Body:
I am trying to make dos shell which displayes a unix/linux promt. The code is:

@echo off
:hi
set tmpdrv=%cd:~0,2%

if %homedrive% == %tmpdrv% (
  set drvmatch=1
) else (
  set drvmatch=0
)
set "MYSTRING=abcdef!%%^^()^!"
set MYSTRING=%homepath%
:strlen
(echo "%MYSTRING%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%-5
set tmppath1=%cd:~2%
CALL set tmppath2=%%tmppath1:~0,%STRLENGTH%%%
if %homepath% == %tmppath2% (
  set homematch=1
) else (
  set homematch=0
)

set homepathmatch=0
if %homepath% == %tmppath2% (
    if %homedrive% == %tmpdrv% (
    set homepathmatch=1
    )
)

if %homepathmatch%==1 (
    REM set /a STRLENGTH=%STRLENGTH%+2
        CALL set newpath=%%tmppath1:~%STRLENGTH%%%
    set newpath1=~%newpath%
)
set newpath2=%newpath1:\=/%
:check_Permissions

 net session >nul 2>&1
 if %errorLevel% == 0 (
 set "username2=root"
 ) else (
 set username2=%username%
 )
set /p %command%="%username2%@%computername%:%newpath2%$ "
%command%
goto :hi

I want it to display directory name like in unix/linux but it displays a ~. What is wrong in my code? Can you please help me improve it?

Body:
Probably not quite on the ball with the prompts specific situational substring modification, but the Method of setting the Prompt is.

@ECHO OFF & Setlocal EnableDelayedExpansion & TITLE %~n0
cls & MODE 1000 & CD %userprofile%\desktop

    For /F "tokens=* Delims=\" %%A In ("%userprofile%") Do (
        Set "C_Prompt=%%A"
        Set "C_Prompt=!C_Prompt:\=!"
        Set "C_Prompt=!C_Prompt:Users=!"
    For %%A in (a,b,c,d,e,f,g,h,i) Do (Set "C_Prompt=!C_Prompt:%%A:=!")
    )
    Set DirPath=:!CD:\=/!
    For %%A in (a,b,c,d,e,f,g,h,i) Do (Set "DirPath=!DirPath:%%A:=!")
    Set "C_Prompt=!C_Prompt!@!computername!!DirPath! $$ "

prompt !C_Prompt!

Start /B cmd.exe

The above does not refresh the command prompt with the working directory, however will result in commands behaving as expected without expansion issues.

This linked Macro will refresh the Prompt when the working Directory changes, however the act of expanding commands within a user defined variable can result in unexpected results.


问:
Globalization difference in inline tags in ASP.NET
Is there any advantage/downfalls between using the inline write tag instead of the resource tag? Example:

```<code><%=Resources.Site.SampleString %>
</code>```

The resources tag (expression tag) as seen in any MSDN example:

```<code><asp:Literal id="Literal1" runat="server" text="<%$ Resources:Site, SampleString %>" />
</code>```

I find the first option far easier to use, and it has IntelliSense, but maybe it won't function the same?

答:
I realised after some time that the <%=Resources.Site.SampleString %> method does not have designer support (which is understandable). This doesn't bother me, but it is a difference (for future readers).

So if you need or want designer support, the second option would be necessary.

Body:
Is there any advantage/downfalls between using the inline write tag instead of the resource tag? Example:

<%=Resources.Site.SampleString %>

The resources tag (expression tag) as seen in any MSDN example:

<asp:Literal id="Literal1" runat="server" text="<%$ Resources:Site, SampleString %>" />

I find the first option far easier to use, and it has IntelliSense, but maybe it won't function the same?


问:
Transposing a 2D-array in JavaScript
I've got an array of arrays, something like:

```<code>[
    [1,2,3],
    [1,2,3],
    [1,2,3],
]
</code>```

I would like to transpose it to get the following array:

```<code>[
    [1,1,1],
    [2,2,2],
    [3,3,3],
]
</code>```

It's not difficult to programmatically do so using loops:

```<code>function transposeArray(array, arrayLength){
    var newArray = [];
    for(var i = 0; i < array.length; i++){
        newArray.push([]);
    };

    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < arrayLength; j++){
            newArray[j].push(array[i][j]);
        };
    };

    return newArray;
}
</code>```

This, however, seems bulky, and I feel like there should be an easier way to do it. Is there?

答:
I didn't find an answer that satisfied me, so I wrote one myself, I think it is easy to understand and implement and suitable for all situations.</p>

```<code>    transposeArray: function (mat) {
        let newMat = [];
        for (let j = 0; j < mat[0].length; j++) {  // j are columns
            let temp = [];
            for (let i = 0; i < mat.length; i++) {  // i are rows
                temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
            }
            newMat.push(temp);  // then just push every column in newMat
        }
        return newMat;
    }
</code>```

Title: Transposing a 2D-array in JavaScript

Body:
I've got an array of arrays, something like:

[
    [1,2,3],
    [1,2,3],
    [1,2,3],
]

I would like to transpose it to get the following array:

[
    [1,1,1],
    [2,2,2],
    [3,3,3],
]

It's not difficult to programmatically do so using loops:

function transposeArray(array, arrayLength){
    var newArray = [];
    for(var i = 0; i < array.length; i++){
        newArray.push([]);
    };

    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < arrayLength; j++){
            newArray[j].push(array[i][j]);
        };
    };

    return newArray;
}

This, however, seems bulky, and I feel like there should be an easier way to do it. Is there?

Body:
I didn't find an answer that satisfied me, so I wrote one myself, I think it is easy to understand and implement and suitable for all situations.

    transposeArray: function (mat) {
        let newMat = [];
        for (let j = 0; j < mat[0].length; j++) {  // j are columns
            let temp = [];
            for (let i = 0; i < mat.length; i++) {  // i are rows
                temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
            }
            newMat.push(temp);  // then just push every column in newMat
        }
        return newMat;
    }