问:
Using decorators to implement Observer Pattern in Python3
This question is not in general about the observer pattern. It is focused on the use of decorators in that pattern. The question is based on the answer of a similar question.

```<code>#!/usr/bin/env python3

class Observable:
    """
        The object that need to be observed. Alternative names are 'Subject'.
        In the most cases it is a data object.
    """
    def __init__(self):
        self._observers = []

    def register_observer(self, callback):
        self._observers.append(callback)
        return callback

    def _broadcast_observers(self, *args, **kwargs):
        for callback in self._observers:
            callback(*args, **kwargs)

class TheData(Observable):
    """
        Example of a data class just for demonstration.
    """
    def __init__(self, data):
        Observable.__init__(self)
        self._data = data

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data
        self._broadcast_observers()

class TheGUIElement:
    """
        Example of a gui class (Widget) just for demonstration.
        e. g. it could be a text field in GUI.
    """
    def __init__(self, data):
        self._data = data
        #data.register_observer(self._data_updated)
        self._redraw()

    def _redraw(self):
        print('in _redraw(): ' + data.data)

    @Observable.register_observer
    def _data_updated(self, **kwargs):
        """
            This is the callback that is called by the Observable if the
            data changed.
        """
        print('in _data_updated() - kwargs: {}'.format(kwargs))
        self._redraw()

if __name__ == '__main__':
    data = TheData('DATA')
    gui = TheGUIElement(data)

    data.data = 'SECOND DATA'
</code>```

This code doesn't work because of this error.

```<code>Traceback (most recent call last):
  File "./o.py", line 42, in <module>
    class TheGUIElement:
  File "./o.py", line 55, in TheGUIElement
    @Observable.register_observer
TypeError: register_observer() missing 1 required positional argument: 'callback'
</code>```

It is unclear to me how to use a decorator for to register the observers (e.g. TheGUIElement).

答:
I was recently looking for something similar and here's what I came up with.  It works by intercepting the __setattr__ method -- a useful stunt I plan on keeping in my pocket for later.</p>

```<code>def watchableClass(cls):
    """
    Class Decorator!

    * If the class has a "dirty" member variable, then it will be
    automatically set whenever any class value changes
    * If the class has an "onChanged()" method, it will be called
    automatically whenever any class value changes
    * All this only takes place if the value is different from what it was
    that is, if myObject.x is already 10 and you set myObject.x=10
    nothing happens
    * DOES NOT work with getter/setter functions.  But then, you are
    already in a function, so do what you want!

    EXAMPLE:
        @watchableClass
        class MyClass:
            def __init__(self):
                self.dirty=False
            def onChanged(self):
                print('class has changed')
    """
    if hasattr(cls,'__setattr__'):
        cls.__setattr_unwatched__=cls.__setattr__
        cls.__setattr__=_setObjValueWatchedCascade
    else:
        cls.__setattr__=_setObjValueWatched
    return cls

def _setObjValueWatched(ob,k,v):
    """
    called when an object value is set
    """
    different=not k in ob.__dict__ or ob.__dict__[k]!=v
    if different:
        ob.__dict__[k]=v
        if k not in ('dirty'):
            if hasattr(ob,'dirty'):
                ob.dirty=True
            if hasattr(ob,'onChanged'):
                ob.onChanged()

def _setObjValueWatchedCascade(ob,k,v):
    """
    called when an object value is set
    IF the class had its own __setattr__ member defined!
    """
    different=not k in ob.__dict__ or ob.__dict__[k]!=v
    ob.__setattr_unwatched__(k,v)
    if different:
        if k not in ('dirty'):
            if hasattr(ob,'dirty'):
                ob.dirty=True
            if hasattr(ob,'onChanged'):
                ob.onChanged()
</code>```

Body:
This question is not in general about the observer pattern. It is focused on the use of decorators in that pattern. The question is based on the answer of a similar question.

#!/usr/bin/env python3

class Observable:
    """
        The object that need to be observed. Alternative names are 'Subject'.
        In the most cases it is a data object.
    """
    def __init__(self):
        self._observers = []

    def register_observer(self, callback):
        self._observers.append(callback)
        return callback

    def _broadcast_observers(self, *args, **kwargs):
        for callback in self._observers:
            callback(*args, **kwargs)

class TheData(Observable):
    """
        Example of a data class just for demonstration.
    """
    def __init__(self, data):
        Observable.__init__(self)
        self._data = data

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data
        self._broadcast_observers()

class TheGUIElement:
    """
        Example of a gui class (Widget) just for demonstration.
        e. g. it could be a text field in GUI.
    """
    def __init__(self, data):
        self._data = data
        #data.register_observer(self._data_updated)
        self._redraw()

    def _redraw(self):
        print('in _redraw(): ' + data.data)

    @Observable.register_observer
    def _data_updated(self, **kwargs):
        """
            This is the callback that is called by the Observable if the
            data changed.
        """
        print('in _data_updated() - kwargs: {}'.format(kwargs))
        self._redraw()

if __name__ == '__main__':
    data = TheData('DATA')
    gui = TheGUIElement(data)

    data.data = 'SECOND DATA'

This code doesn't work because of this error.

Traceback (most recent call last):
  File "./o.py", line 42, in <module>
    class TheGUIElement:
  File "./o.py", line 55, in TheGUIElement
    @Observable.register_observer
TypeError: register_observer() missing 1 required positional argument: 'callback'

It is unclear to me how to use a decorator for to register the observers (e.g. TheGUIElement).

Body:
I was recently looking for something similar and here's what I came up with.  It works by intercepting the __setattr__ method -- a useful stunt I plan on keeping in my pocket for later.

def watchableClass(cls):
    """
    Class Decorator!

    * If the class has a "dirty" member variable, then it will be
    automatically set whenever any class value changes
    * If the class has an "onChanged()" method, it will be called
    automatically whenever any class value changes
    * All this only takes place if the value is different from what it was
    that is, if myObject.x is already 10 and you set myObject.x=10
    nothing happens
    * DOES NOT work with getter/setter functions.  But then, you are
    already in a function, so do what you want!

    EXAMPLE:
        @watchableClass
        class MyClass:
            def __init__(self):
                self.dirty=False
            def onChanged(self):
                print('class has changed')
    """
    if hasattr(cls,'__setattr__'):
        cls.__setattr_unwatched__=cls.__setattr__
        cls.__setattr__=_setObjValueWatchedCascade
    else:
        cls.__setattr__=_setObjValueWatched
    return cls

def _setObjValueWatched(ob,k,v):
    """
    called when an object value is set
    """
    different=not k in ob.__dict__ or ob.__dict__[k]!=v
    if different:
        ob.__dict__[k]=v
        if k not in ('dirty'):
            if hasattr(ob,'dirty'):
                ob.dirty=True
            if hasattr(ob,'onChanged'):
                ob.onChanged()

def _setObjValueWatchedCascade(ob,k,v):
    """
    called when an object value is set
    IF the class had its own __setattr__ member defined!
    """
    different=not k in ob.__dict__ or ob.__dict__[k]!=v
    ob.__setattr_unwatched__(k,v)
    if different:
        if k not in ('dirty'):
            if hasattr(ob,'dirty'):
                ob.dirty=True
            if hasattr(ob,'onChanged'):
                ob.onChanged()


来源: stackexchange

问:
Write to file cut off
My goal is to take a file of sentences, apply some basic filtering, and output the remaining sentences to a file and the terminal. I'm using the Hunspell library.

Here's how I get sentences from the file:

```<code>    public static string[] sentencesFromFile_old(string path)
    {
        string s = "";
        using (StreamReader rdr = File.OpenText(path))
        {
            s = rdr.ReadToEnd();
        }
        s = s.Replace(Environment.NewLine, " ");
        s = Regex.Replace(s, @"\s+", " ");
        s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);
        string[] sentences = Regex.Split(s, @"(?<=\. |[!?]+ )");
        return sentences;
    }
</code>```

Here's the code that writes to file:

```<code>        List<string> sentences = new List<string>(Checker.sentencesFromFile_old(path));
        StreamWriter w = new StreamWriter(outFile);
        foreach(string x in xs)
            if(Checker.check(x, speller))
            {
                w.WriteLine("[{0}]", x);
                Console.WriteLine("[{0}]", x);
            }
</code>```

Here's the checker:

```<code>    public static bool check(string s, NHunspell.Hunspell speller)
    {
        char[] punctuation = {',', ':', ';', ' ', '.'};
        bool upper = false;
        // Check the string length.
        if(s.Length <= 50 || s.Length > 250)
            return false;
        // Check if the string contains only allowed punctuation and letters.
        // Also disallow words with multiple consecutive caps.
        for(int i = 0; i < s.Length; ++i)
        {
            if(punctuation.Contains(s[i]))
                continue;
            if(Char.IsUpper(s[i]))
            {
                if(upper)
                    return false;
                upper = true;
            }
            else if(Char.IsLower(s[i]))
            {
                upper = false;
            }
            else return false;
        }
        // Spellcheck each word.
        string[] words = s.Split(' ');
        foreach(string word in words)
            if(!speller.Spell(word))
                return false;
        return true;
    }
</code>```

The sentences are printed on the terminal just fine, but the text file cuts off mid-sentence at 2015 characters. What's up with that?

EDIT: When I remove some parts of the check method, the file is cut off at various lengths somewhere around either 2000 or 4000. Removing the spellcheck eliminates the cutoff entirely.

答:
You need to flush the stream before closing it.

```<code>w.Flush();
w.Close();
</code>```

The using statement (which you should also use) will Close the stream automatically, but it will not flush it.

