答:
One way to do is by using below code snippet -

```<code>DECLARE @xmltext XML = N'<RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>'
SELECT T.C.value('CUSTOMERNO[1]', 'varchar(255)') FROM @xmltext.nodes('/RESPONSEINFO') T(C)
</code>```

Edit: Based on the changed question, modified the code snippet -

```<code>DECLARE @xmltext XML = '<?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
 <CreateCustomerResponse xmlns="http://tempuri.org/">
 <CreateCustomerResult><RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>
 </CreateCustomerResult>
 </CreateCustomerResponse>
 </soap:Body>
 </soap:Envelope>'
SELECT CAST(T.C.value('(.)[1]', 'nvarchar(max)') AS XML).value('(/RESPONSEINFO/CUSTOMERNO)[1]','nvarchar(100)')
FROM @xmltext.nodes('/*:Envelope/*:Body/*:CreateCustomerResponse/*:CreateCustomerResult') T(C)
</code>```

Title: Read XML value using TSQL

Body:
One way to do is by using below code snippet -

DECLARE @xmltext XML = N'<RESPONSEINFO><STATUS><TRANSACTIONNO>60878693</TRANSACTIONNO><ERRORNO>1002</ERRORNO><MESSAGE>Success</MESSAGE></STATUS><CUSTOMERNO>9021325146</CUSTOMERNO></RESPONSEINFO>'
SELECT T.C.value('CUSTOMERNO[1]', 'varchar(255)') FROM @xmltext.nodes('/RESPONSEINFO') T(C)

Edit: Based on the changed question, modified the code snippet -

DECLARE @xmltext XML = '<?xml version="1.0" encoding="utf-8"?>
 <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
 <CreateCustomerResponse xmlns="http://tempuri.org/">
 <CreateCustomerResult>&lt;RESPONSEINFO&gt;&lt;STATUS&gt;&lt;TRANSACTIONNO&gt;60878693&lt;/TRANSACTIONNO&gt;&lt;ERRORNO&gt;1002&lt;/ERRORNO&gt;&lt;MESSAGE&gt;Success&lt;/MESSAGE&gt;&lt;/STATUS&gt;&lt;CUSTOMERNO&gt;9021325146&lt;/CUSTOMERNO&gt;&lt;/RESPONSEINFO&gt;
 </CreateCustomerResult>
 </CreateCustomerResponse>
 </soap:Body>
 </soap:Envelope>'
SELECT CAST(T.C.value('(.)[1]', 'nvarchar(max)') AS XML).value('(/RESPONSEINFO/CUSTOMERNO)[1]','nvarchar(100)')
FROM @xmltext.nodes('/*:Envelope/*:Body/*:CreateCustomerResponse/*:CreateCustomerResult') T(C)


来源: stackexchange

问:
How to split lines from Windows text file (/r/n separation)
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

```<code>string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array
</code>```

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

答:
You can use this overload of String.Split, which takes an array of strings that can serve as delimiters:

```<code>string[] lines = operationtext.Split(new[] { Environment.NewLine },
                                     StringSplitOptions.RemoveEmptyEntries);
</code>```

Of course, if you already have the file-path, it's much simpler to use File.ReadAllLines:

```<code>string[] lines = File.ReadAllLines(filePath);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My question is quite simple. I need to get all text lines from Windows text file.
All lines are separated by \r\n symbols. I use String.Split, but its not cool, because
it only splits 'by one symbol' leaving empty string that I need to remove with options flag. Is there a better way?

My implementation

string wholefile = GetFromSomeWhere();

// now parsing
string[] lines = operationtext.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

// ok now I have lines array

UPDATE

File.ReadAllXXX is of no use here coz GetFromSomeWhere is actually RegEx, so I've no file after this point.

Body:
You can use this overload of String.Split, which takes an array of strings that can serve as delimiters:

string[] lines = operationtext.Split(new[] { Environment.NewLine },
                                     StringSplitOptions.RemoveEmptyEntries);

Of course, if you already have the file-path, it's much simpler to use File.ReadAllLines:

string[] lines = File.ReadAllLines(filePath);


问:
Remove duplicate rows from joined table
I have following sql query

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Which provide following result

```<code>School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1
</code>```

My question is how to remove those duplicates and get only following.

```<code> School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1
</code>```

I tried with

```<code>   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School
</code>```

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

答:
You have to only add distinct keyword like this :-</p>

```<code> SELECT DISTINCT  m.School, c.avgscore
  FROM postswithratings c
 join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

ContentLicense: CC BY-SA 3.0

Title: Remove duplicate rows from joined table

Body:
I have following sql query

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.

 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with

   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

Body:
You have to only add distinct keyword like this :-

 SELECT DISTINCT  m.School, c.avgscore
  FROM postswithratings c
 join ZEntrycriteria on c.fk_postID= m.schoolcode


问:
In Doctrine QueryBuilder, trying to select records based on number of related entity records
Spent all day on this one so far...

I have entities Room and User. Many users to a room. That relationship is working great.

I'm trying to select all rooms that have fewer than four related users. Seems like it should be pretty straightforward with either DQL or QueryBuilder, but it's been giving me trouble. Couldn't find anything exactly fitting in searches. Most frequent unexpected results are either a) returning no results b) returning a single result that may or may not have <4 users.

Below is the code as I would have expected it to work. Any help would be appreciated, thank you!

```<code>$rooms_with_space = $em->createQueryBuilder()
    ->select('c')
    ->from('MyBundle:Room', 'c')
    ->leftJoin('c.users', 'u')
    ->having('COUNT(u.id) > 4')
    ->getQuery()
    ->getResult();
</code>```

答:
As I know, COUNT function on HAVING works when there is having a GROUP BY.

I think you need to add a GROUP BY of Room ID:

```<code>$rooms_with_space = $em->createQueryBuilder()
    ->select('c')
    ->from('MyBundle:Room', 'c')
    ->leftJoin('c.users', 'u')
    ->groupBy('c.id')
    ->having('COUNT(u.id) > 4')
    ->getQuery()
    ->getResult();
</code>```

Hope this can help you!

Body:
Spent all day on this one so far...

I have entities Room and User. Many users to a room. That relationship is working great.

I'm trying to select all rooms that have fewer than four related users. Seems like it should be pretty straightforward with either DQL or QueryBuilder, but it's been giving me trouble. Couldn't find anything exactly fitting in searches. Most frequent unexpected results are either a) returning no results b) returning a single result that may or may not have <4 users.

Below is the code as I would have expected it to work. Any help would be appreciated, thank you!

$rooms_with_space = $em->createQueryBuilder()
    ->select('c')
    ->from('MyBundle:Room', 'c')
    ->leftJoin('c.users', 'u')
    ->having('COUNT(u.id) > 4')
    ->getQuery()
    ->getResult();

Body:
As I know, COUNT function on HAVING works when there is having a GROUP BY.

I think you need to add a GROUP BY of Room ID:

$rooms_with_space = $em->createQueryBuilder()
    ->select('c')
    ->from('MyBundle:Room', 'c')
    ->leftJoin('c.users', 'u')
    ->groupBy('c.id')
    ->having('COUNT(u.id) > 4')
    ->getQuery()
    ->getResult();

Hope this can help you!


问:
How to know if lazy loading worked via hibernate mapping?
I have a Person object with 5 columns and i used following properties:

```<code> property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"
</code>```

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks

答: You can use the config hibernate.show_sql=true and view the output SQL.

Body:
I have a Person object with 5 columns and i used following properties:

 property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks


问:
Quartz Cron Job scheduling
I want to schedule a Job in the Quartz Cron job format to run everyday at 4:30am. so i did   0 30 4 */1 * ?   . Will this work good.  How different is this expression when compared to  0 30 4 * * ?  . Plz tell me, if they are going to work the same or not !</p>

答: Yes, they should work equally. */1 is cron idiom for "every 1 day", but that is already the default for cron expressions unless specified otherwise.

Title: Quartz Cron Job scheduling

ContentLicense: CC BY-SA 4.0


问:
How to get a list of all propriety name of a geoJson?
I have a geoJson file structured this way:

```<code>"type":"Feature",
         "id":"AFG",
         "properties":{
            "name":"Afghanistan"
         },
         "geometry":{
            "type":"Polygon",
            "coordinates":[
               [
                  [
                     61.210817,
                     35.650072
</code>```

It's the whole world and I need to grab all the country names and have them as a list the following in order to be able to use them for the autocomplete:

```<code>var availableTags = [
"Afghanistan",
"Angola",
"Albania",
"United Arab Emirates",
    "Angola",
    "Albania",
    "United Arab Emirates",
    ....
</code>```

How would I grab the country names as a list based on the geoJson object?

答:
You can use Array#map()

```<code>data.features.map(o=>o.properties.name)
</code>```

here is your updated JsFiddle

Body:
I have a geoJson file structured this way:

"type":"Feature",
         "id":"AFG",
         "properties":{
            "name":"Afghanistan"
         },
         "geometry":{
            "type":"Polygon",
            "coordinates":[
               [
                  [
                     61.210817,
                     35.650072

It's the whole world and I need to grab all the country names and have them as a list the following in order to be able to use them for the autocomplete:

var availableTags = [
"Afghanistan",
"Angola",
"Albania",
"United Arab Emirates",
    "Angola",
    "Albania",
    "United Arab Emirates",
    ....

How would I grab the country names as a list based on the geoJson object?

Body:
You can use Array#map()

data.features.map(o=>o.properties.name)

here is your updated JsFiddle


问:
MySQL TRUNCATE or ROUND with variable decimal length
I am not able to TRUNCATE (or round) a decimal on variable decimal lengh.
Here's my MySQL query:

```<code>SELECT
TRUNCATE( `amount` , `decimal_length` ) AS truncated_decimal,
FROM table

-- sample data
amount    decimal length
123.123    0
456.456    1
789.789    2

--expected outcome
truncated_decimal
123
456.4
789.78

--current outcome (wrong)
truncated_decimal
123.123
456.456
789.789
</code>```

My truncated_decimal variable is returned WITHOUT truncation, i.e. default decimal length from table. Same behavior with ROUND function.
Variable decimal_length is an integer that is different for different rows in table.

Any ideas?

答:
So the correct answer to get variable length decimals is to use FORMAT function:

```<code>SELECT
FORMAT( `amount` , `decimal_length` ) AS truncated_decimal,
FROM table
</code>```

It does go with rounding, but at least you get needed variable length decimals.

Body:
I am not able to TRUNCATE (or round) a decimal on variable decimal lengh.
Here's my MySQL query:

SELECT
TRUNCATE( `amount` , `decimal_length` ) AS truncated_decimal,
FROM table

-- sample data
amount    decimal length
123.123    0
456.456    1
789.789    2

--expected outcome
truncated_decimal
123
456.4
789.78

--current outcome (wrong)
truncated_decimal
123.123
456.456
789.789

My truncated_decimal variable is returned WITHOUT truncation, i.e. default decimal length from table. Same behavior with ROUND function.
Variable decimal_length is an integer that is different for different rows in table.

Any ideas?

Body:
So the correct answer to get variable length decimals is to use FORMAT function:

SELECT
FORMAT( `amount` , `decimal_length` ) AS truncated_decimal,
FROM table

It does go with rounding, but at least you get needed variable length decimals.


问:
Using C# to make Application for Maemo (convert code to QT)
I want to make an application for my phone (Nokia N900) It uses the Maemo Platform, which is a Linux variant. Most applications are made with either QT or Python, i only have experience in C#, and am wondering if it is at all possible to convert C# to QT, or would i have to use something like Mono or Vala to write the code in C# and create the applications for the N900??

Cheers,

Brendan

答:
C# as a programming language is controlled by Microsoft. While Microsoft has stated that they will provide a "patent convenant" regarding C#, it is hard to believe them since they have been so eager to sue in the past. ;)

If you want to "convert" your C# app, you'll need to incorporate it into Mono. Mono is a 'cross-platform, opensource .NET development framework." http://www.mono-project.com/Main_Page

Once you've got your app working in Mono, you'll need to interface into Maemo. There are a couple of routes to do this, but Qt is the most likely one to choose. It might be so much work to port your app to Qt that you decide to re-write it, fortunately Qt supports a number of programming languages so you may be able to find something similar to Mono if not Mono and C# itself.


问:
How to deal with missing values in python scikit NMF
I am trying to apply NMF on my dataset, using python scikit-learn. My dataset contains 0 values and missing values. But scikit-learn does not allow NaN value in data matrix. Some posts said that replace missing values with zeros.

my questions are:

If I replace missing value with zeros, how can the algorithm tell the missing values and real zero values?

Is there any other NMF implementations can deal with missing values?

Or if there are any other matrix factorization algorithms can do the missing value prediction?

答:
SGD will do the job here, but scikit-learn does not have one that could be applied for the task. Writing your own one will do the job, but will be really slow since one cannot directly parallelise matrix factorization SGD.
Check Distributed SGD algorithm described here. It is not so hard to implement and it speeds up things significantly.


问:
findFragmentById always returns null
I'm defining an ID for my fragment in the xml layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...
</code>```

Then I add this fragment in the activity's onCreate method:

```<code>MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
</code>```

This is all working fine. Replacing fragments and is also working.

Later I'm trying to retrieve this fragment by its ID in one of the activity's methods:

```<code>MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
</code>```

Doing so leads to myFragment being null. Always.

When I try to do the same with tags instead of IDs I can retrieve the fragment by its tag without any problems:

```<code>MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
</code>```

...

```<code>MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
</code>```

Why can't findFragmentById find the fragment, but findFragmentByTag does so? Am I missing something?

答:
```<code>FragmentB fragmentB =
(FragmentB) getSupportFragmentManager().findFragmentById(R.id.containerb);

if(fragmentB != null)
{
   fragmentB.showuserResponse(msg);
}
</code>```

Use container id as fragment id. And then check for null reference.

Title: findFragmentById always returns null

Body:
I'm defining an ID for my fragment in the xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...

Then I add this fragment in the activity's onCreate method:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();

This is all working fine. Replacing fragments and is also working.

Later I'm trying to retrieve this fragment by its ID in one of the activity's methods:

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);

Doing so leads to myFragment being null. Always.

When I try to do the same with tags instead of IDs I can retrieve the fragment by its tag without any problems:

MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();

...

MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");

Why can't findFragmentById find the fragment, but findFragmentByTag does so? Am I missing something?

Body:
FragmentB fragmentB =
(FragmentB) getSupportFragmentManager().findFragmentById(R.id.containerb);

if(fragmentB != null)
{
   fragmentB.showuserResponse(msg);
}

Use container id as fragment id. And then check for null reference.


问:
c# - dll not working properly
Didn't know which title to set, because I don't exactly know what is the problem.
I had a working c# code, i wrapped it into dll to separate client from other functions, but now it doesn't work like intended. It is a client-server over udp. Here is my code:

```<code>HandlerFactory factory = new HandlerFactory();
        factory.RegisterHandler(RequestType.Options, () => new OptionsHandler());
        factory.RegisterHandler(RequestType.Unauthorized, () => new UnauthorizedHandler());
        factory.RegisterHandler(RequestType.Ok, () => new OkHandler());
        factory.RegisterHandler(RequestType.Invite, () => new InviteHandler());
        factory.RegisterHandler(RequestType.Bye, () => new ByeHandler());
        factory.RegisterHandler(RequestType.Error, () => new ErrorHandler());

        Application.SetCompatibleTextRenderingDefault(false);

        Client client = new Client(factory);
        client.Start();
        client.Register();
</code>```

And in client:

```<code>    private void Listen()
    {
        while (!_stopping)
        {
            try
            {
                var asyncResult = MyUdpClient.BeginReceive(HandleIncomingUdpRequest, null);
                WaitHandle.WaitAny(new[] { _stopHandle, asyncResult.AsyncWaitHandle });
            }
            catch (Exception ex)
            {
                using (var sw = new StreamWriter("log.txt"))
                {
                    sw.WriteLine("Date:" + DateTime.Now + "\r\nError:" + ex.Message + "\r\n");
                }
            }
        }
        MyUdpClient.Close();
    }

private void HandleIncomingUdpRequest(IAsyncResult ar)
        {
            var received = MyUdpClient.EndReceive(ar, ref _serverAddress);
            var requestString = Encoding.ASCII.GetString(received);
            var type = Helper.GetRequestType(requestString);
            if (type != RequestType.Trying && type != RequestType.Unknown)
            {
                ProcessRequest(type, requestString);
            }
        }
</code>```

So, i wrapped it into dll, and now use it like this:

```<code>        var factory = new Factory.HandlerFactory();
        factory.RegisterHandler(RequestType.Options, ()=> new OptionsHandler());
        factory.RegisterHandler(RequestType.Unauthorized, () => new UnauthorizedHandler());
        factory.RegisterHandler(RequestType.Ok, () => new OkHandler());
        factory.RegisterHandler(RequestType.Invite, () => new InviteHandler());
        factory.RegisterHandler(RequestType.Bye, () => new ByeHandler());
        factory.RegisterHandler(RequestType.Error, () => new ErrorHandler());
        Client cl = new Client(factory);
        cl.Start();
        cl.Register();
        cl.Call("2");
</code>```

The problem is, on cl.Call("2") i get "An unhandled exception of type 'System.ObjectDisposedException' occurred in System.dll" in

```<code>                var received = MyUdpClient.EndReceive(ar, ref _serverAddress);
</code>```

And in Register(), client should send Register Request, get response that he is not Unauthorized and call UnauthorizedHandler, but this is not happening.

答:
The problem was - I don't know how it happened - in this code:

```<code>private void Listen()
    {
        while (!_stopping)
        {
            try
            {
                var asyncResult = MyUdpClient.BeginReceive(HandleIncomingUdpRequest, null);
                WaitHandle.WaitAny(new[] { _stopHandle, asyncResult.AsyncWaitHandle });
            }
            catch (Exception ex)
            {
                using (var sw = new StreamWriter("log.txt"))
                {
                    sw.WriteLine("Date:" + DateTime.Now + "\r\nError:" + ex.Message + "\r\n");
                }
            }
            MyUdpClient.Close();
        }
    }
</code>```

MyUdpClient.Close() was called inside the loop. I must have changed try-catch blocks and accidentally put that inside the loop, and when I asked this question i copypasted it from different source.

Title: c# - dll not working properly

Body:
Didn't know which title to set, because I don't exactly know what is the problem.
I had a working c# code, i wrapped it into dll to separate client from other functions, but now it doesn't work like intended. It is a client-server over udp. Here is my code:

HandlerFactory factory = new HandlerFactory();
        factory.RegisterHandler(RequestType.Options, () => new OptionsHandler());
        factory.RegisterHandler(RequestType.Unauthorized, () => new UnauthorizedHandler());
        factory.RegisterHandler(RequestType.Ok, () => new OkHandler());
        factory.RegisterHandler(RequestType.Invite, () => new InviteHandler());
        factory.RegisterHandler(RequestType.Bye, () => new ByeHandler());
        factory.RegisterHandler(RequestType.Error, () => new ErrorHandler());

        Application.SetCompatibleTextRenderingDefault(false);

        Client client = new Client(factory);
        client.Start();
        client.Register();

And in client:

    private void Listen()
    {
        while (!_stopping)
        {
            try
            {
                var asyncResult = MyUdpClient.BeginReceive(HandleIncomingUdpRequest, null);
                WaitHandle.WaitAny(new[] { _stopHandle, asyncResult.AsyncWaitHandle });
            }
            catch (Exception ex)
            {
                using (var sw = new StreamWriter("log.txt"))
                {
                    sw.WriteLine("Date:" + DateTime.Now + "\r\nError:" + ex.Message + "\r\n");
                }
            }
        }
        MyUdpClient.Close();
    }

private void HandleIncomingUdpRequest(IAsyncResult ar)
        {
            var received = MyUdpClient.EndReceive(ar, ref _serverAddress);
            var requestString = Encoding.ASCII.GetString(received);
            var type = Helper.GetRequestType(requestString);
            if (type != RequestType.Trying && type != RequestType.Unknown)
            {
                ProcessRequest(type, requestString);
            }
        }

So, i wrapped it into dll, and now use it like this:

        var factory = new Factory.HandlerFactory();
        factory.RegisterHandler(RequestType.Options, ()=> new OptionsHandler());
        factory.RegisterHandler(RequestType.Unauthorized, () => new UnauthorizedHandler());
        factory.RegisterHandler(RequestType.Ok, () => new OkHandler());
        factory.RegisterHandler(RequestType.Invite, () => new InviteHandler());
        factory.RegisterHandler(RequestType.Bye, () => new ByeHandler());
        factory.RegisterHandler(RequestType.Error, () => new ErrorHandler());
        Client cl = new Client(factory);
        cl.Start();
        cl.Register();
        cl.Call("2");

The problem is, on cl.Call("2") i get "An unhandled exception of type 'System.ObjectDisposedException' occurred in System.dll" in

                var received = MyUdpClient.EndReceive(ar, ref _serverAddress);

And in Register(), client should send Register Request, get response that he is not Unauthorized and call UnauthorizedHandler, but this is not happening.

Body:
The problem was - I don't know how it happened - in this code:

private void Listen()
    {
        while (!_stopping)
        {
            try
            {
                var asyncResult = MyUdpClient.BeginReceive(HandleIncomingUdpRequest, null);
                WaitHandle.WaitAny(new[] { _stopHandle, asyncResult.AsyncWaitHandle });
            }
            catch (Exception ex)
            {
                using (var sw = new StreamWriter("log.txt"))
                {
                    sw.WriteLine("Date:" + DateTime.Now + "\r\nError:" + ex.Message + "\r\n");
                }
            }
            MyUdpClient.Close();
        }
    }

MyUdpClient.Close() was called inside the loop. I must have changed try-catch blocks and accidentally put that inside the loop, and when I asked this question i copypasted it from different source.


问:
How to make '?' non gready
I have a CLASSPATH value C:\Windows\abc;C:\Windows\def;C:\Windows\ghi and need to get C:\Windows\def. Value of CLASSPATH can vary except def of middle path (or only one path \..\..\parent\def be present in CLASSPATH).

Regex is ;?(.*def) but it is matching C:\Windows\abc;C:\Windows\def

I want only C:\Windows\def regardless of presence of ; just before C:\Windows\def

What is the proper way to achieve it ?

答:
Greediness isn’t the issue here; rather, you need to exclude semicolons.

Match a sequence of characters not containing ; but ending in def:

[^;]*def```

<p>and make sure it’s followed by the end of the string or a <code>;</code>:</p>

<pre class="lang-none prettyprint-override"><code>[^;]*def<b>(?=;|$)</b></code>```

Title: How to make '?' non gready

Body:
Greediness isn’t the issue here; rather, you need to exclude semicolons.

Match a sequence of characters not containing ; but ending in def:

[^;]*def

and make sure it’s followed by the end of the string or a ;:

[^;]*def(?=;|$)


问:
Rails Tutorial: Undefined method errors in chapter 6
I'm currently working on 6.3.1 of Hartl's tutorial http://www.railstutorial.org/book/modeling_users

After running  rails test I'm getting the following failures - I'm sure I'm misunderstanding the instructions or something. I'm grateful for any insight into what I'm doing wrong:

```<code>Error:
UserTest#test_should_be_valid:
NoMethodError: undefined method `valid?' for nil:NilClass
    test/models/user_test.rb:15:in `block in <class:UserTest>'

Error:
UserTest#test_email_should_be_present:
NoMethodError: undefined method `email=' for nil:NilClass
    test/models/user_test.rb:24:in `block in <class:UserTest>'

Error:
UserTest#test_email_addresses_should_be_saved_as_lower-case:
NoMethodError: undefined method `email=' for nil:NilClass
    test/models/user_test.rb:46:in `block in <class:UserTest>'
</code>```

/test/models/user_test.rb

```<code>require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    def setup
      @user = User.new(name: "Example User", email: "user@example.com",
                       password: "foobar", password_confirmation: "foobar")

    end

  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should be present" do
    @user.name = "a" * 51
    assert_not @user.valid?
  end

  test "email should be present" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should accept valid adresses" do
    valid_adresses = %w[user@example.com USER@foo.COM A_US_ER@foo.bar.org
                        first.last@foo.jp alice+bob@baz.cn]
    valid_adresses.each do |valid_adresses|
      @user.email = valid_adresses
      assert @user.valid?, "#{valid_adresses.inspect} should be valid"
    end
  end

  test "email adresses should be unique" do
    duplicate_user = @user.dup
    duplicate_user.email = @user.email.upcase
    @user.save
    assert_not duplicate_user.valid?
  end

  test "email addresses should be saved as lower-case" do
    mixed_case_email = "Foo@ExAMPle.CoM"
    @user.email = mixed_case_email
    @user.save
    assert_equal mixed_case_email.downcase, @user.reload.email
  end
end
</code>```

/app/models/user.rb

```<code>class User < ApplicationRecord
  before_save { self.email = email.downcase }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false}
has_secure_password

end
</code>```

Gemfile

```<code>source 'https://rubygems.org'

gem 'rails',        '5.0.2'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt'
gem 'puma',         '3.4.0'
gem 'sass-rails',   '5.0.6'
gem 'bootstrap-sass', '3.3.6'
gem 'uglifier',     '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks',   '5.0.1'
gem 'coffee-script-source', '1.8.0'
gem 'jbuilder',     '2.4.1'

group :development, :test do
  gem 'sqlite3', '1.3.12'
  gem 'byebug',  '9.0.0', platform: :mri
end

group :development do
  gem 'web-console',           '3.1.1'
  gem 'listen',                '3.0.8'
  gem 'spring',                '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'
end

group :test do
  gem 'rails-controller-testing', '0.1.1'
  gem 'minitest-reporters',       '1.1.9'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '0.18.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

Thanks so much in advance!

答:
As per your post setup method you define wrongly

1) you write def setup and inside of it again def setup

2) Please check test database prepare properly.

your code:

```<code>def setup
  def setup
    @user = User.new(name: "Example User", email: "user@example.com",
                       password: "foobar", password_confirmation: "foobar")
    end
end
</code>```

Please try below

```<code>require 'test_helper'

class UserTest < ActiveSupport::TestCase
   setup do
     @user = User.new(name: "Example User", email: "user@example.com",
                      password: "foobar", password_confirmation: "foobar")
   end

   ...
 end
</code>```

Body:
I'm currently working on 6.3.1 of Hartl's tutorial http://www.railstutorial.org/book/modeling_users

After running  rails test I'm getting the following failures - I'm sure I'm misunderstanding the instructions or something. I'm grateful for any insight into what I'm doing wrong:

Error:
UserTest#test_should_be_valid:
NoMethodError: undefined method `valid?' for nil:NilClass
    test/models/user_test.rb:15:in `block in <class:UserTest>'

Error:
UserTest#test_email_should_be_present:
NoMethodError: undefined method `email=' for nil:NilClass
    test/models/user_test.rb:24:in `block in <class:UserTest>'

Error:
UserTest#test_email_addresses_should_be_saved_as_lower-case:
NoMethodError: undefined method `email=' for nil:NilClass
    test/models/user_test.rb:46:in `block in <class:UserTest>'

/test/models/user_test.rb

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    def setup
      @user = User.new(name: "Example User", email: "user@example.com",
                       password: "foobar", password_confirmation: "foobar")

    end

  end

  test "should be valid" do
    assert @user.valid?
  end

  test "name should be present" do
    @user.name = "a" * 51
    assert_not @user.valid?
  end

  test "email should be present" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should accept valid adresses" do
    valid_adresses = %w[user@example.com USER@foo.COM A_US_ER@foo.bar.org
                        first.last@foo.jp alice+bob@baz.cn]
    valid_adresses.each do |valid_adresses|
      @user.email = valid_adresses
      assert @user.valid?, "#{valid_adresses.inspect} should be valid"
    end
  end

  test "email adresses should be unique" do
    duplicate_user = @user.dup
    duplicate_user.email = @user.email.upcase
    @user.save
    assert_not duplicate_user.valid?
  end

  test "email addresses should be saved as lower-case" do
    mixed_case_email = "Foo@ExAMPle.CoM"
    @user.email = mixed_case_email
    @user.save
    assert_equal mixed_case_email.downcase, @user.reload.email
  end
end

/app/models/user.rb

class User < ApplicationRecord
  before_save { self.email = email.downcase }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false}
has_secure_password

end

Gemfile

source 'https://rubygems.org'

gem 'rails',        '5.0.2'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'bcrypt', git: 'https://github.com/codahale/bcrypt-ruby.git', :require => 'bcrypt'
gem 'puma',         '3.4.0'
gem 'sass-rails',   '5.0.6'
gem 'bootstrap-sass', '3.3.6'
gem 'uglifier',     '3.0.0'
gem 'coffee-rails', '4.2.1'
gem 'jquery-rails', '4.1.1'
gem 'turbolinks',   '5.0.1'
gem 'coffee-script-source', '1.8.0'
gem 'jbuilder',     '2.4.1'

group :development, :test do
  gem 'sqlite3', '1.3.12'
  gem 'byebug',  '9.0.0', platform: :mri
end

group :development do
  gem 'web-console',           '3.1.1'
  gem 'listen',                '3.0.8'
  gem 'spring',                '1.7.2'
  gem 'spring-watcher-listen', '2.0.0'
end

group :test do
  gem 'rails-controller-testing', '0.1.1'
  gem 'minitest-reporters',       '1.1.9'
  gem 'guard',                    '2.13.0'
  gem 'guard-minitest',           '2.4.4'
end

group :production do
  gem 'pg', '0.18.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Thanks so much in advance!

Body:
As per your post setup method you define wrongly

1) you write def setup and inside of it again def setup

