问:
Determine if a given year is a leap year
UPDATE The problem I was trying to solve required a bit more than the Date implementation, as it required a method to take into account both the post-1752 Gregorian and the pre-1752 Julian calendars' differing definitions of a leap year.

The following is my solution, which passed all my RSpecs and is a considerable improvement on the nested conditional I started with:

```<code>def leap_year?(year)

  gregorian_year = true if year >= 1752
  julian_year = true if year < 1752

  gregorian_test = true if year % 4 == 0 && year % 100 != 0 || year % 400 == 0
  julian_test = true if year % 4 == 0

  case
  when gregorian_year && gregorian_test
    true
  when julian_year && julian_test
    true
  else
    false
  end
end
</code>```

ORIGINAL QUESTION

I wrote a simple, ugly nested conditional to achieve the following:

To achieve the following:

Return "true" if the year meets the following conditions:

Is divisible by four

AND is not a century year (e.g.) 1900

UNLESS it is divisible by 400 (e.g. 400, 800, 2000)

I wrote an ugly nested conditional:

```<code>if year % 4 == 0
  puts "Divisible by four"
  if year % 100 == 0
    puts "Century year"
    if year % 400 == 0
      puts "Quad-century year, leap year"
      true
    else
      "Not a Quad-century year, not a leap year"
      false
    end
  else
    puts "Not a century year, leap year"
    true
  end
else
  puts "Not divisible by four: not a leap year."
  false
end
</code>```

I tried to achieve the same with a case conditional, but it fails to detect the number 2016 as leap year:

```<code>case year
when (year % 4 == 0 && year % 100 != 0)
  true
when year % 400
  true
when year % 4 != 0
  false
end
</code>```

Two questions:

What am I doing wrong in my case conditional?

Is there a better way to achieve this?

答:
Remove the year from case year if your when arguments are all boolean:

```<code>  case
  when (year % 4 == 0 && year % 100 != 0)
    true
  when year % 400 == 0
    true
  else
    false
  end
</code>```

You can check it works :

```<code>def is_leap?(year)
  case
  when (year % 4 == 0 && year % 100 != 0)
    true
  when year % 400 == 0
    true
  else
    false
  end
end

require 'date'

p (0..2050).all?{|y| Date.leap?(y) == is_leap?(y)}
# true
</code>```

This variant might be a bit more readable :

```<code>def is_leap?(year)
  case
  when year % 400 == 0
    true
  when year % 100 == 0
    false
  when year % 4 == 0
    true
  else
    false
  end
end
</code>```

Finally, you could just write a single expression without any if or case :

```<code>year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
</code>```

Body:
UPDATE The problem I was trying to solve required a bit more than the Date implementation, as it required a method to take into account both the post-1752 Gregorian and the pre-1752 Julian calendars' differing definitions of a leap year.

The following is my solution, which passed all my RSpecs and is a considerable improvement on the nested conditional I started with:

def leap_year?(year)

  gregorian_year = true if year >= 1752
  julian_year = true if year < 1752

  gregorian_test = true if year % 4 == 0 && year % 100 != 0 || year % 400 == 0
  julian_test = true if year % 4 == 0

  case
  when gregorian_year && gregorian_test
    true
  when julian_year && julian_test
    true
  else
    false
  end
end

ORIGINAL QUESTION

I wrote a simple, ugly nested conditional to achieve the following:

To achieve the following:

Return "true" if the year meets the following conditions:

Is divisible by four

AND is not a century year (e.g.) 1900

UNLESS it is divisible by 400 (e.g. 400, 800, 2000)

I wrote an ugly nested conditional:

if year % 4 == 0
  puts "Divisible by four"
  if year % 100 == 0
    puts "Century year"
    if year % 400 == 0
      puts "Quad-century year, leap year"
      true
    else
      "Not a Quad-century year, not a leap year"
      false
    end
  else
    puts "Not a century year, leap year"
    true
  end
else
  puts "Not divisible by four: not a leap year."
  false
end

I tried to achieve the same with a case conditional, but it fails to detect the number 2016 as leap year:

case year
when (year % 4 == 0 && year % 100 != 0)
  true
when year % 400
  true
when year % 4 != 0
  false
end

Two questions:

What am I doing wrong in my case conditional?

Is there a better way to achieve this?

Body:
Remove the year from case year if your when arguments are all boolean:

  case
  when (year % 4 == 0 && year % 100 != 0)
    true
  when year % 400 == 0
    true
  else
    false
  end

You can check it works :

def is_leap?(year)
  case
  when (year % 4 == 0 && year % 100 != 0)
    true
  when year % 400 == 0
    true
  else
    false
  end
end

require 'date'

p (0..2050).all?{|y| Date.leap?(y) == is_leap?(y)}
# true

This variant might be a bit more readable :

def is_leap?(year)
  case
  when year % 400 == 0
    true
  when year % 100 == 0
    false
  when year % 4 == 0
    true
  else
    false
  end
end

Finally, you could just write a single expression without any if or case :

year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)


来源: stackexchange

问:
Can’t make application into type application
script error: Can’t make application into type application. (-1700)
Bad parameter data was detected or there was a failure while performing a coercion. (Line 17, Character 28). I think it may be a problem with my dialog popup or script the line below.</p>

```<code>using terms from application 'Messages'
  on message sent theMessage with eventDescription
    display dialog (eventDescription)
  end message sent

  on message received theText from theBuddy with eventDescription
  end message received

  on chat room message received theText with eventDescription from theBuddy for theChat
    set getname to name of theBuddy as text
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try
    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end chat room message received

  on active chat message received theText with eventDescription from theBuddy for theChat
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try

    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end active chat message received

  on addressed message received theText with eventDescription from theBuddy for theChat
    set getname to name of theBuddy as text
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try
    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end addressed message received

  on received text invitation with eventDescription
  end received text invitation

  on received audio invitation theText from theBuddy for theChat with eventDescription
  end received audio invitation

  on received video invitation theText from theBuddy for theChat with eventDescription
  end received video invitation

  on buddy authorization requested with eventDescription
  end buddy authorization requested

  on addressed chat room message received with eventDescription
  end addressed chat room message received

  on login finished with eventDescription
  end login finished

  on logout finished with eventDescription
  end logout finished

  on buddy became available with eventDescription
  end buddy became available

  on buddy became unavailable with eventDescription
  end buddy became unavailable

  on received file transfer invitation theFileTransfer with eventDescription
  end received file transfer invitation

  on av chat started with eventDescription
  end av chat started

  on av chat ended with eventDescription
  end av chat ended

  on completed file transfer with eventDescription
  end completed file transfer

end using terms from
</code>```

答:
I simply changed 'Messages' to "Messages" and that allowed me to compile, perhaps this will help you.

Change the first line from:

```<code>using terms from application 'Messages'
</code>```

To:

```<code>using terms from application "Messages"
</code>```

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
script error: Can’t make application into type application. (-1700)
Bad parameter data was detected or there was a failure while performing a coercion. (Line 17, Character 28). I think it may be a problem with my dialog popup or script the line below.

using terms from application 'Messages'
  on message sent theMessage with eventDescription
    display dialog (eventDescription)
  end message sent

  on message received theText from theBuddy with eventDescription
  end message received

  on chat room message received theText with eventDescription from theBuddy for theChat
    set getname to name of theBuddy as text
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try
    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end chat room message received

  on active chat message received theText with eventDescription from theBuddy for theChat
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try

    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end active chat message received

  on addressed message received theText with eventDescription from theBuddy for theChat
    set getname to name of theBuddy as text
    try
      set myresult to get id of theBuddy
    on error errMsg
      set errMsgParts to splitText(errMsg, "\"")
      set errCount to count of errMsgParts
      set myresult to item (errCount - 1) of errMsgParts
    end try
    display dialog ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
    do shell script ("/Home/Peter/repos/imessage/message '" & theText & getname & myresult & "'")
  end addressed message received

  on received text invitation with eventDescription
  end received text invitation

  on received audio invitation theText from theBuddy for theChat with eventDescription
  end received audio invitation

  on received video invitation theText from theBuddy for theChat with eventDescription
  end received video invitation

  on buddy authorization requested with eventDescription
  end buddy authorization requested

  on addressed chat room message received with eventDescription
  end addressed chat room message received

  on login finished with eventDescription
  end login finished

  on logout finished with eventDescription
  end logout finished

  on buddy became available with eventDescription
  end buddy became available

  on buddy became unavailable with eventDescription
  end buddy became unavailable

  on received file transfer invitation theFileTransfer with eventDescription
  end received file transfer invitation

  on av chat started with eventDescription
  end av chat started

  on av chat ended with eventDescription
  end av chat ended

  on completed file transfer with eventDescription
  end completed file transfer

end using terms from

Body:
I simply changed 'Messages' to "Messages" and that allowed me to compile, perhaps this will help you.

Change the first line from:

using terms from application 'Messages'

To:

using terms from application "Messages"

Hope this helps!


问:
python prints folders and sub folders when only folders needed in python
I am making a program that prints all the folders over 90 days in python.

Here is my code:

```<code>import os
from datetime import date
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

old_dirs = []
today = date.today()

home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to
scan from: ")
path = path.encode('utf-8')

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
</code>```