```<code>using( var w = new StreamWriter(...) )
{
  // Do stuff
  w.Flush();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Write to file cut off

Body:
My goal is to take a file of sentences, apply some basic filtering, and output the remaining sentences to a file and the terminal. I'm using the Hunspell library.

Here's how I get sentences from the file:

    public static string[] sentencesFromFile_old(string path)
    {
        string s = "";
        using (StreamReader rdr = File.OpenText(path))
        {
            s = rdr.ReadToEnd();
        }
        s = s.Replace(Environment.NewLine, " ");
        s = Regex.Replace(s, @"\s+", " ");
        s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);
        string[] sentences = Regex.Split(s, @"(?<=\. |[!?]+ )");
        return sentences;
    }

Here's the code that writes to file:

        List<string> sentences = new List<string>(Checker.sentencesFromFile_old(path));
        StreamWriter w = new StreamWriter(outFile);
        foreach(string x in xs)
            if(Checker.check(x, speller))
            {
                w.WriteLine("[{0}]", x);
                Console.WriteLine("[{0}]", x);
            }

Here's the checker:

    public static bool check(string s, NHunspell.Hunspell speller)
    {
        char[] punctuation = {',', ':', ';', ' ', '.'};
        bool upper = false;
        // Check the string length.
        if(s.Length <= 50 || s.Length > 250)
            return false;
        // Check if the string contains only allowed punctuation and letters.
        // Also disallow words with multiple consecutive caps.
        for(int i = 0; i < s.Length; ++i)
        {
            if(punctuation.Contains(s[i]))
                continue;
            if(Char.IsUpper(s[i]))
            {
                if(upper)
                    return false;
                upper = true;
            }
            else if(Char.IsLower(s[i]))
            {
                upper = false;
            }
            else return false;
        }
        // Spellcheck each word.
        string[] words = s.Split(' ');
        foreach(string word in words)
            if(!speller.Spell(word))
                return false;
        return true;
    }

The sentences are printed on the terminal just fine, but the text file cuts off mid-sentence at 2015 characters. What's up with that?

EDIT: When I remove some parts of the check method, the file is cut off at various lengths somewhere around either 2000 or 4000. Removing the spellcheck eliminates the cutoff entirely.

Body:
You need to flush the stream before closing it.

w.Flush();
w.Close();

The using statement (which you should also use) will Close the stream automatically, but it will not flush it.

using( var w = new StreamWriter(...) )
{
  // Do stuff
  w.Flush();
}


问:
How can I start a timer on keydown and stop on keyup?
I would like to be able to press the spacebar and left arrow key at the same time and have a timer start for ten seconds. If the user stops pressing the key then the timer should stop as well and the result should be cancelled.
I have already tried to use the clearInterval() method.

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(startTimer);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="time"></div></code>```

When I press down on the key, the timer continues to try to restart but when I lift up the timer continues counting.

答:
The clearInterval() method clears a timer set with the setInterval() method.
You will need a reference of the setInterval to clear the interval. I assigned the setInterval to a variable, and later clearing Interval using the variable.

var timeInterval;

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  timeInterval = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(timeInterval);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="time"></div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to be able to press the spacebar and left arrow key at the same time and have a timer start for ten seconds. If the user stops pressing the key then the timer should stop as well and the result should be cancelled.
I have already tried to use the clearInterval() method.

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(startTimer);
  }
});

When I press down on the key, the timer continues to try to restart but when I lift up the timer continues counting.

Body:
The clearInterval() method clears a timer set with the setInterval() method.
You will need a reference of the setInterval to clear the interval. I assigned the setInterval to a variable, and later clearing Interval using the variable.

var timeInterval;

function startTimer(duration, display) {
  var timer = duration;
  var minutes, seconds;
  timeInterval = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (--timer < 0) {
      window.open('1.html', '_self')
    }
  }, 1000);
}

var start = timeFunction = function() {
  var fiveMinutes = 1 * 10;
  var display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

var timesdown = 0;

document.addEventListener('keypress', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    if (timesdown == 0) {
      start();
      timesdown = 1;
    }
  }
});

document.addEventListener('keyup', function(event) {
  if (event.code == 'Space' && 'LeftArrow') {
    timesdown = 0
    clearInterval(timeInterval);
  }
});

<div id="time"></div>


问:
Ajax Request to included JSON - readystate 4, status 0
I am performing an Ajax GET request on a JSON file included in my website. So the JSON file is included in a separate sheet. The readystate of the request is "4" while the status is "0". So the request has been sent, but the responsetext is empty.

I have validated the JSON data.
The javascript file returns data where it should on HTML5 page.
Error handling gives readystate "4" and status "0".

This is the code of the javascript file, JSON data is correct and tested.. HTML5 connection also functions as it should, tested.. The javascript file inserts data on the correct element in HTML..

Can anyone spot the error? Thanks everyone!

```<code>var xhr = new XMLHttpRequest();                 //create Request Object

xhr.onload = function(){                        //when the Request is loaded, parse it in a responsetext

if(xhr.status === 200){

    var responseObject = JSON.parse(xhr.responseText);

    var newContent ='';

    for (var i=0; i<responseObject.events.length; i++){

        newContent += responseObject.events[i].color;

        newContent += responseObject.events[i].value;

    }

    document.getElementById("jsonreturn_option").innerHTML = newContent;
}

else{

    document.getElementById("jsonreturn_option").innerHTML = xhr.readyState + "    " + xhr.status  ;

    //readystate is 4, which means that the request has been sent..
    //request status is 0, which means that the responsetext is empty..
}
};

xhr.open('GET','json/options_form.json',true);
xhr.send(null);                                         //no additional data to be sent
</code>```

The JSON Data File

```<code>{
"events":[

{  "color": "red", "value": "#f00"},
{  "color": "green", "value": "#0f0"},
{  "color": "blue", "value": "#00f"},
{  "color": "cyan", "value": "#0ff"}
]
}
</code>```

答:
you need create javaweb project and then setup a tomcat server

put all files to javaweb project and then startup tomcat server

open browser type like :  http://localhost:8080/javaweb/test.html

because xhr.open('GET','json/options_form.json',true); can not request local file,   must request server file

Body:
I am performing an Ajax GET request on a JSON file included in my website. So the JSON file is included in a separate sheet. The readystate of the request is "4" while the status is "0". So the request has been sent, but the responsetext is empty.

I have validated the JSON data.
The javascript file returns data where it should on HTML5 page.
Error handling gives readystate "4" and status "0".

This is the code of the javascript file, JSON data is correct and tested.. HTML5 connection also functions as it should, tested.. The javascript file inserts data on the correct element in HTML..

Can anyone spot the error? Thanks everyone!

var xhr = new XMLHttpRequest();                 //create Request Object

xhr.onload = function(){                        //when the Request is loaded, parse it in a responsetext

if(xhr.status === 200){

    var responseObject = JSON.parse(xhr.responseText);

    var newContent ='';

    for (var i=0; i<responseObject.events.length; i++){

        newContent += responseObject.events[i].color;

        newContent += responseObject.events[i].value;

    }

    document.getElementById("jsonreturn_option").innerHTML = newContent;
}

else{

    document.getElementById("jsonreturn_option").innerHTML = xhr.readyState + "    " + xhr.status  ;

    //readystate is 4, which means that the request has been sent..
    //request status is 0, which means that the responsetext is empty..
}
};

xhr.open('GET','json/options_form.json',true);
xhr.send(null);                                         //no additional data to be sent

The JSON Data File

{
"events":[

{  "color": "red", "value": "#f00"},
{  "color": "green", "value": "#0f0"},
{  "color": "blue", "value": "#00f"},
{  "color": "cyan", "value": "#0ff"}
]
}


问:
Debian MySQL Server doesn't start anymore
I installed and tried to configure MySQL Server on Debian. After I restarted the Service it crashed and I couldn't start it again.

Her is the following Service Status output:

```<code>● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sat 2019-06-01 19:23:14 CEST; 3min 18s ago
  Process: 11112 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid (code=exited, status=1/FAILURE)
  Process: 11077 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
 Main PID: 2845 (code=exited, status=0/SUCCESS)

Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Unit entered failed state.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Failed with result 'exit-code'.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: Stopped MySQL Community Server.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Start request repeated too quickly.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: Failed to start MySQL Community Server.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Unit entered failed state.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Failed with result 'exit-code'.
</code>```

---EDIT SECTION:---

Output of dpkg -l | grep mysql:

```<code>ii  mysql-client                  5.7.26-1debian9                amd64        MySQL Client meta package depending on latest version
ii  mysql-common                  5.8+1.0.2                      all          MySQL database common files, e.g. /etc/mysql/my.cnf
ii  mysql-community-client        5.7.26-1debian9                amd64        MySQL Client
ii  mysql-community-server        5.7.26-1debian9                amd64        MySQL Server
ii  mysql-server                  5.7.26-1debian9                amd64        MySQL Server meta package depending on latest version
rc  php7.0-mysql                  7.0.33-0+deb9u3                amd64        MySQL module for PHP
</code>```

Output of service mysql start:

```<code>Job for mysql.service failed because the control process exited with error code.
See "systemctl status mysql.service" and "journalctl -xe" for details.
</code>```

答:
please run this as root:

```<code>/usr/sbin/mysqld
</code>```

does it start ? if it's not - what does it say?

Body:
I installed and tried to configure MySQL Server on Debian. After I restarted the Service it crashed and I couldn't start it again.

Her is the following Service Status output:

● mysql.service - MySQL Community Server
   Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Sat 2019-06-01 19:23:14 CEST; 3min 18s ago
  Process: 11112 ExecStart=/usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid (code=exited, status=1/FAILURE)
  Process: 11077 ExecStartPre=/usr/share/mysql/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
 Main PID: 2845 (code=exited, status=0/SUCCESS)

Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Unit entered failed state.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Failed with result 'exit-code'.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Service hold-off time over, scheduling restart.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: Stopped MySQL Community Server.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Start request repeated too quickly.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: Failed to start MySQL Community Server.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Unit entered failed state.
Jun 01 19:23:14 h2836596.stratoserver.net systemd[1]: mysql.service: Failed with result 'exit-code'.