2) Please check test database prepare properly.

your code:

def setup
  def setup
    @user = User.new(name: "Example User", email: "user@example.com",
                       password: "foobar", password_confirmation: "foobar")
    end
end

Please try below

require 'test_helper'

class UserTest < ActiveSupport::TestCase
   setup do
     @user = User.new(name: "Example User", email: "user@example.com",
                      password: "foobar", password_confirmation: "foobar")
   end

   ...
 end


问:
Convert integer (YYYYMMDD) to date format (mm/dd/yyyy) in python
I have following dataframe.

```<code>id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124
</code>```

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

```<code>id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015
</code>```

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

```<code>date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
</code>```

but date is in datetime object, how to put it as date in pandas DF?

Body:
I have following dataframe.

id int_date
1  20160228
2  20161231
3  20160618
4  20170123
5  20151124

How to convert above date in int format to date format of mm/dd/yyyy? Want this in particular format for further excel operations?

id int_date
1  02/28/2016
2  12/31/2016
3  06/18/2016
4  01/23/2017
5  11/24/2015

IS it also possible to generate third column with only Month in words? like January, February etc from int_date?

I tried following

date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

but date is in datetime object, how to put it as date in pandas DF?

Body:
Build a new column with applymap:

import pandas as pd

dates = [
    20160228,
    20161231,
    20160618,
    20170123,
    20151124,
]

