问:
DQN with prioritized experience replay and target network does not improve
I tried to code a neural network to solve OpenAI's CartPole environment with Tensorflow and Keras. The network uses prioritized experience replay and a seperate target network which is updated every tenth episode. Here's the code:

```<code>import numpy as np
import gym
import matplotlib.pyplot as plt
from collections import deque

from tensorflow import keras

class agent:
    def __init__(self,inputs,outputs,gamma):
        self.gamma = gamma
        self.epsilon = 1.0
        self.epsilon_decay = 0.999
        self.epsilon_min = 0.01
        self.inputs = inputs
        self.outputs = outputs
        self.network = self._build_net()
        self.target_network = self._build_net()
        self.replay_memory = deque(maxlen=100000)

        self.target_network.set_weights(self.network.get_weights())

    def _build_net(self):
        model = keras.models.Sequential()

        model.add(keras.layers.Dense(10,activation='relu',input_dim=self.inputs))
        model.add(keras.layers.Dense(10,activation='relu'))
        model.add(keras.layers.Dense(10,activation='relu'))
        model.add(keras.layers.Dense(self.outputs,activation='sigmoid'))
        model.compile(optimizer='adam',loss='categorical_crossentropy')

        return model

    def act(self,state,testing=False):
        if not testing:
            if self.epsilon > np.random.rand():
                return np.random.randint(self.outputs)
            else:
                return np.argmax(self.network.predict(np.array([state])))

        else:
            return np.argmax(self.network.predict(np.array([state])))

    def remember(self,state,action,next_state,reward,win):
        self.replay_memory.append((state,action,next_state,reward,win))

    def get_batch(self):
        batch = []
        losses = []
        targets = []

        if len(self.replay_memory) >= 32:
            for state,action,next_state,reward,done in self.replay_memory:
                target_f = np.zeros([1,self.outputs])
                if done != False:
                    target = (reward + self.gamma * np.amax(self.target_network.predict(np.array([next_state]))[0]))
                    target_f[0][action] = target

                targets.append(target_f)
                loss = np.mean(self.network.predict(np.array([state]))-target_f)**2
                losses.append(loss)

            indexes = np.argsort(losses)[:32]

            for indx in indexes:
                batch.append((self.replay_memory[indx][0], targets[indx]))

            return batch

    def replay(self,batch):
        for state,target in batch:
            self.network.fit(np.array([state]), target, epochs=1, verbose=0)
        self.epsilon = max(self.epsilon_min, self.epsilon*self.epsilon_decay)

    def update_target_network(self):
        self.target_network.set_weights(self.network.get_weights())

    def save(self):
        self.network.save_weights('./DQN.model')

    def load(self):
        self.network.load_weights('./DQN.model')

env = gym.make('CartPole-v0')
episodes = 1000
agent = agent(env.observation_space.shape[0],env.action_space.n,0.99)
rewards = []

state = env.reset()
for _ in range(500):
    action = agent.act(state,1.0)
    next_state, reward, win, _ = env.step(action)
    agent.remember(state,action,next_state,reward,win)
    state = next_state

    if win:
        state = env.reset()

for e in range(episodes):
    print('episode:',e+1)
    batch = agent.get_batch()
    state = env.reset()
    for t in range(400):
        action = agent.act(state)
        next_state, reward, win, _ = env.step(action)
        agent.remember(state,action,next_state,reward,win)
        state = next_state

        if win:
            break

        agent.replay(batch)

    print('score:',t)
    print('epsilon:',agent.epsilon)
    print('')

    if e%10 == 0:
        agent.update_target_network()
        agent.save()

    rewards.append(t)
    plt.plot(list(range(e+1)),rewards)
    plt.savefig('./reward.png')
</code>```

The problem is that the agent gets worse as epsilon decreases. And when epsilon is a its lowest value, the agent only gets through 7-9 steps before the Pole falls, as seen in the Image below. Can someone tell me why my agent isn't learning anything and how to fix it?

答: Try making the reward = -reward if done. It helps</p>

Body:
I tried to code a neural network to solve OpenAI's CartPole environment with Tensorflow and Keras. The network uses prioritized experience replay and a seperate target network which is updated every tenth episode. Here's the code:

import numpy as np
import gym
import matplotlib.pyplot as plt
from collections import deque

from tensorflow import keras

class agent:
    def __init__(self,inputs,outputs,gamma):
        self.gamma = gamma
        self.epsilon = 1.0
        self.epsilon_decay = 0.999
        self.epsilon_min = 0.01
        self.inputs = inputs
        self.outputs = outputs
        self.network = self._build_net()
        self.target_network = self._build_net()
        self.replay_memory = deque(maxlen=100000)

        self.target_network.set_weights(self.network.get_weights())

    def _build_net(self):
        model = keras.models.Sequential()

        model.add(keras.layers.Dense(10,activation='relu',input_dim=self.inputs))
        model.add(keras.layers.Dense(10,activation='relu'))
        model.add(keras.layers.Dense(10,activation='relu'))
        model.add(keras.layers.Dense(self.outputs,activation='sigmoid'))
        model.compile(optimizer='adam',loss='categorical_crossentropy')

        return model

    def act(self,state,testing=False):
        if not testing:
            if self.epsilon > np.random.rand():
                return np.random.randint(self.outputs)
            else:
                return np.argmax(self.network.predict(np.array([state])))

        else:
            return np.argmax(self.network.predict(np.array([state])))

    def remember(self,state,action,next_state,reward,win):
        self.replay_memory.append((state,action,next_state,reward,win))

    def get_batch(self):
        batch = []
        losses = []
        targets = []

        if len(self.replay_memory) >= 32:
            for state,action,next_state,reward,done in self.replay_memory:
                target_f = np.zeros([1,self.outputs])
                if done != False:
                    target = (reward + self.gamma * np.amax(self.target_network.predict(np.array([next_state]))[0]))
                    target_f[0][action] = target

                targets.append(target_f)
                loss = np.mean(self.network.predict(np.array([state]))-target_f)**2
                losses.append(loss)

            indexes = np.argsort(losses)[:32]

            for indx in indexes:
                batch.append((self.replay_memory[indx][0], targets[indx]))

            return batch

    def replay(self,batch):
        for state,target in batch:
            self.network.fit(np.array([state]), target, epochs=1, verbose=0)
        self.epsilon = max(self.epsilon_min, self.epsilon*self.epsilon_decay)

    def update_target_network(self):
        self.target_network.set_weights(self.network.get_weights())

    def save(self):
        self.network.save_weights('./DQN.model')

    def load(self):
        self.network.load_weights('./DQN.model')

env = gym.make('CartPole-v0')
episodes = 1000
agent = agent(env.observation_space.shape[0],env.action_space.n,0.99)
rewards = []

state = env.reset()
for _ in range(500):
    action = agent.act(state,1.0)
    next_state, reward, win, _ = env.step(action)
    agent.remember(state,action,next_state,reward,win)
    state = next_state

    if win:
        state = env.reset()

for e in range(episodes):
    print('episode:',e+1)
    batch = agent.get_batch()
    state = env.reset()
    for t in range(400):
        action = agent.act(state)
        next_state, reward, win, _ = env.step(action)
        agent.remember(state,action,next_state,reward,win)
        state = next_state

        if win:
            break

        agent.replay(batch)

    print('score:',t)
    print('epsilon:',agent.epsilon)
    print('')

    if e%10 == 0:
        agent.update_target_network()
        agent.save()

    rewards.append(t)
    plt.plot(list(range(e+1)),rewards)
    plt.savefig('./reward.png')

The problem is that the agent gets worse as epsilon decreases. And when epsilon is a its lowest value, the agent only gets through 7-9 steps before the Pole falls, as seen in the Image below. Can someone tell me why my agent isn't learning anything and how to fix it?


来源: stackexchange

问:
Count Instances of Class
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

```<code>System.GC.numberOf< Foo >()
</code>```

or something.