The problem is that this prints all folders, but it also prints the sub folders of the folders, which I don't need. How can I change the code so that it only prints the folders?

答:
As per the documentation of os.walk():

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; [...]

```<code>for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
    del dirs[:]
</code>```

Body:
I am making a program that prints all the folders over 90 days in python.

Here is my code:

import os
from datetime import date
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog

old_dirs = []
today = date.today()

home1 = os.path.join(os.environ["HOMEPATH"], "Desktop")
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

root = Tk()
root.withdraw()
path = tkFileDialog.askdirectory(initialdir=desktop, title="Select folder to
scan from: ")
path = path.encode('utf-8')

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)

The problem is that this prints all folders, but it also prints the sub folders of the folders, which I don't need. How can I change the code so that it only prints the folders?

Body:
As per the documentation of os.walk():

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; [...]

for root, dirs, files in os.walk(path):
    for name in dirs:
        filedate = date.fromtimestamp(os.path.getmtime(os.path.join(root, name)))
        if (today - filedate).days > 90:
            print name
            old_dirs.append(name)
    del dirs[:]


答:
If you would like to determine if a given year is a leap year, that has already been implemented for you in the Date class as Date#leap?:

```<code>Date.leap?(2000)
#=> true

# Or, alternatively:

Date.gregorian_leap?(1900)
#=> false

Date.julian_leap?(1900)
#=> true
</code>```

More info in the Ruby documentation: Date#leap?

If you would like to build it yourself regardless, this should work:

```<code>def leap_year?(year)
  return false unless year % 4 == 0
  return true unless year % 100 == 0
  year % 400 == 0
end

leap_year?(2016)
#=> true
</code>```

Title: Determine if a given year is a leap year

Body:
If you would like to determine if a given year is a leap year, that has already been implemented for you in the Date class as Date#leap?:

Date.leap?(2000)
#=> true

# Or, alternatively:

Date.gregorian_leap?(1900)
#=> false

Date.julian_leap?(1900)
#=> true

More info in the Ruby documentation: Date#leap?

If you would like to build it yourself regardless, this should work:

def leap_year?(year)
  return false unless year % 4 == 0
  return true unless year % 100 == 0
  year % 400 == 0
end

leap_year?(2016)
#=> true


问:
How I can make the program keep go next line after complete on if statement
im trying to write a code but for some reason the program is stuck in a loop of the if statements

```<code>#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
}
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
        keep_window_open();

}
</code>```

So my purpose is that after it checks the "if else" even is some of them true or not I need it to performe  cout << "blabla\n";
the code is not finished, I just need to understand how to make it jump to another line so I will be able to keep write the continue.

答:
Your problem is either not printing "blabla" while in the loop or not exiting the loop. For the latter see the answer by Ron.

For printing "blabla" while in the loop you need to make a block of the statements which you want executed in your loop. I.e. open a pair of {} right after the while and close it after the last statement you want inside the loop.

I have minimally edited your code to demonstrate the block:

```<code>#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
    { // starting the block of looped statements
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
        }
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
    } // end the block of looped statements,

    // guessing that this is NOT supposed to be inside the loop
    keep_window_open();
}
</code>```

Body:
im trying to write a code but for some reason the program is stuck in a loop of the if statements

#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
}
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
        keep_window_open();

}

So my purpose is that after it checks the "if else" even is some of them true or not I need it to performe  cout << "blabla\n";
the code is not finished, I just need to understand how to make it jump to another line so I will be able to keep write the continue.

Body:
Your problem is either not printing "blabla" while in the loop or not exiting the loop. For the latter see the answer by Ron.

For printing "blabla" while in the loop you need to make a block of the statements which you want executed in your loop. I.e. open a pair of {} right after the while and close it after the last statement you want inside the loop.

I have minimally edited your code to demonstrate the block:

#include "std_lib_facilities.h"
int main()
{
    double i = 0;
    double u = 0;
    cout << "Enter one numbers:\n";
    while (cin >> i)
    { // starting the block of looped statements
        if (i > u)
        {
            cout << "the largest number is: " << i << '\n'
            << "the smallest number is " << u << "\n";
        }
        else if (i < u) {
            cout << "the largest number is " << u << '\n'
                << "the smallest number is " << i << "\n";
        }
        else if (i == u) {
            cout << "The numbers are equal\n";
        }
        cout << "blabla\n";
    } // end the block of looped statements,

    // guessing that this is NOT supposed to be inside the loop
    keep_window_open();
}


问:
Why don't the values for a single studentid add up while i execute this SQL statement even though i used Distinct?

I have to write a query to display the studentid and the total fees paid by each student and then sort the result based on studentid in ascending order.

I have used Distinct so that studid is displayed only once but still I don't get the expected output.

My code:

```<code>select distinct s.studid,c.fees as total_fees from Student s join
Registration r on s.studid=r.studid join Course c on r.courseid=c.courseid
group by s.studid,c.fees order by s.studid;
</code>```

My Output:

Expected Output:

答:
You are querying by distinct combination of the student ID and the fees instead of summing the fees:

```<code>SELECT   s.studid, SUM(c.fees) as total_fees
FROM     student s
JOIN     registration r ON s.studid = r.studid
JOIN     course c ON r.courseid=c.courseid
GROUP BY s.studid
ORDER BY s.studid ASC
</code>```

Body:
I have to write a query to display the studentid and the total fees paid by each student and then sort the result based on studentid in ascending order.

I have used Distinct so that studid is displayed only once but still I don't get the expected output.

My code:

select distinct s.studid,c.fees as total_fees from Student s join
Registration r on s.studid=r.studid join Course c on r.courseid=c.courseid
group by s.studid,c.fees order by s.studid;

My Output:

Expected Output:

Body:
You are querying by distinct combination of the student ID and the fees instead of summing the fees:

SELECT   s.studid, SUM(c.fees) as total_fees
FROM     student s
JOIN     registration r ON s.studid = r.studid
JOIN     course c ON r.courseid=c.courseid
GROUP BY s.studid
ORDER BY s.studid ASC


问:
PANIC: Missing emulator engine program for 'arm' CPUS
I am getting the same issue as mentioned in below link.But this one has been put on hold and I am still seeking for a solution.
https://stackoverflow.com/questions/27146511/panic-missing-emulator-engine-program-for-arm-cpus-eclipse

So I would like to frame the question and ask here. Until yesterday, emulator were working fine. But since today I am receiving the following error while I am trying to open emulator

```<code>PANIC: Missing emulator engine program for 'arm' CPUS
</code>```

My AVD:

This is the error I am receiving:

I have updated and installed components through SDK Manager and I even tried to restart eclipse and my pc as well.
I tried creating new AVD But nothing worked here.

Thank You in advance.

答:
If you are trying to use an Android Virtual Device (AVD) with an Android Version, whose SDK platform version you have not installed, this error also appears.

Download all the Android SDK versions whose AVD you might use, i.e., be sure you have the API level installed whose AVD you will use.

Furthermore, check the first line the next image in the column CPU (this was also giving an error). Change the CPU of your AVD, to x86 and then it will work.

Body:
I am getting the same issue as mentioned in below link.But this one has been put on hold and I am still seeking for a solution.
https://stackoverflow.com/questions/27146511/panic-missing-emulator-engine-program-for-arm-cpus-eclipse

So I would like to frame the question and ask here. Until yesterday, emulator were working fine. But since today I am receiving the following error while I am trying to open emulator

PANIC: Missing emulator engine program for 'arm' CPUS

My AVD:

This is the error I am receiving:

I have updated and installed components through SDK Manager and I even tried to restart eclipse and my pc as well.
I tried creating new AVD But nothing worked here.

Thank You in advance.


问:
Python URL get middle string
How to get this string "534641" (this value is dynamic, can be 6,5,4 digits)? How to find "-" before "534641"?

```<code>import re

string = "http://www.test.com.my/white-red-gift-perfume-powerbank-yellow-534641.html?ff=1\u0026s=Ebsr"
m = re.search('-(.+?).html', string).group(1)
print (m)
</code>```

https://repl.it/JSxp

答:
You already have the number at the end. Just split on the dashes using: </p>

```<code>m = re.search('-(.+?).html', string).group(1).split("-")
# last element in m is the number you are looking for
print (m[-1])
</code>```

Title: Python URL get middle string

Body:
How to get this string "534641" (this value is dynamic, can be 6,5,4 digits)? How to find "-" before "534641"?

import re

string = "http://www.test.com.my/white-red-gift-perfume-powerbank-yellow-534641.html?ff=1\u0026s=Ebsr"
m = re.search('-(.+?).html', string).group(1)
print (m)

https://repl.it/JSxp

Body:
You already have the number at the end. Just split on the dashes using:

m = re.search('-(.+?).html', string).group(1).split("-")
# last element in m is the number you are looking for
print (m[-1])


问:
cross_val_score on Windows10, error with parallel-computing
I encountered an error when I tried to use cross_val_score with n_job not equal to 1.

My system was Intel-i7 cpu, Windows10, python3.6, Spyder.

Below is my code:

```<code>from numpy.random import randn
import pandas as pd
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense

# build a data set
dataset = pd.DataFrame(randn(100, 2), columns='X1 X2'.split())
dataset["Y"]=dataset["X1"]+dataset["X2"]

# seperate X and y
X = dataset.iloc[:, 0:2].values
Y = dataset.iloc[:, 2].values

# define classifier
def build_classifier():
    classifier = Sequential()
    classifier.add(Dense(units = 2, kernel_initializer = 'uniform', activation = 'relu', input_dim = 2))
    classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 1, epochs = 4)

class testnjob():
    def run():
        accuracies = cross_val_score(estimator = classifier, X = X, y = Y, cv = 5, n_jobs = -1)
        return(accuracies)
if __name__ == '__main__':
    accuracies = testnjob.run()
</code>```

The error message was:

```<code>ImportError: [joblib] Attempting to do parallel computing without protecting
your import on a system that does not support forking. To use parallel-
computing in a script, you must protect your main loop using
"if __name__ == '__main__'". Please see the joblib documentation on Parallel
for more information
</code>```

The code worked if I set n_jobs=1.

Is there a way to resolve this problem?

Added: The code works on linux virtual machine. I tried with Ubuntu on Virtualbox, anaconda (python 3.6)+ spyder (Tensorflow backend).

Added: I tried the same code in pycharm, a different error message showed up:

```<code>AttributeError: Can't get attribute 'build_classifier' on
<module '__main__' (built-in)>
</code>```

Thank you!

答:
You can try this since you use spyder it should work fine :

Code

```<code>import...

Class Test(object):
    def __init__(self):
        accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
        ###code here
        ###code here

if __name__ == '__main__':
    Test()
</code>```

Hope this helps.

Similar problem with spyder and n_jobs solved by my post here link

EDIT

I modified the last part of your code and it runs fine on Windows 8.1.

Also, I use: Theano backend.

Changed part:

```<code>from numpy.random import randn
...
...
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 1, epochs = 4)

####################################################################
#changed part from here

class run():
    def __init__(self):
        cross_val_score(estimator = classifier, X = X, y = Y, cv = 5, n_jobs = -1)

if __name__ == '__main__':
    run()
</code>```

Screenshot:

Body:
I encountered an error when I tried to use cross_val_score with n_job not equal to 1.

My system was Intel-i7 cpu, Windows10, python3.6, Spyder.

Below is my code:

from numpy.random import randn
import pandas as pd
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from keras.models import Sequential
from keras.layers import Dense

# build a data set
dataset = pd.DataFrame(randn(100, 2), columns='X1 X2'.split())
dataset["Y"]=dataset["X1"]+dataset["X2"]

# seperate X and y
X = dataset.iloc[:, 0:2].values
Y = dataset.iloc[:, 2].values

# define classifier
def build_classifier():
    classifier = Sequential()
    classifier.add(Dense(units = 2, kernel_initializer = 'uniform', activation = 'relu', input_dim = 2))
    classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))
    classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
    return classifier
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 1, epochs = 4)

class testnjob():
    def run():
        accuracies = cross_val_score(estimator = classifier, X = X, y = Y, cv = 5, n_jobs = -1)
        return(accuracies)
if __name__ == '__main__':
    accuracies = testnjob.run()

The error message was:

ImportError: [joblib] Attempting to do parallel computing without protecting
your import on a system that does not support forking. To use parallel-
computing in a script, you must protect your main loop using
"if __name__ == '__main__'". Please see the joblib documentation on Parallel
for more information

The code worked if I set n_jobs=1.

Is there a way to resolve this problem?

Added: The code works on linux virtual machine. I tried with Ubuntu on Virtualbox, anaconda (python 3.6)+ spyder (Tensorflow backend).

Added: I tried the same code in pycharm, a different error message showed up:

AttributeError: Can't get attribute 'build_classifier' on
<module '__main__' (built-in)>

Thank you!

Body:
You can try this since you use spyder it should work fine :

Code

import...

Class Test(object):
    def __init__(self):
        accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10, n_jobs = -1)
        ###code here
        ###code here

if __name__ == '__main__':
    Test()

Hope this helps.

Similar problem with spyder and n_jobs solved by my post here link

EDIT

I modified the last part of your code and it runs fine on Windows 8.1.

Also, I use: Theano backend.

Changed part:

from numpy.random import randn
...
...
classifier = KerasClassifier(build_fn = build_classifier, batch_size = 1, epochs = 4)

####################################################################
#changed part from here

class run():
    def __init__(self):
        cross_val_score(estimator = classifier, X = X, y = Y, cv = 5, n_jobs = -1)

if __name__ == '__main__':
    run()

Screenshot:


问:
template v-if="main", not working with return this.$route.path.indexOf('/') === 0 in computed "main"
works with my other routes like "/dashboard", etc, but is appearing in all routes. I basically want this template to only appear when the url is "/". Have tried it throughout my project and just plum doesn't work. PLease help and thank you!! for any suggestions.</p>

```<code><template v-if="main">
  <div id="accordion-nav">
    <div class="accordion-panels">
      <a href="/dashboard">Dashboard <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
    <div class="accordion-panels">
      <a href="/shifts">Shifts <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
    <div class="accordion-panels">
      <a href="/other">Other <i class="fa fa-caret-right" aria-hidden="true"></i></a>
    </div>
  </div>
</template>

<script>
export default {
  name: 'accordion-nav',
  computed: {
    main: function () {
      return this.$route.path.indexOf('/') === 0
    }
  }
}
</script>

<style scoped>
</style>
</code>```

答:
Setup the v-if in the sidebar component itself

```<code>'<template>
  <div id="sidebar" class="sidebar"
    :class="{ isOpen: isOpen }">
     <div class="sidebar-opener"
        @click="toggle">{{openerText}}</div>
     <accordion-nav v-if="main"></accordion-nav>
     <accordion></accordion>
   </div>
</template>'

<script>
export default {
  data () {
    return {

        }
  },
  computed:{
      main(){
          return this.$route.path === '/'
      }
  }
}
</script>
</code>```

With this.$route.path you get a string that equals the path of the current route resolved as absolute path  in any component of your app.
So you can use this to check whether you are in the root route using:

this.$route.path === '/'

Here is the example fiddle

Body:
works with my other routes like "/dashboard", etc, but is appearing in all routes. I basically want this template to only appear when the url is "/". Have tried it throughout my project and just plum doesn't work. PLease help and thank you!! for any suggestions.

<template v-if="main">

      Dashboard

      Shifts

      Other

</template>

Body:
Setup the v-if in the sidebar component itself

'<template>
  <div id="sidebar" class="sidebar"
    :class="{ isOpen: isOpen }">
     <div class="sidebar-opener"
        @click="toggle">{{openerText}}</div>
     <accordion-nav v-if="main"></accordion-nav>
     <accordion></accordion>
   </div>
</template>'

<script>
export default {
  data () {
    return {

        }
  },
  computed:{
      main(){
          return this.$route.path === '/'
      }
  }
}
</script>

With this.$route.path you get a string that equals the path of the current route resolved as absolute path  in any component of your app.
So you can use this to check whether you are in the root route using:

this.$route.path === '/'

Here is the example fiddle


问:
Embed image into a textbox
I have a Windows Forms (.Net 2.0) app and I have a request to embed some custom images into some textboxes(like the new version of Tortoise does). </p>

答:
What you can do is to create a new class that inherits from the System.Windows.Forms.TextBox class. Then you must set the UserPaint style of the control using

```<code>SetStyle(ControlStyles.UserPaint, true)
</code>```

in the constructor to enable you to draw the text box yourself, and finally you must override either OnPaint or OnPaintBackground to draw your control.

I suspect this won't be trivial since text drawing can be quite complex, but it should be possible.

OwnerDisplayName: nobody

LastEditorDisplayName: nobody

ContentLicense: CC BY-SA 2.5

Title: Embed image into a textbox

Body:
What you can do is to create a new class that inherits from the System.Windows.Forms.TextBox class. Then you must set the UserPaint style of the control using

SetStyle(ControlStyles.UserPaint, true)

in the constructor to enable you to draw the text box yourself, and finally you must override either OnPaint or OnPaintBackground to draw your control.

I suspect this won't be trivial since text drawing can be quite complex, but it should be possible.

OwnerDisplayName: Rune Grimstad


答:
An example using os.listdir:

```<code>root = os.getcwd()

for name in os.listdir(path):
    full_path = os.path.join(root, name)

    if os.path.isdir(full_path):
        filedate = date.fromtimestamp(os.path.getmtime(full_path))

        if (today - filedate).days > 90:
            old_dirs.append(name)
</code>```

os.path.isdir will return true if a file is a directory only.

Title: python prints folders and sub folders when only folders needed in python

Body:
An example using os.listdir:

root = os.getcwd()

for name in os.listdir(path):
    full_path = os.path.join(root, name)

    if os.path.isdir(full_path):
        filedate = date.fromtimestamp(os.path.getmtime(full_path))

        if (today - filedate).days > 90:
            old_dirs.append(name)

os.path.isdir will return true if a file is a directory only.


问:
calculating the sum total of the columns and display in footer when colum names are dynamic
I have a DataTable whose data are retrieved from the database. I am trying to get sum of the values of each cells every column wise and display in the footer of the DataTable .