df = pd.DataFrame(data=list(enumerate(dates, start=1)), columns=['id','int_date'])

df[['str_date']] = df[['int_date']].applymap(str).applymap(lambda s: "{}/{}/{}".format(s[4:6],s[6:], s[0:4]))

print(df)

Emits:

$ python test.py
   id  int_date    str_date
0   1  20160228  02/28/2016
1   2  20161231  12/31/2016
2   3  20160618  06/18/2016
3   4  20170123  01/23/2017
4   5  20151124  11/24/2015


问:
Django - download file without reloading the page
The flow looks like that:

user is filling the form

form is passed to the server by ajax

form is saved to db, then the pdf with the form data is created and saved in the app folder (probably a bad move here...)

ajax success causes the page to append a button 'Download' with value equal to current pdf's name so button 'Download' appears to the user

If user presses the button the very pdf that was just saved is gonna download.

Refreshing the page makes the button disappear.

I've got stuck on point 5. I have created another ajax (to avoid reloading the page) bound to the Download button. It correctly asks the server to look for the file, creates a django File object: pdf_file = File(open(file_path, 'rb'))
and creates a HttpResponse with file, and content_type='application/pdf' or 'application/download'.
response['Content-Disposition'] is attachment.

Then the ajax returns response - only it does not. Server raises no error but ajax error function is called.

I've read that downloading with ajax is not possible. Could you help me a bit to get it straight? If above snippets are not clear, I shall provide more code.
Python 3.5, Django 1.10

答:
Do like

```<code>window.location.href = "/url/to/downloadfile/"
</code>```

in javascript after success of posting form. OR

```<code>#html
<button onclick="myfiledownload()">Download</download>
#javascript
function myfiledownload(){
    window.location.href = "/url/to/downloadfile/"
}
</code>```

Body:
Do like

window.location.href = "/url/to/downloadfile/"

in javascript after success of posting form. OR

#html
<button onclick="myfiledownload()">Download</download>
#javascript
function myfiledownload(){
    window.location.href = "/url/to/downloadfile/"
}


问:
Google Analytics eCommerce Report Local Currency
new here and looking for help.

I'm trying to get the amount people are spending on a products for a website in local currency.

I'm looking at a GA page for someone overseas and the currency values from itemRevenue for each productName I'm seeing in my report in Sheets are not looking like they're local to that store but rather my countries currency. I've tried localItemRevenue but that gave an error saying the dimensions and metrics can't be used together. I've got date/hour included as well in the report.

I tried to use itemRevenue with currencyCode to get around this but they couldn't be used together either.

I thought I could use transactionRevenue along with productName/date/hour/minute but that didn't work (I realised because more than one item can be bought per transaction).

Could someone tell me what GoogleAnalytics uses for currency here and if it can be solved easily?

答:
Google Analytics uses the currency settings that are set in the data view settings.

If you send a different currency, as specified by the currency field in the e-commerce-tracking, GA will convert it to the currency set in the view settings as long as it is on the list of supported currencies.

So the first thing to do would be to check the view settings - this defaults to USD, and it happens amazingly often that people fail to set the proper currency.

Next thing to check would be to see what is actually sent to the property - if there is a mismatch between view currency and currency set in the code the values will be converted from the latter to the former.


问:
datePickerDialog spinner instead od calendar java programatically api 24
I want to display datePicker as dialog after user click a button. I followed this tutorial : https://developer.android.com/guide/topics/ui/controls/pickers.html and it works fina but I get displayed calendar instead of spinner. I tried a lot of things e.g.
1) set theme the has mode spinner,
2) There was an api :

```<code>    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
    dialog.getDatePicker().setCalendarViewShown(false)
    dialog.getDatePicker().setSpinnerShown(true)
</code>```

but those method are deprecated and has no effect.

The only thing that worked is that I decompiled DatePicker and there was a code :

```<code>   private static final int MODE_SPINNER = 1;
   private static final int MODE_CALENDAR = 2;

    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePicker,
            defStyleAttr, defStyleRes);
    final int mode = a.getInt(R.styleable.DatePicker_datePickerMode, MODE_SPINNER);
    final int firstDayOfWeek = a.getInt(R.styleable.DatePicker_firstDayOfWeek, 0);
    a.recycle();

    switch (mode) {
        case MODE_CALENDAR:
            mDelegate = createCalendarUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
        case MODE_SPINNER:
        default:
            mDelegate = createSpinnerUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
    }
</code>```

if I changed "mode" in debug mode to value = "1" spinner appeared. But how can I set this value ? How to set style R.styleable.DatePicker_datePickerMode to 1 ?

Additionally R is some kind internal - don't know what it is:

```<code>    import com.android.internal.R;
</code>```

答:
You can use the Theme to set a spinner like date picker. like below.

```<code>DatePickerDialog mDatePickerDialog = new DatePickerDialog(getActivity(),android.R.style.Theme_Holo_Light, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                }
            }, YEAR, MONTH, DAY);

mDatePickerDialog.show();
</code>```

Note : See the DatePickerDialog constructor argument android.R.style.Theme_Holo_Light this will make your dialog as a spinner.

Hope this works for you.

Body:
I want to display datePicker as dialog after user click a button. I followed this tutorial : https://developer.android.com/guide/topics/ui/controls/pickers.html and it works fina but I get displayed calendar instead of spinner. I tried a lot of things e.g.
1) set theme the has mode spinner,
2) There was an api :

    DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
    dialog.getDatePicker().setCalendarViewShown(false)
    dialog.getDatePicker().setSpinnerShown(true)

but those method are deprecated and has no effect.

The only thing that worked is that I decompiled DatePicker and there was a code :

   private static final int MODE_SPINNER = 1;
   private static final int MODE_CALENDAR = 2;

    final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePicker,
            defStyleAttr, defStyleRes);
    final int mode = a.getInt(R.styleable.DatePicker_datePickerMode, MODE_SPINNER);
    final int firstDayOfWeek = a.getInt(R.styleable.DatePicker_firstDayOfWeek, 0);
    a.recycle();

    switch (mode) {
        case MODE_CALENDAR:
            mDelegate = createCalendarUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
        case MODE_SPINNER:
        default:
            mDelegate = createSpinnerUIDelegate(context, attrs, defStyleAttr, defStyleRes);
            break;
    }

if I changed "mode" in debug mode to value = "1" spinner appeared. But how can I set this value ? How to set style R.styleable.DatePicker_datePickerMode to 1 ?

Additionally R is some kind internal - don't know what it is:

    import com.android.internal.R;

Body:
You can use the Theme to set a spinner like date picker. like below.

DatePickerDialog mDatePickerDialog = new DatePickerDialog(getActivity(),android.R.style.Theme_Holo_Light, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                }
            }, YEAR, MONTH, DAY);

mDatePickerDialog.show();

Note : See the DatePickerDialog constructor argument android.R.style.Theme_Holo_Light this will make your dialog as a spinner.

Hope this works for you.


问:
Should React.PureComponent be used for components that are updated frequently?
If a component needs to render several times a second because of a prop change, should this component extend React.PureComponent?

The component has no child components, however, it is itself deeply nested... so the props are travelling through several other components.

In general, what are some key things to consider when deciding if React.PureComponent should be used or not.  In which scenarios is it bad to use?

答:
Yes this sounds like a good case for PureComponent because your component is unnecessarily being re-rendered frequently with the same props.

A child component extended from React.Component will call render every time its parent calls render.  If instead the child component is extended from PureComponent it will only call render when the parent passes props that don't shallowEqual the previously passed props.

It's generally safe to use PureComponent as long as

your component and its children don't rely on context updates

your component doesn't have object or array props that are directly mutated by its parents (shallowEqual will not detect these changes)


问:
Generating Conway 'look and say' numbers
I was inspired to write a small C++11 program that would generate so-called Conway numbers, or 'look and say' numbers. Essentially, given the nth term, e.g. 11112, the next is simply the pronunciation of the former term; in our case 4112, because there were 4 1's and only one 2. Another example: '13' to '1113'.

The following is the source code of the program in its entirety for completeness (omit stdafx.h include if not compiling with MS Visual Studio):