I was looking through the garbage collectors but I could not find any relevant methods.

答: Quick and dirty: if you can't change the class, maybe you can just put a counter in another part of the project, incrementing it when you instantiate said class?</p>

ContentLicense: CC BY-SA 3.0

Title: Count Instances of Class

Body:
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

System.GC.numberOf< Foo >()

or something.

I was looking through the garbage collectors but I could not find any relevant methods.


问:
How to calculate the (smallest) distance between a set of lines and a point?
So basically I am trying to label if some GPS points are very close to a road.

I have vectors of lat-lon coordinates which, when connected to the the subsequent/antecedent row in the vector, form a line which represents a road (depicted as matplotlib plots in colors)
I also have simple geographic points (lat-lon) (depicted as matplotlib scatter plot in black)

i would like to label whether a point is near a road (e.g. within 0.001 radians distance) - for that, I am guessing one would need to calculate the closest distance of a point to this set of vectors.

#example vector 1
[[-84.3146272, 33.7741084], [-84.3145183, 33.7741196]]
#example vector 2
[[-84.4043106, 33.7700542], [-84.4045421, 33.770055]]

#example point to predict wether it will be near one of these two lines
[-84.31106, 33.73887]
```

How can one tackle this problem? I cannot think of a way to solve this, but when looking at the plot it seems simple... Is there a library that could help?

答:
I am assuming you are working with the spherical model of the Earth. Then I suppose what you call "lines" are in fact arc-segments of great circles (the straight lines of spherical geometry). In other words, you have one point p1 on the surface of the sphere with lat-lon coordinates [lat1, lon1] and another point p2 on the sphere with lat-lon coordinates [lat2, lon2]. What is considered "the straight line" on the sphere that passes through p1 and p2 is the unique circle (called great circle) obtained by the intersection of the sphere with the plane that passes through the center of the sphere and the two points p1 and p2. Then, what you call a "line", is the smaller of the two circular arcs from this great circle, bounded by the two points p1 and p2.

The distance you would like to calculate (in radians) could be the distance from a third point p with lat-lon coordinates [lat, lon] to the arc-segment determined by the two points p1 and p2. The said distance should be the arc-length of the arc from the great circle passing through p and perpendicular to the great circle of p1 and p2. This perpendicular great circle is the one determined by the intersection of the sphere with the plane perpendicular to the plane of the great circle of p1 and p2 and passing through the point  p and the center of the sphere. If the intersection of the perpendicular great circle with the great-circle arc p1 p2 is a point h inside the arc-segment p1 p2, then the length of the great circle arc p h is the sought distance. If, however, h is outside the arc p1 p2 the the sought distance is either p p1 or p p2 whichever is smaller.

Here is some Matlab code that calculates the shortest distance between a point and an arc-interval:

lat_lon = [lat, lon];
lat_lon1 = [lat1, lon1];
lat_lon2 = [lat2, lon2];

function dist = dist_point_2_road(lat_lon, lat_lon1, lat_lon2)

   % you may have to convert lat-long angles from degrees to radians

   % First, convert from lat-long coordinates to 3D coordinates of points on the unit
   % sphere. Since Earth's radius cancels out in our computations, we simply assume it
   % is R = 1
   lat = lat_lon(1);
   lon = lat_lon(2);

   lat1 = lat_lon1(1);
   lon1 = lat_lon1(2);

   lat2 = lat_lon2(1);
   lon2 = lat_lon2(2);

   p1 = [ cosd(lat1)*cosd(lon1),  cosd(lat1)*sind(lon1),  sind(lat1) ]; %cosd = cos(degrees)
   p2 = [ cosd(lat2)*cosd(lon2),  cosd(lat2)*sind(lon2),  sind(lat2) ]; %sind = sin(degrees)
   p = [ cosd(lat)*cosd(lon),  cosd(lat)*sind(lon),  sind(lat) ];

   % n12 is the unit vector perpendicular to the plane of the great circle
   % determined by the points p1 and p2
   n12 = cross(p1, p2);
   n12 = n12 / sqrt(dot(n12, n12));
   sin_of_dist = dot(p, n12); % sine of the angle that equals arc-distance
                              % from point p to the great arc p1 p2

   dist = pi/2 - acos(abs(sin_of_dist)); % acos = arccos, abs() = absolute value
          % dist is the shortest distance in radians from p to the
          % great circle determined by the points p1 and p2

   n1 = cross(p1, p);
   n1 = n1 / sqrt(dot(n1, n1));
   % unit normal vector perpendicular to the great-arc determined by p and p1

   n2 = cross(p, p2);
   n2 = n1 / sqrt(dot(n2, n2));
   % unit normal vector perpendicular to the great-arc determined by p and p2

   if dot(n12, n1) < 0 % if the angle of spherical triangle p p1 p2 at vertex p1 is obtuse
      dist = acos(dot(p, p1)); % the shortest distance is p p1
   elseif dot(n12, n2) < 0 % if the angle of spherical triangle p p1 p2 at vertex p2 is obtuse
      dist = acos(dot(p, p2)); % the shortest distance is p p2
   end

   % the function returns the appropriate dist as output

end
```

<p>You can iterate this for the sequence of arc-intervals that form a road and select the smallest distance to an arc-interval. </p>

<p>According to this computation, the distance of the point to the first "vector 1" is
<code>0.0000615970599633145</code> radians and the distance to the second "vector 2" is
<code>0.00162840939265068</code> radians. The point is closest to a point inside vector 1, but for vector 2, it is closest to to one of the ends of the arc-interval. </p>

<p><strong>Edit.</strong> Now, if one wants to use Euculdiean (flat) approximation, ignoring Earths curvature, one may needs to convert lat-lon coordinates into Euclidean flat approximation coordinates. To avoid any map specific coordinates, one may be tempted to plot latitude against longitude coordinates. That may be ok around the equator, but the closer to the poles one gets, the more innaccurate these coordinates gets at representing distance data. This is because closer to the poles, distance along a fixed latitude is much shorter than distance along a fixed longitude. That is why we need to correct this discrepancy. This is done by using the Riemannian metric on the sphere in lat-long coordinates, or simply by looking at the 3D geometry of latitude and longitude circles near a given point on the sphere. </p>

<pre class="lang-matlab prettyprint-override"><code>lat_lon = [lat, lon];
lat_lon1 = [lat1, lon1];
lat_lon2 = [lat2, lon2];

%center of approximate Euclidean coordinate system is point p
% with lat_long coordinates and the scaling coefficient of longitude,
% which equalizes longitude and latitude distance at point p, is

a = cosd(lat_long(1));

function  x = convert_2_Eucl(lat_long1, lat_long, a)
   x = [lat_long1(1) - lat_long(1),  a*(lat_long1(2) - lat_long(2))];
end

% convert from lat-long to approximate Euclidean coordinates
x1 = convert_2_Eucl(lat_long1, lat_long, a);
x2 = convert_2_Eucl(lat_long2, lat_long, a);

function dist = dist_point_2_road(x1, x2)

   dist = dot(x1, x1) * dot(x2 - x1, x2 - x1) - dot(x1, x2 - x1)^2 ;
   dist = sqrt( dist / ( dot(x2 - x1, x2 - x1)^2) );
   % dist is the distance from the point p, which has Eucl coordinates [0,0]
   % to the straight Euclidean interval x1 x2 representing the interval p1 p2

   if dot(x1, x2 - x1) > 0
      dist = sqrt( dot(x1, x1) );
   elseif dot(x2, x1 - x2) > 0
      dist = sqrt( dot(x2, x2) );
   end