But the problem is, my retrieved column names are dynamic, they vary every time user gives different input. How can I get the sum of the each column when my column names are dynamic.

```<code>protected void search_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = new DataTable();
        string from_date = srch_date.Text.ToString();
        string to_date = srch_to_date.Text.ToString();

        dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);
        if (dt != null && dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt_;
            GridView1.DataBind();
        }
    }
    catch (Exception ex) { }
}
</code>```

答:
You can loop all the columns and rows in the DataTable and show the results in the footer.</p>

```<code>DataTable dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);

//create a array to store the total column values
int[] RowTotals = new int[dt.Columns.Count];

//loop all the rows in the datatable
foreach (DataRow row in dt.Rows)
{
    //loop all the columns in the row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        //add the values for each cell to the total
        RowTotals[i] += Convert.ToInt32(row[dt.Columns[i].ColumnName]);
    }
}

//loop all the columns again to set the values in the footer
for (int i = 0; i < dt.Columns.Count; i++)
{
    GridView1.FooterRow.Cells[i].Text = string.Format("{0:N2}", RowTotals[i]);
}
</code>```

Body:
I have a DataTable whose data are retrieved from the database. I am trying to get sum of the values of each cells every column wise and display in the footer of the DataTable .

But the problem is, my retrieved column names are dynamic, they vary every time user gives different input. How can I get the sum of the each column when my column names are dynamic.

protected void search_Click(object sender, EventArgs e)
{
    try
    {
        DataTable dt = new DataTable();
        string from_date = srch_date.Text.ToString();
        string to_date = srch_to_date.Text.ToString();

        dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);
        if (dt != null && dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt_;
            GridView1.DataBind();
        }
    }
    catch (Exception ex) { }
}

Body:
You can loop all the columns and rows in the DataTable and show the results in the footer.

DataTable dt = new DAL_Reports().Rpt_Count_Transpose(from_date, to_date);

//create a array to store the total column values
int[] RowTotals = new int[dt.Columns.Count];

//loop all the rows in the datatable
foreach (DataRow row in dt.Rows)
{
    //loop all the columns in the row
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        //add the values for each cell to the total
        RowTotals[i] += Convert.ToInt32(row[dt.Columns[i].ColumnName]);
    }
}

//loop all the columns again to set the values in the footer
for (int i = 0; i < dt.Columns.Count; i++)
{
    GridView1.FooterRow.Cells[i].Text = string.Format("{0:N2}", RowTotals[i]);
}


问:
Alternative for Math.round()
In JavaScript when value is 4.3, i want it to round off to 4 and if value is 4.5 or above it rounds off to 5. I want all this without using Math.round().

答:
You could also do this:

```<code>round=num=>(num-~~num>=0.5?1:0)+~~num;
</code>```

Explanation:

```<code>~~num
</code>```

is a double bitwise OR, actually it removes everything behind the point so 1.5 => 1

```<code>num-~~num
</code>```

gets the distance to the next lower integer, so e.g. 5.4 => 0.4, 5.6 => 0.6

Some testcases:

http://jsbin.com/gulegoruxi/edit?console

Title: Alternative for Math.round()

Body:
You could also do this:

round=num=>(num-~~num>=0.5?1:0)+~~num;

Explanation:

~~num

is a double bitwise OR, actually it removes everything behind the point so 1.5 => 1

num-~~num

gets the distance to the next lower integer, so e.g. 5.4 => 0.4, 5.6 => 0.6

Some testcases:

http://jsbin.com/gulegoruxi/edit?console


问:
Ionic 2 after installing firebase and angularfire2 I can't build my app any more
I worked on app for a long time and at the end i needed small use of firebase so I installed it using npm install angularfire2 firebase --save,
and followed this steps : steps,
firebase works good for me, but when I got ready to run on my device I got this error on ionic cordova run android

```<code>Error occurred during command execution from a CLI plugin (@ionic/cli-plugin-cordova). Your plugins may be out of
       date.
Error: ./~/firebase/app/shared_promise.js
Module not found: Error: Can't resolve 'promise-polyfill' in 'J:\Ionic2\Driver2\Driver\node_modules\firebase\app'
resolve 'promise-polyfill' in 'J:\Ionic2\Driver2\Driver\node_modules\firebase\app'
  Parsed request is a module
  using description file: J:\Ionic2\Driver2\Driver\node_modules\firebase\package.json (relative path: ./app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: J:\Ionic2\Driver2\Driver\node_modules\firebase\package.json (relative path: ./app)
    resolve as module
      looking for modules in J:\Ionic2\Driver2\Driver\node_modules
        using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules)
          using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules/promise-polyfill)
            as directory
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill doesn't exist
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.json doesn't exist
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.ts]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.js]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.json]
 @ ./~/firebase/app/shared_promise.js 38:35-62
 @ ./~/firebase/app/firebase_app.js
 @ ./~/firebase/app.js
 @ ./~/firebase/database.js
 @ ./~/angularfire2/database/firebase_list_factory.js
 @ ./~/angularfire2/database.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts
</code>```

my ionic info is:

```<code>global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 7.0.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.6
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.2.3
    Ionic Framework                 : ionic-angular 3.1.1

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 3.10.10
</code>```

答:
i want to share the answer after i found it:
this solved my problem https://github.com/ionic-team/ionic-app-scripts/issues/1001#issuecomment-302993092</p>

```<code>npm install promise-polyfill --save-exact
</code>```

Body:
I worked on app for a long time and at the end i needed small use of firebase so I installed it using npm install angularfire2 firebase --save,
and followed this steps : steps,
firebase works good for me, but when I got ready to run on my device I got this error on ionic cordova run android

Error occurred during command execution from a CLI plugin (@ionic/cli-plugin-cordova). Your plugins may be out of
       date.
Error: ./~/firebase/app/shared_promise.js
Module not found: Error: Can't resolve 'promise-polyfill' in 'J:\Ionic2\Driver2\Driver\node_modules\firebase\app'
resolve 'promise-polyfill' in 'J:\Ionic2\Driver2\Driver\node_modules\firebase\app'
  Parsed request is a module
  using description file: J:\Ionic2\Driver2\Driver\node_modules\firebase\package.json (relative path: ./app)
    Field 'browser' doesn't contain a valid alias configuration
  after using description file: J:\Ionic2\Driver2\Driver\node_modules\firebase\package.json (relative path: ./app)
    resolve as module
      looking for modules in J:\Ionic2\Driver2\Driver\node_modules
        using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
        after using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules)
          using description file: J:\Ionic2\Driver2\Driver\package.json (relative path: ./node_modules/promise-polyfill)
            as directory
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill doesn't exist
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill doesn't exist
            .ts
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.ts doesn't exist
            .js
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.js doesn't exist
            .json
              Field 'browser' doesn't contain a valid alias configuration
              J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.json doesn't exist
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.ts]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.js]
[J:\Ionic2\Driver2\Driver\node_modules\promise-polyfill.json]
 @ ./~/firebase/app/shared_promise.js 38:35-62
 @ ./~/firebase/app/firebase_app.js
 @ ./~/firebase/app.js
 @ ./~/firebase/database.js
 @ ./~/angularfire2/database/firebase_list_factory.js
 @ ./~/angularfire2/database.js
 @ ./src/app/app.module.ts
 @ ./src/app/main.ts

my ionic info is:

global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 7.0.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.6
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.2.3
    Ionic Framework                 : ionic-angular 3.1.1

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 3.10.10

Body:
i want to share the answer after i found it:
this solved my problem https://github.com/ionic-team/ionic-app-scripts/issues/1001#issuecomment-302993092

npm install promise-polyfill --save-exact


问:
SQL return list of ntext and convert it to XML
I have a query that will return and a list of ntext, and in these ntext they contain XML value.
my question is how to convert each of ntext to xml and do logic with it

Query:

```<code>select a.content
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'
</code>```

result:

what I want to do here is to check rather the Query returns contain the value that I looking for. lets say the page title = "hello World"

I tried below.But it returns many empty rows and with one correct row

```<code>select cast(a.content_html as xml).query('(//root[pagetitle/text()="AAA"])') content_html1
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'
</code>```

expected result is: return only one row where it's not empty (row 54)

答:
First of all: NTEXT, TEXT and IMAGE are deprecated for centuries and will not be supported in future versions! Get rid of this type as soon as possible!

SQL-Server does not store the XML as the text you see, but as a hierarchically stuctured tree. This makes the handling of an XML astonishingly fast (no parsing on string level!). Your approach has to parse each and every XML over and over, which is a very expensive operation! Change your XML's storage to the native XML type and you will be very happy with the new performance!

If you have to stick with this, you can try as such:

```<code>DECLARE @t TABLE (ID INT IDENTITY, YourXML NTEXT);
INSERT INTO @t VALUES('<root><pagetitle>111</pagetitle></root>')
                    ,('<root><pagetitle>aaa</pagetitle></root>')
                    ,('<root><pagetitle>222</pagetitle></root>')
SELECT A.CastedXML
      ,B.pt.query('.')
FROM @t AS t
CROSS APPLY(SELECT CAST(YourXML AS XML) AS CastedXML) AS A
CROSS APPLY A.CastedXML.nodes('/root/pagetitle[text()="aaa"]') AS B(pt);
</code>```

