问:
explosion animation not in the right place when it is played
I was making an enemy death animation on unity(again) when it did not want to work, now when I say it did not want to work I mean it did not want to work in the position it is supposed to be in(which is where the enemy is)</p>

```<code>public class EnemyController : MonoBehaviour
{
    public int health = 3;
    public GameObject explosion;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void TakeDamage()
    {
        health--;
        if(health <= 0)
        {
            Destroy(gameObject);
             Instantiate(explosion, transform.position, transform.rotation);
        }
    }
}
</code>```

答:
You're using the transform of an object that you have already destroyed, as transform is a property of gameObject.
Try instantiating the Explosion prefab before calling Destroy(gameobject).

```<code>public void TakeDamage()
{
    health--;
    if (health <= 0)
    {
        Instantiate(explosion, transform.position, transform.rotation);
        Destroy(gameObject);
    }
}
</code>```

Body:
I was making an enemy death animation on unity(again) when it did not want to work, now when I say it did not want to work I mean it did not want to work in the position it is supposed to be in(which is where the enemy is)

public class EnemyController : MonoBehaviour
{
    public int health = 3;
    public GameObject explosion;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
    public void TakeDamage()
    {
        health--;
        if(health <= 0)
        {
            Destroy(gameObject);
             Instantiate(explosion, transform.position, transform.rotation);
        }
    }
}

Body:
You're using the transform of an object that you have already destroyed, as transform is a property of gameObject.
Try instantiating the Explosion prefab before calling Destroy(gameobject).

public void TakeDamage()
{
    health--;
    if (health <= 0)
    {
        Instantiate(explosion, transform.position, transform.rotation);
        Destroy(gameObject);
    }
}


来源: stackexchange

问:
Randomly distribute a seed spot to 128 teams using php
I have 128 teams participating in a single-elimination tournament. I want to achieve the following:

By pressing a button be able to put these teams randomly facing each other (meaning 64 matches)

Understand if you win where you will be placed in the next game and who you will face

Currently my database has these tables:

teams (list of 500 teams)

tournaments (this tournament for e.g. is id = 1)

participation (list of 128 teams that want to play in tournament id = 1)

match (this is where I need to somehow add team 1 and team 2 randomly and also know where in the bracket they stand)

At the moment for the match table I have:

id

tournament_id