end
</code>```

Remark: the latter function calculates distance, but it might be equally convenient to just calculate dist^2, avoiding the calculation of the square root sqrt in order to speed up the performance. Measuring with respect to dist^2 should work just as well.

You choose which function you want, the spherical one or approximately Euclidean. The latter is probably faster. You can choose to remove the square root and calculate distance squared to make things even faster.

I wrote this in a hurry, so there might be some inaccuracies.

ContentLicense: CC BY-SA 4.0

Body:
So basically I am trying to label if some GPS points are very close to a road.

I have vectors of lat-lon coordinates which, when connected to the the subsequent/antecedent row in the vector, form a line which represents a road (depicted as matplotlib plots in colors)
I also have simple geographic points (lat-lon) (depicted as matplotlib scatter plot in black)

i would like to label whether a point is near a road (e.g. within 0.001 radians distance) - for that, I am guessing one would need to calculate the closest distance of a point to this set of vectors.

#example vector 1
[[-84.3146272, 33.7741084], [-84.3145183, 33.7741196]]
#example vector 2
[[-84.4043106, 33.7700542], [-84.4045421, 33.770055]]

#example point to predict wether it will be near one of these two lines
[-84.31106, 33.73887]

How can one tackle this problem? I cannot think of a way to solve this, but when looking at the plot it seems simple... Is there a library that could help?

Body:
I am assuming you are working with the spherical model of the Earth. Then I suppose what you call "lines" are in fact arc-segments of great circles (the straight lines of spherical geometry). In other words, you have one point p1 on the surface of the sphere with lat-lon coordinates [lat1, lon1] and another point p2 on the sphere with lat-lon coordinates [lat2, lon2]. What is considered "the straight line" on the sphere that passes through p1 and p2 is the unique circle (called great circle) obtained by the intersection of the sphere with the plane that passes through the center of the sphere and the two points p1 and p2. Then, what you call a "line", is the smaller of the two circular arcs from this great circle, bounded by the two points p1 and p2.

The distance you would like to calculate (in radians) could be the distance from a third point p with lat-lon coordinates [lat, lon] to the arc-segment determined by the two points p1 and p2. The said distance should be the arc-length of the arc from the great circle passing through p and perpendicular to the great circle of p1 and p2. This perpendicular great circle is the one determined by the intersection of the sphere with the plane perpendicular to the plane of the great circle of p1 and p2 and passing through the point  p and the center of the sphere. If the intersection of the perpendicular great circle with the great-circle arc p1 p2 is a point h inside the arc-segment p1 p2, then the length of the great circle arc p h is the sought distance. If, however, h is outside the arc p1 p2 the the sought distance is either p p1 or p p2 whichever is smaller.

Here is some Matlab code that calculates the shortest distance between a point and an arc-interval:

lat_lon = [lat, lon];
lat_lon1 = [lat1, lon1];
lat_lon2 = [lat2, lon2];

function dist = dist_point_2_road(lat_lon, lat_lon1, lat_lon2)

   % you may have to convert lat-long angles from degrees to radians

   % First, convert from lat-long coordinates to 3D coordinates of points on the unit
   % sphere. Since Earth's radius cancels out in our computations, we simply assume it
   % is R = 1
   lat = lat_lon(1);
   lon = lat_lon(2);

   lat1 = lat_lon1(1);
   lon1 = lat_lon1(2);

   lat2 = lat_lon2(1);
   lon2 = lat_lon2(2);

   p1 = [ cosd(lat1)*cosd(lon1),  cosd(lat1)*sind(lon1),  sind(lat1) ]; %cosd = cos(degrees)
   p2 = [ cosd(lat2)*cosd(lon2),  cosd(lat2)*sind(lon2),  sind(lat2) ]; %sind = sin(degrees)
   p = [ cosd(lat)*cosd(lon),  cosd(lat)*sind(lon),  sind(lat) ];

   % n12 is the unit vector perpendicular to the plane of the great circle
   % determined by the points p1 and p2
   n12 = cross(p1, p2);
   n12 = n12 / sqrt(dot(n12, n12));
   sin_of_dist = dot(p, n12); % sine of the angle that equals arc-distance
                              % from point p to the great arc p1 p2

   dist = pi/2 - acos(abs(sin_of_dist)); % acos = arccos, abs() = absolute value
          % dist is the shortest distance in radians from p to the
          % great circle determined by the points p1 and p2

   n1 = cross(p1, p);
   n1 = n1 / sqrt(dot(n1, n1));
   % unit normal vector perpendicular to the great-arc determined by p and p1

   n2 = cross(p, p2);
   n2 = n1 / sqrt(dot(n2, n2));
   % unit normal vector perpendicular to the great-arc determined by p and p2

   if dot(n12, n1) < 0 % if the angle of spherical triangle p p1 p2 at vertex p1 is obtuse
      dist = acos(dot(p, p1)); % the shortest distance is p p1
   elseif dot(n12, n2) < 0 % if the angle of spherical triangle p p1 p2 at vertex p2 is obtuse
      dist = acos(dot(p, p2)); % the shortest distance is p p2
   end

   % the function returns the appropriate dist as output

end

You can iterate this for the sequence of arc-intervals that form a road and select the smallest distance to an arc-interval.

According to this computation, the distance of the point to the first "vector 1" is
0.0000615970599633145 radians and the distance to the second "vector 2" is
0.00162840939265068 radians. The point is closest to a point inside vector 1, but for vector 2, it is closest to to one of the ends of the arc-interval.

Edit. Now, if one wants to use Euculdiean (flat) approximation, ignoring Earths curvature, one may needs to convert lat-lon coordinates into Euclidean flat approximation coordinates. To avoid any map specific coordinates, one may be tempted to plot latitude against longitude coordinates. That may be ok around the equator, but the closer to the poles one gets, the more innaccurate these coordinates gets at representing distance data. This is because closer to the poles, distance along a fixed latitude is much shorter than distance along a fixed longitude. That is why we need to correct this discrepancy. This is done by using the Riemannian metric on the sphere in lat-long coordinates, or simply by looking at the 3D geometry of latitude and longitude circles near a given point on the sphere.

lat_lon = [lat, lon];
lat_lon1 = [lat1, lon1];
lat_lon2 = [lat2, lon2];

%center of approximate Euclidean coordinate system is point p
% with lat_long coordinates and the scaling coefficient of longitude,
% which equalizes longitude and latitude distance at point p, is

a = cosd(lat_long(1));

function  x = convert_2_Eucl(lat_long1, lat_long, a)
   x = [lat_long1(1) - lat_long(1),  a*(lat_long1(2) - lat_long(2))];
end

% convert from lat-long to approximate Euclidean coordinates
x1 = convert_2_Eucl(lat_long1, lat_long, a);
x2 = convert_2_Eucl(lat_long2, lat_long, a);

function dist = dist_point_2_road(x1, x2)

   dist = dot(x1, x1) * dot(x2 - x1, x2 - x1) - dot(x1, x2 - x1)^2 ;
   dist = sqrt( dist / ( dot(x2 - x1, x2 - x1)^2) );
   % dist is the distance from the point p, which has Eucl coordinates [0,0]
   % to the straight Euclidean interval x1 x2 representing the interval p1 p2

   if dot(x1, x2 - x1) > 0
      dist = sqrt( dot(x1, x1) );
   elseif dot(x2, x1 - x2) > 0
      dist = sqrt( dot(x2, x2) );
   end

end

Remark: the latter function calculates distance, but it might be equally convenient to just calculate dist^2, avoiding the calculation of the square root sqrt in order to speed up the performance. Measuring with respect to dist^2 should work just as well.

You choose which function you want, the spherical one or approximately Euclidean. The latter is probably faster. You can choose to remove the square root and calculate distance squared to make things even faster.

I wrote this in a hurry, so there might be some inaccuracies.


问:
SQL Server create rows from custom delimited text
I am to calculate of CO2 emissions for flight itineraries. A flight itinerary can consist of 1 hop like DXB/CDG, or ABJ/ADD/BKK/KUL/ADD/ABJ which would be 5 hops. My challenge is I need to break the itinerary information to individual flight information as the CO2 emission is calculated per flight:

Source: ABJ/ADD/BKK/KUL/ADD/ABJ

And convert it to:

答:
To get your expected results, you can create a function which will split your string into rows using supplied delimiters. After that, you can make further adjustment or apply changes on returned data based on your requirement.

Step-1: Create the function

```<code>CREATE  FUNCTION [dbo].[splitstring] ( @stringToSplit VARCHAR(MAX) ,@Delimiter VARCHAR(10))
RETURNS @returnList TABLE ([Word] [nvarchar] (500))
AS
BEGIN
    DECLARE @name NVARCHAR(255)
    DECLARE @pos INT
    DECLARE @RN INT = 1

    WHILE CHARINDEX(@Delimiter, @stringToSplit) > 0
    BEGIN
        SELECT @pos  = CHARINDEX(@Delimiter, @stringToSplit)
        SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

        INSERT INTO @returnList([Word],RN)
        SELECT @name,@RN

        SET @RN = @RN + 1

        SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
    END

    INSERT INTO @returnList([Word],RN)
    SELECT @stringToSplit,@RN