Body:
I have a query that will return and a list of ntext, and in these ntext they contain XML value.
my question is how to convert each of ntext to xml and do logic with it

Query:

select a.content
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'

result:

what I want to do here is to check rather the Query returns contain the value that I looking for. lets say the page title = "hello World"

I tried below.But it returns many empty rows and with one correct row

select cast(a.content_html as xml).query('(//root[pagetitle/text()="AAA"])') content_html1
from dbo.content as a
inner join dbo.xml_collection_tbl as b on a.xml_fg_id = b.xml_collection_id
where a.inherit_from='val1' and b.collection_title='val2' and a.content_table= 'val3'

expected result is: return only one row where it's not empty (row 54)

Body:
First of all: NTEXT, TEXT and IMAGE are deprecated for centuries and will not be supported in future versions! Get rid of this type as soon as possible!

SQL-Server does not store the XML as the text you see, but as a hierarchically stuctured tree. This makes the handling of an XML astonishingly fast (no parsing on string level!). Your approach has to parse each and every XML over and over, which is a very expensive operation! Change your XML's storage to the native XML type and you will be very happy with the new performance!

If you have to stick with this, you can try as such:

DECLARE @t TABLE (ID INT IDENTITY, YourXML NTEXT);
INSERT INTO @t VALUES('<root><pagetitle>111</pagetitle></root>')
                    ,('<root><pagetitle>aaa</pagetitle></root>')
                    ,('<root><pagetitle>222</pagetitle></root>')
SELECT A.CastedXML
      ,B.pt.query('.')
FROM @t AS t
CROSS APPLY(SELECT CAST(YourXML AS XML) AS CastedXML) AS A
CROSS APPLY A.CastedXML.nodes('/root/pagetitle[text()="aaa"]') AS B(pt);


问:
Using GeoFire to Populate Firebase Recycler View in android
I want to populate my recycler view so that, I can see who are the people/places nearby. I am using GeoFire to Query my database, which looks something like this.

```<code> GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latLngCenter.latitude, latLngCenter.longitude), 0.1);
        geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
            @Override
            public void onKeyEntered(String key, GeoLocation location) {
                System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
                Log.e("TAG", key + location.latitude + location.longitude);

            }

            @Override
            public void onKeyExited(String key) {
                System.out.println(String.format("Key %s is no longer in the search area", key));
            }

            @Override
            public void onKeyMoved(String key, GeoLocation location) {
                System.out.println(String.format("Key %s moved within the search area to [%f,%f]", key, location.latitude, location.longitude));
                Log.e("TAG", key + location.latitude + location.longitude);
            }

            @Override
            public void onGeoQueryReady() {
                System.out.println("All initial data has been loaded and events have been fired!");
            }

            @Override
            public void onGeoQueryError(DatabaseError error) {
                System.err.println("There was an error with this query: " + error);
            }
        });
</code>```

and I am using this Firebase RecyclerView

```<code> RecyclerView recycler = (RecyclerView) findViewById(R.id.RecyclerView);
    recycler.setHasFixedSize(true);
    recycler.setLayoutManager(new LinearLayoutManager(this));

    FirebaseRecyclerAdapter<Chat, ChatHolder> mAdapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(Chat.class, R.layout.recyclerview, ChatHolder.class, mUsers) {

        @Override
        public void populateViewHolder(final ChatHolder chatMessageViewHolder, final Chat chatMessage, int position) {

                    chatMessageViewHolder.setName(chatMessage.getName());
                    chatMessageViewHolder.setText(chatMessage.getText());
                    chatMessageViewHolder.setTimestamp(chatMessage.getTimestamp());

        }
    };
    recycler.setAdapter(mAdapter);
</code>```

with these Chat Holder class and chat object class

```<code>public static class ChatHolder extends RecyclerView.ViewHolder {
    View mView;

    public ChatHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setName(String name) {
        TextView field = (TextView) mView.findViewById(R.id.textViewName);
        field.setText(name);
    }

    public void setText(String text) {
        TextView field = (TextView) mView.findViewById(R.id.textViewMessage);
        field.setText(text);
    }

    public void setTimestamp(String text) {
        TextView field = (TextView) mView.findViewById(R.id.textViewTime);
        field.setText(text);
    }
}

public static class Chat {

    String name;
    String text;
    String uid;
    String timestamp;

    public Chat() {
    }

    public Chat(String name, String uid, String message, String timestamp) {
        this.name = name;
        this.text = message;
        this.uid = uid;
        this.timestamp = timestamp;
    }

    public String getName() {
        return name;
    }

    public String getUid() {
        return uid;
    }

    public String getText() {
        return text;
    }

    public String getTimestamp() {
        return timestamp;
    }
}
</code>```

Currently this, adapter which is provided in FirebaseUI library, populates recyclerview so that, only one reference is used and all child events are shown in the view,
Now, I want to populate my recyclerView so that when ever a key enters it populates my recyclerview based on my key = to my reference, this how my firebase database looksmy firebase database

答:
It'll be simpler to push all data (which is also uid) you have retrieved from geofire to a new node to store geofire results in firebase, something like

```<code>my-node //your new firebase node to store all uids retrieved from geofire
- {chatUid}: true //true is just a dummy data, you can use anything else except null and empty string.
- {chatUid}: true
- ...
</code>```

and set FirebaseRecyclerAdapter ref to that node.

```<code>DatabaseReference ref = FirebaseDatabase.getInstance().getReference("my-node");
FirebaseRecyclerAdapter fra = new FirebaseRecyclerAdapter<Boolean, MyVH>(Boolean.class, R.layout.my_layout, MyVH.class, ref) { ... }
</code>```

and then, in populateViewHolder() method in your implementation of FirebaseRecyclerAdapter, you can use the String key to fetch data from main node that contains the data.

```<code>public void populateViewHolder(MyVH viewHolder, Boolean model, int position){
    // Get references of child views
    final TextView nameTextView = viewHolder.getItemView().findViewById(R.id.my_name_text_view_in_vh_layout);
    final TextView addressTextView = viewHolder.getItemView().findViewById(R.id.my_address_text_view_in_vh_layout);

    // Key in this position.
    String key = getRef(position).key;

    // Query the full data of the current key located in the `main-data-node`
    FirebaseDatabase.getInstance().getReference("main-data-node").child(key).addValueEventListener(new ValueEventListener(){
        ... //Truncated onCancelled

        @Override
        public void onDataChange(snap: DataSnapshot){
            MyDataModel model = snap.getValue(MyDataModel.class);

            nameTextView = model.getName();
            addressTextView = model.getAddress();
        }
    }
}

// The data model class
public class MyDataModel {
    private String name;
    private String address;
    ... // Truncated getter, setter, constructor
}
</code>```

For any changes in geofire result, just push those results to my-node, and it will automatically informs your FirebaseRecyclerAdapter.

P.S. I'm too lazy to match my solution to your data model (sorry), so I made a simplified sample class, so if anyone stumbled upon this, they can understand it easier.

P.S.S. It's been a while since I code in java, I mainly use kotlin (and you soon should too lol), so, if there're some syntax mistakes out there, feel free to edit.

Body:
I want to populate my recycler view so that, I can see who are the people/places nearby. I am using GeoFire to Query my database, which looks something like this.

 GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(latLngCenter.latitude, latLngCenter.longitude), 0.1);
        geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
            @Override
            public void onKeyEntered(String key, GeoLocation location) {
                System.out.println(String.format("Key %s entered the search area at [%f,%f]", key, location.latitude, location.longitude));
                Log.e("TAG", key + location.latitude + location.longitude);

            }

            @Override
            public void onKeyExited(String key) {
                System.out.println(String.format("Key %s is no longer in the search area", key));
            }

            @Override
            public void onKeyMoved(String key, GeoLocation location) {
                System.out.println(String.format("Key %s moved within the search area to [%f,%f]", key, location.latitude, location.longitude));
                Log.e("TAG", key + location.latitude + location.longitude);
            }

            @Override
            public void onGeoQueryReady() {
                System.out.println("All initial data has been loaded and events have been fired!");
            }

            @Override
            public void onGeoQueryError(DatabaseError error) {
                System.err.println("There was an error with this query: " + error);
            }
        });

and I am using this Firebase RecyclerView

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

    FirebaseRecyclerAdapter<Chat, ChatHolder> mAdapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(Chat.class, R.layout.recyclerview, ChatHolder.class, mUsers) {

        @Override
        public void populateViewHolder(final ChatHolder chatMessageViewHolder, final Chat chatMessage, int position) {

                    chatMessageViewHolder.setName(chatMessage.getName());
                    chatMessageViewHolder.setText(chatMessage.getText());
                    chatMessageViewHolder.setTimestamp(chatMessage.getTimestamp());

        }
    };
    recycler.setAdapter(mAdapter);

with these Chat Holder class and chat object class

public static class ChatHolder extends RecyclerView.ViewHolder {
    View mView;

    public ChatHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setName(String name) {
        TextView field = (TextView) mView.findViewById(R.id.textViewName);
        field.setText(name);
    }