```<code>#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

void print_usage(){

    cout << endl << "Conway Number Generator";
    cout << endl << "Arguments: initializer followed by nth term to be printed" << endl;
}

string say(string s){

    // Returns string said phonetically
    // e.g. '111' becomes '31'

    unsigned int sz = s.size();

    if (sz == 1){
        s.insert(0, "1");
    }
    else{
        s.insert(0, to_string(sz));
        s.erase(2, sz-1);
    }
    return s;
}

string get_next(string x){

    // Returns next term in Conway sequence

    unsigned prev_point = 0;
    vector<string> grp;
    string tmp;
    tmp.resize(x.size());

    // Organize sequence in group of identical consecutive characters

    for (unsigned int i = 0; i < x.size(); ++i){

        if (i != x.size() - 1){

            if (x.at(i) != x.at(i + 1)){
                tmp.assign(x, prev_point, i - prev_point);
                grp.push_back(tmp);
                prev_point = i + 1;
                tmp.clear();
            }
        }
        else if (i != 0){

            if (x.at(i) != x.at(i - 1)){
                tmp = x.at(i);
                grp.push_back(tmp);
                tmp.clear();
            }
        }
    }

    // Phonetically say each group

    // Could use a lambda: transform(begin(grp), end(grp), begin(said_grp)[=](string s){return say(s);});
    // if I create a new vector<string> said_grp to copy in
    // That didn't help the runtime error

    for (auto& i : grp)
        i = say(i);

    // Join each vector<string> entry into a single string

    string next_seq;
    next_seq = accumulate(begin(grp), end(grp), string(""));
    return next_seq;
}

string conway(string init, int n){

    // Print out nth Conway term
    // starting sequence at init

    for (int i = 1; i <= n; ++i)
        init = get_next(init);
    return init;
}

int main(int argc, const char* argv[]){

    if (argc < 3){
        print_usage();
        return 0;
    }
    cout << endl << "Conway number: " << conway(argv[1], stoi(argv[2])) << endl;
    return 0;
}
</code>```

The general approach:

Accept two arguments: the first term of the Conway sequence, and an integer n choose to compute the nth term of that sequence.

The function conway(...) loops through applying get_next() to the initial string n times.

The function say() 'pronounces' the numbers.

get_next() functions by splitting the entire number into consecutive identical numbers; each is then transformed by say().

The issue I'm having is an error, std::out_of_range, from the return statement of my say() function. However, I can recall testing say() alone with various inputs, and it never caused an exception. I must be using it incorrectly somehow. As I note in the code comments, I tried using the STL transform instead of a for loop with a lambda before, same error.

Note: to those interested in the Conway sequence, see the original paper by Conway. They admit some interesting properties, and it appears they give rise to a constant known as Conway's constant which was shown to be algebraic.

答:
I have looked at your source code, and noticed that your function get_next() can be simplified. I have replaced it with the following version:

```<code>string get_next(const string & inStr) {
    string result;
    int len = inStr.size();
    int count = 0;
    // Loop over non-duplicates
    for (int i = 0; i < len; i += count) {
        // Calculate total number of duplicates for inStr[i]:
        for (count = 0; i+count < len; count++) {
            if (inStr[i+count] != inStr[i]) {
                break;
            }
        }
        // Append count + non-duplicate (count and say)
        result += to_string(count) + inStr[i];
    }
    return result;
}
</code>```

When I run the new code with “1” as the initial string and 5 as n, I get the following output result:

Conway number: 312211

which is correct: 1 -> 11 -> 21 -> 1211 -> 111221 -> 312211

No debugging is needed. Hope this helps.

Body:
I was inspired to write a small C++11 program that would generate so-called Conway numbers, or 'look and say' numbers. Essentially, given the nth term, e.g. 11112, the next is simply the pronunciation of the former term; in our case 4112, because there were 4 1's and only one 2. Another example: '13' to '1113'.

The following is the source code of the program in its entirety for completeness (omit stdafx.h include if not compiling with MS Visual Studio):

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <numeric>
#include <string>
#include <vector>

using namespace std;

void print_usage(){

    cout << endl << "Conway Number Generator";
    cout << endl << "Arguments: initializer followed by nth term to be printed" << endl;
}

string say(string s){

    // Returns string said phonetically
    // e.g. '111' becomes '31'

    unsigned int sz = s.size();

    if (sz == 1){
        s.insert(0, "1");
    }
    else{
        s.insert(0, to_string(sz));
        s.erase(2, sz-1);
    }
    return s;
}

string get_next(string x){

    // Returns next term in Conway sequence

    unsigned prev_point = 0;
    vector<string> grp;
    string tmp;
    tmp.resize(x.size());

    // Organize sequence in group of identical consecutive characters

    for (unsigned int i = 0; i < x.size(); ++i){

        if (i != x.size() - 1){

            if (x.at(i) != x.at(i + 1)){
                tmp.assign(x, prev_point, i - prev_point);
                grp.push_back(tmp);
                prev_point = i + 1;
                tmp.clear();
            }
        }
        else if (i != 0){

            if (x.at(i) != x.at(i - 1)){
                tmp = x.at(i);
                grp.push_back(tmp);
                tmp.clear();
            }
        }
    }

    // Phonetically say each group

    // Could use a lambda: transform(begin(grp), end(grp), begin(said_grp)[=](string s){return say(s);});
    // if I create a new vector<string> said_grp to copy in
    // That didn't help the runtime error

    for (auto& i : grp)
        i = say(i);

    // Join each vector<string> entry into a single string

    string next_seq;
    next_seq = accumulate(begin(grp), end(grp), string(""));
    return next_seq;
}

string conway(string init, int n){

    // Print out nth Conway term
    // starting sequence at init

    for (int i = 1; i <= n; ++i)
        init = get_next(init);
    return init;
}

int main(int argc, const char* argv[]){

    if (argc < 3){
        print_usage();
        return 0;
    }
    cout << endl << "Conway number: " << conway(argv[1], stoi(argv[2])) << endl;
    return 0;
}

The general approach:

Accept two arguments: the first term of the Conway sequence, and an integer n choose to compute the nth term of that sequence.

The function conway(...) loops through applying get_next() to the initial string n times.

The function say() 'pronounces' the numbers.

get_next() functions by splitting the entire number into consecutive identical numbers; each is then transformed by say().

The issue I'm having is an error, std::out_of_range, from the return statement of my say() function. However, I can recall testing say() alone with various inputs, and it never caused an exception. I must be using it incorrectly somehow. As I note in the code comments, I tried using the STL transform instead of a for loop with a lambda before, same error.

Note: to those interested in the Conway sequence, see the original paper by Conway. They admit some interesting properties, and it appears they give rise to a constant known as Conway's constant which was shown to be algebraic.

Body:
I have looked at your source code, and noticed that your function get_next() can be simplified. I have replaced it with the following version:

string get_next(const string & inStr) {
    string result;
    int len = inStr.size();
    int count = 0;
    // Loop over non-duplicates
    for (int i = 0; i < len; i += count) {
        // Calculate total number of duplicates for inStr[i]:
        for (count = 0; i+count < len; count++) {
            if (inStr[i+count] != inStr[i]) {
                break;
            }
        }
        // Append count + non-duplicate (count and say)
        result += to_string(count) + inStr[i];
    }
    return result;
}

When I run the new code with “1” as the initial string and 5 as n, I get the following output result:

Conway number: 312211

which is correct: 1 -> 11 -> 21 -> 1211 -> 111221 -> 312211

No debugging is needed. Hope this helps.


问:
How to pass container ip as ENV to other container in docker-compose file
this is my docker-compose file:

```<code>version: '3.0'
services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: $(APP_DB_IP)
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db

 app-db:
  build: ./db
  expose:
   - "5432"

  volumes:
   - /var/lib/postgresql/data
</code>```

I want to pass to app-web the ip of app-db (Postgresql in this case) as ENV var so it can connect to the DB smoothly... any idea on how to achieve it?

答:
You actually don't need to do any of this, since you're already using the links feature in Docker Compose. Just get rid of the PG_HOST variable and use the app-db hostname:

```<code>services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db
</code>```

Since you included the app-db entry under links, you can simply use app-db as a hostname in your app-web container. Docker will set up a hostname mapping in the app-web container that resolves the app-db hostname to the database container's IP address.

You can verify that by running the following, which will try to ping the app-db container from the app-web container:

```<code>docker-compose exec app-web bash -c "ping app-db"
</code>```

This should show output from the ping command showing the resolved IP address of the app-db container, for example like this:

```<code>PING app-db (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: icmp_seq=0 ttl=64 time=0.055 ms
64 bytes from 172.19.0.2: icmp_seq=1 ttl=64 time=0.080 ms
64 bytes from 172.19.0.2: icmp_seq=2 ttl=64 time=0.098 ms
</code>```

Press ctrl+c to stop the ping command.

Like shown in the other answer, if you still want to pass in the hostname (which is probably a good idea, just in case you ever want to point to a different database), you can just use app-db as a value:

```<code>services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: app-db
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db
</code>```

Body:
this is my docker-compose file:

version: '3.0'
services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: $(APP_DB_IP)
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db

 app-db:
  build: ./db
  expose:
   - "5432"

  volumes:
   - /var/lib/postgresql/data

I want to pass to app-web the ip of app-db (Postgresql in this case) as ENV var so it can connect to the DB smoothly... any idea on how to achieve it?

Body:
You actually don't need to do any of this, since you're already using the links feature in Docker Compose. Just get rid of the PG_HOST variable and use the app-db hostname:

services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db

Since you included the app-db entry under links, you can simply use app-db as a hostname in your app-web container. Docker will set up a hostname mapping in the app-web container that resolves the app-db hostname to the database container's IP address.

You can verify that by running the following, which will try to ping the app-db container from the app-web container:

docker-compose exec app-web bash -c "ping app-db"

This should show output from the ping command showing the resolved IP address of the app-db container, for example like this:

PING app-db (172.19.0.2): 56 data bytes
64 bytes from 172.19.0.2: icmp_seq=0 ttl=64 time=0.055 ms
64 bytes from 172.19.0.2: icmp_seq=1 ttl=64 time=0.080 ms
64 bytes from 172.19.0.2: icmp_seq=2 ttl=64 time=0.098 ms

Press ctrl+c to stop the ping command.

Like shown in the other answer, if you still want to pass in the hostname (which is probably a good idea, just in case you ever want to point to a different database), you can just use app-db as a value:

services:
 app-web:
  restart: always
  build: ./web
  environment:
    PG_HOST: app-db
    PG_PORT: 5432
  ports:
   - "8081:8080"
  links:
   - app-db


问:
Adding business logic to a spring-data-rest application
I have been experimenting with spring-data-rest (SDR) and am really impressed with how quickly I can build a rest api. My application is based around the following repository which gives me GET /attachements and POST /attachements

```<code>package com.deepskyblue.attachment.repository;

import java.util.List;

import org.springframework.data.repository.Repository;

import com.deepskyblue.attachment.domain.Attachment;

public interface AttachmentRepository extends Repository<Attachment, Long> {

    List<Attachment> findAll();

    Attachment save(Attachment attachment);
}
</code>```