round (where a 128 team tournament can go up to 7 rounds: 128 / 64 / 32 / 16 / 8 / 4 / 2

game (meaning on the bracket where it stand, was thinking this way I can define Round 2 has Game 1 and Game 2 of Round 1 playing each other etc. not sure this is a good idea)

team1_id

team2_id

team1_score

team2_score

winner_team_id

status

Does anyone have experience on this?

Thanks.

答:
Select all rows from teams in a random order:

```<code>SELECT * FROM teams ORDER BY RAND()
/* Or: https://dba.stackexchange.com/questions/955/what-is-the-best-way-to-get-a-random-ordering */
</code>```

With PHP: for every two rows you retrieve, insert a row into match, using the first team's teams.id as team1_id and the 2nd team's teams.id as team2_id, and the other fields filled out accordingly.

ContentLicense: CC BY-SA 4.0

Body:
Select all rows from teams in a random order:

SELECT * FROM teams ORDER BY RAND()
/* Or: https://dba.stackexchange.com/questions/955/what-is-the-best-way-to-get-a-random-ordering */

With PHP: for every two rows you retrieve, insert a row into match, using the first team's teams.id as team1_id and the 2nd team's teams.id as team2_id, and the other fields filled out accordingly.


问:
How do I determine the number of lines of text that will fit into a browser window
I want to display enough lines of text to fill the current size of the browser window.
Also, I'd like to update the value if the browser window changes size. Does javascript have the equivalent of SIGWINCH?

Thanks

答:
Once you figure out the height of each line (will depend on your css) you can do something like this (using jquery):</p>

```<code>$(function() {
    $(window).resize(function() {
        var text = '',
            i = 0,
            lineHeight = 12, // replace with correct value
            numLines = Math.floor($(this).height() / lineHeight);

        for(i; i < numLines; i++) {
            text += "text <br />";
        }

        $('body').html(text);
    });
    window.resize();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Once you figure out the height of each line (will depend on your css) you can do something like this (using jquery):

$(function() {
    $(window).resize(function() {
        var text = '',
            i = 0,
            lineHeight = 12, // replace with correct value
            numLines = Math.floor($(this).height() / lineHeight);

        for(i; i < numLines; i++) {
            text += "text <br />";
        }

        $('body').html(text);
    });
    window.resize();
});


问:
screen snipping program leaves left over square after snip
I'm attempting to resolved an issue with a left over square after my snipping program is done snipping. I would like to delete any instance of the square drawing after the initial snip

.

Steps to replicate:

Select "mode" > select "snip" > drag rectangle and take a screen snip

Select "mode" > select "snip" > now observe the previous snip still has the rectangle on the screen (as shown in the picture)

My code:

```<code>import sys

from PyQt5 import QtCore, QtGui, QtWidgets

from PIL import ImageGrab
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication

class App(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()
        self.topMenu()

    def initUI(self):
        self.setWindowTitle("Lil Snippy")
        self.setWindowIcon(QtGui.QIcon("assets/lilSnippyIcon.png"))
        self.setGeometry(400, 300, 400, 300)

        # QApplication.setOverrideCursor(Qt.WaitCursor)
    def topMenu(self):
        menubar = self.menuBar()

        fileMenu = menubar.addMenu("File")
        saveAct = QtWidgets.QAction(QtGui.QIcon("assets/saveIcon.png"), "Save", self)
        saveAsAct = QtWidgets.QAction(
            QtGui.QIcon("assets/saveAsIcon.png"), "Save As", self
        )

        modeMenu = menubar.addMenu("Mode")
        snipAct = QtWidgets.QAction(QtGui.QIcon("assets/cameraIcon.png"), "Snip", self)
        snipAct.setShortcut(QtGui.QKeySequence("F1"))
        snipAct.triggered.connect(self.activateSnipping)
        videoAct = QtWidgets.QAction(QtGui.QIcon("assets/videoIcon.png"), "Video", self)
        videoAct.setShortcut("F2")
        soundAct = QtWidgets.QAction(QtGui.QIcon("assets/audioIcon.png"), "Sound", self)
        soundAct.setShortcut("F3")
        autoAct = QtWidgets.QAction(
            QtGui.QIcon("assets/automationIcon.png"), "Automation", self
        )
        autoAct.setShortcut("F4")

        optionsMenu = menubar.addMenu("Options")

        helpMenu = menubar.addMenu("Help")
        helpAct = QtWidgets.QAction(QtGui.QIcon("assets/helpIcon.png"), "Help", self)
        aboutAct = QtWidgets.QAction(QtGui.QIcon("assets/aboutIcon.png"), "About", self)

        fileMenu.addAction(saveAct)
        fileMenu.addAction(saveAsAct)
        modeMenu.addAction(snipAct)
        modeMenu.addAction(videoAct)
        modeMenu.addAction(soundAct)
        modeMenu.addAction(autoAct)
        helpMenu.addAction(helpAct)
        helpMenu.addAction(aboutAct)

        self.snipper = SnippingWidget()
        self.snipper.closed.connect(self.on_closed)

    def activateSnipping(self):
        self.snipper.showFullScreen()
        QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
        self.hide()

    def on_closed(self):
        self.show()

class SnippingWidget(QtWidgets.QMainWindow):
    closed = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(SnippingWidget, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.setStyleSheet("background:transparent;")
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.outsideSquareColor = "red"
        self.squareThickness = 2

        self.start_point = QtCore.QPoint()
        self.end_point = QtCore.QPoint()

    def mousePressEvent(self, event):
        self.start_point = event.pos()
        self.end_point = event.pos()
        self.update()

    def mouseMoveEvent(self, event):
        self.end_point = event.pos()
        self.update()

    def mouseReleaseEvent(self, QMouseEvent):
        r = QtCore.QRect(self.start_point, self.end_point).normalized()
        self.hide()
        img = ImageGrab.grab(bbox=r.getCoords())
        img.save("snips/testImage.png")
        QApplication.restoreOverrideCursor()
        self.closed.emit()

    def paintEvent(self, event):
        trans = QtGui.QColor(22, 100, 233)
        r = QtCore.QRectF(self.start_point, self.end_point).normalized()
        qp = QtGui.QPainter(self)
        trans.setAlphaF(0.2)
        qp.setBrush(trans)
        outer = QtGui.QPainterPath()
        outer.addRect(QtCore.QRectF(self.rect()))
        inner = QtGui.QPainterPath()
        inner.addRect(r)
        r_path = outer - inner
        qp.drawPath(r_path)
        qp.setPen(
            QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
        )
        trans.setAlphaF(0)
        qp.setBrush(trans)
        qp.drawRect(r)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    application = App()
    application.show()
    sys.exit(app.exec_())
</code>```

答:
You have to reset self.start_point and self.end_point:

```<code>def mouseReleaseEvent(self, QMouseEvent):
    r = QtCore.QRect(self.start_point, self.end_point).normalized()
    self.hide()
    img = ImageGrab.grab(bbox=r.getCoords())
    img.save("snips/testImage.png")
    QApplication.restoreOverrideCursor()
    self.closed.emit()
    <b>self.start_point = QtCore.QPoint()
    self.end_point = QtCore.QPoint()</b></code>```

Body:
I'm attempting to resolved an issue with a left over square after my snipping program is done snipping. I would like to delete any instance of the square drawing after the initial snip

.

Steps to replicate:

Select "mode" > select "snip" > drag rectangle and take a screen snip

Select "mode" > select "snip" > now observe the previous snip still has the rectangle on the screen (as shown in the picture)

My code:

import sys

from PyQt5 import QtCore, QtGui, QtWidgets

from PIL import ImageGrab
from PyQt5.QtGui import QCursor
from PyQt5.QtWidgets import QApplication

class App(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()
        self.topMenu()

    def initUI(self):
        self.setWindowTitle("Lil Snippy")
        self.setWindowIcon(QtGui.QIcon("assets/lilSnippyIcon.png"))
        self.setGeometry(400, 300, 400, 300)

        # QApplication.setOverrideCursor(Qt.WaitCursor)
    def topMenu(self):
        menubar = self.menuBar()

        fileMenu = menubar.addMenu("File")
        saveAct = QtWidgets.QAction(QtGui.QIcon("assets/saveIcon.png"), "Save", self)
        saveAsAct = QtWidgets.QAction(
            QtGui.QIcon("assets/saveAsIcon.png"), "Save As", self
        )

        modeMenu = menubar.addMenu("Mode")
        snipAct = QtWidgets.QAction(QtGui.QIcon("assets/cameraIcon.png"), "Snip", self)
        snipAct.setShortcut(QtGui.QKeySequence("F1"))
        snipAct.triggered.connect(self.activateSnipping)
        videoAct = QtWidgets.QAction(QtGui.QIcon("assets/videoIcon.png"), "Video", self)
        videoAct.setShortcut("F2")
        soundAct = QtWidgets.QAction(QtGui.QIcon("assets/audioIcon.png"), "Sound", self)
        soundAct.setShortcut("F3")
        autoAct = QtWidgets.QAction(
            QtGui.QIcon("assets/automationIcon.png"), "Automation", self
        )
        autoAct.setShortcut("F4")

        optionsMenu = menubar.addMenu("Options")

        helpMenu = menubar.addMenu("Help")
        helpAct = QtWidgets.QAction(QtGui.QIcon("assets/helpIcon.png"), "Help", self)
        aboutAct = QtWidgets.QAction(QtGui.QIcon("assets/aboutIcon.png"), "About", self)

        fileMenu.addAction(saveAct)
        fileMenu.addAction(saveAsAct)
        modeMenu.addAction(snipAct)
        modeMenu.addAction(videoAct)
        modeMenu.addAction(soundAct)
        modeMenu.addAction(autoAct)
        helpMenu.addAction(helpAct)
        helpMenu.addAction(aboutAct)

        self.snipper = SnippingWidget()
        self.snipper.closed.connect(self.on_closed)

    def activateSnipping(self):
        self.snipper.showFullScreen()
        QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
        self.hide()

    def on_closed(self):
        self.show()

class SnippingWidget(QtWidgets.QMainWindow):
    closed = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(SnippingWidget, self).__init__(parent)
        self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
        self.setStyleSheet("background:transparent;")
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        self.outsideSquareColor = "red"
        self.squareThickness = 2

        self.start_point = QtCore.QPoint()
        self.end_point = QtCore.QPoint()

    def mousePressEvent(self, event):
        self.start_point = event.pos()
        self.end_point = event.pos()
        self.update()

    def mouseMoveEvent(self, event):
        self.end_point = event.pos()
        self.update()

    def mouseReleaseEvent(self, QMouseEvent):
        r = QtCore.QRect(self.start_point, self.end_point).normalized()
        self.hide()
        img = ImageGrab.grab(bbox=r.getCoords())
        img.save("snips/testImage.png")
        QApplication.restoreOverrideCursor()
        self.closed.emit()

    def paintEvent(self, event):
        trans = QtGui.QColor(22, 100, 233)
        r = QtCore.QRectF(self.start_point, self.end_point).normalized()
        qp = QtGui.QPainter(self)
        trans.setAlphaF(0.2)
        qp.setBrush(trans)
        outer = QtGui.QPainterPath()
        outer.addRect(QtCore.QRectF(self.rect()))
        inner = QtGui.QPainterPath()
        inner.addRect(r)
        r_path = outer - inner
        qp.drawPath(r_path)
        qp.setPen(
            QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
        )
        trans.setAlphaF(0)
        qp.setBrush(trans)
        qp.drawRect(r)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    application = App()
    application.show()
    sys.exit(app.exec_())

Body:
You have to reset self.start_point and self.end_point:

def mouseReleaseEvent(self, QMouseEvent):
    r = QtCore.QRect(self.start_point, self.end_point).normalized()
    self.hide()
    img = ImageGrab.grab(bbox=r.getCoords())
    img.save("snips/testImage.png")
    QApplication.restoreOverrideCursor()
    self.closed.emit()
    self.start_point = QtCore.QPoint()
    self.end_point = QtCore.QPoint()


问:
Selecting next quoted text in Vim
I wanted to create a text object for the "next quoted text", for example in the code:

```<code>My cursor is HERE.
I want to delete 'what is inside here'
</code>```

If the cursor is at the beginning of the word HERE, I would like to have something like din', for delete inner next quotes. What is the correct sequence of keys to move to the next quoted text?

Observe that simply /'<cr> doesn't work properly. Consider:

```<code>'My cursor is HERE. But I do not want to delete this'
...
'But this!'
</code>```

As the example suggests, if I press din' (and the cursor is at the beginning of HERE), I want to delete the next quoted text, that is 'But this!'.
For example, the following text object would delete 'My cursor is HERE. But I don't want to delete this':

```<code>vnoremap <silent> in' :<C-U> execute "normal! /)\rvi'"<CR>
onoremap <silent> in' :<C-U> execute "normal! /)\rvi'"<CR>
</code>```

答:
you can do:

```<code>2/'<CR>di'
</code>```

Alternatively you can use the * command:

```<code>f'*di'
</code>```

Title: Selecting next quoted text in Vim

Body:
I wanted to create a text object for the "next quoted text", for example in the code:

My cursor is HERE.
I want to delete 'what is inside here'

If the cursor is at the beginning of the word HERE, I would like to have something like din', for delete inner next quotes. What is the correct sequence of keys to move to the next quoted text?

Observe that simply /'<cr> doesn't work properly. Consider:

'My cursor is HERE. But I do not want to delete this'
...
'But this!'

As the example suggests, if I press din' (and the cursor is at the beginning of HERE), I want to delete the next quoted text, that is 'But this!'.
For example, the following text object would delete 'My cursor is HERE. But I don't want to delete this':

vnoremap <silent> in' :<C-U> execute "normal! /)\rvi'"<CR>
onoremap <silent> in' :<C-U> execute "normal! /)\rvi'"<CR>

Body:
you can do:

2/'<CR>di'

Alternatively you can use the * command:

f'*di'


问:
android gravity right cursor shows left of the input text EditText
I am using Kotlin. I have used gravity right so that input number start from right. But EditText cursor keep stay always left of the input text in EditText. I want to keep gravity right & text right to left.Here is the image

Here is my EditText xml code..

```<code><EditText
        android:id="@+id/et_amount"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="numberDecimal"
        android:ellipsize="end"
        android:gravity="right|center_horizontal|center_vertical"
        android:textStyle="bold"
        android:maxLength="6" >
        <requestFocus />
    </EditText>
</code>```

Please help me so that input text start from left to right & cursor show always right.

答:
Try to add this to your edittext:
android:textDirection="rtl"

Body:
I am using Kotlin. I have used gravity right so that input number start from right. But EditText cursor keep stay always left of the input text in EditText. I want to keep gravity right & text right to left.Here is the image

Here is my EditText xml code..

<EditText
        android:id="@+id/et_amount"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="numberDecimal"
        android:ellipsize="end"
        android:gravity="right|center_horizontal|center_vertical"
        android:textStyle="bold"
        android:maxLength="6" >
        <requestFocus />
    </EditText>

Please help me so that input text start from left to right & cursor show always right.


问:
how to convert baseclass to subclass(subclass s = basceclass as subclass, but i dont' know this subclass type)
For example:

```<code>   class a { }
   class b : a { }
   class c : a { }
   ....

   List<a> a = new List<a>();
   a.Add(new b());
   c.Add(new c());
   ....
</code>```

There are lots of subclass inherit a, but i don't know which one. how to convert one of the elements into subclasses, such as ( a[i] as subclass ) the subclass which I don't know but it inherits a ?
   I search in Google, many answers tell me to use reflection and Assembly.GetIntance, but  I think it create a new object, all the data owned by the subClass will be lost.
  Hope for help.

答: You can't convert to a type which you don't know (but it is not clear why you think you need to do that, hence @stickybit's comments about this being an XY problem). If you are trying to determine what type an object is so you can convert to it, then the is operator can be used to do that, or pattern matching can be used, although in many (most?) cases it is better from a design standpoint to add a virtual method to the superclass and override it in each subclass to do something different, so that you can retrieve an element from your List as an instance of the superclass and call the virtual method on it without needing to know which specific subclass the object actually is.</p>

Body:
For example:

   class a { }
   class b : a { }
   class c : a { }
   ....

   List a = new List();
   a.Add(new b());
   c.Add(new c());
   ....

There are lots of subclass inherit a, but i don't know which one. how to convert one of the elements into subclasses, such as ( a[i] as subclass ) the subclass which I don't know but it inherits a ?
   I search in Google, many answers tell me to use reflection and Assembly.GetIntance, but  I think it create a new object, all the data owned by the subClass will be lost.
  Hope for help.


问:
In IntelliJ, Maven can't resolve dependencies
Right now, I get errors on the dependencies shown in Maven. </p>

<p>I've tried the things listed here Intellij idea cannot resolve anything in maven such as changing my Maven Home Directory and Selecting Import Maven automatically. I'm not sure what else it could be...
Also, the project was initially done in Eclipse. </p>

答:
If you are done with mvn clean install, just click this icon.

If in rare case you still face the issue type command
 mvn -U idea:idea (its deprecated but will do the job).

Body:
Right now, I get errors on the dependencies shown in Maven.

I've tried the things listed here Intellij idea cannot resolve anything in maven such as changing my Maven Home Directory and Selecting Import Maven automatically. I'm not sure what else it could be...
Also, the project was initially done in Eclipse.


问:
Has FB.Canvas.setAutoResize() stopped working for anyone else?
I maintain a few different Facebook applications, and across them I use

```<code>FB.Canvas.setAutoResize();
</code>```

to resize the height of the application.

In the last few hours this has stopped working on all of my applications, without any of my code being changed.

I found a user that seems to have the same problem here.

My main question is, has anyone else had this happen to their applications today?

Does anyone know if this is a bug or has support for setAutoResize() suddenly been dropped?

答: Currently, live platform status says FB team is working on this. For more please check here and here</p>

Body:
I maintain a few different Facebook applications, and across them I use

FB.Canvas.setAutoResize();

to resize the height of the application.

In the last few hours this has stopped working on all of my applications, without any of my code being changed.

I found a user that seems to have the same problem here.

My main question is, has anyone else had this happen to their applications today?

Does anyone know if this is a bug or has support for setAutoResize() suddenly been dropped?


问:
Object property called with dot notation showing console.log 'undefined'
fairly new to Javascript.

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as ‘undefined’ but when put in a function it works fine. Why does it show undefined with just the console log? Why doesn't it get displayed and why does it need a function to do so.

Here’s the code.

```<code>var toDoList = {
// Holding the List
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}
</code>```

This will display it as ‘undefined’ when I try to access the object property displayMyList with dot notation. However when a method is used it displays the list fine. I am wondering why is that?

```<code> var toDoList = {
    // Holding the List
    myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
    // Displaying the List
    displayMyList: function(){
  console.log(this.myList)
}
    }
</code>```

答:
First of all, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

```<code>var toDoList = {
  // Holding the List
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: console.log(this.myList)
}
</code>```

There are a couple problems here with your first example above.

First, you are setting a property in toDoList called displayMyList to the RETURN VALUE of console.log(this.myList). console.log() does not return any value (see: https://developer.mozilla.org/en-US/docs/Web/API/Console/log) so the value being assigned to displayMyList will always be undefined.

And second, it will evaluate this and see what it returns (at this time this refers to the global this unless it has otherwise been set to another context. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis. So you'll be looking at the property myList of globalThis (or otherwise what this is bound to in that context).

```<code>var toDoList = {
  // Holding the List
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: function() {
    console.log(this.myList)
  }
};
</code>```

This fixes those, you are:

Assigning displayMyList to be a FUNCTION that you will run later in the context of toDoList being this.

Note how the use of function keyword here rebinds this to the containing object.

If you defined the function without function keyword, e.g. displayMyList: () => console.log(this.myList), it would also not work because arrow functions do not rebind this. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Similarly, even if you used the function keyword. If you called the function in a different way, it would also not work. Examples below:

```<code>// Won't work
const x = toDoList.displayMyList;
x();

// Won't work
toDoList.displayMyList.call(globalThis);

// Won't work
toDoList.displayMyList.apply({});
</code>```

Body:
fairly new to Javascript.

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as ‘undefined’ but when put in a function it works fine. Why does it show undefined with just the console log? Why doesn't it get displayed and why does it need a function to do so.

Here’s the code.

var toDoList = {
// Holding the List
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}

This will display it as ‘undefined’ when I try to access the object property displayMyList with dot notation. However when a method is used it displays the list fine. I am wondering why is that?

 var toDoList = {
    // Holding the List
    myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
    // Displaying the List
    displayMyList: function(){
  console.log(this.myList)
}
    }

Body:
First of all, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

var toDoList = {
  // Holding the List
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: console.log(this.myList)
}

There are a couple problems here with your first example above.

First, you are setting a property in toDoList called displayMyList to the RETURN VALUE of console.log(this.myList). console.log() does not return any value (see: https://developer.mozilla.org/en-US/docs/Web/API/Console/log) so the value being assigned to displayMyList will always be undefined.

And second, it will evaluate this and see what it returns (at this time this refers to the global this unless it has otherwise been set to another context. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis. So you'll be looking at the property myList of globalThis (or otherwise what this is bound to in that context).

var toDoList = {
  // Holding the List
  myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
  // Displaying the List
  displayMyList: function() {
    console.log(this.myList)
  }
};

This fixes those, you are:

Assigning displayMyList to be a FUNCTION that you will run later in the context of toDoList being this.

Note how the use of function keyword here rebinds this to the containing object.

If you defined the function without function keyword, e.g. displayMyList: () => console.log(this.myList), it would also not work because arrow functions do not rebind this. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Similarly, even if you used the function keyword. If you called the function in a different way, it would also not work. Examples below:

// Won't work
const x = toDoList.displayMyList;
x();

// Won't work
toDoList.displayMyList.call(globalThis);

// Won't work
toDoList.displayMyList.apply({});


问:
Resolve Git merge conflicts in favor of their changes during a pull
How do I resolve a git merge conflict in favor of pulled changes?

I want to remove all conflicting changes from a working tree without having to go through all of the conflicts with git mergetool, while keeping all conflict-free changes. Preferably, I want to do this while pulling, not afterwards.

答:
If you're already in conflicted state, and do not want to checkout path one by one. You may try</p>

```<code>git merge --abort
git pull -X theirs
</code>```

Body:
If you're already in conflicted state, and do not want to checkout path one by one. You may try

git merge --abort
git pull -X theirs


问:
RefreshIndicator not working with SingleChildScrollView as child
I am trying to use RefreshIndicator to reload a list I show on my home screen. The code looks similar to this:

class Home extends StatefulWidget {
  @override
  _StartHomeState createState() => _StartHomeState();
}

class _StartHomeState extends State<Home> {
  EventsList events;

  @override
  void initState() {
    super.initState();
    events = EventsList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: RefreshIndicator(
        onRefresh: resfreshEventList,
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            children: [
              HomeTopBar(),
              events,
            ],
          ),
        ),
      ),
    );
  }

  Future<Null> resfreshEventList() async {
    await Future.delayed(Duration(seconds: 2));

    setState(() {
      events = EventsList();
    });
    return null;
  }
}
```

EventsList is another stateful widget that will call an API and map the response to a list of widgets. I have tried setting the physics property of the SingleChildScrollView as mentioned here: https://github.com/flutter/flutter/issues/22180 but no luck. Using ListView instead of the SingleChildScrollView doesn't work either.

答:
It seems to be working fine in this example When I pull to refresh then  resfreshEventList gets fired and also setState is working without any problem.

Here is the code which I am using:

```<code>import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _StartHomeState createState() => _StartHomeState();
}

class _StartHomeState extends State<Home> {
  // EventsList events;
  int number = 0;

  @override
  // void initState() {
  //   super.initState();
  //   events = EventsList();
  // }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text("RefreshIndicator Example"),
      ),
      resizeToAvoidBottomPadding: false,
      body: RefreshIndicator(
        onRefresh: resfreshEventList,
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            children: [
              // HomeTopBar(),
              // events,
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              )
            ],
          ),
        ),
      ),
    ));
  }

  Future<Null> resfreshEventList() async {
    // await Future.delayed(Duration(seconds: 2));

    // setState(() {
    //   events = EventsList();
    // });
    setState(() {
      number = number + 1;
    });
    print("Refresh Pressed");
    return null;
  }
}

</code>```

Output:

Body:
I am trying to use RefreshIndicator to reload a list I show on my home screen. The code looks similar to this:

class Home extends StatefulWidget {
  @override
  _StartHomeState createState() => _StartHomeState();
}

class _StartHomeState extends State<Home> {
  EventsList events;

  @override
  void initState() {
    super.initState();
    events = EventsList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body: RefreshIndicator(
        onRefresh: resfreshEventList,
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            children: [
              HomeTopBar(),
              events,
            ],
          ),
        ),
      ),
    );
  }

  Future<Null> resfreshEventList() async {
    await Future.delayed(Duration(seconds: 2));

    setState(() {
      events = EventsList();
    });
    return null;
  }
}