    public void setText(String text) {
        TextView field = (TextView) mView.findViewById(R.id.textViewMessage);
        field.setText(text);
    }

    public void setTimestamp(String text) {
        TextView field = (TextView) mView.findViewById(R.id.textViewTime);
        field.setText(text);
    }
}

public static class Chat {

    String name;
    String text;
    String uid;
    String timestamp;

    public Chat() {
    }

    public Chat(String name, String uid, String message, String timestamp) {
        this.name = name;
        this.text = message;
        this.uid = uid;
        this.timestamp = timestamp;
    }

    public String getName() {
        return name;
    }

    public String getUid() {
        return uid;
    }

    public String getText() {
        return text;
    }

    public String getTimestamp() {
        return timestamp;
    }
}

Currently this, adapter which is provided in FirebaseUI library, populates recyclerview so that, only one reference is used and all child events are shown in the view,
Now, I want to populate my recyclerView so that when ever a key enters it populates my recyclerview based on my key = to my reference, this how my firebase database looksmy firebase database

Body:
It'll be simpler to push all data (which is also uid) you have retrieved from geofire to a new node to store geofire results in firebase, something like

my-node //your new firebase node to store all uids retrieved from geofire
- {chatUid}: true //true is just a dummy data, you can use anything else except null and empty string.
- {chatUid}: true
- ...

and set FirebaseRecyclerAdapter ref to that node.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("my-node");
FirebaseRecyclerAdapter fra = new FirebaseRecyclerAdapter<Boolean, MyVH>(Boolean.class, R.layout.my_layout, MyVH.class, ref) { ... }

and then, in populateViewHolder() method in your implementation of FirebaseRecyclerAdapter, you can use the String key to fetch data from main node that contains the data.