One thing I am confused about though is how I add custom business logic. SDR seems great if I just want a rest API to my data, however a traditional Spring application would normally have a service tier where I can have business logic. Is there a way of adding this business logic with SDR?

答:
I guess you are talking about the 3 tier architecture business tier, presentation tier and persistence tier.

I usually follow this to group my code together presentation tier will be the one that has all the classes [@RestController] Rest annotations and methods that is directly interacting with the post and get calls by the front end .

These classes will in turn Autowire the business tier and Service tier for getting data from the database or adding some business logic before fetching from the database.

Even ou can make use of RepositoryRestController . To take advantage of Spring Data REST’s settings, message converters, exception handling, and more,

Hope this is what you were looking at.

Body:
I have been experimenting with spring-data-rest (SDR) and am really impressed with how quickly I can build a rest api. My application is based around the following repository which gives me GET /attachements and POST /attachements

package com.deepskyblue.attachment.repository;

import java.util.List;

import org.springframework.data.repository.Repository;

import com.deepskyblue.attachment.domain.Attachment;

public interface AttachmentRepository extends Repository<Attachment, Long> {

    List<Attachment> findAll();

    Attachment save(Attachment attachment);
}

One thing I am confused about though is how I add custom business logic. SDR seems great if I just want a rest API to my data, however a traditional Spring application would normally have a service tier where I can have business logic. Is there a way of adding this business logic with SDR?


问:
fb:serverfbml won't render on Opera and IE
I asked the same question in Facebook developer forum, but for some reasons I want to repost it here. I hope that's okay.

I have the following fb:serverfbml snippet.

```<code><fb:serverfbml id="invite_friends_form" style="width: 100%">
  <script type="text/fbml">
    <fb:fbml><p>Testing FBML rendering</p></fb:fbml>
  </script>
</fb:serverfbml>

<script>
    $(document).ready(function()
    {
        // Parse XFBML tags
        FB.XFBML.parse();
    });
</script>
</code>```

It renders correctly in Firefox and Chrome. I got the usual Facebook loading animation for a moment, and then the sentence "Testing FBML rendering" is displayed.

BUT, when I test this on Opera 10 and Internet Explorer 8, it doesn't work. I do see the Facebook loading animation, but it never finished. When I see my network monitor, I saw a request to http://www.facebook.com/plugins/serverfbml.php with my to-be-rendered FBML passed in the query string.

The request is already completed with proper response from facebook, but still, the loading animation goes on.

Does anyone know, what might be the problem here?

Thanks, Andree.

答:
I have had the same problem for the whole morning, and I finally solved it! :)

Add:

```<code><div id="fb-root"></div>
</code>```

...some place inside your body.

Also, add xmlns:fb="http://www.facebook.com/2008/fbml" to the html tag, so that it reads:

```<code><html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
</code>```

I'm going to post my whole code so that you can compare:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
    <title></title>
</head>

<body style="margin:0px 0px 0px 0px;overflow:hidden;text-align:center;">

    <div id="fb-root"></div>

    <fb:serverFbml>
        <script type="text/fbml">
            <fb:fbml>
                <fb:request-form
                    method="POST"
                    type="jugar a Mahou Liga Chapas"
                    action="http://mahouligachapas.unusualwonder.com"
                    content='¿ Te echas un partido conmigo?
                        <fb:req-choice url="http://apps.facebook.com/mahouligachapas" label="Sí" />
                        <fb:req-choice url="http://www.facebook.com" label="No" />'
                >
                    <fb:multi-friend-selector actiontext="Invita a tus amigos a jugar a Mahou Liga Chapas"/>
                </fb:request-form>
            </fb:fbml>
        </script>
    </fb:serverFbml>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://connect.facebook.net/es_ES/all.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            FB.init({ appId: 'XXXXXXXXXXX', status: true, cookie: true, xfbml: true });
        });

    </script>

</body>
</html>
</code>```

Body:
I asked the same question in Facebook developer forum, but for some reasons I want to repost it here. I hope that's okay.

I have the following fb:serverfbml snippet.

<fb:serverfbml id="invite_friends_form" style="width: 100%">

</fb:serverfbml>

It renders correctly in Firefox and Chrome. I got the usual Facebook loading animation for a moment, and then the sentence "Testing FBML rendering" is displayed.

BUT, when I test this on Opera 10 and Internet Explorer 8, it doesn't work. I do see the Facebook loading animation, but it never finished. When I see my network monitor, I saw a request to http://www.facebook.com/plugins/serverfbml.php with my to-be-rendered FBML passed in the query string.

The request is already completed with proper response from facebook, but still, the loading animation goes on.

Does anyone know, what might be the problem here?

Thanks, Andree.

Body:
I have had the same problem for the whole morning, and I finally solved it! :)

Add:

<div id="fb-root"></div>

...some place inside your body.

Also, add xmlns:fb="http://www.facebook.com/2008/fbml" to the html tag, so that it reads:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">

I'm going to post my whole code so that you can compare:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
    <title></title>
</head>

<body style="margin:0px 0px 0px 0px;overflow:hidden;text-align:center;">

    <div id="fb-root"></div>

    <fb:serverFbml>
        <script type="text/fbml">
            <fb:fbml>
                <fb:request-form
                    method="POST"
                    type="jugar a Mahou Liga Chapas"
                    action="http://mahouligachapas.unusualwonder.com"
                    content='¿ Te echas un partido conmigo?
                        <fb:req-choice url="http://apps.facebook.com/mahouligachapas" label="Sí" />
                        <fb:req-choice url="http://www.facebook.com" label="No" />'
                >
                    <fb:multi-friend-selector actiontext="Invita a tus amigos a jugar a Mahou Liga Chapas"/>
                </fb:request-form>
            </fb:fbml>
        </script>
    </fb:serverFbml>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://connect.facebook.net/es_ES/all.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            FB.init({ appId: 'XXXXXXXXXXX', status: true, cookie: true, xfbml: true });
        });

    </script>

</body>
</html>


问:
Write IAM Policy in which any user with full access of EC2 cannot delete instance of any other user in AWS account
I want to write IAM policy in which any user with full access of ec2 is not permitted to terminate instance of any other user.

Second scenario : If i'm a normal user in aws  (with all privileges except IAM and Admin access )I want to list instance I had created and other user instance are not visible to me. Eg In Azure when i give resource level access to any other user he's not able to list see other user activities.

答:
```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "ThisLimitAccessToOwnerAccess",
        "Effect": "Allow",
        "Action": [
            "ec2:RebootInstances",
            "ec2:StopInstances",
            "ec2:TerminateInstances",
            "ec2:StartInstances",
            "ec2:AttachVolume",
            "ec2:DetachVolume"
        ],
        "Resource": "arn:aws:ec2:us-east-1:123456789:instance/*",
        "Condition": {
            "StringEquals": {
                "ec2:ResourceTag/Owner": "${aws:username}"
            }
        }
    }
]
}
</code>```

<p>(edited to correct formatting)</p>

Body:
{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "ThisLimitAccessToOwnerAccess",
        "Effect": "Allow",
        "Action": [
            "ec2:RebootInstances",
            "ec2:StopInstances",
            "ec2:TerminateInstances",
            "ec2:StartInstances",
            "ec2:AttachVolume",
            "ec2:DetachVolume"
        ],
        "Resource": "arn:aws:ec2:us-east-1:123456789:instance/*",
        "Condition": {
            "StringEquals": {
                "ec2:ResourceTag/Owner": "${aws:username}"
            }
        }
    }
]
}

(edited to correct formatting)


问:
Xcode 8.1 images are not shown
Images are not shown in Xcode 8.1 in UIImageView or any control in which we can show images.
I have @3x set of images added. Please help me out how to resolve the issue.

答:
using Xcode 8.2.1

I ran into the same issue. You need to add images for all three sizes (1x, 2x, 3x), because although the eventual build uses whatever size alternative it can find, the storyboard requires the image size for the device you've selected when Xcode asked you to choose one for "show as".

If you want to use the same image for all sizes, drag the same file in all three size containers in Assets.xcassets, example below.

Title: Xcode 8.1 images are not shown


问:
How to get the last x lines of a string in Java?
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.

How can get the last x lines of a string in Java?

答:
Algorithm

Split input text with line break character and save as a list lines

If number of lines required, linesRequired is less than size of lines, ie, lineCount

Then return sublist of lines starting from lineCount - linesRequired to lineCount.

Otherwise, throw exception or return all lines based on the requrement.

Sample Implementation

```<code>private static final String SEPARATOR = "\n";

public static List<String> getLastLines(String string, int numLines) {
    List<String> lines = Arrays.asList(string.split(SEPARATOR));
    int lineCount = lines.size();
    return lineCount > numLines ? lines.subList(lineCount - numLines, lineCount) : lines;
}
</code>```

Body:
Algorithm

Split input text with line break character and save as a list lines

If number of lines required, linesRequired is less than size of lines, ie, lineCount

Then return sublist of lines starting from lineCount - linesRequired to lineCount.

Otherwise, throw exception or return all lines based on the requrement.

Sample Implementation

private static final String SEPARATOR = "\n";

public static List<String> getLastLines(String string, int numLines) {
    List<String> lines = Arrays.asList(string.split(SEPARATOR));
    int lineCount = lines.size();
    return lineCount > numLines ? lines.subList(lineCount - numLines, lineCount) : lines;
}


问:
Configure .bash_profile on linux (CENTOS) for multiple ORACLE HOMEs
I am using a server with CENTOS 5.11 and for different circumstances I need to use two versions of Oracle. I have already installed Oracle 10g successfully, however I want to install the 12c, in part to migrate my DB.

The problem is that I do not know how to configure the .bash_profile which is where the ORACLE_HOME is configured in the following way:

```<code>    ## Oracle Env Settings
    export TMP=/tmp
    export TMPDIR=$TMP
    export ORACLE_HOSTNAME=oracle.localdomain
    export ORACLE_UNQNAME=MYDB
    export ORACLE_BASE=/u01/app/oracle
    export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
    export ORACLE_SID=MYDB
    export PATH=/usr/sbin:$PATH
    export PATH=$ORACLE_HOME/bin:$PATH
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
    export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