EventsList is another stateful widget that will call an API and map the response to a list of widgets. I have tried setting the physics property of the SingleChildScrollView as mentioned here: https://github.com/flutter/flutter/issues/22180 but no luck. Using ListView instead of the SingleChildScrollView doesn't work either.

Body:
It seems to be working fine in this example When I pull to refresh then  resfreshEventList gets fired and also setState is working without any problem.

Here is the code which I am using:

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _StartHomeState createState() => _StartHomeState();
}

class _StartHomeState extends State<Home> {
  // EventsList events;
  int number = 0;

  @override
  // void initState() {
  //   super.initState();
  //   events = EventsList();
  // }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text("RefreshIndicator Example"),
      ),
      resizeToAvoidBottomPadding: false,
      body: RefreshIndicator(
        onRefresh: resfreshEventList,
        child: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(
            children: [
              // HomeTopBar(),
              // events,
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              ),
              Divider(),
              Container(
                height: 200,
                width: 200,
                color: Colors.red,
                child: Center(
                  child: Text(number.toString()),
                ),
              )
            ],
          ),
        ),
      ),
    ));
  }

  Future<Null> resfreshEventList() async {
    // await Future.delayed(Duration(seconds: 2));

    // setState(() {
    //   events = EventsList();
    // });
    setState(() {
      number = number + 1;
    });
    print("Refresh Pressed");
    return null;
  }
}