public void populateViewHolder(MyVH viewHolder, Boolean model, int position){
    // Get references of child views
    final TextView nameTextView = viewHolder.getItemView().findViewById(R.id.my_name_text_view_in_vh_layout);
    final TextView addressTextView = viewHolder.getItemView().findViewById(R.id.my_address_text_view_in_vh_layout);

    // Key in this position.
    String key = getRef(position).key;

    // Query the full data of the current key located in the `main-data-node`
    FirebaseDatabase.getInstance().getReference("main-data-node").child(key).addValueEventListener(new ValueEventListener(){
        ... //Truncated onCancelled

        @Override
        public void onDataChange(snap: DataSnapshot){
            MyDataModel model = snap.getValue(MyDataModel.class);

            nameTextView = model.getName();
            addressTextView = model.getAddress();
        }
    }
}

// The data model class
public class MyDataModel {
    private String name;
    private String address;
    ... // Truncated getter, setter, constructor
}

For any changes in geofire result, just push those results to my-node, and it will automatically informs your FirebaseRecyclerAdapter.

P.S. I'm too lazy to match my solution to your data model (sorry), so I made a simplified sample class, so if anyone stumbled upon this, they can understand it easier.

P.S.S. It's been a while since I code in java, I mainly use kotlin (and you soon should too lol), so, if there're some syntax mistakes out there, feel free to edit.


问:
Why doesn't drawing an ellipse with Pen::DashPattern set produce the expected result?
I'm trying to (simply) draw some lines rotating along an ellipse path and thought I had a nice easy way of doing it. Unfortunately, my solution seems to have some problems:

```<code>void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    for( int i = 0; i < 15; i ++ )
    {
        Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
        myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
        myPen->Width = 3;
        myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
        array<Single>^ pattern = {4, ellipseCircumference};

        Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
        myPen2->DashPattern = pattern;
        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}
</code>```

...produces:

http://www.joncage.co.uk/media/img/BadPattern.png

...so why are the second two ellipses fully white? ...and how can I avoid the problem?

答:
I can't imagine it will fix the problem, but you can take a lot of the processing out of the loop:</p>

```<code>void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
    myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
    myPen->Width = 3;
    myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;

    float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
    array<Single>^ pattern = {4, ellipseCircumference};

    Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
    myPen2->DashPattern = pattern;

    for( int i = 0; i < 15; i ++ )
    {
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}
</code>```

Body:
I'm trying to (simply) draw some lines rotating along an ellipse path and thought I had a nice easy way of doing it. Unfortunately, my solution seems to have some problems:

void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    for( int i = 0; i < 15; i ++ )
    {
        Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
        myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
        myPen->Width = 3;
        myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
        array<Single>^ pattern = {4, ellipseCircumference};

        Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
        myPen2->DashPattern = pattern;
        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}

...produces:

http://www.joncage.co.uk/media/img/BadPattern.png

...so why are the second two ellipses fully white? ...and how can I avoid the problem?

Body:
I can't imagine it will fix the problem, but you can take a lot of the processing out of the loop:

void EllipseDisplayControl::OnPaint(PaintEventArgs^ e)
{
    Graphics^ gfx = e->Graphics;
    gfx->SmoothingMode = Drawing2D::SmoothingMode::AntiAlias;

    int width = 100;
    int height = 10;

    Drawing::Pen^ myPen = (Drawing::Pen^) Drawing::Pens::RoyalBlue->Clone(); //use the standard blue as a start point
    myPen->Color = Drawing::Color::FromArgb(64, 32, 111, 144);
    myPen->Width = 3;
    myPen->DashStyle = Drawing::Drawing2D::DashStyle::Solid;

    float ellipseCircumference = Math::PI * Math::Sqrt(2* (Math::Pow(0.5*width,2) + Math::Pow(0.5*height,2)));
    array<Single>^ pattern = {4, ellipseCircumference};

    Drawing::Pen^ myPen2 = (Drawing::Pen^) Drawing::Pens::White->Clone(); //use the standard blue as a start point
    myPen2->DashPattern = pattern;

    for( int i = 0; i < 15; i ++ )
    {
        gfx->DrawEllipse(myPen, 0, 50+i*20, width, height); // Draw the blue ring

        myPen2->DashOffset = i*10;
        gfx->DrawEllipse(myPen2, 0, 50+i*20, width, height); // Draw the rotating white dot
    }
}


问:
bitbucket rebase a branch on a previous commit
I'm using bitbucket with source tree. I would like to rebase my remote branch to a previous commit.

There are some change that I made locally that was merged with remote. The remote is on a non working state. I would like to make a simple operation of getting back to the previous state. If I rebase on the remote branch my local version becomes operational but the remote version is still on the wrong state. If I try to push it will refuse because Updates were rejected because the tip of your current branch is behind

I can't reverse commit because a merge occurred. I can't also force push because the button is disabled.

答:
First, backup your repository:

Copy it and save it somewhere.

Second checkout your remote branch:

```<code>git checkout -b mybranch origin/mybranch -u
</code>```

If you want to revert back to a previous state, you have three options:

```<code> 1. Revert - git revert <previous_commit>
 2. Rebase - git rebase -i <previous_commit>
 3. Reset - git reset <previous_commit>
</code>```

Option 1 is the safest because it creates a new commit that reverts the current commit.

Option 2 re-writes history by interactively rebasing commits starting from a previous commit.  You can selectively choose which commits are part of
the new history.

Option 3 also re-writes history by forcing the branch HEAD to point to a previous commit (as if the future commits did not happen). You may need to run this with the --hard option if you have checked out files (take care to not lose your work!)

Since Option 2 and Option 3 re-writes history, you should take care that your team is notified of the change. They will need to force get the latest branch (or just re-clone the repository from the source). Once you've made the changes and you're satisfied, push the changes to your remote branch:

```<code>git push origin mybranch --force
</code>```

Or simply

```<code>git push --force
</code>```

since there is an upstream branch already setup.

Body:
First, backup your repository:

Copy it and save it somewhere.

Second checkout your remote branch:

git checkout -b mybranch origin/mybranch -u

If you want to revert back to a previous state, you have three options:

 1. Revert - git revert <previous_commit>
 2. Rebase - git rebase -i <previous_commit>
 3. Reset - git reset <previous_commit>

Option 1 is the safest because it creates a new commit that reverts the current commit.

Option 2 re-writes history by interactively rebasing commits starting from a previous commit.  You can selectively choose which commits are part of
the new history.

Option 3 also re-writes history by forcing the branch HEAD to point to a previous commit (as if the future commits did not happen). You may need to run this with the --hard option if you have checked out files (take care to not lose your work!)

Since Option 2 and Option 3 re-writes history, you should take care that your team is notified of the change. They will need to force get the latest branch (or just re-clone the repository from the source). Once you've made the changes and you're satisfied, push the changes to your remote branch:

git push origin mybranch --force

Or simply

git push --force

since there is an upstream branch already setup.


问:
Measuring distance of values / strings
martin fownler was discussing event sourcing

https://martinfowler.com/eaaDev/EventSourcing.html

e.g. storing data as a set of events.

Now an example would be an account. You create an account with balance 0.

Then you put 10$. You withdraw 5$. You put another 100$. Now the balance is 105$, but you don't store 105$. What you do store is

```<code>+10
-5
+100
</code>```

as a series of events in the database.

Now if I want I can say "undo the last 2 steps." then I just remove the 2 last changes in the database -> account is 10

Now: how can you do that with strings?

Say account name first is empty string. Then
dirk dietmeier then hans hansenmann then foo bar how can you capture this data as set of changes? While letting it be reversable e.g. the events need to be able to reverse itself. E.g. you could just say 'delete everything and then put foo bar but is there no better solution?

is there like a svn or git like algorithm? some encoding (hex, binary?)?

答:
Now if I want I can say "undo the last 2 steps." then I just remove
  the 2 last changes in the database -> account is 10

Not if you want to preserve the history. In production event sourced applications, I would issue a compensating event. E.g. New event Y that undoes what event X did. The git analogue to this would be git revert.

Now: how can you do that with strings?

It depends on your application.

If you are tracking changes to code, it makes sense to do some research on how to express differences between two files, such that you can revert at a later time. In this sense, your event would be similar to a git commit. I suggest you look at the diff linux command http://linuxcommand.org/man_pages/diff1.html and look at the source code, or how you can implement it.

If your event is something like CustomerFirstNameChanged, doing a diff makes very little sense. You would always want to revert to a previous state such as John or Rick.

Number 2 would also make sense with an event such as ArticleRedrafted, where you can go back to a previous version. Content editors don't see revisions as we see git commits when we use git revert... They see them as points in time that can be returned to.

Title: Measuring distance of values / strings

Body:
martin fownler was discussing event sourcing

https://martinfowler.com/eaaDev/EventSourcing.html

e.g. storing data as a set of events.

Now an example would be an account. You create an account with balance 0.

Then you put 10$. You withdraw 5$. You put another 100$. Now the balance is 105$, but you don't store 105$. What you do store is

+10
-5
+100

as a series of events in the database.

Now if I want I can say "undo the last 2 steps." then I just remove the 2 last changes in the database -> account is 10

Now: how can you do that with strings?

Say account name first is empty string. Then
dirk dietmeier then hans hansenmann then foo bar how can you capture this data as set of changes? While letting it be reversable e.g. the events need to be able to reverse itself. E.g. you could just say 'delete everything and then put foo bar but is there no better solution?

is there like a svn or git like algorithm? some encoding (hex, binary?)?


问:
Gulp: convert java scripts extension in index.html
I am trying to convert java scripts extension '.js' to '.js.gz'. For this i chose gulp-html-replace module. But i am unable to get the desired result. For below example i am using two scripts but i have more.

index.html (Before):

```<code><!-- build:js -->
    <script src="routing_components/app-routing/app-routing.component.js"></script>
    <script src="routing_components/home-routing/home-routing.component.js"></script>
<!-- endbuild -->
</code>```

index.html (After gulp index.html should be like this):

```<code><script src="routing_components/app-routing/app-routing.component.js.gz"></script>
<script src="routing_components/home-routing/home-routing.component.js.gz"></script>
</code>```

But instead i am getting this after running gulp task

```<code><script src="index.js.gz"></script>
</code>```

Gulp task:

```<code>gulp.task('index_gzip', function () {
    gulp.src('app/index.html')
        .pipe(htmlreplace({
            js: {
                src: null,
                tpl: '<script src="%f.js.gz"></script>'
            }
        }))
        .pipe(gulp.dest(function (file) {
            return file.base;
        }))
});
</code>```

If somebody know better module for this kind of task, please recommend. And please help to correct my gulp task

答:
Try this plugin gulp-replace. But I don't know why regex grouping Not working properly.</p>

```<code>var replace = require('gulp-replace');
gulp.task('index_gzip', function () {
    gulp.src('app/index.html')
        .pipe(replace(/(<script.*?src=\")(.*?).js\"/g, '$1$2.js.gz"'))
        .pipe(gulp.dest(function (file) {
            return file.base;
        }))
});
</code>```

Body:
I am trying to convert java scripts extension '.js' to '.js.gz'. For this i chose gulp-html-replace module. But i am unable to get the desired result. For below example i am using two scripts but i have more.

index.html (Before):

index.html (After gulp index.html should be like this):

But instead i am getting this after running gulp task

Gulp task:

gulp.task('index_gzip', function () {
    gulp.src('app/index.html')
        .pipe(htmlreplace({
            js: {
                src: null,
                tpl: ''
            }
        }))
        .pipe(gulp.dest(function (file) {
            return file.base;
        }))
});

If somebody know better module for this kind of task, please recommend. And please help to correct my gulp task

Body:
Try this plugin gulp-replace. But I don't know why regex grouping Not working properly.

var replace = require('gulp-replace');
gulp.task('index_gzip', function () {
    gulp.src('app/index.html')
        .pipe(replace(/(<script.*?src=\")(.*?).js\"/g, '$1$2.js.gz"'))
        .pipe(gulp.dest(function (file) {
            return file.base;
        }))
});


问:
What is the difference between resources and map.resources in Rails
I have been using both of them for a while so I am just curious what is their difference?</p>

答: One answer could be that in rails 2.x you'd use map.resources and in rails 3.x it's just resources. You don't specify which you're using though or give any examples so it's hard to give a meaningful answer.</p>


问:
RecyclerView not shown
I used techniques given in other answers like downgrading the versions of dependencies to 24... and 25.0.1.Did not work.I have width and height of RecyclerView as match_parent.
Following is the code.I am using RecyclerView for post title and post description in a blog app:

```<code>package com.awani.pocketblog;

import android.content.ClipData;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

private RecyclerView mBlogList;
private DatabaseReference mDatabase;

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

    mBlogList = (RecyclerView) findViewById(R.id.blog_list);
    mBlogList.setHasFixedSize(true);
    mBlogList.setLayoutManager(new LinearLayoutManager(this));
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
}

@Override
protected void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>( Blog.class,
            R.layout.blog_row,
            BlogViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());//model means Blog class over here
            viewHolder.setDesc(model.getDesc());

        }
    };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

//holder for the recyclerView
public static class BlogViewHolder extends RecyclerView.ViewHolder{

    View mView;

    public BlogViewHolder(View itemView) {
        super(itemView);

        mView = itemView;
    }

    public void setTitle(String title){

        TextView post_title = (TextView) mView.findViewById(R.id.post_title);
        post_title.setText(title);

    }

    public void setDesc(String desc){

        TextView post_description = (TextView) mView.findViewById(R.id.post_description);
        post_description.setText(desc);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.action_add){
        startActivity(new Intent(MainActivity.this,PostActivity.class));
    }

    return super.onOptionsItemSelected(item);
}
}
</code>```

log cat statement which might be causing this..

```<code>07-08 17:22:10.761 23308-23308/com.awani.pocketblog W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
</code>```

this is activity_main.xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.awani.pocketblog.MainActivity">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/blog_list">
</android.support.v7.widget.RecyclerView>

</android.widget.RelativeLayout>
</code>```

My android studio version is 2.3.2 and he dependencies are 25.3.1
and firebase dependencies are 10.0.1
firebase ui dependency 1.1.1

答:
```<code>Follow This Example Step by Step

public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener {

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area_list);
       recyclerView=(RecyclerView)findViewById(R.id.recycler_view1);

                    populateRecyclerView();
                    recyclerView.setHasFixedSize(true);
                    GridLayoutManager layoutManager = new GridLayoutManager(AreaListActivity.this,3);
                    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(AreaListActivity.this, layoutManager.getOrientation());
                    recyclerView.addItemDecoration(dividerItemDecoration);
                    recyclerView.setLayoutManager(layoutManager);

        //recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
     //   recyclerView.setLayoutManager(new GridLayoutManager(this,3));
     //   recyclerView.getLayoutManager().scrollToPosition(5);

    }

    public void populateRecyclerView(){
        //pass the allAreaList to it
        RecyclerViewAdapter adapter=new RecyclerViewAdapter(AreaListActivity.this,ArrayList,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        //recyclerView.setAdapter(new RecyclerViewAdapter(MainActivity.this,this));
    }

    @Override
    public void recyclerViewListClicked(View v, int position) {
        Intent myIntent=new Intent(MainActivity.this,SecondActivity.class);

        myIntent.putExtra("position",position);
        startActivity(myIntent);
        finish();
    }

@Override
public void onBackPressed() {
    Intent myIntent=new Intent(MainActivity.this,HomeActivity.class);
    startActivity(myIntent);
    finish();
}
}
</code>```

RecyclerViewHolder Class

public class RecyclerViewHolder extends RecyclerView.ViewHolder  {

```<code>//view holder is for girdview as we used in the listView
public ImageView imageView,imageView2;
public RecyclerViewHolder(View itemView) {
    super(itemView);
    this.imageView=(ImageView)itemView.findViewById(R.id.image);
}
</code>```

}

Adapter Class
public class RecyclerView_Adapter extends RecyclerView.Adapter {

```<code>//RecyclerView will extend to recayclerview Adapter
private ArrayList<ModelClass> arrayList;
private Context context;
private static RecyclerViewClickListener itemListener;
//constructor of the RecyclerView Adapter
RecyclerView_Adapter(Context context,ArrayList<ModelClass> arrayList,RecyclerViewClickListener itemListener){
    this.context=context;
    this.arrayList=arrayList;
    this.itemListener=itemListener;
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //this method will inflate the custom layout and return as viewHolder
    LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
    ViewGroup mainGroup=(ViewGroup) layoutInflater.inflate(R.layout.single_item,parent,false);
    RecyclerViewHolder listHolder=new RecyclerViewHolder(mainGroup);

    return listHolder;
}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, final int position) {

    final ModelClass modelClass=arrayList.get(position);
    //holder
    RecyclerViewHolder mainHolder=(RecyclerViewHolder)holder;
    //convert the drawable image into bitmap
    Bitmap image= BitmapFactory.decodeResource(context.getResources(),modelClass.getImage());
    //set the image into imageView
    mainHolder.imageView.setImageBitmap(image);
    //to handle on click event when clicked on the recyclerview item and
    // get it through the RecyclerViewHolder class we have defined the views there
    mainHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //get the position of the image which is clicked
         itemListener.recyclerViewListClicked(v,position);
        }
    });

}