</code>```

I have searched and in the documentation of Oracle only mention that to install another version just need to install it in another ORACLE_HOME. So, my question is, how to add the new ORACLE_HOME in .bash_profile? and likewise if I can use the same users and groups for the new installation.

答:
An excellent question!
I stumbled upon the following:

The Ask Tom's solution:

In brief - use DBCA to configure the second installation (it will take care of those details for you and don't worry about the listener). This means that when you install the second DB, just store the files with the Universal Installer and then configure this with DBCA.

This solution over here.

In brief - use soft links for the ORACLE_SID and ORACLE_HOME. It's really a long tutorial, so there's no meaning to paste it here.

My personal favorite - Go over Point1 :-).

Now seriously - if you need to make it only through the .bash_profile, just put some if statements in it or create some external scripts for the different databases and just source them, or make .bash_profile call them, when you source it.

To wrap it all up - always "install" the database by just storing the files, don't trust the installer. After deployment, run DBCA to configure the installation. In all cases it should take care of these configurations for you. In some cases, if not all, DBCA will actually set the same ORACLE_HOME and ORACLE_SID for both, but they will have different unique names, which you'll use to connect with sqlplus to start/stop them.
As far as I see - all the solutions gravitate around the same thing I just mention in the paragraph above.

Cheers

Body:
I am using a server with CENTOS 5.11 and for different circumstances I need to use two versions of Oracle. I have already installed Oracle 10g successfully, however I want to install the 12c, in part to migrate my DB.

The problem is that I do not know how to configure the .bash_profile which is where the ORACLE_HOME is configured in the following way:

    ## Oracle Env Settings
    export TMP=/tmp
    export TMPDIR=$TMP
    export ORACLE_HOSTNAME=oracle.localdomain
    export ORACLE_UNQNAME=MYDB
    export ORACLE_BASE=/u01/app/oracle
    export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
    export ORACLE_SID=MYDB
    export PATH=/usr/sbin:$PATH
    export PATH=$ORACLE_HOME/bin:$PATH
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
    export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib

I have searched and in the documentation of Oracle only mention that to install another version just need to install it in another ORACLE_HOME. So, my question is, how to add the new ORACLE_HOME in .bash_profile? and likewise if I can use the same users and groups for the new installation.


答:
Here is another possible solution:

```<code>public class LastNLines {
    public static List<String> getLastNLines(String inputString, int n) {
        if(n < 0) {
            return new ArrayList<>();
        }
        String[] tmp = inputString.split("(\\n|\\r)+");
        if(n < tmp.length) {
            return Arrays.asList(Arrays.copyOfRange(tmp, tmp.length - n, tmp.length));
        }
        return Arrays.asList(tmp);
    }

    public static void main(String[] args) {
         String myExample =
            "  \n\r\r\n\nsome_text_1  " +
            "\n" +
            "some_text_2\n\n" +
            "\n" +
            "    some_text_3\n\r    " +
            "\n" +
            "some_text_4\n" +
            "\n" +
            "some_text_5\n\n\n";
        List<String> result = LastNLines.getLastNLines(myExample, 2);
        System.out.println(result.toString());
    }
}
</code>```

This one splits by multiple new lines at once, so a text like this \n\n\n\n\n will contain no Strings after splitting and the result will be empty.

Title: How to get the last x lines of a string in Java?

Body:
I get some result from an external command (semi-api) and want to parse the result.
I'm only interested in the last few lines of the result.

How can get the last x lines of a string in Java?

Body:
Here is another possible solution:

public class LastNLines {
    public static List<String> getLastNLines(String inputString, int n) {
        if(n < 0) {
            return new ArrayList<>();
        }
        String[] tmp = inputString.split("(\\n|\\r)+");
        if(n < tmp.length) {
            return Arrays.asList(Arrays.copyOfRange(tmp, tmp.length - n, tmp.length));
        }
        return Arrays.asList(tmp);
    }

    public static void main(String[] args) {
         String myExample =
            "  \n\r\r\n\nsome_text_1  " +
            "\n" +
            "some_text_2\n\n" +
            "\n" +
            "    some_text_3\n\r    " +
            "\n" +
            "some_text_4\n" +
            "\n" +
            "some_text_5\n\n\n";
        List<String> result = LastNLines.getLastNLines(myExample, 2);
        System.out.println(result.toString());
    }
}

This one splits by multiple new lines at once, so a text like this \n\n\n\n\n will contain no Strings after splitting and the result will be empty.


问:
HowTo for installing Informix ClientSDK on OpenSuSE 11.2
Is there a simple tutorial or HowTo that describes the installation of the IBM Informix ClientSDK on OpenSuSE 11.2? I was not able to get it work.... I set all the system environment variables like INFORMIXDIR, encoding vars, but that didn't work for me.</p>

答:
Do you have problems with installing client or with connecting database?

In clientsdk.3.70.UC1.LINUX.tar there is client_install_guide.pdf. If you have any problems then try describe it: show us error message, trace log, environment etc.

PS With installing newest, 3.70UC1 version I had problem problem on one of my old Debian machine, but it installed without problems on Ubuntu-server 9.10.


问:
If any input field value entered zero then disable else enable
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

答:
Pure HTML version. It won't put a disabled attribute on the button but it will throw a native error if you try to submit the form if any input has a value less than 1. Good to put that min property on there in any case.</p>

```<code><form>
<input type="number" min="1"/>
  <input type="number" min="1"/>
  <input type="number" min="1"/>
<button type="submit">submit</button>
</form>
</code>```

Body:
Pure HTML version. It won't put a disabled attribute on the button but it will throw a native error if you try to submit the form if any input has a value less than 1. Good to put that min property on there in any case.

<form>
<input type="number" min="1"/>
  <input type="number" min="1"/>
  <input type="number" min="1"/>
<button type="submit">submit</button>
</form>


问:
Bind Paste Function to JQuery Text Editor
Can anybody tell me why I get no output from this function?

```<code>$('.jqte_editor').bind('paste', function() {
    console.log("hi")
});
</code>```

I have also tried on(

```<code>$('.jqte_editor').on('paste', function() {
    console.log("hi")
});
</code>```

HTML:

<textarea class="jqte" style="margin-bottom: -20px;" rows="50" cols="50" name="body" id="body"></textarea>

Rendered HTML:

答:
Try this.

$(document).on("paste", ".jqte_editor", function(e) {

```<code>//Do here what you want.
</code>```

});

Body:
Can anybody tell me why I get no output from this function?

$('.jqte_editor').bind('paste', function() {
    console.log("hi")
});

I have also tried on(

$('.jqte_editor').on('paste', function() {
    console.log("hi")
});

HTML:

<textarea class="jqte" style="margin-bottom: -20px;" rows="50" cols="50" name="body" id="body"></textarea>

Rendered HTML:

Body:
Try this.

$(document).on("paste", ".jqte_editor", function(e) {

//Do here what you want.

});


问:
Solr cloud - reloading elevate.xml
I am using Apache Solr 6.5 with Query Elevation Component (/elevate endpoint) to support elevation of particular documents in my queries.

I am using elevate.xml file in

```<code><instanceDir>/conf/<config-file>
</code>```

directory. However on production server (Solr configured as cloud with zookepper to maintain configuration) changes in the elevate.xml are not loaded. To check if it works, I just query the elevated phrase and as a result I get elevated documents from previous version of elevate.xml.

Of course I am restarting all Solr cloud instances after loading new version of elevate.xml and updated file is visible in the Solr's Admin UI files section (of the particular core of course).

The query I am using to test results, to prove that I am not using stardard /query component:

```<code>/elevate?df=name&fl=id,name,[elevated]&indent=on&q=heart&wt=json
</code>```

What should I do to actually tell Solr that the new elevate.xml was loaded? That works fine on my development standalone configuration of Solr (not cloud one) after the solr service is restarted, the documents are elevated by updated elevate.xml file.

答:
You should be doing this:

upload the elevate.xml file to zookeeper as explained here

reload the collection with the RELOAD collection api, no need to restart Solr

Title: Solr cloud - reloading elevate.xml

Body:
I am using Apache Solr 6.5 with Query Elevation Component (/elevate endpoint) to support elevation of particular documents in my queries.

I am using elevate.xml file in

<instanceDir>/conf/<config-file>

directory. However on production server (Solr configured as cloud with zookepper to maintain configuration) changes in the elevate.xml are not loaded. To check if it works, I just query the elevated phrase and as a result I get elevated documents from previous version of elevate.xml.

Of course I am restarting all Solr cloud instances after loading new version of elevate.xml and updated file is visible in the Solr's Admin UI files section (of the particular core of course).

The query I am using to test results, to prove that I am not using stardard /query component:

/elevate?df=name&fl=id,name,[elevated]&indent=on&q=heart&wt=json

What should I do to actually tell Solr that the new elevate.xml was loaded? That works fine on my development standalone configuration of Solr (not cloud one) after the solr service is restarted, the documents are elevated by updated elevate.xml file.


问:
Is it possible to get code editors in virtualenv?
I recently downloaded virtualenv on my MacOSX Sierra (10.12.2). I'm not very experienced with virtualenv and I've been coding using the interactive interpreter in terminal and I was wondering if there was an alternate way that I could use an editor(IDLE, Sublime, etc.) and still use it in virtualenv. Would I just install an editor into virtualenv or am I limited to only the interactive shell?</p>

答:
You are not limited to only interactive shell. For your coding part you can download and install sublime text and open your project (any project irrespective of the language you use) and get started. Here is a quick guide for getting started in sublime text : sublime text getting started

You might also want to take a look at this post: SublimeREPL plugin


问:
Convert string vector to float vector or array
I am trying to convert a string vector to a float vector ideally i would like to convert it to a float array as this would be easier for me to work with but from research i have come to understand that a vector is preferable to an array. This is the code i am still a beginner c++ coder and i only kinda of understand whats going on in the code lol. The program keeps giving me and error when i try to run it i don't understand why but i know it has something to do with my attempt at converting the string vector to a float.</p>

```<code>#include <vector>
#include <string>
#include <iostream>
#include "sqlite3.h"
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;