Output:


答:
a method using pyspark</p>

```<code>from pyspark import SparkContext

sc = SparkContext()

l = sc.parallelize(sum_weekly)

r = l.map(lambda x: (x[0].split("/")[1], x[1])).reduceByKey(lambda p, q: (p + q)).collect()

print(r) #[('04', 13), ('02', 360), ('01', 242), ('03', 220), ('05', 67)]
</code>```

Title: Group items in a list and calculate sums

Body:
I have a list with weekly figures and need to obtain the grouped totals by month.

The following code does the job, but there should be a more pythonic way of doing it with using the  standard libraries.
The drawback of the code below is that the list needs to be in sorted order.

#Test data (not sorted)
sum_weekly=[('2020/01/05', 59), ('2020/01/19', 88), ('2020/01/26', 95), ('2020/02/02', 89),
 ('2020/02/09', 113), ('2020/02/16', 90), ('2020/02/23', 68), ('2020/03/01', 74), ('2020/03/08', 85),
  ('2020/04/19', 6), ('2020/04/26', 5), ('2020/05/03', 14),
 ('2020/05/10', 5), ('2020/05/17', 20), ('2020/05/24', 28),('2020/03/15', 56), ('2020/03/29', 5), ('2020/04/12', 2),]

month = sum_weekly[0][0].split('/')[1]
count=0
out=[]
for item in sum_weekly:
    m_sel = item[0].split('/')[1]
    if m_sel!=month:
        out.append((month, count))
        count=item[1]
    else:
        count+=item[1]
    month = m_sel
out.append((month, count))

# monthly sums output as ('01', 242), ('02', 360), ('03', 220), ('04', 13), ('05', 67)
print (out)

Body:
a method using pyspark

from pyspark import SparkContext

sc = SparkContext()

l = sc.parallelize(sum_weekly)

r = l.map(lambda x: (x[0].split("/")[1], x[1])).reduceByKey(lambda p, q: (p + q)).collect()

print(r) #[('04', 13), ('02', 360), ('01', 242), ('03', 220), ('05', 67)]


问:
Can AbstractProcessor detect if annotated method has compilation errors?
My AbstractProcessorimplementation gets called even though the annotated method contains code that results in compiler errors. (I.e. the processor is triggered by the presence of an annotation whose target is ElementType.METHOD).

Having experimented a bit I get the impression that syntax errors in the method body results in the AbstractProcessor not being triggered, whereas "reference errors", fx trying to call a private method that can't be reached, does result in the AbstractProcessor being called.

I am glad that the AbstractProcessor is being called, but I need to know if the annotated method contains any errors.

I have two questions:

How can my AbstractProcessor code know, if the ExecutableElement my method is found on, contains errors? I am aware of Google Auto's SuperficialValidation, but I can't get it to detect these errors - perhaps it only works on TypeElements?

Can I be sure that all compiler versions have the same behavior with regards to with kinds of errors prevents the AbstractProcessor from being called, and which ones will let it perform its logic?

答:
The JavaCompiler has multiple phases that run.
You can see if the processing is complete from the RoundEnvironment.processingOver() and walk the tree using a TreePathScanner.
However a lot of the actual errors are found after annotation processing is complete and can be found in the diagnostics. You might be able to find some information by supplying a DiagnosticListener.

There are some ways to detect that an error has occurred from inspecting the Symbol/Type of the symbol.
Using a TreePathScanner inside the visitMethodInvocatio you would expect the symbol to be a method, but if that method doesn't exist it may be null or a ClassSymbol.


问:
How to change the color of a text/item/css inside a *ngFor?
I have one item creater using an array, that creates a list of items using the *ngFor="let option.

I want to change the color of those items based on their values, but I cant seem to do it.

tankItAwnserArray = ['Yes','Yes','Option','NO'];```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ion-item *ngFor="let option of tankItAwnserArray">
        <ion-item> Move Damage:  {{option}}</ion-item>
      </ion-item></code>```

I want the "Yes" value to be Green, the "Option" to be orange and the "No" to be red.

I tried a lot of things but I cant see to make it work.

Can anyone help me?

答:
```<code>    interface Colors {
    yes: string;
    option: string;
    no: string;
    }

    const colors: Colors = {
    yes: '#336699',
    option: '#223366',
    no: '#223366'
    }

Push the colors from your JSON directly into the inline styles like...

<span [ngStyle]="{'color': colors[option.toLowercase()]}">{{option}}</span>
</code>```

Body:
I have one item creater using an array, that creates a list of items using the *ngFor="let option.

I want to change the color of those items based on their values, but I cant seem to do it.

tankItAwnserArray = ['Yes','Yes','Option','NO'];

 <ion-item *ngFor="let option of tankItAwnserArray">
        <ion-item> Move Damage:  {{option}}</ion-item>
      </ion-item>

I want the "Yes" value to be Green, the "Option" to be orange and the "No" to be red.

I tried a lot of things but I cant see to make it work.

Can anyone help me?


问:
Why are these loop & hashing operations take O(N) time complexity?
Given the array :

```<code>int arr[]= {1, 2, 3, 2, 3, 1, 3}
</code>```

You are asked to find a number within the array that occurs odd number of times. It's 3 (occurring 3 times). The time complexity should be at least O(n).
The solution is to use an HashMap. Elements become keys and their counts become values of the hashmap.

```<code>// Code belongs to geeksforgeeks.org
// function to find the element occurring odd
    // number of times

    static int getOddOccurrence(int arr[], int n)
    {
        HashMap<Integer,Integer> hmap = new HashMap<>();
        // Putting all elements into the HashMap
        for(int i = 0; i < n; i++)
        {
            if(hmap.containsKey(arr[i]))
            {
                int val = hmap.get(arr[i]);
                // If array element is already present then
                // increase the count of that element.
                hmap.put(arr[i], val + 1);
            }
            else
                // if array element is not present then put
                // element into the HashMap and initialize
                // the count to one.
                hmap.put(arr[i], 1);
        }

        // Checking for odd occurrence of each element present
          // in the HashMap
        for(Integer a:hmap.keySet())
        {
            if(hmap.get(a) % 2 != 0)
                return a;
        }
        return -1;
    }
</code>```

I don't get why this overall operation takes O(N) time complexity. If I think about it, the loop alone takes O(N) time complexity. Those hmap.put (an insert operation) and hmap.get(a find operations) take O(N) and they are nested within the loop. So normally I would think this function takes O(N^2) times. Why it instead takes O(N)?.