@Override
public int getItemCount() {
    return (null!=arrayList?arrayList.size():0);
}
</code>```

}

Interface

public interface RecyclerViewClickListener {

```<code>//this is method to handle the event when clicked on the image in Recyclerview
public void recyclerViewListClicked(View v,int position);
</code>```

}

//and to call this method in activity
RecyclerView_Adapter adapter=new RecyclerView_Adapter(Wallpaper.this,arrayList,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

```<code>@Override
public void  recyclerViewListClicked(View v,int position){

    imageView.setImageResource(wallpaperImages[position]);

}
</code>```

Title: RecyclerView not shown

Body:
I used techniques given in other answers like downgrading the versions of dependencies to 24... and 25.0.1.Did not work.I have width and height of RecyclerView as match_parent.
Following is the code.I am using RecyclerView for post title and post description in a blog app:

package com.awani.pocketblog;

import android.content.ClipData;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {

private RecyclerView mBlogList;
private DatabaseReference mDatabase;

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

    mBlogList = (RecyclerView) findViewById(R.id.blog_list);
    mBlogList.setHasFixedSize(true);
    mBlogList.setLayoutManager(new LinearLayoutManager(this));
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
}

@Override
protected void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<Blog,BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>( Blog.class,
            R.layout.blog_row,
            BlogViewHolder.class,
            mDatabase

    ) {
        @Override
        protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
            viewHolder.setTitle(model.getTitle());//model means Blog class over here
            viewHolder.setDesc(model.getDesc());

        }
    };

    mBlogList.setAdapter(firebaseRecyclerAdapter);
}

//holder for the recyclerView
public static class BlogViewHolder extends RecyclerView.ViewHolder{

    View mView;

    public BlogViewHolder(View itemView) {
        super(itemView);

        mView = itemView;
    }

    public void setTitle(String title){

        TextView post_title = (TextView) mView.findViewById(R.id.post_title);
        post_title.setText(title);

    }

    public void setDesc(String desc){

        TextView post_description = (TextView) mView.findViewById(R.id.post_description);
        post_description.setText(desc);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu,menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.action_add){
        startActivity(new Intent(MainActivity.this,PostActivity.class));
    }

    return super.onOptionsItemSelected(item);
}
}

log cat statement which might be causing this..

07-08 17:22:10.761 23308-23308/com.awani.pocketblog W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

this is activity_main.xml code:

<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.awani.pocketblog.MainActivity">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/blog_list">
</android.support.v7.widget.RecyclerView>

</android.widget.RelativeLayout>

My android studio version is 2.3.2 and he dependencies are 25.3.1
and firebase dependencies are 10.0.1
firebase ui dependency 1.1.1

Body:
Follow This Example Step by Step

public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener {

    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area_list);
       recyclerView=(RecyclerView)findViewById(R.id.recycler_view1);

                    populateRecyclerView();
                    recyclerView.setHasFixedSize(true);
                    GridLayoutManager layoutManager = new GridLayoutManager(AreaListActivity.this,3);
                    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(AreaListActivity.this, layoutManager.getOrientation());
                    recyclerView.addItemDecoration(dividerItemDecoration);
                    recyclerView.setLayoutManager(layoutManager);

        //recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
     //   recyclerView.setLayoutManager(new GridLayoutManager(this,3));
     //   recyclerView.getLayoutManager().scrollToPosition(5);

    }

    public void populateRecyclerView(){
        //pass the allAreaList to it
        RecyclerViewAdapter adapter=new RecyclerViewAdapter(AreaListActivity.this,ArrayList,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        //recyclerView.setAdapter(new RecyclerViewAdapter(MainActivity.this,this));
    }

    @Override
    public void recyclerViewListClicked(View v, int position) {
        Intent myIntent=new Intent(MainActivity.this,SecondActivity.class);

        myIntent.putExtra("position",position);
        startActivity(myIntent);
        finish();
    }

@Override
public void onBackPressed() {
    Intent myIntent=new Intent(MainActivity.this,HomeActivity.class);
    startActivity(myIntent);
    finish();
}
}

RecyclerViewHolder Class

public class RecyclerViewHolder extends RecyclerView.ViewHolder  {

//view holder is for girdview as we used in the listView
public ImageView imageView,imageView2;
public RecyclerViewHolder(View itemView) {
    super(itemView);
    this.imageView=(ImageView)itemView.findViewById(R.id.image);
}

}

Adapter Class
public class RecyclerView_Adapter extends RecyclerView.Adapter {

//RecyclerView will extend to recayclerview Adapter
private ArrayList<ModelClass> arrayList;
private Context context;
private static RecyclerViewClickListener itemListener;
//constructor of the RecyclerView Adapter
RecyclerView_Adapter(Context context,ArrayList<ModelClass> arrayList,RecyclerViewClickListener itemListener){
    this.context=context;
    this.arrayList=arrayList;
    this.itemListener=itemListener;
}

@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    //this method will inflate the custom layout and return as viewHolder
    LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
    ViewGroup mainGroup=(ViewGroup) layoutInflater.inflate(R.layout.single_item,parent,false);
    RecyclerViewHolder listHolder=new RecyclerViewHolder(mainGroup);

    return listHolder;
}

@Override
public void onBindViewHolder(RecyclerViewHolder holder, final int position) {

    final ModelClass modelClass=arrayList.get(position);
    //holder
    RecyclerViewHolder mainHolder=(RecyclerViewHolder)holder;
    //convert the drawable image into bitmap
    Bitmap image= BitmapFactory.decodeResource(context.getResources(),modelClass.getImage());
    //set the image into imageView
    mainHolder.imageView.setImageBitmap(image);
    //to handle on click event when clicked on the recyclerview item and
    // get it through the RecyclerViewHolder class we have defined the views there
    mainHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //get the position of the image which is clicked
         itemListener.recyclerViewListClicked(v,position);
        }
    });

}

@Override
public int getItemCount() {
    return (null!=arrayList?arrayList.size():0);
}

}

Interface

public interface RecyclerViewClickListener {

//this is method to handle the event when clicked on the image in Recyclerview
public void recyclerViewListClicked(View v,int position);

}

//and to call this method in activity
RecyclerView_Adapter adapter=new RecyclerView_Adapter(Wallpaper.this,arrayList,this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

@Override
public void  recyclerViewListClicked(View v,int position){

    imageView.setImageResource(wallpaperImages[position]);

}


问:
Using sed command how can I replace Linux path to Windows path
I want to change the Linux path to a Windows Path, using "sed" command, for example:

Linux path: /opt/test/dash/apps/tomcat to Windows Path:
  c:\\test\\dash\\apps\\tomcat

I tried with:

```<code>sed -i 's|'/opt/test/dash/apps/tomcat'|'c:\\\\\\\test\\\\\\\dash\\\\\\\apps\\\\\\\tomcat'|g' /filename - But no luck!!
</code>```

What I exactly want all /opt/ should replace by c:\\ and rest of the "/" should be replace by "\\".

NOTE: I am executing this command remotely using ssh2_exec, All "sed" commands are working except the above.

Thanks in advance!!

答:
I'd use regular expressions and so:

```<code>sed -r 's@/(.*)/(.*)/(.*)/(.*)/(.*)@C:\\\\\2\\\\\3\\\\\4\\\\\5@'
</code>```

Using -r to enable interpretation of regular expressions and @ as the sed separator, split the path in 5 parts and then refer to them in the translated section with \1 \2 etc.

Body:
I want to change the Linux path to a Windows Path, using "sed" command, for example:

Linux path: /opt/test/dash/apps/tomcat to Windows Path:
  c:\\test\\dash\\apps\\tomcat

I tried with:

sed -i 's|'/opt/test/dash/apps/tomcat'|'c:\\\\\\\test\\\\\\\dash\\\\\\\apps\\\\\\\tomcat'|g' /filename - But no luck!!

What I exactly want all /opt/ should replace by c:\\ and rest of the "/" should be replace by "\\".

NOTE: I am executing this command remotely using ssh2_exec, All "sed" commands are working except the above.

Thanks in advance!!

Body:
I'd use regular expressions and so:

sed -r 's@/(.*)/(.*)/(.*)/(.*)/(.*)@C:\\\\\2\\\\\3\\\\\4\\\\\5@'

Using -r to enable interpretation of regular expressions and @ as the sed separator, split the path in 5 parts and then refer to them in the translated section with \1 \2 etc.