---EDIT SECTION:---

Output of dpkg -l | grep mysql:

ii  mysql-client                  5.7.26-1debian9                amd64        MySQL Client meta package depending on latest version
ii  mysql-common                  5.8+1.0.2                      all          MySQL database common files, e.g. /etc/mysql/my.cnf
ii  mysql-community-client        5.7.26-1debian9                amd64        MySQL Client
ii  mysql-community-server        5.7.26-1debian9                amd64        MySQL Server
ii  mysql-server                  5.7.26-1debian9                amd64        MySQL Server meta package depending on latest version
rc  php7.0-mysql                  7.0.33-0+deb9u3                amd64        MySQL module for PHP

Output of service mysql start:

Job for mysql.service failed because the control process exited with error code.
See "systemctl status mysql.service" and "journalctl -xe" for details.

Body:
please run this as root:

/usr/sbin/mysqld

does it start ? if it's not - what does it say?


问:
What is Java Servlet?
I read many articles to understand Java servlet but I did not succeed.

Can you please give brief introduction of Java servlets (in easy language). What is a servlet? What are the advantages?

I can't understand the difference between server-side programming languages (PHP, ASP) and servlets.

答:
Servlets are Java classes that run certain functions when a website user requests a URL from a server. These functions can complete tasks like saving data to a database, executing logic, and returning information (like JSON data) needed to load a page.

Most Java programs use a main() method that executes code when the program in run. Java servlets contain doGet() and doPost() methods that act just like the main() method. These functions are executed when the user makes a GET or POST request to the URL mapped to that servlet. So the user can load a page for a GET request, or store data from a POST request.

When the user sends a GET or POST request, the server reads the @WebServlet at the top of each servlet class in your directory to decide which servlet class to call. For example, let's say you have a ChatBox class and there's this at the top:

```<code>@WebServlet("/chat")
public class ChatBox extends HttpServlet {
</code>```

When a user requests the /chat URL, your ChatBox class with be executed.

Title: What is Java Servlet?

Body:
Servlets are Java classes that run certain functions when a website user requests a URL from a server. These functions can complete tasks like saving data to a database, executing logic, and returning information (like JSON data) needed to load a page.

Most Java programs use a main() method that executes code when the program in run. Java servlets contain doGet() and doPost() methods that act just like the main() method. These functions are executed when the user makes a GET or POST request to the URL mapped to that servlet. So the user can load a page for a GET request, or store data from a POST request.

When the user sends a GET or POST request, the server reads the @WebServlet at the top of each servlet class in your directory to decide which servlet class to call. For example, let's say you have a ChatBox class and there's this at the top:

@WebServlet("/chat")
public class ChatBox extends HttpServlet {

When a user requests the /chat URL, your ChatBox class with be executed.


问:
What do we mean hibernate session is not thread safe and should close as soon as possible
I am new to hibernate and I did not understand why we say that we should close session as soon as possible. Also how we care if it is a thread safe or not when each thread have a different session, Does the context say that should we share session between thread, which i don't think who would be doing that.</p>

答: Closing the session means releasing JDBC connection.so if we don't close the session ,we are not releasing the JDBC Connection,so as per the sizeof connection pool JDBC Connection will be establised and beyond that all the request will be in waiting state,since none of JDBC connection are free.</p>


问:
How to remove ending zeros in binary bit sequence in R?
I need to remove ending zeros from binary bit sequences.
The length of the bit sequence is fixed, say 52. i.e.,

```<code>0101111.....01100000 (52-bit),
10111010..1010110011 (52-bit),
10111010..1010110100 (52-bit).
</code>```

From converting decimal number to normalized double precision, significand is 52 bit, and hence zeros are populated to the right hand side even if significand is less than 52 bit at first step. I am reversing the process: i.e., I am trying to convert a normalized double precision in memory to decimal number, hence, I have to remove zeros (at the end) that are used to populate 52 bits for significand.

It is not guaranteed that the sequence in hand necessarily have 0s in the end (like the 2nd example above). If there is, all ending zeros must be truncated:

```<code>f(0101111.....01100000) # 0101111.....011; leading 0 must be kept
f(10111010..1010110011) # 10111010..1010110011; no truncation
f(10111010..1010110100) # 10111010..10101101
</code>```

Unfortunately, the number of truncated 0s at the end differs. (5 in the 1st example; 2 in the 3rd example).

It is OK for me if input and output class are string:

```<code>f("0101111.....01100000") # "0101111.....011"; leading 0 must be kept
f("10111010..1010110011") # "10111010..1010110011"; no truncation
f("10111010..1010110100") # "10111010..10101101"
</code>```

Any help is greatly appreciated.

答:
This is a simple regular expression.

```<code>f <- function(x) sub('0+$', '', x)
</code>```

Explanation:

0 - matches the character 0.

0+ - the character zero repeated at least one time, meaning, one or more times.

$ matches the end of the string.

0+$ the character 0 repeated one or more times and nothing else until the end of the string.

Replace the sub-string matched by the pattern with the empty string, ''.

Now test the function.

```<code>f("010111101100000")
#[1] "0101111011"
f("0100000001010101100010000000000000000000000000000000000000000000")
#[1] "010000000101010110001"
f("010000000101010110001000000")
#[1] "010000000101010110001"
f("00010000000101010110001000000")
#[1] "00010000000101010110001"
</code>```

Body:
I need to remove ending zeros from binary bit sequences.
The length of the bit sequence is fixed, say 52. i.e.,

0101111.....01100000 (52-bit),
10111010..1010110011 (52-bit),
10111010..1010110100 (52-bit).

From converting decimal number to normalized double precision, significand is 52 bit, and hence zeros are populated to the right hand side even if significand is less than 52 bit at first step. I am reversing the process: i.e., I am trying to convert a normalized double precision in memory to decimal number, hence, I have to remove zeros (at the end) that are used to populate 52 bits for significand.

It is not guaranteed that the sequence in hand necessarily have 0s in the end (like the 2nd example above). If there is, all ending zeros must be truncated:

f(0101111.....01100000) # 0101111.....011; leading 0 must be kept
f(10111010..1010110011) # 10111010..1010110011; no truncation
f(10111010..1010110100) # 10111010..10101101

Unfortunately, the number of truncated 0s at the end differs. (5 in the 1st example; 2 in the 3rd example).

It is OK for me if input and output class are string:

f("0101111.....01100000") # "0101111.....011"; leading 0 must be kept
f("10111010..1010110011") # "10111010..1010110011"; no truncation
f("10111010..1010110100") # "10111010..10101101"

Any help is greatly appreciated.

Body:
This is a simple regular expression.

f <- function(x) sub('0+$', '', x)

Explanation:

0 - matches the character 0.

0+ - the character zero repeated at least one time, meaning, one or more times.

$ matches the end of the string.

0+$ the character 0 repeated one or more times and nothing else until the end of the string.

Replace the sub-string matched by the pattern with the empty string, ''.

Now test the function.

f("010111101100000")
#[1] "0101111011"
f("0100000001010101100010000000000000000000000000000000000000000000")
#[1] "010000000101010110001"
f("010000000101010110001000000")
#[1] "010000000101010110001"
f("00010000000101010110001000000")
#[1] "00010000000101010110001"


问:
How can I check if a value of a column in a dataframe in r corresponds to a single occurence of another columns for each row of the dataframe?
I have a dataframe like this with the names of marine fish species in one of the column and their respective BIN in another column (which is a sort of ID for each species). Sometimes a single BIN number can correspond to more than one species and I want to check which species correspond to a single BIN and which ones have more than one BIN for each single species in each row. I'm sorry if I'm being confusing but I'm very lost in how I can do this.
Thank you in advance for any suggestion</p>

```<code> 1.  species          BIN
 2. Tilapia guineensis BOLD:AAL5979
 3. Tilapia zillii BOLD:AAB9042
 4. Fundulus rubrifrons BOLD:AAI7245
 5. Eutrigla gurnardus BOLD:AAC0262
 6.  Sprattus sprattus BOLD:AAE9187
 7.  Gadus morhua BOLD:ACF1143
 8. Clupea harengus BOLD:AAB7944
 (...)
</code>```

答:
With dplyr, you can do (I used sample data with a species having two BINs):

```<code>df %>%
 group_by(species) %>%
 summarise(occurrence = n_distinct(BIN),
           BIN = paste(unique(BIN), collapse = ","))

  species             occurrence BIN
  <chr>                    <int> <chr>
1 Clupea_harengus              1 BOLD:AAB7944
2 Eutrigla_gurnardus           2 BOLD:AAC0262,BOLD:AAE9187
3 Fundulus_rubrifrons          1 BOLD:AAI7245
4 Gadus_morhua                 1 BOLD:ACF1143
5 Sprattus_sprattus            1 BOLD:AAE9187
6 Tilapia_guineensis           1 BOLD:AAL5979
7 Tilapia_zillii               1 BOLD:AAB9042
</code>```

It counts the number of BINs per "species" and combines together the name of unique BINs belonging to a species.

Sample data:

```<code>df <- read.table(text = "species          BIN
 2 Tilapia_guineensis BOLD:AAL5979
 3 Tilapia_zillii BOLD:AAB9042
 4 Fundulus_rubrifrons BOLD:AAI7245
 5 Eutrigla_gurnardus BOLD:AAC0262
 6 Eutrigla_gurnardus BOLD:AAE9187
 7  Sprattus_sprattus BOLD:AAE9187
 8  Gadus_morhua BOLD:ACF1143
 9 Clupea_harengus BOLD:AAB7944", header = TRUE,
                 stringsAsFactors = FALSE)
</code>```

Body:
I have a dataframe like this with the names of marine fish species in one of the column and their respective BIN in another column (which is a sort of ID for each species). Sometimes a single BIN number can correspond to more than one species and I want to check which species correspond to a single BIN and which ones have more than one BIN for each single species in each row. I'm sorry if I'm being confusing but I'm very lost in how I can do this.
Thank you in advance for any suggestion