答:
I don't get why this overall operation takes O(N) time complexity.

You must examine all elements of the array - O(N)

For each element of the array you call contain, get and put on the array.  These are O(1) operations.  Or more precisely, they are O(1) on averaged amortized over the lifefime of the HashMap.  This is due to the fact that a HashMap will grow its hash array when the ratio of the array size to the number of elements exceeds the load factor.

O(N) repetitions of 2 or 3 O(1) operations is O(N).  QED

Reference:

Is a Java hashmap really O(1)?

Strictly speaking there are a couple of scenarios where a HashMap is not O(1).

If the hash function is poor (or the key distribution is pathological) the hash chains will be unbalanced.  With early HashMap implementations, this could lead to (worst case) O(N) operations because operations like get had to search a long hash chain.  With recent implementations, HashMap will construct a balanced binary tree for any hash chain that is too long.  That leads to worst case O(logN) operations.

HashMap is unable to grow the hash array beyond 2^31 hash buckets.  So at that point HashMap complexity starts transitioning to O(log N) complexity.  However if you have a map that size, other secondary effects will probably have affected the real performance anyway.

Body:
Given the array :

int arr[]= {1, 2, 3, 2, 3, 1, 3}

You are asked to find a number within the array that occurs odd number of times. It's 3 (occurring 3 times). The time complexity should be at least O(n).
The solution is to use an HashMap. Elements become keys and their counts become values of the hashmap.

// Code belongs to geeksforgeeks.org
// function to find the element occurring odd
    // number of times

    static int getOddOccurrence(int arr[], int n)
    {
        HashMap<Integer,Integer> hmap = new HashMap<>();
        // Putting all elements into the HashMap
        for(int i = 0; i < n; i++)
        {
            if(hmap.containsKey(arr[i]))
            {
                int val = hmap.get(arr[i]);
                // If array element is already present then
                // increase the count of that element.
                hmap.put(arr[i], val + 1);
            }
            else
                // if array element is not present then put
                // element into the HashMap and initialize
                // the count to one.
                hmap.put(arr[i], 1);
        }

        // Checking for odd occurrence of each element present
          // in the HashMap
        for(Integer a:hmap.keySet())
        {
            if(hmap.get(a) % 2 != 0)
                return a;
        }
        return -1;
    }

I don't get why this overall operation takes O(N) time complexity. If I think about it, the loop alone takes O(N) time complexity. Those hmap.put (an insert operation) and hmap.get(a find operations) take O(N) and they are nested within the loop. So normally I would think this function takes O(N^2) times. Why it instead takes O(N)?.


问:
How to use mapbox-gl-csp.js file with npm?
I am trying to use the mapbox csp feature. The documentation shows there's a CDN bundle for the CSP distribution. I'm wondering how I could use the CSP distribution with npm. From the node_module, it looks like mapbox-gl-csp.js is included in the mapbox module.
mapbox module dist folder

However, I'm having a hard time understanding how I can switch to the csp distribution rather than the regular mapbox-gl.js in npm. I've tried to add a path in my tsconfig.json, but it doesn't seem to be working and still using the regular mapbox-gl.js:

```<code>"compilerOptions": {
    ...
    "paths": {
        "mapbox-gl": ["./node_modules/mapbox-gl/dist/mapbox-gl-csp.js"]
    }
}
</code>```

I'm wondering what I should do to make my project use the mapbox csp bundle with npm?

答:
You should be able to do something like:

import MapboxGl from 'mapbox-gl/dist/mapbox-gl-csp;

Body:
I am trying to use the mapbox csp feature. The documentation shows there's a CDN bundle for the CSP distribution. I'm wondering how I could use the CSP distribution with npm. From the node_module, it looks like mapbox-gl-csp.js is included in the mapbox module.
mapbox module dist folder

However, I'm having a hard time understanding how I can switch to the csp distribution rather than the regular mapbox-gl.js in npm. I've tried to add a path in my tsconfig.json, but it doesn't seem to be working and still using the regular mapbox-gl.js:

"compilerOptions": {
    ...
    "paths": {
        "mapbox-gl": ["./node_modules/mapbox-gl/dist/mapbox-gl-csp.js"]
    }
}

I'm wondering what I should do to make my project use the mapbox csp bundle with npm?


问:
Codechef recipe wrong answer
Why am I getting a wrong answer to this question? The program gives correct answers to the example testcases.

Question link: https://www.codechef.com/problems/RECIPE

```<code>for i in range(int(input())):
    ingredients,*items = map(int,input().split())
    if (0 not in items):
        trial = [x%min(items)==0 for x in items]
        if all(trial):
            print(*[int(x//min(items)) for x in items ])
        else:
            print(*items)

</code>```

答:
Dividing all of the numbers by min(items) works for the sample cases they give, but it isn't sufficiently general. Consider the third sample case:

3 15 9 6

Dividing everything by 3 gives the correct answer. But what if I changed the 3 to a 6?

6 15 9 6

Dividing by 3 would still be the correct strategy, but 3 doesn't appear in the input. (Dividing by 6 doesn't work because 15 and 9 are odd numbers.)

The right way to do this is to find the greatest common divisor, or GCD. The GCD is the largest number that divides each of the numbers. If you don't know how to calculate the GCD I'll challenge you to try to figure it out without looking up how. If you get stuck you can look up an algorithm, but it's a simple enough adjustment to what you already have that you should be able to do it yourself.

Title: Codechef recipe wrong answer

Body:
Why am I getting a wrong answer to this question? The program gives correct answers to the example testcases.

Question link: https://www.codechef.com/problems/RECIPE