RETURN
END
</code>```

Step-2: Achieve required data using that function

```<code>SELECT A.Word+'/'+B.Word FROM
(
    SELECT Word,RN
    FROM [dbo].[splitstring]('ABJ/ADD/BKK/KUL/ADD/ABJ','/')
) A
INNER JOIN
(
    SELECT Word,RN
    FROM [dbo].[splitstring]('ABJ/ADD/BKK/KUL/ADD/ABJ','/')
)B ON A.RN = B.RN-1
</code>```

Output will be-

```<code>ABJ/ADD
ADD/BKK
BKK/KUL
KUL/ADD
ADD/ABJ
</code>```

Body:
To get your expected results, you can create a function which will split your string into rows using supplied delimiters. After that, you can make further adjustment or apply changes on returned data based on your requirement.

Step-1: Create the function

CREATE  FUNCTION [dbo].[splitstring] ( @stringToSplit VARCHAR(MAX) ,@Delimiter VARCHAR(10))
RETURNS @returnList TABLE ([Word] [nvarchar] (500))
AS
BEGIN
    DECLARE @name NVARCHAR(255)
    DECLARE @pos INT
    DECLARE @RN INT = 1

    WHILE CHARINDEX(@Delimiter, @stringToSplit) > 0
    BEGIN
        SELECT @pos  = CHARINDEX(@Delimiter, @stringToSplit)
        SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

        INSERT INTO @returnList([Word],RN)
        SELECT @name,@RN

        SET @RN = @RN + 1

        SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
    END

    INSERT INTO @returnList([Word],RN)
    SELECT @stringToSplit,@RN

RETURN
END

Step-2: Achieve required data using that function

SELECT A.Word+'/'+B.Word FROM
(
    SELECT Word,RN
    FROM [dbo].[splitstring]('ABJ/ADD/BKK/KUL/ADD/ABJ','/')
) A
INNER JOIN
(
    SELECT Word,RN
    FROM [dbo].[splitstring]('ABJ/ADD/BKK/KUL/ADD/ABJ','/')
)B ON A.RN = B.RN-1

Output will be-

ABJ/ADD
ADD/BKK
BKK/KUL
KUL/ADD
ADD/ABJ


问:
Calling array values based on DOM return
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

```<code>User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12
</code>```

```<code>User Input Example #2: 1,2,5
User Input Output #2: 1,2,5
</code>```

How can I do this?

答:
According to this answer, you can recursively use Date to accomplish this, given input months:

```<code>months.split(",").map((month) => {
  return (isNaN(month) ? new Date(Date.parse(month +" 1, 2019")).getMonth()+1 : month)
}).join(",")
</code>```

This function iterates over each code/number string using map, checks whether or not the a given string is not number using isNaN() in a ternary operator, and accordingly returns the given number/converted code.

Body:
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12

User Input Example #2: 1,2,5
User Input Output #2: 1,2,5

How can I do this?

Body:
According to this answer, you can recursively use Date to accomplish this, given input months:

months.split(",").map((month) => {
  return (isNaN(month) ? new Date(Date.parse(month +" 1, 2019")).getMonth()+1 : month)
}).join(",")

This function iterates over each code/number string using map, checks whether or not the a given string is not number using isNaN() in a ternary operator, and accordingly returns the given number/converted code.


问:
R Custom Max Function
```<code>data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))
</code>```

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

```<code>data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))
</code>```

答:
We could use cummax for score higher than 3 or more or keep the score as it is. To get NAs after first 4 we can replace the duplicated 4 values as NA.

```<code>library(dplyr)

data %>%
  group_by(person) %>%
    mutate(WANT2 = ifelse(score >= 3 | (row_number() >= which.max(score == 3)),
                   cummax(score), score),
            WANT2 = replace(WANT2, duplicated(WANT2 == 4) & WANT2 == 4, NA))

#   person score  WANT WANT2
#    <dbl> <dbl> <dbl> <dbl>
# 1      1     1     1     1
# 2      1     2     2     2
# 3      1     3     3     3
# 4      1     2     3     3
# 5      2     2     2     2
# 6      2     1     1     1
# 7      2     2     2     2
# 8      2     3     3     3
# 9      3     2     2     2
#10      3     3     3     3
#11      3     1     3     3
#12      3     4     4     4
#13      4     1     1     1
#14      4     4     4     4
#15      4     3    NA    NA
</code>```

Title: R Custom Max Function

Body:
data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))

Body:
We could use cummax for score higher than 3 or more or keep the score as it is. To get NAs after first 4 we can replace the duplicated 4 values as NA.

library(dplyr)

data %>%
  group_by(person) %>%
    mutate(WANT2 = ifelse(score >= 3 | (row_number() >= which.max(score == 3)),
                   cummax(score), score),
            WANT2 = replace(WANT2, duplicated(WANT2 == 4) & WANT2 == 4, NA))

#   person score  WANT WANT2
#    <dbl> <dbl> <dbl> <dbl>
# 1      1     1     1     1
# 2      1     2     2     2
# 3      1     3     3     3
# 4      1     2     3     3
# 5      2     2     2     2
# 6      2     1     1     1
# 7      2     2     2     2
# 8      2     3     3     3
# 9      3     2     2     2
#10      3     3     3     3
#11      3     1     3     3
#12      3     4     4     4
#13      4     1     1     1
#14      4     4     4     4
#15      4     3    NA    NA


问:
How to connect PostgreSQL with Spring Mvc
I want to set up the database connection on Spring MVC with PostgreSQL, how do I do it?
I have tried  google search but still, I have not found what I am looking for, so far I have added a PostgreSQL dependency on my project and here are the codes

```<code><dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>9.4-1206-jdbc42</version>
  </dependency>
</code>```

So where do I go from here?
how do I create the configuration files for db?
What is the default login credentials for db?
Where do I see the database table?

答:
You need to configure your database connection. You can create a classe  to configure this. For example:

```<code>@Configuration
public class DatabaseConfig {

@Bean
public DriverManagerDataSource getDataSource() {

    DriverManagerDataSource bds = new DriverManagerDataSource();
    bds.setDriverClassName("org.postgresql.Drive");
    bds.setUrl("jdbc:mysql://localhost:5432/dbname");
    bds.setUsername("user");
    bds.setPassword("pass");

    return bds;
}
</code>```

}

And then, you can inject the datasource in your bens.

```<code>@Controller
public class MyController {