sqlite3* db;

using Records = vector<Record>;

int select_callback(void *p_data, int num_fields, char **p_fields, char **p_col_names)
{
Records* records = static_cast<Records*>(p_data);
try {
  records->emplace_back(p_fields, p_fields + num_fields);
}
catch (...) {
// abort select on failure, don't let exception propogate thru sqlite3 call-stack
return 1;
}
return 0;
}

Records select_stmt(const char* stmt)
{
Records records;
char *errmsg;
int ret = sqlite3_exec(db, stmt, select_callback, &records, &errmsg);
if (ret != SQLITE_OK) {
  std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
else {
  std::cerr << records.size() << " records returned.\n";
}

return records;
}

void sql_stmt(const char* stmt)
{
char *errmsg;
int ret = sqlite3_exec(db, stmt, 0, 0, &errmsg);
if (ret != SQLITE_OK) {
std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
}

 int main()
{
 if (sqlite3_open("BandDia.db", &db) != SQLITE_OK) {
   std::cerr << "Could not open database.\n";
 return 1;
}

Records records = select_stmt("SELECT * FROM k_EnergyEig_T2 ");
sqlite3_close(db);

vector<float> v;
istringstream iss(Records);

std::copy(std::istream_iterator<float>(iss),
    std::istream_iterator<float>(),
    std::back_inserter(v));

// Put the result on standard out
std::copy(v.begin(), v.end(),
    std::ostream_iterator<float>(std::cout, ", "));
std::cout << "\n";

/*  for (auto& record : records) {
// do something with your records
puts("Hello,World");

}*/

return 0;
}
</code>```

答:
If I understand the question correctly, you have a string which contains comma separated values and you want to convert this into an array of floats.

The first thing that I would do is split the string into substrings. Each substring will contain one value. Examples of this can be found here.

The next thing to do is to iterate over these strings and convert them into floats. For this you can use the atof function. atof stands for 'a' (string) to 'f' (float). Note that you can easily convert a std::string into a c string using s.c_str().

Finally, it's probably better to use vectors here because they can be resized dynamically. If you really want to convert the output to an array, you can always do this:

```<code>float* a = new float[v.size()];
memcpy(a, &v[0], sizeof(float) * v.size());
</code>```

Body:
I am trying to convert a string vector to a float vector ideally i would like to convert it to a float array as this would be easier for me to work with but from research i have come to understand that a vector is preferable to an array. This is the code i am still a beginner c++ coder and i only kinda of understand whats going on in the code lol. The program keeps giving me and error when i try to run it i don't understand why but i know it has something to do with my attempt at converting the string vector to a float.

#include <vector>
#include <string>
#include <iostream>
#include "sqlite3.h"
#include <cassert>
#include <sstream>
#include <iterator>
#include <algorithm>
using namespace std;

sqlite3* db;

using Records = vector<Record>;

int select_callback(void *p_data, int num_fields, char **p_fields, char **p_col_names)
{
Records* records = static_cast<Records*>(p_data);
try {
  records->emplace_back(p_fields, p_fields + num_fields);
}
catch (...) {
// abort select on failure, don't let exception propogate thru sqlite3 call-stack
return 1;
}
return 0;
}

Records select_stmt(const char* stmt)
{
Records records;
char *errmsg;
int ret = sqlite3_exec(db, stmt, select_callback, &records, &errmsg);
if (ret != SQLITE_OK) {
  std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
else {
  std::cerr << records.size() << " records returned.\n";
}

return records;
}

void sql_stmt(const char* stmt)
{
char *errmsg;
int ret = sqlite3_exec(db, stmt, 0, 0, &errmsg);
if (ret != SQLITE_OK) {
std::cerr << "Error in select statement " << stmt << "[" << errmsg << "]\n";
}
}

 int main()
{
 if (sqlite3_open("BandDia.db", &db) != SQLITE_OK) {
   std::cerr << "Could not open database.\n";
 return 1;
}

Records records = select_stmt("SELECT * FROM k_EnergyEig_T2 ");
sqlite3_close(db);

vector<float> v;
istringstream iss(Records);

std::copy(std::istream_iterator<float>(iss),
    std::istream_iterator<float>(),
    std::back_inserter(v));

// Put the result on standard out
std::copy(v.begin(), v.end(),
    std::ostream_iterator<float>(std::cout, ", "));
std::cout << "\n";

/*  for (auto& record : records) {
// do something with your records
puts("Hello,World");

}*/

return 0;
}

Body:
If I understand the question correctly, you have a string which contains comma separated values and you want to convert this into an array of floats.

The first thing that I would do is split the string into substrings. Each substring will contain one value. Examples of this can be found here.

The next thing to do is to iterate over these strings and convert them into floats. For this you can use the atof function. atof stands for 'a' (string) to 'f' (float). Note that you can easily convert a std::string into a c string using s.c_str().

Finally, it's probably better to use vectors here because they can be resized dynamically. If you really want to convert the output to an array, you can always do this:

float* a = new float[v.size()];
memcpy(a, &v[0], sizeof(float) * v.size());


问:
How to do an MPI_Scatter in MPI to all nodes except the root?
In MPI, if I perform an MPI_Scatter on MPI_COMM_WORLD, all the nodes receive some data (including the sending root).

How do I perform an MPI_Scatter from a root node to all the other nodes and make sure the root node does not receive any data?

Is creating a new MPI_Comm containing all the nodes but the root a viable approach?

答:
Let's imagine your code looks like that:

int rank, size;    // rank of the process and size of the communicator
int root = 0;      // root process of our scatter
int recvCount = 4; // or whatever
double *sendBuf = rank == root ? new double[recvCount * size] : NULL;
double *recvBuf = new double[recvCount];

MPI_Scatter( sendBuf, recvCount, MPI_DOUBLE,
             recvBuf, recvCount, MPI_DOUBLE,
             root, MPI_COMM_WORLD );
```

<p>So in here, indeed, the <code>root</code> process will send data to itself although this could be avoided.
Here are the two obvious methods that come to mind to achieve that.</p>

<p><strong>Using <code>MPI_IN_PLACE</code></strong><br>
The call to <code>MPI_Scatter()</code> wouldn't have to change. The only change in the code would be for the definition of the receiving buffer, which would become something like this:</p>

<pre class="lang-cpp prettyprint-override"><code>double *recvBuf = rank == root ?
                  static_cast<double*>( MPI_IN_PLACE ) :
                  new double[recvCount];
</code>```

Using MPI_Scatterv()

With that, you'd have to define an array of integers describing the individual receiving sizes, an array of displacements describing the starting indexes and use them in a call to MPI_Scatterv() which would replace you call to MPI_Scatter() like this:

int sendCounts[size] = {recvCount};  // everybody receives recvCount data
sendCounts[root] = 0;                // but the root process
int displs[size];
for ( int i = 0; i < size; i++ ) {
    displs[i] = i * recvCount;
}

MPI_Scatterv( sendBuf, sendCounts, displs, MPI_DOUBLE,
              recvBuf, recvCount, MPI_DOUBLE,
              root, MPI_COMM_WORLD );
```

Of course in both cases no data would be on receiving buffer for process root and this would have to be accounted for in your code.

I personally prefer the first option, but both work.

Body:
Let's imagine your code looks like that:

int rank, size;    // rank of the process and size of the communicator
int root = 0;      // root process of our scatter
int recvCount = 4; // or whatever
double *sendBuf = rank == root ? new double[recvCount * size] : NULL;
double *recvBuf = new double[recvCount];

MPI_Scatter( sendBuf, recvCount, MPI_DOUBLE,
             recvBuf, recvCount, MPI_DOUBLE,
             root, MPI_COMM_WORLD );

So in here, indeed, the root process will send data to itself although this could be avoided.
Here are the two obvious methods that come to mind to achieve that.

Using MPI_IN_PLACE

The call to MPI_Scatter() wouldn't have to change. The only change in the code would be for the definition of the receiving buffer, which would become something like this:

double *recvBuf = rank == root ?
                  static_cast<double*>( MPI_IN_PLACE ) :
                  new double[recvCount];

Using MPI_Scatterv()

With that, you'd have to define an array of integers describing the individual receiving sizes, an array of displacements describing the starting indexes and use them in a call to MPI_Scatterv() which would replace you call to MPI_Scatter() like this:

int sendCounts[size] = {recvCount};  // everybody receives recvCount data
sendCounts[root] = 0;                // but the root process
int displs[size];
for ( int i = 0; i < size; i++ ) {
    displs[i] = i * recvCount;
}

MPI_Scatterv( sendBuf, sendCounts, displs, MPI_DOUBLE,
              recvBuf, recvCount, MPI_DOUBLE,
              root, MPI_COMM_WORLD );

Of course in both cases no data would be on receiving buffer for process root and this would have to be accounted for in your code.

I personally prefer the first option, but both work.


答:
Here you go. This works on multiple fields as well

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == 0) {
                empty = true;
            }
        });

        if (empty) {
            $('#submit').attr('disabled', 'disabled');
        } else {
            $('#submit').removeAttr('disabled');
        }
    });
})()

/* instead of form we can use the IDs of certain fields only. In case not all fields are mandatory */```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    Enter number<br />
    <input type="number" id="user_input" name="number" /><br />
    <input type="number" id="user_input2" name="number" /><br />
    <input type="submit" id="submit" value="submit" disabled="disabled" />
</form>
<div id="test">
</div></code>```

Title: If any input field value entered zero then disable else enable

Body:
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

Body:
Here you go. This works on multiple fields as well

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == 0) {
                empty = true;
            }
        });

        if (empty) {
            $('#submit').attr('disabled', 'disabled');
        } else {
            $('#submit').removeAttr('disabled');
        }
    });
})()

/* instead of form we can use the IDs of certain fields only. In case not all fields are mandatory */

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    Enter number<br />
    <input type="number" id="user_input" name="number" /><br />
    <input type="number" id="user_input2" name="number" /><br />
    <input type="submit" id="submit" value="submit" disabled="disabled" />
</form>
<div id="test">
</div>