for i in range(int(input())):
    ingredients,*items = map(int,input().split())
    if (0 not in items):
        trial = [x%min(items)==0 for x in items]
        if all(trial):
            print(*[int(x//min(items)) for x in items ])
        else:
            print(*items)


问:
jQuery width() not returning correct value on a div with generated content
With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped.  So in this case I get 95 in the alert.  If I alert parent().width() I get 100.

The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not.  The width of the content doesn't seem to have any bearing on what .width() returns.

So my question is, how do I get the true pixel width of #main?

CSS:

```<code>#container {
    width: 100%;
}

#main {
    width: 95%;
    overflow: hidden;
}
</code>```

HTML:

```<code><div id="conatiner">
    <div id="main"></div>
</div>
</code>```

Javascript/jQuery:

```<code>$.get('page.php', function(result) {
    $('#main').html(result);
});
alert($('#main').width();
</code>```

答:
This works if you fix the last line of your code:

```<code>alert($('#main').width());
</code>```

Here is the fiddle

http://jsfiddle.net/UMAbx/

Also, div id=container was spelled incorrectly in the HTML.  Fixed in the fiddle.

Body:
With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped.  So in this case I get 95 in the alert.  If I alert parent().width() I get 100.

The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not.  The width of the content doesn't seem to have any bearing on what .width() returns.

So my question is, how do I get the true pixel width of #main?

CSS:

#container {
    width: 100%;
}

#main {
    width: 95%;
    overflow: hidden;
}

HTML:

Javascript/jQuery:

$.get('page.php', function(result) {
    $('#main').html(result);
});
alert($('#main').width();

Body:
This works if you fix the last line of your code:

alert($('#main').width());

Here is the fiddle

http://jsfiddle.net/UMAbx/

Also, div id=container was spelled incorrectly in the HTML.  Fixed in the fiddle.


问:
Auto tab and copy/cut/paste clipboard in Neovim
I'm new to nvim and I have some questions when I use nvim

I often work with Javascript and I want nvim can tab automatically like VS Code when I press enter. How can I do that?

How can I cut/copy/paste with clipboard in Neovim, Should I use some plugin?

This is some Pluging I'm using:

```<code>Plug 'preservim/nerdtree'
Plug 'drewtempelmeyer/palenight.vim'
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'pangloss/vim-javascript'
Plug 'w0rp/ale'
Plug 'prettier/vim-prettier', { 'do': 'npm install' }
Plug 'yuezk/vim-js'
Plug 'maxmellon/vim-jsx-pretty'
Plug 'kassio/neoterm'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-fugitive'
Plug 'alvan/vim-closetag'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'raimondi/delimitmate'
Plug 'ekalinin/dockerfile.vim'
Plug 'scrooloose/nerdcommenter'
</code>```

Thanks for any helps.

答:
For auto tab, I suppose you mean auto indentation. You can turn on autoindent and smartindent option.

```<code>set autoindent smartindent
</code>```

To use clipboard for cut and paste, set clipboard option

```<code>set clipboard+=unnamedplus
</code>```

See :h clipboard for more info.

Body:
I'm new to nvim and I have some questions when I use nvim

I often work with Javascript and I want nvim can tab automatically like VS Code when I press enter. How can I do that?

How can I cut/copy/paste with clipboard in Neovim, Should I use some plugin?

This is some Pluging I'm using:

Plug 'preservim/nerdtree'
Plug 'drewtempelmeyer/palenight.vim'
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes'
Plug 'pangloss/vim-javascript'
Plug 'w0rp/ale'
Plug 'prettier/vim-prettier', { 'do': 'npm install' }
Plug 'yuezk/vim-js'
Plug 'maxmellon/vim-jsx-pretty'
Plug 'kassio/neoterm'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-fugitive'
Plug 'alvan/vim-closetag'
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'raimondi/delimitmate'
Plug 'ekalinin/dockerfile.vim'
Plug 'scrooloose/nerdcommenter'

Thanks for any helps.

Body:
For auto tab, I suppose you mean auto indentation. You can turn on autoindent and smartindent option.

set autoindent smartindent

To use clipboard for cut and paste, set clipboard option

set clipboard+=unnamedplus

See :h clipboard for more info.


问:
OCaml find number of times n is present in list
I am a beginner with OCmal. I have a list named l and a number stored in N.
I need to find the number of times N repeats in l.

```<code>let l = [1;2;3;4;5;6;7;1;9;10;11];;
let n = 1;;
</code>```

I want to write a function which tells that number of times n is present in l.

I started like this but I am blocked:

```<code>for i = 0 to (List.length l) do
(* codes here: i want to find that the value of N is present twice in the list *)
done;;
</code>```

答:
Can you use List.fold?

```<code>List.fold_left(fun acc x -> if x = N then acc + 1 else acc)0 l
</code>```

Body:
I am a beginner with OCmal. I have a list named l and a number stored in N.
I need to find the number of times N repeats in l.

let l = [1;2;3;4;5;6;7;1;9;10;11];;
let n = 1;;

I want to write a function which tells that number of times n is present in l.

I started like this but I am blocked:

for i = 0 to (List.length l) do
(* codes here: i want to find that the value of N is present twice in the list *)
done;;

Body:
Can you use List.fold?

List.fold_left(fun acc x -> if x = N then acc + 1 else acc)0 l


问:
How to get end time as float in Android
I had a String time format like 08:25 now how can I convert to float time value

```<code>    String guestclosetime = getCurrentTime();
    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {

        System.out.println("starttime"+ TestRideFragment.getCurrentTime());
        // convert12to24format(guestclosetime);
        Date date1 = timeFormat.parse("00:20");//run
        Date date2 = timeFormat.parse(guestclosetime);
        //Date date3=timeFormat.parse(idle_time);

        long sum = date1.getTime() + date2.getTime();

        String date3 = timeFormat.format(new Date(sum));
        System.out.println("The sum is "+date3);// 08:28
</code>```

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that

答:
Here</p>

```<code>String date3 = timeFormat.format(new Date(sum));
// First you have to replace ":" to "." to get valid string that can be converted to float
String strDate = date3.replace(":", ".");
// Use Float.value() to convert
Float floatValue = Float.valueOf(strDate);
</code>```

Title: How to get end time as float in Android

Body:
I had a String time format like 08:25 now how can I convert to float time value

    String guestclosetime = getCurrentTime();
    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {

        System.out.println("starttime"+ TestRideFragment.getCurrentTime());
        // convert12to24format(guestclosetime);
        Date date1 = timeFormat.parse("00:20");//run
        Date date2 = timeFormat.parse(guestclosetime);
        //Date date3=timeFormat.parse(idle_time);

        long sum = date1.getTime() + date2.getTime();

        String date3 = timeFormat.format(new Date(sum));
        System.out.println("The sum is "+date3);// 08:28

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that

Body:
Here

String date3 = timeFormat.format(new Date(sum));
// First you have to replace ":" to "." to get valid string that can be converted to float
String strDate = date3.replace(":", ".");
// Use Float.value() to convert
Float floatValue = Float.valueOf(strDate);


问:
How to click button in my login form in my Android Studio project
I am a beginner to Android. I tried a lot to find this error but I haven't got a satisfactory answer. In my program I created a login and register page and connected to Firebase. But since I am not able to click the button I am not able to register the user.

When I click the button it does nothing. And even I linked another button to a login page that is also not working.

```<code> private EditText inputEmail, inputPassword;
    private Button btnSignIn, btnSignUp;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginreg);
        auth = FirebaseAuth.getInstance();

        btnSignIn = (Button) findViewById(R.id.lo);//This is sign in button
        btnSignUp = (Button) findViewById(R.id.register_btn);//This is the sign up button
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                //create user
                auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(loginreg.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(loginreg.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Toast.makeText(loginreg.this, "Authentication failed." + task.getException(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    startActivity(new Intent(loginreg.this, activity_second.class));
                                             finish()
                                }
                            }
                        });

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }
</code>```

This is my XML code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary"
    tools:context=".loginreg">

    <EditText
        android:id="@+id/name"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="62dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/username"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="11dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Password"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/password"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="256dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Conform Password"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionDone"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/username"
        tools:ignore="RtlCompat" />

    <Button
        android:id="@+id/register_btn"
        android:layout_width="112dp"
        android:layout_height="63dp"
        android:layout_alignTop="@+id/name"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="236dp"
        android:layout_marginBottom="107dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Register"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <Button
        android:id="@+id/lo"
        android:layout_width="363dp"
        android:layout_height="51dp"
        android:layout_alignTop="@+id/username"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="290dp"
        android:layout_marginBottom="14dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="164dp"
        android:layout_height="476dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="129dp"
        android:layout_marginLeft="129dp"
        android:layout_marginTop="-170dp"
        app:srcCompat="@drawable/film_1" />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="162dp"
        android:layout_height="64dp"
        android:layout_above="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="171dp"
        android:layout_marginBottom="90dp"
        android:text="Register"
        android:textColor="@android:color/white"
        android:textSize="40dp" />
</RelativeLayout>
</code>```

答:
You have disabled your button by setting
android:enabled="false"
Remove this line to enable it.

Body:
I am a beginner to Android. I tried a lot to find this error but I haven't got a satisfactory answer. In my program I created a login and register page and connected to Firebase. But since I am not able to click the button I am not able to register the user.

When I click the button it does nothing. And even I linked another button to a login page that is also not working.

 private EditText inputEmail, inputPassword;
    private Button btnSignIn, btnSignUp;
    private ProgressBar progressBar;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginreg);
        auth = FirebaseAuth.getInstance();

        btnSignIn = (Button) findViewById(R.id.lo);//This is sign in button
        btnSignUp = (Button) findViewById(R.id.register_btn);//This is the sign up button
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (TextUtils.isEmpty(email)) {
                    Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (password.length() < 6) {
                    Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
                    return;
                }

                progressBar.setVisibility(View.VISIBLE);
                //create user
                auth.createUserWithEmailAndPassword(email, password)
                        .addOnCompleteListener(loginreg.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                Toast.makeText(loginreg.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.GONE);
                                // If sign in fails, display a message to the user. If sign in succeeds
                                // the auth state listener will be notified and logic to handle the
                                // signed in user can be handled in the listener.
                                if (!task.isSuccessful()) {
                                    Toast.makeText(loginreg.this, "Authentication failed." + task.getException(),
                                            Toast.LENGTH_SHORT).show();
                                } else {
                                    startActivity(new Intent(loginreg.this, activity_second.class));
                                             finish()
                                }
                            }
                        });

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        progressBar.setVisibility(View.GONE);
    }

This is my XML code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="@color/colorPrimary"
    tools:context=".loginreg">

    <EditText
        android:id="@+id/name"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="62dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/username"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_above="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="11dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Password"
        android:inputType="textEmailAddress"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:ignore="RtlCompat" />

    <EditText
        android:id="@+id/password"
        android:layout_width="357dp"
        android:layout_height="36dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginBottom="256dp"
        android:background="@drawable/usr"
        android:gravity="center_vertical"
        android:hint="Conform Password"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionDone"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"
        android:textAlignment="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/username"
        tools:ignore="RtlCompat" />

    <Button
        android:id="@+id/register_btn"
        android:layout_width="112dp"
        android:layout_height="63dp"
        android:layout_alignTop="@+id/name"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="236dp"
        android:layout_marginBottom="107dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Register"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <Button
        android:id="@+id/lo"
        android:layout_width="363dp"
        android:layout_height="51dp"
        android:layout_alignTop="@+id/username"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_gravity="start"
        android:layout_marginTop="290dp"
        android:layout_marginBottom="14dp"
        android:background="@drawable/round"
        android:enabled="false"
        android:text="Login"
        android:textAllCaps="false"
        android:textColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"
        app:layout_constraintVertical_bias="0.2" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="164dp"
        android:layout_height="476dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginStart="129dp"
        android:layout_marginLeft="129dp"
        android:layout_marginTop="-170dp"
        app:srcCompat="@drawable/film_1" />

    <ProgressBar
        android:id="@+id/progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/textView8"
        android:layout_width="162dp"
        android:layout_height="64dp"
        android:layout_above="@+id/name"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="171dp"
        android:layout_marginBottom="90dp"
        android:text="Register"
        android:textColor="@android:color/white"
        android:textSize="40dp" />
</RelativeLayout>


问:
Accessing a list with only recursion and lambdas
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

```<code>myList=['Hello','World']
</code>```

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

```<code>function(next(myList))
</code>```

Also tried using next(myList) but sometimes the list can have 1000+ elements.

答:
Use lambda with map for apply a function to each element: </p>

```<code>myList=['Hello','World']

list(map(lambda x: x.upper(), myList))
</code>```

Body:
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

myList=['Hello','World']

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

function(next(myList))

Also tried using next(myList) but sometimes the list can have 1000+ elements.

Body:
Use lambda with map for apply a function to each element:

myList=['Hello','World']

list(map(lambda x: x.upper(), myList))


问:
Selecting elements within the vector inaccuracy in Swirl?
I made an anonymous function to select the first element of the vector
Then to select the last element of the vector. When I selected the last element, it said Incorrect. When I selected the second element, it said correct. I am tracking R is 1 based. NOT zero based. So when I select the last element of the vector should it not be x[3]???

The first part: My function, what I used to select the first element per the problem.
| Try using evaluate() along with an anonymous function to return the first element of
| the vector c(8, 4, 0). Your anonymous function should only take one argument which
| should be a variable x.

evaluate(function(x){x[1]}, c(8, 4, 0))
  [1] 8

| You got it!

The second part of the problem: Select the last element of the vector

| Now try using evaluate() along with an anonymous function to return the last element
| of the vector c(8, 4, 0). Your anonymous function should only take one argument which
| should be a variable x.

evaluate(function(x){x[3]}, c(8, 4, 0))
  [1] 0

| That's not exactly what I'm looking for. Try again. Or, type info() for more options.

| You may need to recall how to index vector elements. Remember that your anonymous
| function should only have one argument, and that argument should be named x. Using
| the length() function in your anonymous function may help you.

evaluate(function(x){x[2]}, c(8, 4, 0))
  [1] 4

| You are really on a roll!

What the heck, I had to use x[2] in order to select the last element of the vector. Why is it not x[3]?

I am using Swirl right now in R.

答:
What Swirl expected was to use the length() argument to find the last element in the vector, as in:

```<code>evaluate(function(x){x[length(x)]}, c(8, 4, 0))
</code>```

This exercise is in module 9 of the R programming swirl course. About 2/3 through the lesson, I replicate the correct answer.

Body:
What Swirl expected was to use the length() argument to find the last element in the vector, as in:

evaluate(function(x){x[length(x)]}, c(8, 4, 0))

This exercise is in module 9 of the R programming swirl course. About 2/3 through the lesson, I replicate the correct answer.


问:
firebase.intializeApp is not a function
so im stuck at this error. Im making a telegram bot with the telegram bot api and now im trying to set up a firebae DB to save the score of a group member - so the score is not resetted after restarting the bot. can someone tell me what the problem is? i read a lot of other issues here with similiar problems, but none of these answers fixed my problem.

bot.js

```<code>var TelegramBot = require('node-telegram-bot-api');
var firebase = require('firebase');

var token = 'mytoken';
// Setup polling way
var bot = new TelegramBot(token, {polling: true});

var app = firebase.intializeApp({
  serviceAccount: "C:/Mayer/scorebot/telegramscorebot.json",
  databaseURL: "https://blazing-heat-2008.firebaseio.com/"
});

/* function Person(name, score) {
this.name = name;
this.score = score;
}

var member = new Array();
member[0] = new Person("name1", 0);
member[1] = new Person("name2", 0);
member[2] = new Person("name3", 0);
member[3] = new Person("name4", 0);
member[4] = new Person("name5", 0); */

bot.onText(/\/echo (.+)/, function (msg, match) {
  var fromId = msg.from.id;
  if (match[1] == 'test') {
  var resp = match[1];
  bot.sendMessage(fromId, resp); }
  else {
  bot.sendMessage(fromId, 'error!!');}
});

bot.onText(/\/vote (.+)/, function (msg, match) {
  var fromId = msg.from.id;

for (var i = 0; i <= 4; i++) {
    if(member[i].name == match[1]){
        member[i].score += 1;
        bot.sendMessage(fromId, member[i].name + ' hat einen Score von ' +         member[i].score);}
}
});
</code>```

package.json

```<code>   {
   "name": "scorebot",
   "version": "1.0.0",
   "description": "",
   "main": "bot.js",
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node bot.js"
   },
   "author": "me",
   "license": "ISC",
   "dependencies": {
     "bower": "1.7.9",
    "firebase": "3.0.2"
   }
 }
</code>```

Error message

```<code> bot.js:8 var app = firebase.intializeApp({
                    ^

  TypeError: firebase.intializeApp is not a function
      at Object.<anonymous> (C:\Mayer\scorebot\bot.js:8:20)
      at Module._compile (module.js:413:34)
      at Object.Module._extensions..js (module.js:422:10)
      at Module.load (module.js:357:32)
      at Function.Module._load (module.js:314:12)
      at Function.Module.runMain (module.js:447:10)
      at startup (node.js:141:18)
      at node.js:933:3
</code>```

答:
For those reading this later, I'm using ES Modules from Node v14 and solved it with:

```<code>import firebase from '@firebase/app';
import "@firebase/database";

firebase.default.initializeApp(firebaseConfig);
let db = firebase.default.database();
</code>```

☕

Title: firebase.intializeApp is not a function

Body:
so im stuck at this error. Im making a telegram bot with the telegram bot api and now im trying to set up a firebae DB to save the score of a group member - so the score is not resetted after restarting the bot. can someone tell me what the problem is? i read a lot of other issues here with similiar problems, but none of these answers fixed my problem.

bot.js

var TelegramBot = require('node-telegram-bot-api');
var firebase = require('firebase');

var token = 'mytoken';
// Setup polling way
var bot = new TelegramBot(token, {polling: true});

var app = firebase.intializeApp({
  serviceAccount: "C:/Mayer/scorebot/telegramscorebot.json",
  databaseURL: "https://blazing-heat-2008.firebaseio.com/"
});

/* function Person(name, score) {
this.name = name;
this.score = score;
}

var member = new Array();
member[0] = new Person("name1", 0);
member[1] = new Person("name2", 0);
member[2] = new Person("name3", 0);
member[3] = new Person("name4", 0);
member[4] = new Person("name5", 0); */

bot.onText(/\/echo (.+)/, function (msg, match) {
  var fromId = msg.from.id;
  if (match[1] == 'test') {
  var resp = match[1];
  bot.sendMessage(fromId, resp); }
  else {
  bot.sendMessage(fromId, 'error!!');}
});

bot.onText(/\/vote (.+)/, function (msg, match) {
  var fromId = msg.from.id;

for (var i = 0; i <= 4; i++) {
    if(member[i].name == match[1]){
        member[i].score += 1;
        bot.sendMessage(fromId, member[i].name + ' hat einen Score von ' +         member[i].score);}
}
});

package.json

   {
   "name": "scorebot",
   "version": "1.0.0",
   "description": "",
   "main": "bot.js",
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node bot.js"
   },
   "author": "me",
   "license": "ISC",
   "dependencies": {
     "bower": "1.7.9",
    "firebase": "3.0.2"
   }
 }

Error message

 bot.js:8 var app = firebase.intializeApp({
                    ^

  TypeError: firebase.intializeApp is not a function
      at Object.<anonymous> (C:\Mayer\scorebot\bot.js:8:20)
      at Module._compile (module.js:413:34)
      at Object.Module._extensions..js (module.js:422:10)
      at Module.load (module.js:357:32)
      at Function.Module._load (module.js:314:12)
      at Function.Module.runMain (module.js:447:10)
      at startup (node.js:141:18)
      at node.js:933:3

Body:
For those reading this later, I'm using ES Modules from Node v14 and solved it with:

import firebase from '@firebase/app';
import "@firebase/database";

firebase.default.initializeApp(firebaseConfig);
let db = firebase.default.database();

☕


问:
How to make C++ debug statements appear in the gdb console
I am trying to debug an application in gdb running on Ubuntu 18.04.

In some parts of the code, I can set breakpoints and successfully debug problems.

But in other parts, triggering a breakpoint causes the process to exit.

Is there some way I can get debut statements to appear in the gdb console?

I currently use gdb to attach to the process and then debug from that point.

答:
I have code (std::cout) that sends statements to standard out but they are not showing up in the gdb console.

Nor should you expect them to.

When an application is started, its std::cout messages are going to file descriptor 1 (stdout). This can be the terminal window in which the app was started, or a file if the output was redirected. It could also be a pipe or /dev/null.

GDB does not "steal" that output (if it did, it would be harder to debug a program that is the source of input for another program going through a pipe).

Your first task should be to determine where the output is going. On Linux, this is usually as easy as ls -l /proc/$pid/fds/1 (replace $pid with the actual process id of the process you are debugging).

An additional complication is that the stdout can be fully buffered (if it goes into a file, pipe or socket), and may not be flushed by the time your breakpoint is hit.

P.S. In theory, you can "steal" the output from wherever it's going to your current terminal by running the following GDB commands:

```<code>(gdb) print open("/dev/tty", 2, 0)  # open new fd in the inferior process
                                    # going to current terminal.
                                    # This will print something, e.g. 5

# Now make stdout go to that newly-opened fd
(gdb) call dup2($whatever_last_command_printed, 1)
</code>```

but I wouldn't recommend this, as it can interfere with the program in unexpected ways.

Body:
I have code (std::cout) that sends statements to standard out but they are not showing up in the gdb console.

Nor should you expect them to.

When an application is started, its std::cout messages are going to file descriptor 1 (stdout). This can be the terminal window in which the app was started, or a file if the output was redirected. It could also be a pipe or /dev/null.

GDB does not "steal" that output (if it did, it would be harder to debug a program that is the source of input for another program going through a pipe).

Your first task should be to determine where the output is going. On Linux, this is usually as easy as ls -l /proc/$pid/fds/1 (replace $pid with the actual process id of the process you are debugging).

An additional complication is that the stdout can be fully buffered (if it goes into a file, pipe or socket), and may not be flushed by the time your breakpoint is hit.

P.S. In theory, you can "steal" the output from wherever it's going to your current terminal by running the following GDB commands:

(gdb) print open("/dev/tty", 2, 0)  # open new fd in the inferior process
                                    # going to current terminal.
                                    # This will print something, e.g. 5

# Now make stdout go to that newly-opened fd
(gdb) call dup2($whatever_last_command_printed, 1)

but I wouldn't recommend this, as it can interfere with the program in unexpected ways.


问:
Can someone explain why I have to instantiate subclass?
Why do you have to instantiate subclass() in the mymethod() ? I thought that we only need to make objects in the main() method.(which is done here too) Why do we have to do it twice? Is there a special property of inheritance here? </p>

```<code>class Super_class {
   int num = 20;

   // display method of superclass
   public void display() {
      System.out.println("This is the display method of superclass");
   }
}

public class Sub_class extends Super_class {
   int num = 10;

   // display method of sub class
   public void display() {
      System.out.println("This is the display method of subclass");
   }

   public void my_method() {
      // Instantiating subclass - why do you have to do this?
      Sub_class sub = new Sub_class();

      // Invoking the display() method of sub class
      sub.display();

      // Invoking the display() method of superclass
      super.display();

      // printing the value of variable num of subclass
      System.out.println("value of the variable named num in sub class:"+ sub.num);

      // printing the value of variable num of superclass
      System.out.println("value of the variable named num in super class:"+ super.num);
   }

   public static void main(String args[]) {
      Sub_class obj = new Sub_class();
      obj.my_method();
   }
}
</code>```

答:
You don't have to do these things you've done on the subclass. When you're inside the class you don't need to instantiate it to call its attribute and methods: you can do it directly, so doing like this is enough:</p>

```<code>  public void my_method() {

  // Invoking the display() method of sub class
  display();

  // Invoking the display() method of superclass
  super.display();

  // printing the value of variable num of subclass
  System.out.println("value of the variable named num in sub class:"+ num);

  // printing the value of variable num of superclass
  System.out.println("value of the variable named num in super class:"+ super.num);
  }
</code>```

Body:
Why do you have to instantiate subclass() in the mymethod() ? I thought that we only need to make objects in the main() method.(which is done here too) Why do we have to do it twice? Is there a special property of inheritance here?

class Super_class {
   int num = 20;

   // display method of superclass
   public void display() {
      System.out.println("This is the display method of superclass");
   }
}

public class Sub_class extends Super_class {
   int num = 10;

   // display method of sub class
   public void display() {
      System.out.println("This is the display method of subclass");
   }

   public void my_method() {
      // Instantiating subclass - why do you have to do this?
      Sub_class sub = new Sub_class();

      // Invoking the display() method of sub class
      sub.display();

      // Invoking the display() method of superclass
      super.display();

      // printing the value of variable num of subclass
      System.out.println("value of the variable named num in sub class:"+ sub.num);

      // printing the value of variable num of superclass
      System.out.println("value of the variable named num in super class:"+ super.num);
   }

   public static void main(String args[]) {
      Sub_class obj = new Sub_class();
      obj.my_method();
   }
}

Body:
You don't have to do these things you've done on the subclass. When you're inside the class you don't need to instantiate it to call its attribute and methods: you can do it directly, so doing like this is enough:

  public void my_method() {

  // Invoking the display() method of sub class
  display();

  // Invoking the display() method of superclass
  super.display();

  // printing the value of variable num of subclass
  System.out.println("value of the variable named num in sub class:"+ num);

  // printing the value of variable num of superclass
  System.out.println("value of the variable named num in super class:"+ super.num);
  }


问:
Default path in AWS API gateway?
We have an Rest API config in AWS API gateway where we want to route to handle a default path

```<code>/
 /api
 /$default (default path here)
</code>```

Note we are not looking for the greedy path {proxy+}

```<code>/
 /api
 /{proxy+}
</code>```

the problem with the  greedy path is no request will route to /api ...always the {proxy+}
will take precedence even though the request has /api (tried it out)

Any help from the community in pointing us in the right direction would be of great help.

答:
You can use the $default route to catche requests that don't explicitly match other routes in your API.

When the $default route receives a request, API Gateway sends the full request path to the integration. For example, you can create an API with only a $default route and integrate it on the ANY method with the https://petstore-demo-endpoint.execute-api.com HTTP endpoint.

When you send a request to https://api-id.execute-api.us-east-2.amazonaws.com/store/checkout, API Gateway sends a request to https://petstore-demo-endpoint.execute-api.com/store/checkout.

You can read more about it here.

Title: Default path in AWS API gateway?

Body:
We have an Rest API config in AWS API gateway where we want to route to handle a default path

/
 /api
 /$default (default path here)

Note we are not looking for the greedy path {proxy+}

/
 /api
 /{proxy+}

the problem with the  greedy path is no request will route to /api ...always the {proxy+}
will take precedence even though the request has /api (tried it out)

Any help from the community in pointing us in the right direction would be of great help.


问:
Browser support of multipart responses
I would like to create a HTTP response, using multipart/mixed, but I'm not sure which browsers support it; and if it's as convenient as it sounds, from the client's point of view.
To be honest, I do not need specifically that content type. I just want to transmit more than one file in the same response; maybe there's another content-type more used.</p>

答:
 Multi part it yourself

(A good option)

A multipart response can be made manually!

So one can write a no multipart response! Let's say in chunked mode! There it make sense!

So you are streaming the data!

Send all as blunt text!

Make your own separators! Between each part!

In the browser! Extract and parse the data! Split to get each part separately!

And parse each appart! Depending on what type of data it hold!

So if a part is json! You parse it as so!

Quick illustration! Let say we want to send a csv file! Or some other type of file! Along that we want to send too a json object!

And that by streaming it by chunk

Here a code that illustrate that in express:

```<code>const data = {
    initCapital: fileState.mappingObj.initialCapital
};

res.write(JSON.stringify(data, undefined, 0));
res.write('>>>>'); // parts separator
fileState.readStream.pipe(res); // continue streaming the file (chunk by chunk)
</code>```

And in the client

```<code>export function parseBackTestFetchedData(data: string) {
    const [_data, csvData] = data.split('>>>>');
    return {
        data: JSON.parse(_data),
        backTestStatesData: parseCsv(csvData)
    };
}
</code>```

That way! it doesn't matter who the client is!

ContentLicense: CC BY-SA 2.5

Title: Browser support of multipart responses

Body:
 Multi part it yourself

(A good option)

A multipart response can be made manually!

So one can write a no multipart response! Let's say in chunked mode! There it make sense!

So you are streaming the data!

Send all as blunt text!

Make your own separators! Between each part!

In the browser! Extract and parse the data! Split to get each part separately!

And parse each appart! Depending on what type of data it hold!

So if a part is json! You parse it as so!

Quick illustration! Let say we want to send a csv file! Or some other type of file! Along that we want to send too a json object!

And that by streaming it by chunk

Here a code that illustrate that in express:

const data = {
    initCapital: fileState.mappingObj.initialCapital
};

res.write(JSON.stringify(data, undefined, 0));
res.write('>>>>'); // parts separator
fileState.readStream.pipe(res); // continue streaming the file (chunk by chunk)

And in the client

export function parseBackTestFetchedData(data: string) {
    const [_data, csvData] = data.split('>>>>');
    return {
        data: JSON.parse(_data),
        backTestStatesData: parseCsv(csvData)
    };
}

That way! it doesn't matter who the client is!