   @Autowired
  private DataSource dataSource;
}
</code>```

Try to use Spring boot with spring data. Is very simple to configure a database connection and create repositories for data manipulations (CRUD). See this https://dzone.com/articles/spring-boot-with-spring-data-jpa

Body:
I want to set up the database connection on Spring MVC with PostgreSQL, how do I do it?
I have tried  google search but still, I have not found what I am looking for, so far I have added a PostgreSQL dependency on my project and here are the codes

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>9.4-1206-jdbc42</version>
  </dependency>

So where do I go from here?
how do I create the configuration files for db?
What is the default login credentials for db?
Where do I see the database table?

Body:
You need to configure your database connection. You can create a classe  to configure this. For example:

@Configuration
public class DatabaseConfig {

@Bean
public DriverManagerDataSource getDataSource() {

    DriverManagerDataSource bds = new DriverManagerDataSource();
    bds.setDriverClassName("org.postgresql.Drive");
    bds.setUrl("jdbc:mysql://localhost:5432/dbname");
    bds.setUsername("user");
    bds.setPassword("pass");

    return bds;
}

}

And then, you can inject the datasource in your bens.

@Controller
public class MyController {

   @Autowired
  private DataSource dataSource;
}

Try to use Spring boot with spring data. Is very simple to configure a database connection and create repositories for data manipulations (CRUD). See this https://dzone.com/articles/spring-boot-with-spring-data-jpa


问:
C# to pass class type to base constructor
Well, this is a convoluted/complicated question, and here it goes:

I have two pair of classes

Derived class inherits from the Base class (class Derived: Base{})

Class2 inherits from Class1 (class Class2: Class1 {})

My current Class1 constructor has:

```<code>Derived d = new Derived();
</code>```

What I want is that the type Derived is passed from the Class2 constructor into its base (Class1) constructor. Is that possible?

More complete code:

```<code>class Base
{
    public Base() {
        Console.WriteLine("Inside Base Constructor");
    }
    ~Base() {
        Console.WriteLine("Inside Base Destructor");
    }
}

class Derived1: Base {
    public Derived1() {
        Console.WriteLine("Inside The Derived1 Constructor");
    }
    ~Derived1() {
        Console.WriteLine("Inside The Derived1 Destructor");
    }
}

class Derived2: Base {
    public Derived2() {
        Console.WriteLine("Inside The Derived2 Constructor");
    }
    ~Derived2() {
        Console.WriteLine("Inside The Derived2 Destructor");
    }
}

class Class1
{
    protected int a, b;
    public Class1() {
        a = 0;
        b = 0;
        Derived1 obj=new Derived1();
        Console.WriteLine("Inside base class default constructor");
    }
    public Class1(int a, int b, Derived1) {
        this.a = a;
        this.b = b;
        Derived1 obj=new Derived1();
        Console.WriteLine("Inside base class parameterized constructor");
    }
}
class Class2: Class1 {
    int c;
    public Class2(int a, int b, int c): base(a, b, Derived1) {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}
</code>```

I.e., by base(a, b, Derived1) I want to pass from Class2 constructor/definition, what type Class1 will new, whether it is Derived1 or Derived2.

Hope that I've made this convoluted/complicated question clear.

答:
You can also use the typeof keyword used below:

```<code>class Class2 : Class1
{
    int c;
    public Class2(int a, int b, int c) : base(a, b, typeof(Derived1))
    {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}

void Main()
{
    Class2 c2 = new Class2(1,2, 3);
}
</code>```

Or write more generic form using C# generics like this:

```<code>class Class1<T> where T: new()
{
    protected int a, b;
    public Class1()
    {
        a = 0;
        b = 0;
        T obj = new T();
        Console.WriteLine("Inside base class parameterized constructor, with {0}", typeof (T));
    }

    public Class1(int a, int b)
    {
        this.a = a;
        this.b = b;
        T obj = new T();
        Console.WriteLine("Inside base class parameterized constructor");
    }
}

class Class2<T> : Class1<T> where T: new()
{
    int c;
    public Class2(int a, int b, int c) : base(a, b)
    {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}

void Main()
{
    var c2 = new Class2<Derived1>(1, 2, 3);
    Console.WriteLine("-----");
    var c2_2 = new Class2<Derived2>(1, 2, 3);
}
</code>```

And the output will be:

```<code>Inside Base Constructor
Inside The Derived1 Constructor
Inside base class parameterized constructor, with Derived1
Inside derived class parametrized constructor
-----
Inside Base Constructor
Inside The Derived2 Constructor
Inside base class parameterized constructor, with Derived2
Inside derived class parametrized constructor
</code>```

I hope this help.

Body:
Well, this is a convoluted/complicated question, and here it goes:

I have two pair of classes

Derived class inherits from the Base class (class Derived: Base{})

Class2 inherits from Class1 (class Class2: Class1 {})

My current Class1 constructor has:

Derived d = new Derived();

What I want is that the type Derived is passed from the Class2 constructor into its base (Class1) constructor. Is that possible?

More complete code:

class Base
{
    public Base() {
        Console.WriteLine("Inside Base Constructor");
    }
    ~Base() {
        Console.WriteLine("Inside Base Destructor");
    }
}

class Derived1: Base {
    public Derived1() {
        Console.WriteLine("Inside The Derived1 Constructor");
    }
    ~Derived1() {
        Console.WriteLine("Inside The Derived1 Destructor");
    }
}

class Derived2: Base {
    public Derived2() {
        Console.WriteLine("Inside The Derived2 Constructor");
    }
    ~Derived2() {
        Console.WriteLine("Inside The Derived2 Destructor");
    }
}

class Class1
{
    protected int a, b;
    public Class1() {
        a = 0;
        b = 0;
        Derived1 obj=new Derived1();
        Console.WriteLine("Inside base class default constructor");
    }
    public Class1(int a, int b, Derived1) {
        this.a = a;
        this.b = b;
        Derived1 obj=new Derived1();
        Console.WriteLine("Inside base class parameterized constructor");
    }
}
class Class2: Class1 {
    int c;
    public Class2(int a, int b, int c): base(a, b, Derived1) {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}

I.e., by base(a, b, Derived1) I want to pass from Class2 constructor/definition, what type Class1 will new, whether it is Derived1 or Derived2.

Hope that I've made this convoluted/complicated question clear.

Body:
You can also use the typeof keyword used below:

class Class2 : Class1
{
    int c;
    public Class2(int a, int b, int c) : base(a, b, typeof(Derived1))
    {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}

void Main()
{
    Class2 c2 = new Class2(1,2, 3);
}

Or write more generic form using C# generics like this:

class Class1<T> where T: new()
{
    protected int a, b;
    public Class1()
    {
        a = 0;
        b = 0;
        T obj = new T();
        Console.WriteLine("Inside base class parameterized constructor, with {0}", typeof (T));
    }

    public Class1(int a, int b)
    {
        this.a = a;
        this.b = b;
        T obj = new T();
        Console.WriteLine("Inside base class parameterized constructor");
    }
}

class Class2<T> : Class1<T> where T: new()
{
    int c;
    public Class2(int a, int b, int c) : base(a, b)
    {
        this.c = c;
        Console.WriteLine("Inside derived class parametrized constructor");
    }
}

void Main()
{
    var c2 = new Class2<Derived1>(1, 2, 3);
    Console.WriteLine("-----");
    var c2_2 = new Class2<Derived2>(1, 2, 3);
}

And the output will be:

Inside Base Constructor
Inside The Derived1 Constructor
Inside base class parameterized constructor, with Derived1
Inside derived class parametrized constructor
-----
Inside Base Constructor
Inside The Derived2 Constructor
Inside base class parameterized constructor, with Derived2
Inside derived class parametrized constructor

I hope this help.


问:
Lightbox analog for HTML data
I need some analog of LightBox for HTML loaded via AJAX. And it should work in IE6 :)

I believe there is a bunch of plugins. I prefer most crossbrowser and easiest in setting. So share your expirience, please!

I'll store them here, for our children (I'll add more from comments):

http://fancybox.net/ (IE6 works)

http://flowplayer.org/tools/overlay/index.html (IE6 didn't work)

http://colorpowered.com/colorbox/ (IE6 works)

http://jquery.com/demo/thickbox/ (IE6+)

答:
A project I worked on about 7 months ago used fancybox for displaying HTML loaded by AJAX.  It worked well, and we never really had any complaints with it.

Fortunately, we didn't have to support IE6.

Title: Lightbox analog for HTML data


问:
How do I make my button which is fixed at the bottom of a layout scroll, once the recyclerview on top grows in size
I have a very basic yet difficult issue where I have a button fixed at the bottom of the view,  but below recyclerview container. Once the container size grows, I want the button to go below the recyclerview (scrollable) instead of being fixed at the bottom of the view.Is there a way to achieve this?

I have looked online for a couple of ideas but didn't find anything quite like it yet.

i am basically using

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="@color/white"
    android:clickable="false">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/cl_root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipChildren="false">

        <LinearLayout
            android:id="@+id/activity_g"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:elevation="0dp">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    app:subtitleTextColor="@color/white"
                    app:titleTextAppearance="@style/Toolbar.TitleText"
                    app:titleTextColor="@color/white">

                    <TextView
                        android:id="@+id/nav_back_btn"
                        style="@style/Body1RegLeftBlack"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="20dp"
                        android:layout_marginStart="@dimen/activity_horizontal_margin"
                        android:gravity="center_horizontal"
                        android:background="@drawable/ic_backarrow" />

                    <TextView
                        android:id="@+id/g_main_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="18dp"
                        android:layout_marginTop="15dp"
                        android:letterSpacing="0.01"
                        android:gravity="center_horizontal"
                        android:text="@string/g"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="#de000000"
                        android:textSize="20sp"
                        android:textStyle="normal"

                        />

                </android.support.v7.widget.Toolbar>

            </android.support.design.widget.AppBarLayout>

            <android.support.v4.widget.NestedScrollView
                android:id="@+id/info_scrollview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:id="@+id/infoContainer"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    android:clickable="false"
                    android:orientation="vertical">

                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="30dp">

                        <TextView
                            android:id="@+id/info_location"
                            style="@style/Headline2LeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="@dimen/activity_horizontal_margin"
                            android:textAppearance="@style/TextAppearance.Text.Chronicle"
                            android:textSize="28sp"
                            tools:text="@string/five_thirty_fifth_ave" />

                        <TextView
                            style="@style/Body1RegRightRed"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignBaseline="@+id/info_location"
                            android:layout_alignParentEnd="true"
                            android:layout_marginEnd="@dimen/activity_horizontal_margin"
                            android:layout_toEndOf="@+id/info_location"
                            android:text="@string/location_change"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:visibility="gone" />
                    </RelativeLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:layout_marginTop="44dp"
                        android:gravity="center_vertical"
                        android:weightSum="2">

                        <TextView
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_start_date"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_start_date" />

                        <TextView
                            style="@style/Body1RegRightBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginEnd="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_start_time"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_start_time" />
                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/registerUserSeparatorColor" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:gravity="center_vertical"
                        android:weightSum="2">

                        <TextView
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_end_date"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:visibility="invisible"
                            android:text="@string/g_end_date" />

                        <TextView
                            style="@style/Body1RegRightBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginEnd="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_end_time"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_end_time" />
                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/registerUserSeparatorColor" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="28dp"
                        android:letterSpacing="0.01"
                        android:lineSpacingExtra="4sp"
                        android:paddingTop="30dp"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="@color/black"
                        android:textSize="20sp"
                        android:textStyle="normal"
                        android:text="@string/g" />

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/g_item_list"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:overScrollMode="never"
                        android:divider="@null"
                        tools:listitem="@layout/item_g"/>

                    <TextView
                        style="@style/Body1RegLeftRed"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16sp"
                        android:layout_marginTop="20dp"
                        android:id="@+id/add_g"
                        android:lineHeight="22sp"
                        android:text="@string/add_g"
                        android:textSize="16sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="58dp"
                        android:letterSpacing="0.01"
                        android:lineSpacingExtra="4sp"
                        android:visibility="invisible"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="@color/black"
                        android:textSize="20sp"
                        android:textStyle="normal"
                        android:text="@string/arrival_notifications" />

                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:visibility="gone"
                        android:id="@+id/text_message_container"
                        android:layout_marginStart="16dp">

                        <TextView
                            android:id="@+id/text_message"
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="11dp"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/text_message" />

                        <TextView
                            style="@style/Body2RegLeftGrey"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/text_message"
                            android:layout_marginTop="2dp"
                            android:id="@+id/tap_phone_number_text"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/tap_to_add_a_phone_number" />

                        <android.support.v7.widget.SwitchCompat
                            android:id="@+id/text_message_switch"
                            style="@style/Color1SwitchStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignParentEnd="true"
                            android:layout_centerVertical="true"
                            android:layout_marginEnd="16dp" />
                    </RelativeLayout>
                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_marginStart="16dp"
                        android:visibility="gone"
                        android:layout_marginTop="11dp"
                        android:background="@color/settingsSeparatorLineColor" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="16sp"
                        android:layout_marginTop="100dp"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textStyle="normal"

                        android:letterSpacing="0.07"
                        android:lineSpacingExtra="0sp"
                        android:layout_gravity="center"
                        android:layout_marginBottom="30dp"
                        android:id="@+id/submit_btn"
                        android:text="@string/submit_list"
                        />

                </LinearLayout>
            </android.support.v4.widget.NestedScrollView>
        </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

The problem above is, the submit_list btn doesnt stay fixed, if the recyclerview grows but theres still enough space to spare in the view.

I want to make it such that the button stays fixed and doesnt scroll UNTIL the size of the recyclerview goes beyond a certain limit from the bottom(not visible on the screen anymore), after which the button scrolls relative to the last item of the recyclerview and not aligned to the bottom anymore. any ideas how to go about it?

To give visual examples:

As you can see, initial screen has submit button aligned to the bottom and the rest of the content in place. As I add more users:

It still stays at the bottom since the recyclerview items are still within screen
 now, aqs soon as i add one more item, causing the list to scroll up :

As seen I want it to go below the recyclerview instead of stay fixed at bottom of the screen (the above screenshots are from ios where it works), was wondering if we can do the same for android?

答:
You can achieve this using ConstraintLayout

SAMPLE CODE

layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        app:layout_constraintBottom_toTopOf="@+id/btnBottom"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnBottom"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="12dp"
        android:layout_marginRight="20dp"
        android:padding="12dp"
        android:text="Continue"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:textColor="@android:color/white"
        app:backgroundTint="@color/colorPrimary" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Activity code

```<code>public class MainActivity extends AppCompatActivity {

    RecyclerView myRecyclerView;
    ArrayList<String> arrayList = new ArrayList<>();
    DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myRecyclerView = findViewById(R.id.myRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        myRecyclerView.setHasFixedSize(true);

        addDataToList();

        adapter = new DataAdapter(this, arrayList);
        myRecyclerView.setAdapter(adapter);

    }

    private void addDataToList() {
        for (int i = 0; i < 5; i++) {
            arrayList.add("NILU_PILU :-> " + i);
        }
    }

}
</code>```

DataAdapter class

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    ArrayList<String> arrayList = new ArrayList<>();
    private Context mContext;

    public DataAdapter(Context mContext, ArrayList<String> arrayList) {
        this.mContext = mContext;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.aaa, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.tvText.setText(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvText;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvText = itemView.findViewById(R.id.tvText);
        }
    }
}
</code>```

OUTPUTS

Body:
I have a very basic yet difficult issue where I have a button fixed at the bottom of the view,  but below recyclerview container. Once the container size grows, I want the button to go below the recyclerview (scrollable) instead of being fixed at the bottom of the view.Is there a way to achieve this?

I have looked online for a couple of ideas but didn't find anything quite like it yet.

i am basically using

 <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="@color/white"
    android:clickable="false">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/cl_root_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipChildren="false">

        <LinearLayout
            android:id="@+id/activity_g"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:elevation="0dp">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    app:subtitleTextColor="@color/white"
                    app:titleTextAppearance="@style/Toolbar.TitleText"
                    app:titleTextColor="@color/white">

                    <TextView
                        android:id="@+id/nav_back_btn"
                        style="@style/Body1RegLeftBlack"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="20dp"
                        android:layout_marginStart="@dimen/activity_horizontal_margin"
                        android:gravity="center_horizontal"
                        android:background="@drawable/ic_backarrow" />

                    <TextView
                        android:id="@+id/g_main_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="18dp"
                        android:layout_marginTop="15dp"
                        android:letterSpacing="0.01"
                        android:gravity="center_horizontal"
                        android:text="@string/g"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="#de000000"
                        android:textSize="20sp"
                        android:textStyle="normal"

                        />

                </android.support.v7.widget.Toolbar>

            </android.support.design.widget.AppBarLayout>

            <android.support.v4.widget.NestedScrollView
                android:id="@+id/info_scrollview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:id="@+id/infoContainer"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/white"
                    android:clickable="false"
                    android:orientation="vertical">

                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="30dp">

                        <TextView
                            android:id="@+id/info_location"
                            style="@style/Headline2LeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="@dimen/activity_horizontal_margin"
                            android:textAppearance="@style/TextAppearance.Text.Chronicle"
                            android:textSize="28sp"
                            tools:text="@string/five_thirty_fifth_ave" />

                        <TextView
                            style="@style/Body1RegRightRed"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignBaseline="@+id/info_location"
                            android:layout_alignParentEnd="true"
                            android:layout_marginEnd="@dimen/activity_horizontal_margin"
                            android:layout_toEndOf="@+id/info_location"
                            android:text="@string/location_change"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:visibility="gone" />
                    </RelativeLayout>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:layout_marginTop="44dp"
                        android:gravity="center_vertical"
                        android:weightSum="2">

                        <TextView
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_start_date"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_start_date" />

                        <TextView
                            style="@style/Body1RegRightBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginEnd="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_start_time"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_start_time" />
                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/registerUserSeparatorColor" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="48dp"
                        android:gravity="center_vertical"
                        android:weightSum="2">

                        <TextView
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginStart="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_end_date"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:visibility="invisible"
                            android:text="@string/g_end_date" />

                        <TextView
                            style="@style/Body1RegRightBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginEnd="16dp"
                            android:layout_weight="1"
                            android:id="@+id/g_end_time"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/g_end_time" />
                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@color/registerUserSeparatorColor" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="28dp"
                        android:letterSpacing="0.01"
                        android:lineSpacingExtra="4sp"
                        android:paddingTop="30dp"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="@color/black"
                        android:textSize="20sp"
                        android:textStyle="normal"
                        android:text="@string/g" />

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/g_item_list"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:overScrollMode="never"
                        android:divider="@null"
                        tools:listitem="@layout/item_g"/>

                    <TextView
                        style="@style/Body1RegLeftRed"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16sp"
                        android:layout_marginTop="20dp"
                        android:id="@+id/add_g"
                        android:lineHeight="22sp"
                        android:text="@string/add_g"
                        android:textSize="16sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginStart="16dp"
                        android:layout_marginTop="58dp"
                        android:letterSpacing="0.01"
                        android:lineSpacingExtra="4sp"
                        android:visibility="invisible"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textColor="@color/black"
                        android:textSize="20sp"
                        android:textStyle="normal"
                        android:text="@string/arrival_notifications" />

                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:visibility="gone"
                        android:id="@+id/text_message_container"
                        android:layout_marginStart="16dp">

                        <TextView
                            android:id="@+id/text_message"
                            style="@style/Body1RegLeftBlack"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="11dp"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/text_message" />

                        <TextView
                            style="@style/Body2RegLeftGrey"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@+id/text_message"
                            android:layout_marginTop="2dp"
                            android:id="@+id/tap_phone_number_text"
                            android:textAppearance="@style/TextAppearance.Text.Roboto.Regular"
                            android:text="@string/tap_to_add_a_phone_number" />

                        <android.support.v7.widget.SwitchCompat
                            android:id="@+id/text_message_switch"
                            style="@style/Color1SwitchStyle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_alignParentEnd="true"
                            android:layout_centerVertical="true"
                            android:layout_marginEnd="16dp" />
                    </RelativeLayout>
                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_marginStart="16dp"
                        android:visibility="gone"
                        android:layout_marginTop="11dp"
                        android:background="@color/settingsSeparatorLineColor" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="16sp"
                        android:layout_marginTop="100dp"
                        android:textAppearance="@style/TextAppearance.Text.Roboto.Medium"
                        android:textStyle="normal"

                        android:letterSpacing="0.07"
                        android:lineSpacingExtra="0sp"
                        android:layout_gravity="center"
                        android:layout_marginBottom="30dp"
                        android:id="@+id/submit_btn"
                        android:text="@string/submit_list"
                        />

                </LinearLayout>
            </android.support.v4.widget.NestedScrollView>
        </LinearLayout>
    </android.support.design.widget.CoordinatorLayout>
</android.support.design.widget.CoordinatorLayout>

The problem above is, the submit_list btn doesnt stay fixed, if the recyclerview grows but theres still enough space to spare in the view.

I want to make it such that the button stays fixed and doesnt scroll UNTIL the size of the recyclerview goes beyond a certain limit from the bottom(not visible on the screen anymore), after which the button scrolls relative to the last item of the recyclerview and not aligned to the bottom anymore. any ideas how to go about it?

To give visual examples:

As you can see, initial screen has submit button aligned to the bottom and the rest of the content in place. As I add more users:

It still stays at the bottom since the recyclerview items are still within screen
 now, aqs soon as i add one more item, causing the list to scroll up :

As seen I want it to go below the recyclerview instead of stay fixed at bottom of the screen (the above screenshots are from ios where it works), was wondering if we can do the same for android?

Body:
You can achieve this using ConstraintLayout

SAMPLE CODE

layout file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/myRecyclerView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        app:layout_constraintBottom_toTopOf="@+id/btnBottom"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btnBottom"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="12dp"
        android:layout_marginRight="20dp"
        android:padding="12dp"
        android:text="Continue"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:textColor="@android:color/white"
        app:backgroundTint="@color/colorPrimary" />

</androidx.constraintlayout.widget.ConstraintLayout>

Activity code

public class MainActivity extends AppCompatActivity {

    RecyclerView myRecyclerView;
    ArrayList<String> arrayList = new ArrayList<>();
    DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myRecyclerView = findViewById(R.id.myRecyclerView);
        myRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        myRecyclerView.setHasFixedSize(true);

        addDataToList();

        adapter = new DataAdapter(this, arrayList);
        myRecyclerView.setAdapter(adapter);

    }

    private void addDataToList() {
        for (int i = 0; i < 5; i++) {
            arrayList.add("NILU_PILU :-> " + i);
        }
    }

}

DataAdapter class

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    ArrayList<String> arrayList = new ArrayList<>();
    private Context mContext;

    public DataAdapter(Context mContext, ArrayList<String> arrayList) {
        this.mContext = mContext;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.aaa, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.tvText.setText(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvText;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvText = itemView.findViewById(R.id.tvText);
        }
    }
}

OUTPUTS


问:
Targeting first visible element with pure CSS
I am wondering if it is possible to transpose the following into pure CSS.

```<code>$('.child:visible:first').css({'border-top':'1px solid #cccccc','border-bottom':'1px solid #cccccc'});
</code>```

I cannot seem to find a solution.

答:
I had a case when either one of the 2 top buttons of a list of buttons was visible, applying the style to both solved it:</p>

```<code>.bt:nth-child(1), .bt:nth-child(2) {
   ...
}
</code>```

Body:
I am wondering if it is possible to transpose the following into pure CSS.

$('.child:visible:first').css({'border-top':'1px solid #cccccc','border-bottom':'1px solid #cccccc'});

I cannot seem to find a solution.

Body:
I had a case when either one of the 2 top buttons of a list of buttons was visible, applying the style to both solved it:

.bt:nth-child(1), .bt:nth-child(2) {
   ...
}


问:
socket io Possible EventEmitter memory leak detected
I want to remove Listener to avoid this problem in socket io once the event is done.

I am getting this error

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit

I have tried using removeAllListeners / removeListener / off but none of them work.

```<code>const io = socket(httpServer);

(async () => {
  await io.on('connection', async function (client) {

       // Some Code //

        await client.emit('message', "Done")
        io.removeAllListeners("connection")
    })
})
</code>```

答:
I had the same issue, I am able to resolve the issue by using the below code,

```<code>mqttClient.off('message', mqttClient.listeners("message")[0])
</code>```

it will remove the required listener form the event.

mqttClient.listeners("message") : I will return the array of listner attached to the "message" event.

You can use removeListner() as well
Here I have used MQTT case. you can follow this process for socket io as well.

Body:
I want to remove Listener to avoid this problem in socket io once the event is done.

I am getting this error

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 connection listeners added. Use emitter.setMaxListeners() to increase limit

I have tried using removeAllListeners / removeListener / off but none of them work.

const io = socket(httpServer);

(async () => {
  await io.on('connection', async function (client) {

       // Some Code //

        await client.emit('message', "Done")
        io.removeAllListeners("connection")
    })
})

Body:
I had the same issue, I am able to resolve the issue by using the below code,

mqttClient.off('message', mqttClient.listeners("message")[0])

it will remove the required listener form the event.

mqttClient.listeners("message") : I will return the array of listner attached to the "message" event.

You can use removeListner() as well
Here I have used MQTT case. you can follow this process for socket io as well.


问:
How to determine which window was moved/resized from WM_EXITSIZEMOVE message?
I've been processing all the numerous individual WM_MOVE, WM_SIZING, and WM_SIZE messages for a multiple-GUI/window application, but I've just learned of the WM_EXITSIZEMOVE message and would like to use it if it lets me avoid all those intermediate messages. But since no parameters are provided by that message, how can I determine which GUI/window has been moved or resized? Or is my thinking incorrect?</p>

答:
All of the messages you reference are only sent to the window that was affected by that operation, which is why there are no parameters provided that identify the window. If the window receives it, it is the window that was just moved, sized, or is exiting size/move.

In other words, if you have windows A and B, and B is resized or moved, then it will receive the messages and window A will not.


问:
Is there any way to make a method check if there is existing unique data in database?
My goal is to create a method in android studio that checks if there is an existing username (which is unique) in my database. But my problem is, I have no idea why my implemented code does not work and returns an error in logcat. The app does not crash however.

In fact, I have tried implementing 2 different methods. The first one is to put all selected existing usernames from the database into an arraylist and use the ArrayList.contains(username) method to see if the arraylist contains the similar username.

The other method I have tried using is to select a username in the database that is the same as my inputted username and see if they are the same. (Might sound confusing but I will show you the code).

MainActivity.java

```<code>DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 1);

UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

            if (mydb.existingUsername(tvUsername.getText().toString()) == false) {
                mydb.insertTable(userInfo);
                Intent intent = new Intent(MainActivity.this, Lobby.class);
                intent.putExtra("username", userInfo.getUsername());
                startActivity(intent);
            } else {
                // some code
            }
</code>```

DatabaseHelper.java

```<code>@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(" +
            COLUMN_ID + " integer primary key autoincrement, " +
            COLUMN_USERNAME + " text not null unique, " +
            COLUMN_PASSWORD + " text)");
}

// Method 1 (Commented out)
public ArrayList<UserInfo> existingUsername() {
    UserInfo userInfo;
    ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        userInfo = new UserInfo(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
        userArray.add(userInfo);
        cursor.moveToNext();
    }
    return userArray;
}

// Method 2 (Currently in use)
public boolean existingUsername(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?", new String[]{username});
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        if (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username) {
            return true;
        } else {
            cursor.moveToNext();
        }
    }
    return false;
}
</code>```

Expected results:

I want it to check if the "username" I put already exists in the database or not. If no, run the "if" statement and go to the next activity. If yes, run the "else" statement.

Actual results:

However, it turns out the code keeps running the "if" statement and goes the next activity whether the inputted username already exists in the database or not. If the inputted username already exists in the database, it gives me this error in the logcat.

Logcat

```<code>019-06-01 14:06:19.774 27199-27199/com.karimun.myapplication E/SQLiteDatabase: Error inserting password=232323 username=Igor
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.username (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
    at com.karimun.myapplication.DatabaseHelper.insertTable(DatabaseHelper.java:70)
    at com.karimun.myapplication.MainActivity$2.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

答:
You have a wrong comparison

```<code>cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username
</code>```

This cause your program continue inserting even when the username already exists.

Change to equals() for correct string comparison. Do not use == to compare String (and objects generally)

```<code>username.equals(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))
</code>```

if username is not null

or

```<code>Objects.equals(username, cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))
</code>```

Body:
My goal is to create a method in android studio that checks if there is an existing username (which is unique) in my database. But my problem is, I have no idea why my implemented code does not work and returns an error in logcat. The app does not crash however.

In fact, I have tried implementing 2 different methods. The first one is to put all selected existing usernames from the database into an arraylist and use the ArrayList.contains(username) method to see if the arraylist contains the similar username.

The other method I have tried using is to select a username in the database that is the same as my inputted username and see if they are the same. (Might sound confusing but I will show you the code).

MainActivity.java

DatabaseHelper mydb = new DatabaseHelper(this, "MyUsers", null, 1);

UserInfo userInfo = new UserInfo(tvUsername.getText().toString(), etEnterPassword.getText().toString());

            if (mydb.existingUsername(tvUsername.getText().toString()) == false) {
                mydb.insertTable(userInfo);
                Intent intent = new Intent(MainActivity.this, Lobby.class);
                intent.putExtra("username", userInfo.getUsername());
                startActivity(intent);
            } else {
                // some code
            }

DatabaseHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + "(" +
            COLUMN_ID + " integer primary key autoincrement, " +
            COLUMN_USERNAME + " text not null unique, " +
            COLUMN_PASSWORD + " text)");
}

// Method 1 (Commented out)
public ArrayList<UserInfo> existingUsername() {
    UserInfo userInfo;
    ArrayList<UserInfo> userArray = new ArrayList<UserInfo>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        userInfo = new UserInfo(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)));
        userArray.add(userInfo);
        cursor.moveToNext();
    }
    return userArray;
}

// Method 2 (Currently in use)
public boolean existingUsername(String username) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT " + COLUMN_USERNAME + " FROM " + TABLE_NAME + " WHERE " + COLUMN_USERNAME + " = ?", new String[]{username});
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        if (cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username) {
            return true;
        } else {
            cursor.moveToNext();
        }
    }
    return false;
}

Expected results:

I want it to check if the "username" I put already exists in the database or not. If no, run the "if" statement and go to the next activity. If yes, run the "else" statement.

Actual results:

However, it turns out the code keeps running the "if" statement and goes the next activity whether the inputted username already exists in the database or not. If the inputted username already exists in the database, it gives me this error in the logcat.

Logcat

019-06-01 14:06:19.774 27199-27199/com.karimun.myapplication E/SQLiteDatabase: Error inserting password=232323 username=Igor
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: users.username (code 2067 SQLITE_CONSTRAINT_UNIQUE)
    at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
    at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
    at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
    at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
    at com.karimun.myapplication.DatabaseHelper.insertTable(DatabaseHelper.java:70)
    at com.karimun.myapplication.MainActivity$2.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:6597)
    at android.view.View.performClickInternal(View.java:6574)
    at android.view.View.access$3100(View.java:778)
    at android.view.View$PerformClick.run(View.java:25885)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Body:
You have a wrong comparison

cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)) == username

This cause your program continue inserting even when the username already exists.

Change to equals() for correct string comparison. Do not use == to compare String (and objects generally)

username.equals(cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))

if username is not null

or

Objects.equals(username, cursor.getString(cursor.getColumnIndex(COLUMN_USERNAME)))