 1.  species          BIN
 2. Tilapia guineensis BOLD:AAL5979
 3. Tilapia zillii BOLD:AAB9042
 4. Fundulus rubrifrons BOLD:AAI7245
 5. Eutrigla gurnardus BOLD:AAC0262
 6.  Sprattus sprattus BOLD:AAE9187
 7.  Gadus morhua BOLD:ACF1143
 8. Clupea harengus BOLD:AAB7944
 (...)

Body:
With dplyr, you can do (I used sample data with a species having two BINs):

df %>%
 group_by(species) %>%
 summarise(occurrence = n_distinct(BIN),
           BIN = paste(unique(BIN), collapse = ","))

  species             occurrence BIN
  <chr>                    <int> <chr>
1 Clupea_harengus              1 BOLD:AAB7944
2 Eutrigla_gurnardus           2 BOLD:AAC0262,BOLD:AAE9187
3 Fundulus_rubrifrons          1 BOLD:AAI7245
4 Gadus_morhua                 1 BOLD:ACF1143
5 Sprattus_sprattus            1 BOLD:AAE9187
6 Tilapia_guineensis           1 BOLD:AAL5979
7 Tilapia_zillii               1 BOLD:AAB9042

It counts the number of BINs per "species" and combines together the name of unique BINs belonging to a species.

Sample data:

df <- read.table(text = "species          BIN
 2 Tilapia_guineensis BOLD:AAL5979
 3 Tilapia_zillii BOLD:AAB9042
 4 Fundulus_rubrifrons BOLD:AAI7245
 5 Eutrigla_gurnardus BOLD:AAC0262
 6 Eutrigla_gurnardus BOLD:AAE9187
 7  Sprattus_sprattus BOLD:AAE9187
 8  Gadus_morhua BOLD:ACF1143
 9 Clupea_harengus BOLD:AAB7944", header = TRUE,
                 stringsAsFactors = FALSE)


问:
Selecting thousands separator character with RegEx
I need to change the decimal separator in a given string that has numbers in it.

What RegEx code can ONLY select the thousands separator character in the string?

It need to only select, when there is number around it. For example only when 123,456 I need to select and replace ,

I'm converting English numbers into Persian (e.g: Hello 123 becomes Hello ۱۲۳). Now I need to replace the decimal separator with Persian version too. But I don't know how I can select it with regex. e.g. Hello 121,534 most become Hello ۱۲۱/۵۳۴

The character that needs to be replaced is , with /

答:
According to your question, the main problem you face is to convert the English number into the Persian.

In PHP there is a library available that can format and parse numbers according to the locale, you can find it in the class NumberFormatter which makes use of the Unicode Common Locale Data Repository (CLDR) to handle - in the end - all languages known to the world.

So converting a number 123,456 from en_UK (or en_US) to fa_IR is shown in this little example:

```<code>$string = '123,456';
$float = (new NumberFormatter('en_UK', NumberFormatter::DECIMAL))->parse($string);
var_dump(
    (new NumberFormatter('fa_IR', NumberFormatter::DECIMAL))->format($float)
);
</code>```

Output:

```<code>string(14) "۱۲۳٬۴۵۶"
</code>```

(play with it on 3v4l.org)

Now this shows (somehow) how to convert the number. I'm not so firm with Persian, so please excuse if I used the wrong locale here. There might be options as well to tell which character to use for grouping, but for the moment for the example, it's just to show that conversion of the numbers is taken care of by existing libraries. You don't need to re-invent this, which is even a sort of miss-wording, this isn't anything a single person could do, or at least it would be sort of insane to do this alone.

So after clarifying on how to convert these numbers, question remains on how to do that on the whole text. Well, why not locate all the potential places looking for and then try to parse the match and if successful (and only if successful) convert it to the different locale.

Luckily the NumberFormatter::parse() method returns false if parsing did fail (there is even more error reporting in case you're interested in more details) so this is workable.

For regular expression matching it only needs a pattern which matches a number (largest match wins) and the replacement can be done by callback. In the following example the translation is done verbose so the actual parsing and formatting is more visible:

```<code># some text
$buffer = <<<TEXT
it need to only select , when there is number around it. for example only
when 123,456 i need to select and replace "," I'm converting English
numbers into Persian (e.g: "Hello 123" becomes "Hello ۱۲۳"). now I need to
replace the Decimal separator with Persian version too. but I don't know how
I can select it with regex. e.g: "Hello 121,534" most become
"Hello ۱۲۱/۵۳۴" The character that needs to be replaced is , with /
TEXT;

# prepare formatters
$inFormat = new NumberFormatter('en_UK', NumberFormatter::DECIMAL);
$outFormat = new NumberFormatter('fa_IR', NumberFormatter::DECIMAL);

$bufferWithFarsiNumbers = preg_replace_callback(
    '(\b[1-9]\d{0,2}(?:[ ,.]\d{3})*\b)u',
    function (array $matches) use ($inFormat, $outFormat) {
        [$number] = $matches;

        $result = $inFormat->parse($number);
        if (false === $result) {
            return $number;
        }

        return sprintf("< %s (%.4f) = %s >", $number, $result, $outFormat->format($result));
    },
    $buffer
);

echo $bufferWithFarsiNumbers;
</code>```

Output:

```<code>it need to only select , when there is number around it. for example only
when < 123,456 (123456.0000) = ۱۲۳٬۴۵۶ > i need to select and replace "," I'm converting English
numbers into Persian (e.g: "Hello < 123 (123.0000) = ۱۲۳ >" becomes "Hello ۱۲۳"). now I need to
replace the Decimal separator with Persian version too. but I don't know how
I can select it with regex. e.g: "Hello < 121,534 (121534.0000) = ۱۲۱٬۵۳۴ >" most become
"Hello ۱۲۱/۵۳۴" The character that needs to be replaced is , with /
</code>```

Here the magic is just two bring the string parts into action with the number conversion by making use of preg_replace_callback with a regular expression pattern which should match the needs in your question but is relatively easy to refine as you define the whole number part and false positives are filtered thanks to the NumberFormatter class:

```<code>                    pattern for Unicode UTF-8 strings
                                 |
(\b[1-9]\d{0,2}(?:[ ,.]\d{3})*\b)u
  |                 |          |
  |        grouping character  |
  |                            |
word boundary -----------------+
</code>```

(play with it on regex101.com)

Edit:

To only match the same grouping character over multiple thousand blocks, a named reference can be created and referenced back to it for the repetition:

```<code>(\b[1-9]\d{0,2}(?:(?<grouping_char>[ ,.])\d{3}(?:(?&grouping_char)\d{3})*)?\b)u
</code>```

(now this get's less easy to read, get it deciphered and play with it on regex101.com)

To finalize the answer, only the return clause needs to be condensed to return $outFormat->format($result); and the $outFormat NumberFormatter might need some more configuration but as it is available in the closure, this can be done when it is created.

(play with it on 3v4l.org)

I hope this is helpful and opens up a broader picture to not look for solutions only because hitting a wall (and only there). Regex alone most often is not the answer. I'm pretty sure there are regex-freaks which can give you a one-liner which is pretty stable, but the context of using it will not be very stable. However not saying there is only one answer. Instead bringing together different levels of doings (divide and conquer) allows to rely on a stable number conversion even if yet still unsure on how to regex-pattern an English number.

Body:
According to your question, the main problem you face is to convert the English number into the Persian.

In PHP there is a library available that can format and parse numbers according to the locale, you can find it in the class NumberFormatter which makes use of the Unicode Common Locale Data Repository (CLDR) to handle - in the end - all languages known to the world.

So converting a number 123,456 from en_UK (or en_US) to fa_IR is shown in this little example:

$string = '123,456';
$float = (new NumberFormatter('en_UK', NumberFormatter::DECIMAL))->parse($string);
var_dump(
    (new NumberFormatter('fa_IR', NumberFormatter::DECIMAL))->format($float)
);

Output:

string(14) "۱۲۳٬۴۵۶"

(play with it on 3v4l.org)

Now this shows (somehow) how to convert the number. I'm not so firm with Persian, so please excuse if I used the wrong locale here. There might be options as well to tell which character to use for grouping, but for the moment for the example, it's just to show that conversion of the numbers is taken care of by existing libraries. You don't need to re-invent this, which is even a sort of miss-wording, this isn't anything a single person could do, or at least it would be sort of insane to do this alone.

So after clarifying on how to convert these numbers, question remains on how to do that on the whole text. Well, why not locate all the potential places looking for and then try to parse the match and if successful (and only if successful) convert it to the different locale.

Luckily the NumberFormatter::parse() method returns false if parsing did fail (there is even more error reporting in case you're interested in more details) so this is workable.

For regular expression matching it only needs a pattern which matches a number (largest match wins) and the replacement can be done by callback. In the following example the translation is done verbose so the actual parsing and formatting is more visible:

# some text
$buffer = <<<TEXT
it need to only select , when there is number around it. for example only
when 123,456 i need to select and replace "," I'm converting English
numbers into Persian (e.g: "Hello 123" becomes "Hello ۱۲۳"). now I need to
replace the Decimal separator with Persian version too. but I don't know how
I can select it with regex. e.g: "Hello 121,534" most become
"Hello ۱۲۱/۵۳۴" The character that needs to be replaced is , with /
TEXT;

# prepare formatters
$inFormat = new NumberFormatter('en_UK', NumberFormatter::DECIMAL);
$outFormat = new NumberFormatter('fa_IR', NumberFormatter::DECIMAL);

$bufferWithFarsiNumbers = preg_replace_callback(
    '(\b[1-9]\d{0,2}(?:[ ,.]\d{3})*\b)u',
    function (array $matches) use ($inFormat, $outFormat) {
        [$number] = $matches;

        $result = $inFormat->parse($number);
        if (false === $result) {
            return $number;
        }

        return sprintf("< %s (%.4f) = %s >", $number, $result, $outFormat->format($result));
    },
    $buffer
);

echo $bufferWithFarsiNumbers;

Output:

it need to only select , when there is number around it. for example only
when < 123,456 (123456.0000) = ۱۲۳٬۴۵۶ > i need to select and replace "," I'm converting English
numbers into Persian (e.g: "Hello < 123 (123.0000) = ۱۲۳ >" becomes "Hello ۱۲۳"). now I need to
replace the Decimal separator with Persian version too. but I don't know how
I can select it with regex. e.g: "Hello < 121,534 (121534.0000) = ۱۲۱٬۵۳۴ >" most become
"Hello ۱۲۱/۵۳۴" The character that needs to be replaced is , with /

Here the magic is just two bring the string parts into action with the number conversion by making use of preg_replace_callback with a regular expression pattern which should match the needs in your question but is relatively easy to refine as you define the whole number part and false positives are filtered thanks to the NumberFormatter class:

                    pattern for Unicode UTF-8 strings
                                 |
(\b[1-9]\d{0,2}(?:[ ,.]\d{3})*\b)u
  |                 |          |
  |        grouping character  |
  |                            |
word boundary -----------------+

(play with it on regex101.com)

Edit:

To only match the same grouping character over multiple thousand blocks, a named reference can be created and referenced back to it for the repetition:

(\b[1-9]\d{0,2}(?:(?<grouping_char>[ ,.])\d{3}(?:(?&grouping_char)\d{3})*)?\b)u

(now this get's less easy to read, get it deciphered and play with it on regex101.com)

To finalize the answer, only the return clause needs to be condensed to return $outFormat->format($result); and the $outFormat NumberFormatter might need some more configuration but as it is available in the closure, this can be done when it is created.

(play with it on 3v4l.org)

I hope this is helpful and opens up a broader picture to not look for solutions only because hitting a wall (and only there). Regex alone most often is not the answer. I'm pretty sure there are regex-freaks which can give you a one-liner which is pretty stable, but the context of using it will not be very stable. However not saying there is only one answer. Instead bringing together different levels of doings (divide and conquer) allows to rely on a stable number conversion even if yet still unsure on how to regex-pattern an English number.


问:
Referencing and indexing other dataframe in dplyr mutate workflow
I'm trying to create a new column in a dataframe that computes something based on "matched" variables in another dataframe.

I know I can do this with apply, but it is the only workflow I haven't figured out how to perform in dplyr, and I'd like to find a tidy solution.

I've created a data frame df1 with groups (random animals), years, and some statistic. I'd like to mutate a new column in this dataframe that calculates something using that statistic and the output dataframe from a set of linear models (df2).

```<code># generate reprex df1
year <- seq(1990, 2010, 1)
group <- c("giraffe","rhino","flamingo","shark","turtle")
df1 <- expand.grid(year, group) %>%
  rename(year = Var1,
         group = Var2) %>%
  mutate(stat = runif(length(year),37,44))

# generate reprex df2
term <- c("(Intercept)","y")
df2 <- expand.grid(year, term) %>%
  rename(year = Var1,
         term = Var2) %>%
  mutate(estimate = ifelse(term=="y", -runif(n(), 1.1, 1.3), runif(n(), 50, 60)))
</code>```

I want to feed the stat column from df1 into the equation for each year provided by df2 using the equation for a line (y=ax+b). Note that both the intercept and the slope vary each year in df2. Conceptually, this would look like
mutate(result = df1$stat*df2$estimate[estimate=="y" and year==year of df1] + df2$estimate[estimate=="(Intercept)" and year==year of df1].

For example, for giraffes in 1993, this would be 39.58*(-1.23)+50.14=1.45 (left off some decimal places for readability).

How can I actually do this with dplyr?

答:
Easiest to approach in dplyr if you can first get all the terms you need for your calculation into the row where you need it. tidyr::spread will make y and (Intercept) available to the row where it's needed, and left_join lets you append the matching data from df1, in this case based on matching years (the column both tables share).

```<code>library(tidyverse)
df2 %>%
  spread(term, estimate) %>%
  left_join(df1) %>%
  mutate(result = stat * y + `(Intercept)`)
</code>```

Body:
I'm trying to create a new column in a dataframe that computes something based on "matched" variables in another dataframe.

I know I can do this with apply, but it is the only workflow I haven't figured out how to perform in dplyr, and I'd like to find a tidy solution.

I've created a data frame df1 with groups (random animals), years, and some statistic. I'd like to mutate a new column in this dataframe that calculates something using that statistic and the output dataframe from a set of linear models (df2).

# generate reprex df1
year <- seq(1990, 2010, 1)
group <- c("giraffe","rhino","flamingo","shark","turtle")
df1 <- expand.grid(year, group) %>%
  rename(year = Var1,
         group = Var2) %>%
  mutate(stat = runif(length(year),37,44))

# generate reprex df2
term <- c("(Intercept)","y")
df2 <- expand.grid(year, term) %>%
  rename(year = Var1,
         term = Var2) %>%
  mutate(estimate = ifelse(term=="y", -runif(n(), 1.1, 1.3), runif(n(), 50, 60)))

I want to feed the stat column from df1 into the equation for each year provided by df2 using the equation for a line (y=ax+b). Note that both the intercept and the slope vary each year in df2. Conceptually, this would look like
mutate(result = df1$stat*df2$estimate[estimate=="y" and year==year of df1] + df2$estimate[estimate=="(Intercept)" and year==year of df1].

For example, for giraffes in 1993, this would be 39.58*(-1.23)+50.14=1.45 (left off some decimal places for readability).

How can I actually do this with dplyr?

Body:
Easiest to approach in dplyr if you can first get all the terms you need for your calculation into the row where you need it. tidyr::spread will make y and (Intercept) available to the row where it's needed, and left_join lets you append the matching data from df1, in this case based on matching years (the column both tables share).

library(tidyverse)
df2 %>%
  spread(term, estimate) %>%
  left_join(df1) %>%
  mutate(result = stat * y + `(Intercept)`)


问:
Scroll Views above RecyclerView
I have some view above my RecyclerView and i want to make them all scrollable as follows:

And when i scroll, the toggle button should scroll as shown here:

My layout is as follows:

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <ToggleButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOn="Active"
                android:textOff="Completed"/>

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"
                tools:layout="@layout/fragment_to_do"/>

    </LinearLayout>

    <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@id/BottomAppBar_fromHomeActivity_Main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            app:fabAlignmentMode="center"
            app:navigationIcon="@drawable/ic_menu_dark"
            app:menu="@menu/menu_bottomappbar_main"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_add_dark"
            android:backgroundTint="@color/colorAccent"
            app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

But when i am trying to scroll, the toggle button is staying fixed on the screen. Only the recyclerview is scrolling behind the toggle button.

Can anyone help ?

答:
First, determine whether your recylerview is scrolling up or down. and the Hide/show and animate the toggle layout according to that scrolling.

for example

Animation up for scrolling up and

Animation down for scrolling down.

Here is my code for determining recylerviews up and down

```<code>mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dy > 0 && toggelLayout.getVisibility() == View.VISIBLE) {
            //Hide
        } else if (dy < 0 && toggelLayout.getVisibility() !=View.VISIBLE) {
           //Show
        }
    }
});
</code>```

Title: Scroll Views above RecyclerView

Body:
I have some view above my RecyclerView and i want to make them all scrollable as follows:

And when i scroll, the toggle button should scroll as shown here:

My layout is as follows:

<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <ToggleButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textOn="Active"
                android:textOff="Completed"/>

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"
                tools:layout="@layout/fragment_to_do"/>

    </LinearLayout>

    <com.google.android.material.bottomappbar.BottomAppBar
            android:id="@id/BottomAppBar_fromHomeActivity_Main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            app:fabAlignmentMode="center"
            app:navigationIcon="@drawable/ic_menu_dark"
            app:menu="@menu/menu_bottomappbar_main"/>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_add_dark"
            android:backgroundTint="@color/colorAccent"
            app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

But when i am trying to scroll, the toggle button is staying fixed on the screen. Only the recyclerview is scrolling behind the toggle button.

Can anyone help ?

Body:
First, determine whether your recylerview is scrolling up or down. and the Hide/show and animate the toggle layout according to that scrolling.

for example

Animation up for scrolling up and

Animation down for scrolling down.

Here is my code for determining recylerviews up and down

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (dy > 0 && toggelLayout.getVisibility() == View.VISIBLE) {
            //Hide
        } else if (dy < 0 && toggelLayout.getVisibility() !=View.VISIBLE) {
           //Show
        }
    }
});


问:
Can I convert a null pointer of int to a long type by reinterpret_cast
int *pt = 0;

long i = reinterpret_cast<long>(pt);

Is i guaranteed to be 0? Is this well defined or implementation-defined?
I checked the c++ standard, but it only states that

A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.

In this case, pt doesn't point to any data object. Does the rule apply to this case?

答:
No, i is not necessarily any value. The result is implementation-defined.†

The representation of pointers, in C++, is implementation-defined, including the representation of a null pointer. When you assign an integer value of zero to a pointer, you set that pointer to the implementation-defined null pointer value, which is not necessarily all-bits-zero. The result of casting that value to an integer is, by transitivity, implementation-defined.

Even more troublesome, though, is that the mapping done by reinterpret_cast  is implementation-defined anyway. So even if the null pointer value was all-bits-zero, an implementation is free to make the result whatever it wants. You're only guaranteed that you'll get the original value when you cast back.

That all said, the next sentence after your quote includes the note:

[ Note: It is intended to be unsurprising to those who know the addressing structure
  of the underlying machine. —end note ]

So even though specific mappings are not required, pragmatically you can take an educated guess.

† Assuming long is large enough. In C++0x use uintptr_t, optionally defined in <cstddef>.


问:
Jetty invalidating the session after few requests while running an integration test
Hi I am trying to run integration test cases for my application on jetty 9.4.10, I am making requests to the server using an apache Http Client, passing sessionId as an header to the request. In some of the test cases i observe that after 10-11 successful requests, server is setting the response status as 303 to all the consecutive requests following them, as a result requests to the server are not successful and tests fail. But after 11 requests if i get a new sessionId and try executing the requests in tests, they all pass. I don't understand this behavior of jetty, Am i missing something in the configuration? Is there something to configure for maximum number of requests per minute in a current session? I have been troubleshooting this issue since a week, But I didn't get any lead.

Help is appreciated.

答:
There is no component in Jetty that will produce a 303 status code response.

Check your 3rd party libraries to see where that is coming from.


问:
Mercurial - which head is active in your working directory?
hg head lists multiple heads.  How do you know which head is active in your working directory?

答: From the command line, you can use: hg log -r . to see the revision of your working copy.


问:
Validating user's input
I'm trying to check user's input (3 numbers currently) for having numbers only. And if it's not numbers but anything else, to make the user enter again until all three input would be numbers.

It's ok in terms of finding wrong input, but instead of making user input again, the program just stops.

It does work without a list, so i think it has something to do  with the sequence of loops

```<code>its=[]
entering=True
while entering:
  for x in range(3):
    try:
      x=int(input("enter the number:"))
      print("your input is:"+str(x))
      its.append(x)
      entering=False
    except (SyntaxError, ValueError):
      print("not gonna work")
      continue
</code>```

答:
In the while loop, you can check the number of items in the list until it reaches the amount you want (In this case, 3).</p>

```<code>its = []
while len(its) < 3:
    try:
        x = int(input("enter the number: "))
        print("your input is: " + str(x))
        its.append(x)
    except (SyntaxError, ValueError):
        print("not gonna work, try again")
</code>```

Title: Validating user's input

Body:
I'm trying to check user's input (3 numbers currently) for having numbers only. And if it's not numbers but anything else, to make the user enter again until all three input would be numbers.

It's ok in terms of finding wrong input, but instead of making user input again, the program just stops.

It does work without a list, so i think it has something to do  with the sequence of loops

its=[]
entering=True
while entering:
  for x in range(3):
    try:
      x=int(input("enter the number:"))
      print("your input is:"+str(x))
      its.append(x)
      entering=False
    except (SyntaxError, ValueError):
      print("not gonna work")
      continue

Body:
In the while loop, you can check the number of items in the list until it reaches the amount you want (In this case, 3).

its = []
while len(its) < 3:
    try:
        x = int(input("enter the number: "))
        print("your input is: " + str(x))
        its.append(x)
    except (SyntaxError, ValueError):
        print("not gonna work, try again")


答:
Another option in tidyverse would be to get the distinct rows, grouped by 'species', summarise the 'occurrence' as number of rows (n()) and use str_c (from stringr - part of the tidyverse packages - which would also give a different behavior when there is NA element) to collapse the elements into a single string

```<code>library(dplyr)
library(stringr)
df %>%
    distinct() %>%
    group_by(species) %>%
    summarise(occurrence = n(),
       BIN = str_c(unique(BIN), collapse = ","))
# A tibble: 7 x 3
#  species             occurrence BIN
#  <chr>                    <int> <chr>
#1 Clupea_harengus              1 BOLD:AAB7944
#2 Eutrigla_gurnardus           2 BOLD:AAC0262,BOLD:AAE9187
#3 Fundulus_rubrifrons          1 BOLD:AAI7245
#4 Gadus_morhua                 1 BOLD:ACF1143
#5 Sprattus_sprattus            1 BOLD:AAE9187
#6 Tilapia_guineensis           1 BOLD:AAL5979
#7 Tilapia_zillii               1 BOLD:AAB9042
</code>```

If there are NA elements, the behavior is slightly different (unless we take care of the NAs first)

```<code>paste(c(NA, 'a', 'b'), collapse=",")
#[1] "NA,a,b"
str_c(c(NA, 'a', 'b'), collapse=",")
#[1] NA
</code>```

data

```<code>df <- structure(list(species = c("Tilapia_guineensis", "Tilapia_zillii",
"Fundulus_rubrifrons", "Eutrigla_gurnardus", "Eutrigla_gurnardus",
"Sprattus_sprattus", "Gadus_morhua", "Clupea_harengus"), BIN = c("BOLD:AAL5979",
"BOLD:AAB9042", "BOLD:AAI7245", "BOLD:AAC0262", "BOLD:AAE9187",
"BOLD:AAE9187", "BOLD:ACF1143", "BOLD:AAB7944")),
class = "data.frame", row.names = c("2",
"3", "4", "5", "6", "7", "8", "9"))
</code>```

Title: How can I check if a value of a column in a dataframe in r corresponds to a single occurence of another columns for each row of the dataframe?

Body:
Another option in tidyverse would be to get the distinct rows, grouped by 'species', summarise the 'occurrence' as number of rows (n()) and use str_c (from stringr - part of the tidyverse packages - which would also give a different behavior when there is NA element) to collapse the elements into a single string

library(dplyr)
library(stringr)
df %>%
    distinct() %>%
    group_by(species) %>%
    summarise(occurrence = n(),
       BIN = str_c(unique(BIN), collapse = ","))
# A tibble: 7 x 3
#  species             occurrence BIN
#  <chr>                    <int> <chr>
#1 Clupea_harengus              1 BOLD:AAB7944
#2 Eutrigla_gurnardus           2 BOLD:AAC0262,BOLD:AAE9187
#3 Fundulus_rubrifrons          1 BOLD:AAI7245
#4 Gadus_morhua                 1 BOLD:ACF1143
#5 Sprattus_sprattus            1 BOLD:AAE9187
#6 Tilapia_guineensis           1 BOLD:AAL5979
#7 Tilapia_zillii               1 BOLD:AAB9042

If there are NA elements, the behavior is slightly different (unless we take care of the NAs first)

paste(c(NA, 'a', 'b'), collapse=",")
#[1] "NA,a,b"
str_c(c(NA, 'a', 'b'), collapse=",")
#[1] NA

data

df <- structure(list(species = c("Tilapia_guineensis", "Tilapia_zillii",
"Fundulus_rubrifrons", "Eutrigla_gurnardus", "Eutrigla_gurnardus",
"Sprattus_sprattus", "Gadus_morhua", "Clupea_harengus"), BIN = c("BOLD:AAL5979",
"BOLD:AAB9042", "BOLD:AAI7245", "BOLD:AAC0262", "BOLD:AAE9187",
"BOLD:AAE9187", "BOLD:ACF1143", "BOLD:AAB7944")),
class = "data.frame", row.names = c("2",
"3", "4", "5", "6", "7", "8", "9"))


问:
Anyway to avoid floating point operation for Max Points on Line problem
I'm trying to solve "Max Points on Line" problem on Leet code. I inevitably need to do floating point operation to calculation Y-Intercept and slope of each line. Due to my past bad experience, I'm trying to avoid floating point operations as much as I can. Do you have any suggestion how I can do that here?

I am using LeetCode framework for development and pretty much just have access to standard C++ library.
Tried using double or long double but one of the test cases already pushes the numbers to the limits of the accuracy of these data types.

```<code>//P1[0] is X coordinate for point P1 and P1[1] is Y coordinate

long double slopeCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ( (long double)p2[1] - (long double)p1[1] ) / ((long double)p2[0] - (long double)p1[0]);
}

long double yIntersectionCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ((long double)p1[1]*(long double)p2[0] - (long double)p2[1]*(long double)p1[0]) / (long double)(p2[0] - p1[0]);
}
</code>```

If the two points are (0, 0) and (94911150, 94911151) the slope is calculated as 1 which is inaccurate. I'm trying to avoid the floating point division if possible.

NOTE: Max Points on a Line problem is to be given points in 2D space (in this case integer coordinates) and find the maximum number of points that are on one line. E.g if the points are (0,0), (2,2), (4,3), (1,1) the answer is 3 which are points (0,0), (1,1), and (2,2)

答:
Given points a,b,c, look at the slopes b,c make to a common point, a:

```<code>ba.x = b.x - a.x
ba.y = b.y - a.y

ba.s = ba.y / ba.x

ca.x = c.x - a.x
ca.y = c.y - a.y

ca.s = ca.y / ca.x
</code>```

The points a,b,c are co-linear iff the lines AB and BC have a common slope, i.e.:

```<code>ba.s == ca.s
</code>```

Substituting and rearranging to remove the divides:

```<code>ba.y / ba.x == ca.y / ca.x
ba.y * ca.x / ba.x == ca.y
ba.y * ca.x == ca.y * ba.x
</code>```

Substitute in the original formulas for those, then a,b,c are co-linear iff:

```<code>(b.y - a.y) * (c.x - a.x) == (c.y - a.y) * (b.x - a.x)
</code>```

Note that the determinant answer could also be rearranged into this form which proves this approach. But this form has just 2 multiplications rather than 12 for a naive determinant implementation.

Body:
I'm trying to solve "Max Points on Line" problem on Leet code. I inevitably need to do floating point operation to calculation Y-Intercept and slope of each line. Due to my past bad experience, I'm trying to avoid floating point operations as much as I can. Do you have any suggestion how I can do that here?

I am using LeetCode framework for development and pretty much just have access to standard C++ library.
Tried using double or long double but one of the test cases already pushes the numbers to the limits of the accuracy of these data types.

//P1[0] is X coordinate for point P1 and P1[1] is Y coordinate

long double slopeCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ( (long double)p2[1] - (long double)p1[1] ) / ((long double)p2[0] - (long double)p1[0]);
}

long double yIntersectionCalc( vector<int> &p1, vector<int> &p2 )
{
    if( p1[0] == p2[0] && p1[1] == p2[1] )
    {
        return DBL_MIN;
    }

    if( p1[0] == p2[0] && p1[1] != p2[1] )
    {
        return DBL_MAX;
    }

    return ((long double)p1[1]*(long double)p2[0] - (long double)p2[1]*(long double)p1[0]) / (long double)(p2[0] - p1[0]);
}

If the two points are (0, 0) and (94911150, 94911151) the slope is calculated as 1 which is inaccurate. I'm trying to avoid the floating point division if possible.

NOTE: Max Points on a Line problem is to be given points in 2D space (in this case integer coordinates) and find the maximum number of points that are on one line. E.g if the points are (0,0), (2,2), (4,3), (1,1) the answer is 3 which are points (0,0), (1,1), and (2,2)

Body:
Given points a,b,c, look at the slopes b,c make to a common point, a:

ba.x = b.x - a.x
ba.y = b.y - a.y

ba.s = ba.y / ba.x

ca.x = c.x - a.x
ca.y = c.y - a.y

ca.s = ca.y / ca.x

The points a,b,c are co-linear iff the lines AB and BC have a common slope, i.e.:

ba.s == ca.s

Substituting and rearranging to remove the divides:

ba.y / ba.x == ca.y / ca.x
ba.y * ca.x / ba.x == ca.y
ba.y * ca.x == ca.y * ba.x

Substitute in the original formulas for those, then a,b,c are co-linear iff:

(b.y - a.y) * (c.x - a.x) == (c.y - a.y) * (b.x - a.x)

Note that the determinant answer could also be rearranged into this form which proves this approach. But this form has just 2 multiplications rather than 12 for a naive determinant implementation.


问:
Best/more standard graph representation file format? (GraphSON, Gexf, GraphML? )
What's the standard graph representation file format or otherwise the most used one?
I would say one of these three:

GraphSON

GEXF

GraphML

but it would be great if anyone could point out the advantages/weaknesses from each of them.

答:
GNU Bison outputs Graphviz DOT files to help visualize the parser automaton, which usually are very big graphs. Here you can find a small sample.

I think that DOT is a de-facto standard at least for for open source projects, also because there are many excellent open source tools for producing images from DOT files (e.g. dot, neato, sfdp).

At the moment i'm writing this, Gephi and Tulip don't plot edges labels, which could be a problem for some applications.


问:
Need working C# code to find neighbors of an element in a 2-dimentional array
say array with 12 rows and 10 columns

```<code>int[,] array = new int[12,10];
</code>```

and I select 0,0 it must return all neighbors of 0,0
which will be

```<code>0,1
1,1
1,0
</code>```

say I want neighbors of 2,3 it must return an array of neighbors

```<code>1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3
</code>```

答:
Braindead and non-performing but illustrative and quick:

```<code>        int[,] array = new int[12,10];

        int refx=0, refy=10;

        var neighbours = from x in Enumerable.Range(0,array.GetLength(0)).Where(x => Math.Abs(x - refx)<=1)
                         from y in Enumerable.Range(0,array.GetLength(1)).Where(y => Math.Abs(y - refy)<=1)
                         select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);
</code>```

alternatively

```<code>        neighbours = from x in Enumerable.Range(refx-1, 3)
                     from y in Enumerable.Range(refy-1, 3)
                     where x>=0 && y>=0 && x<array.GetLength(0) && y<array.GetLength(1)
                     select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);
</code>```

Body:
say array with 12 rows and 10 columns

int[,] array = new int[12,10];

and I select 0,0 it must return all neighbors of 0,0
which will be

0,1
1,1
1,0

say I want neighbors of 2,3 it must return an array of neighbors

1,2
1,3
1,4
2,2
2,4
3,1
3,2
3,3

Body:
Braindead and non-performing but illustrative and quick:

        int[,] array = new int[12,10];

        int refx=0, refy=10;

        var neighbours = from x in Enumerable.Range(0,array.GetLength(0)).Where(x => Math.Abs(x - refx)<=1)
                         from y in Enumerable.Range(0,array.GetLength(1)).Where(y => Math.Abs(y - refy)<=1)
                         select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);

alternatively

        neighbours = from x in Enumerable.Range(refx-1, 3)
                     from y in Enumerable.Range(refy-1, 3)
                     where x>=0 && y>=0 && x<array.GetLength(0) && y<array.GetLength(1)
                     select new {x,y};

        neighbours.ToList().ForEach(Console.WriteLine);


问: Using  within a Leaflet marker popup ? If not, is there a way around it (ie is there a way to save what the script returns and implement that return in the marker popup) ?

答:
You may be mixing 2 actions: loading the script and calling the rateYo() function

Loading the script has nothing particular ...

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.js"></script>
</code>```

Then you must call the function when the popup opens:

```<code>var marker = L.marker([51.5, -0.09]).addTo(mymap)
    .bindPopup("I am a popup.<div id=\"rateYo\"></div>");
marker.id = something;

marker.on('popupopen', function (e) {
    // the id of the clicked marker is e.target.id
    // retrieve the rating for this id and use it in the rateYo() call
    $("#rateYo").rateYo({
    rating: 3.6,
    starWidth: "15px"
  });
</code>```

here is an example: https://plnkr.co/8PZIgd2g4Da6AHhWvC2o

Title: Using <script> within a leaflet marker popup

Body:
This is going to be a very simple question.

Is there a way of using  within a Leaflet marker popup ? If not, is there a way around it (ie is there a way to save what the script returns and implement that return in the marker popup) ?

Body:
You may be mixing 2 actions: loading the script and calling the rateYo() function

Loading the script has nothing particular ...

<script src="https://cdnjs.cloudflare.com/ajax/libs/rateYo/2.3.2/jquery.rateyo.min.js"></script>

Then you must call the function when the popup opens:

var marker = L.marker([51.5, -0.09]).addTo(mymap)
    .bindPopup("I am a popup.<div id=\"rateYo\"></div>");
marker.id = something;

marker.on('popupopen', function (e) {
    // the id of the clicked marker is e.target.id
    // retrieve the rating for this id and use it in the rateYo() call
    $("#rateYo").rateYo({
    rating: 3.6,
    starWidth: "15px"
  });

here is an example: https://plnkr.co/8PZIgd2g4Da6AHhWvC2o


问:
Why onBindViewHolder index isn't incrementing in Recycler View?
 infoOfPost.java

```

    package com.sakib23.task1;

    public class infoOfPost {
        String UserName;
        String ProjectTitle, ProjectDescription, ProjectTime;
        boolean ProjectFlag;

        public infoOfPost(String userName, String projectTitle, String projectDescription, String projectTime, boolean projectFlag) {
            UserName = userName;
            ProjectTitle = projectTitle;
            ProjectDescription = projectDescription;
            ProjectTime = projectTime;
            ProjectFlag = projectFlag;
        }

        public String getUserName() {
            return UserName;
        }

        public void setUserName(String userName) {
            UserName = userName;
        }

        public String getProjectTitle() {
            return ProjectTitle;
        }

        public void setProjectTitle(String projectTitle) {
            ProjectTitle = projectTitle;
        }

        public String getProjectDescription() {
            return ProjectDescription;
        }

        public void setProjectDescription(String projectDescription) {
            ProjectDescription = projectDescription;
        }

        public String getProjectTime() {
            return ProjectTime;
        }

        public void setProjectTime(String projectTime) {
            ProjectTime = projectTime;
        }

        public boolean getProjectFlag() {
            return ProjectFlag;
        }

        public void setProjectFlag(boolean projectFlag) {
            ProjectFlag = projectFlag;
        }
    }
    ```

 MainActivity.java
    ```</p>

```package com.sakib23.task1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    ArrayList<infoOfPost> arrayList;

    myAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.RecyclerViewID);
        arrayList = new ArrayList<>();

        arrayList.add(new infoOfPost("A B C", "B", "C", "01/02/12", true));
        arrayList.add(new infoOfPost("B A A", "B", "C", "06/02/12", true));
        arrayList.add(new infoOfPost("A B A", "B", "C", "01/03/12", false));
        arrayList.add(new infoOfPost("C A A", "B", "C", "02/03/12", false));
        arrayList.add(new infoOfPost("A A A", "B", "C", "01/09/12", true));
        arrayList.add(new infoOfPost("A L A", "B", "C", "11/12/12", false));

        adapter = new myAdapter(this, arrayList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }
}
```

<p>```

 myAdapter.java

```

    package com.sakib23.task1;

    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;

    public class myAdapter extends RecyclerView.Adapter {

        Context context;
        ArrayList arrayList;

        public myAdapter(Context context, ArrayList arrayList) {
            this.context = context;
            this.arrayList = arrayList;
            Log.d("TAGG", "Total Size: " + arrayList.size()); // Okay it is fine.

        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(context).inflate(R.layout.sample_post, viewGroup, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
            Log.d("TAGG", "index " + i); // it is not incrementing
            myViewHolder.userName.setText(arrayList.get(i).getUserName());
            myViewHolder.projectTitle.setText(arrayList.get(i).getProjectTitle());
            myViewHolder.projectDescription.setText(arrayList.get(i).getProjectDescription());
            myViewHolder.projectTime.setText(arrayList.get(i).getProjectTime());
            if(arrayList.get(i).getProjectFlag() == false)
                myViewHolder.projectFlag.setText("Not Flagged Post");
             else myViewHolder.projectFlag.setText("Flagged Post");
        }

        @Override
        public int getItemCount() {
            Log.d("TAGG",   " GETSIZE " + arrayList.size()  ); // it is also fine..
            return arrayList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView userName, projectTitle, projectDescription, projectTime, projectFlag;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);

                userName = itemView.findViewById(R.id.usernameID);
                projectTitle = itemView.findViewById(R.id.projecttitleID);
                projectDescription = itemView.findViewById(R.id.projectdesriptionID);
                projectTime = itemView.findViewById(R.id.projecttimeID);
                projectFlag = itemView.findViewById(R.id.projectflagID);
            }
        }
    }

    ```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView

        android:id="@+id/RecyclerViewID"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>
</LinearLayout>
</code>```

 sample_post

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UserName"
        android:id="@+id/usernameID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectTitle"
        android:id="@+id/projecttitleID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectDescription"
        android:id="@+id/projectdesriptionID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectTime"
        android:id="@+id/projecttimeID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flag"
        android:id="@+id/projectflagID"
        />
</LinearLayout>
</code>```

Here in the myAdapter.java file, onBindViewHolder index is not increasing. Please Help me.

答: The view item in your view holder is taking up the entire layout height. Use "wrap_content" instead. For the parent LinearLayout in sample_post.xml please use android:layout_height = "wrap_content"

Body:
 infoOfPost.java

    package com.sakib23.task1;

    public class infoOfPost {
        String UserName;
        String ProjectTitle, ProjectDescription, ProjectTime;
        boolean ProjectFlag;

        public infoOfPost(String userName, String projectTitle, String projectDescription, String projectTime, boolean projectFlag) {
            UserName = userName;
            ProjectTitle = projectTitle;
            ProjectDescription = projectDescription;
            ProjectTime = projectTime;
            ProjectFlag = projectFlag;
        }

        public String getUserName() {
            return UserName;
        }

        public void setUserName(String userName) {
            UserName = userName;
        }

        public String getProjectTitle() {
            return ProjectTitle;
        }

        public void setProjectTitle(String projectTitle) {
            ProjectTitle = projectTitle;
        }

        public String getProjectDescription() {
            return ProjectDescription;
        }

        public void setProjectDescription(String projectDescription) {
            ProjectDescription = projectDescription;
        }

        public String getProjectTime() {
            return ProjectTime;
        }

        public void setProjectTime(String projectTime) {
            ProjectTime = projectTime;
        }

        public boolean getProjectFlag() {
            return ProjectFlag;
        }

        public void setProjectFlag(boolean projectFlag) {
            ProjectFlag = projectFlag;
        }
    }

 MainActivity.java

package com.sakib23.task1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    ArrayList<infoOfPost> arrayList;

    myAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.RecyclerViewID);
        arrayList = new ArrayList<>();

        arrayList.add(new infoOfPost("A B C", "B", "C", "01/02/12", true));
        arrayList.add(new infoOfPost("B A A", "B", "C", "06/02/12", true));
        arrayList.add(new infoOfPost("A B A", "B", "C", "01/03/12", false));
        arrayList.add(new infoOfPost("C A A", "B", "C", "02/03/12", false));
        arrayList.add(new infoOfPost("A A A", "B", "C", "01/09/12", true));
        arrayList.add(new infoOfPost("A L A", "B", "C", "11/12/12", false));

        adapter = new myAdapter(this, arrayList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }
}

 myAdapter.java

    package com.sakib23.task1;

    import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;

    public class myAdapter extends RecyclerView.Adapter {

        Context context;
        ArrayList arrayList;

        public myAdapter(Context context, ArrayList arrayList) {
            this.context = context;
            this.arrayList = arrayList;
            Log.d("TAGG", "Total Size: " + arrayList.size()); // Okay it is fine.

        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(context).inflate(R.layout.sample_post, viewGroup, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
            Log.d("TAGG", "index " + i); // it is not incrementing
            myViewHolder.userName.setText(arrayList.get(i).getUserName());
            myViewHolder.projectTitle.setText(arrayList.get(i).getProjectTitle());
            myViewHolder.projectDescription.setText(arrayList.get(i).getProjectDescription());
            myViewHolder.projectTime.setText(arrayList.get(i).getProjectTime());
            if(arrayList.get(i).getProjectFlag() == false)
                myViewHolder.projectFlag.setText("Not Flagged Post");
             else myViewHolder.projectFlag.setText("Flagged Post");
        }

        @Override
        public int getItemCount() {
            Log.d("TAGG",   " GETSIZE " + arrayList.size()  ); // it is also fine..
            return arrayList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView userName, projectTitle, projectDescription, projectTime, projectFlag;
            public MyViewHolder(@NonNull View itemView) {
                super(itemView);

                userName = itemView.findViewById(R.id.usernameID);
                projectTitle = itemView.findViewById(R.id.projecttitleID);
                projectDescription = itemView.findViewById(R.id.projectdesriptionID);
                projectTime = itemView.findViewById(R.id.projecttimeID);
                projectFlag = itemView.findViewById(R.id.projectflagID);
            }
        }
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView

        android:id="@+id/RecyclerViewID"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>
</LinearLayout>

 sample_post

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UserName"
        android:id="@+id/usernameID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectTitle"
        android:id="@+id/projecttitleID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectDescription"
        android:id="@+id/projectdesriptionID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProjectTime"
        android:id="@+id/projecttimeID"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Flag"
        android:id="@+id/projectflagID"
        />
</LinearLayout>

Here in the myAdapter.java file, onBindViewHolder index is not increasing. Please Help me.


问:
How to find a mathematical method to solve this big value recursion problem?
A python code with a recursion function. To calculate this is to slow by PC. So do there have a easy way to find the answer of this python code?

def rec(n):
    if n<1:
      return 1
    return rec(n//4)+rec(n//2)
print(rec(12345678987654321))
```

答:
Your function returns the Xth Fibonacci number where X = log(n)+3.  Since obtaining the Xth Fibonacci number has an O(X) performance and we are supplying it with log(n). This will give O(log(n)) performance which will be similar to the memoized version but using simpler operations. So the function should run even faster:

```<code>def fibo(n):
    a,b=1,1
    for _ in range(n-1): a,b = b,a+b
    return a

from math import log
def rec2(n) :
    return fibo(int(log(n,2)+3))

print(rec2(12345678987654321)) # 225851433717
</code>```

For n = 12345678987654321, this performs roughly 5 times faster than the memoized version of the original rec() function.

You could also get the performance gain by not making two recursive calls at each iteration.  This would require returning two values so that n//4 (the next iteration) can be brought up to the calling function.

```<code>def rec3(n):
    if n<1 :return 1,1
    a,b = rec3(n//2)
    return a+b,a

rec3(12345678987654321)[0] # 225851433717
</code>```

This is slower than the Fibonacci approach but still faster than the memoized original.

Test results for 1000 runs (2.9 GHz Intel Core i9 laptop):

```<code>rec(12345678987654321)     0.027 sec (Memoized on lru_cache, cleared each run)
rec2(12345678987654321)    0.005 sec (Fibonacci)
                           0.002 sec (fastFibo, see EDIT below)
rec3(12345678987654321)[0] 0.013 sec (Single Recursion)
</code>```

EDIT
If you want to make the Fibonacci approach even faster (2x), you can use this non-iterative fastFibo() function to obtain the Nth Fibonacci number:

```<code>from math import sqrt

sqrt5 = sqrt(5)
golden_ratio = (1 + sqrt5) / 2

def fastFibo(n):
    approx = (golden_ratio**n - (1 - golden_ratio)**n) / sqrt5
    return int(round(approx))
</code>```

This will allow you to write the function as a purely mathematical formula with no iterations/recursions and a performance of O(1):

```<code>from math import log,sqrt
sqrt5 = sqrt(5)
golden_ratio = (1 + sqrt5) / 2
def rec4(n):
    n = int(log(n,2)+3)
    result = (golden_ratio**n - (1 - golden_ratio)**n) / sqrt5
    return int(round(result))
</code>```

note that fastFibo() is an approximation (good up to 70) so this rec4() solution will only be valid up to n = 2^67  (147573952589676412928)

Body:
Your function returns the Xth Fibonacci number where X = log(n)+3.  Since obtaining the Xth Fibonacci number has an O(X) performance and we are supplying it with log(n). This will give O(log(n)) performance which will be similar to the memoized version but using simpler operations. So the function should run even faster:

def fibo(n):
    a,b=1,1
    for _ in range(n-1): a,b = b,a+b
    return a

from math import log
def rec2(n) :
    return fibo(int(log(n,2)+3))

print(rec2(12345678987654321)) # 225851433717

For n = 12345678987654321, this performs roughly 5 times faster than the memoized version of the original rec() function.

You could also get the performance gain by not making two recursive calls at each iteration.  This would require returning two values so that n//4 (the next iteration) can be brought up to the calling function.

def rec3(n):
    if n<1 :return 1,1
    a,b = rec3(n//2)
    return a+b,a

rec3(12345678987654321)[0] # 225851433717

This is slower than the Fibonacci approach but still faster than the memoized original.

Test results for 1000 runs (2.9 GHz Intel Core i9 laptop):

rec(12345678987654321)     0.027 sec (Memoized on lru_cache, cleared each run)
rec2(12345678987654321)    0.005 sec (Fibonacci)
                           0.002 sec (fastFibo, see EDIT below)
rec3(12345678987654321)[0] 0.013 sec (Single Recursion)

EDIT
If you want to make the Fibonacci approach even faster (2x), you can use this non-iterative fastFibo() function to obtain the Nth Fibonacci number:

from math import sqrt

sqrt5 = sqrt(5)
golden_ratio = (1 + sqrt5) / 2

def fastFibo(n):
    approx = (golden_ratio**n - (1 - golden_ratio)**n) / sqrt5
    return int(round(approx))

This will allow you to write the function as a purely mathematical formula with no iterations/recursions and a performance of O(1):

from math import log,sqrt
sqrt5 = sqrt(5)
golden_ratio = (1 + sqrt5) / 2
def rec4(n):
    n = int(log(n,2)+3)
    result = (golden_ratio**n - (1 - golden_ratio)**n) / sqrt5
    return int(round(result))

note that fastFibo() is an approximation (good up to 70) so this rec4() solution will only be valid up to n = 2^67  (147573952589676412928)