问:
Java importing .class files
I've been given two .class files. Using Netbeans, I created a folder in my src to import my classes.

Once I've got my classes in the right directory I add my class folder to the project sources:

-Project.

-Properties.

-Sources.

-Add folder.

-Class folder.

Then confirmed all sources are up to date:

-> Source

-> Scan for external changes

I then construct a new instance of the class in my source code, but am given an error message: "cannot find symbol"

I've successfully Imported the .class files in Eclipse but I don't like the Eclipse UI and would like to stick with Netbeans.

答:
You don't want to put those .class files into the "project sources."  The IDE will expect to find .java files in there.

You want to add your .class files as a dependency somehow.  Is there a way to configure the classpath in Netbeans?  (I imagine there is.)  Look for a way to add a folder to the classpath.

Title: Java importing .class files


来源: stackexchange

问:
async_read_until handler called twice
I am trying to use boost asio library to implement network programming.
Here is the code which is called when some data(which ends with "##") arrives at the endpoint.

```<code>{
    boost::asio::async_read_until(m_socket, m_response,
                std::string("##"),
                boost::bind(&CTcpClient::HandleReceive,
                                shared_from_this(),
                                boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred));

}

void CTcpClient::HandleReceive(const ErrorCodeType p_errorCode, size_t p_length)
{
    IN_FUNCTION

    if ( !p_errorCode )
    {
        logInfo(STR("Data received ..."));

        boost::asio::async_read_until(m_socket, m_response,
            std::string("##"),
            boost::bind(&CTcpClient::HandleReceive,
                            shared_from_this(),
                            boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred));

        m_onReceiveSignal(sbuf2s(m_response));

    }
    else
    {
        Shutdown(p_errorCode);
    }

    OUT_FUNCTION
}
</code>```

Let's say, the data that is sent to the end point is "KINGS##". Hence, the Handlereceive should be called once. But in my code, this is being called twice, once with "KINGS##" and another with a null string.

Can somebody tell me what is the reason and how to fix it ?

答:
I think you just need to call async_read_until(...) after m_onReceiveSignal(...).
Change the order of both inside Handlereceive.

That is under the assumption the first time you call the Handlereceive is from another method (connect maybe) through async_read_untill(...)

ContentLicense: CC BY-SA 3.0

Title: async_read_until handler called twice

Body:
I am trying to use boost asio library to implement network programming.
Here is the code which is called when some data(which ends with "##") arrives at the endpoint.

{
    boost::asio::async_read_until(m_socket, m_response,
                std::string("##"),
                boost::bind(&CTcpClient::HandleReceive,
                                shared_from_this(),
                                boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred));

}

void CTcpClient::HandleReceive(const ErrorCodeType p_errorCode, size_t p_length)
{
    IN_FUNCTION

    if ( !p_errorCode )
    {
        logInfo(STR("Data received ..."));

        boost::asio::async_read_until(m_socket, m_response,
            std::string("##"),
            boost::bind(&CTcpClient::HandleReceive,
                            shared_from_this(),
                            boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred));

        m_onReceiveSignal(sbuf2s(m_response));

    }
    else
    {
        Shutdown(p_errorCode);
    }

    OUT_FUNCTION
}

Let's say, the data that is sent to the end point is "KINGS##". Hence, the Handlereceive should be called once. But in my code, this is being called twice, once with "KINGS##" and another with a null string.

Can somebody tell me what is the reason and how to fix it ?


问:
SQL Server vs MySQL: CONTAINS(*,'FORMSOF(THESAURUS,word)')
I am shocked.

I spent past 3-4 days figuring out how I could implement stemming (and synonyms searches) in mysql when I see in SQL Server the query is incredibly easly:

```<code>Select * from tab where CONTAINS(*,'FORMSOF(THESAURUS,word)')
</code>```

Is possibile on MySql there isn't anything like that?

答:
No, MySQL does not support matching against a user-provided thesaurus.

You can use an external FULLTEXT engine like Sphinx which supports morphology rules, has several stemmers and thesauri built in and allows pluggable ones.

ContentLicense: CC BY-SA 2.5

Body:
I am shocked.

I spent past 3-4 days figuring out how I could implement stemming (and synonyms searches) in mysql when I see in SQL Server the query is incredibly easly:

Select * from tab where CONTAINS(*,'FORMSOF(THESAURUS,word)')

Is possibile on MySql there isn't anything like that?


问:
Can table be used as a stream in PipelineDB
let's assume we have a table test_table like this

```<code>create table test_table(x integer);
</code>```

Is it possible to create a continuous view from this table? Something like this:

```<code>create continuous view test_view as select sum(x) as x_sum from test_table;
</code>```

When I run the above command I get the error:

test=# create continuous view test_view as select sum(x) as x_sum from test_table;
ERROR:  continuous queries must include a stream in the FROM clause
LINE 1: ...ous view test_view as select sum(x) as x_sum from test_table...
                                                             ^
HINT:  To include a relation in a continuous query, JOIN it with a stream.

This is the documentation:

Here’s the syntax for creating a continuous view:

```<code>CREATE CONTINUOUS VIEW name AS query
</code>```

where query is a subset of a PostgreSQL SELECT statement:

```<code>SELECT [ DISTINCT [ ON ( expression [, ...] ) ] ]
    expression [ [ AS ] output_name ] [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY expression [, ...] ]
    [ HAVING condition [, ...] ]
    [ WINDOW window_name AS ( window_definition ) [, ...] ]
</code>```

where from_item can be one of:

```<code>stream_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
table_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
from_item [ NATURAL ] join_type from_item [ ON join_condition ]
</code>```

According to this from_item could also be a table. Is the documentation wrong? If it is not possible to create a continuous view from the table is there a way to load current data from table to some stream.

答:
Jeff from PipelineDB here.

Is there a reason you would want to try and create a continuous view off of a regular table like this? Why not just create a regular view, or materialized view?

PipelineDB is designed to continuously analyze infinite streams of raw data so that data doesn't need to be stored as regular tables and then processed in an ad hoc fashion, so this use case is exactly opposite of PipelineDB's intended purpose.

Body:
let's assume we have a table test_table like this

create table test_table(x integer);

Is it possible to create a continuous view from this table? Something like this:

create continuous view test_view as select sum(x) as x_sum from test_table;

When I run the above command I get the error:

test=# create continuous view test_view as select sum(x) as x_sum from test_table;
ERROR:  continuous queries must include a stream in the FROM clause
LINE 1: ...ous view test_view as select sum(x) as x_sum from test_table...
                                                             ^
HINT:  To include a relation in a continuous query, JOIN it with a stream.

This is the documentation:

Here’s the syntax for creating a continuous view:

CREATE CONTINUOUS VIEW name AS query

where query is a subset of a PostgreSQL SELECT statement:

SELECT [ DISTINCT [ ON ( expression [, ...] ) ] ]
    expression [ [ AS ] output_name ] [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY expression [, ...] ]
    [ HAVING condition [, ...] ]
    [ WINDOW window_name AS ( window_definition ) [, ...] ]

where from_item can be one of:

stream_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
table_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
from_item [ NATURAL ] join_type from_item [ ON join_condition ]

According to this from_item could also be a table. Is the documentation wrong? If it is not possible to create a continuous view from the table is there a way to load current data from table to some stream.


问:
Python 3 | Locations arround a point (lat/long)
Is there a way to verify that a tuple of latitude and longitude values (for example, (-32.0321, -72.3213)) is whithin a R radius (in miles, kilometers, etc) of another tuple of latitude, longitude using some sort of api or function?</p>

答:
Try out Shapely.  The units are arbitrary so that's up to you.

See this example


问:
Find all child processes of my own .NET process / find out if a given process is a child of my own?
I have a .NET class library that spins up a secondary process which is kept running until I dispose of the object.

Due to some occurances of the program lingering in memory, I've decided to add an integration test to ensure that if I let the object lapse to GC/Finalization, that process is spun down.

However, since the process is the Mercurial command line client, and my build server is already running Mercurial as part of its own operations, I envision situations where Mercurial is either already running when that test starts, or that it is started, and is still running, when the test finishes, in relation to the build server, and not my test.

So, I want to make sure the Mercurial client I find (or not) is the one I started, and not just any client that is currently running.

So the question is this:

How can I find out if the Mercurial client I am looking at was started by my process?

By "looking at", I was looking at using the Process.GetProcesses method, but this is not a requirement.

If a different question is better, "How to find all child processes of my own process", ie. easier to answer, that one is more than enough as well.

I found this page: How I can know the parent process ID of a process?, but it seems that I have to give it the process name. If I just give it "hg", isn't that question too ambiguous for the case I'm looking for?

答:
Although the answer of mtijn is probably the closest you can get, the real answer is: you can't.

Windows does not maintain a real process tree where processes are re-structured when a process on an intermediate level dies. However, Windows does remember the parent process ID.

The problematic case is the following:

Original process structure:

```<code>YourApp.exe
- SubApp.exe
  - Second.exe
</code>```

If now SubApp.exe terminates, the parent process ID of Second.exe will not be updated. The new result is

```<code>YourApp.exe
Second.exe
</code>```

You can verify this using SysInternals Process Explorer. It is able to show the processes as a tree. Start CMD, then type start cmd. Into the new window, type start cmd again. You'll have 3 windows open. Now terminate the middle one.

Body:
Although the answer of mtijn is probably the closest you can get, the real answer is: you can't.

Windows does not maintain a real process tree where processes are re-structured when a process on an intermediate level dies. However, Windows does remember the parent process ID.

The problematic case is the following:

Original process structure:

YourApp.exe
- SubApp.exe
  - Second.exe

If now SubApp.exe terminates, the parent process ID of Second.exe will not be updated. The new result is

YourApp.exe
Second.exe

You can verify this using SysInternals Process Explorer. It is able to show the processes as a tree. Start CMD, then type start cmd. Into the new window, type start cmd again. You'll have 3 windows open. Now terminate the middle one.

ContentLicense: CC BY-SA 4.0


问:
Add a constant variable to a cuda.FloatTensor
I have two question:

1) I'd like to know how can I add/subtract a constante torch.FloatTensor of size 1 to all of the elemets of a torch.FloatTensor of size 30.

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each).

My code:

```<code>import torch
dtype = torch.cuda.FloatTensor
def main():
     pop, xmax, xmin   = 30, 5, -5
     x                 = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
     y                 = torch.pow(x, 2)
     [miny, indexmin]  = y.min(0)
     gxbest            = x[indexmin]
     pxbest            = x
     pybest            = y
     v = torch.rand(pop)
     vnext = torch.rand()*v + torch.rand()*(pxbest - x) + torch.rand()*(gxbest - x)

main()
</code>```

What is the best way to do it? I think I should so how convert the gxbest into a torch.FloatTensor of size 30 but how can I do that?
I've try to create a vector:

Variable(torch.from_numpy(np.ones(pop)))*gxbest

But it did not work. The multiplication is not working also.

RuntimeError: inconsistent tensor size

Thank you all for your help!

答:
1) How can I add/subtract a constant torch.FloatTensor of size 1 to all of the elements of a torch.FloatTensor of size 30?

You can do it directly in pytorch 0.2.

```<code>import torch

a = torch.randn(30)
b = torch.randn(1)
print(a-b)
</code>```

In case if you get any error due to size mismatch, you can make a small change as follows.

```<code>print(a-b.expand(a.size(0))) # to make both a and b tensor of same shape
</code>```

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each)?

In pytorch 0.2, you can do it directly as well.

```<code>import torch

a = torch.randn(30)
b = torch.randn(1)
print(a*b)
</code>```

In case, if you get an error due to size mismatch, do as follows.

```<code>print(a*b.expand(a.size(0)))
</code>```

So, in your case you can simply change the size of gxbest tensor from 1 to 30 as follows.

```<code>gxbest = gxbest.expand(30)
</code>```

Body:
I have two question:

1) I'd like to know how can I add/subtract a constante torch.FloatTensor of size 1 to all of the elemets of a torch.FloatTensor of size 30.

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each).

My code:

import torch
dtype = torch.cuda.FloatTensor
def main():
     pop, xmax, xmin   = 30, 5, -5
     x                 = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
     y                 = torch.pow(x, 2)
     [miny, indexmin]  = y.min(0)
     gxbest            = x[indexmin]
     pxbest            = x
     pybest            = y
     v = torch.rand(pop)
     vnext = torch.rand()*v + torch.rand()*(pxbest - x) + torch.rand()*(gxbest - x)

main()

What is the best way to do it? I think I should so how convert the gxbest into a torch.FloatTensor of size 30 but how can I do that?
I've try to create a vector:

Variable(torch.from_numpy(np.ones(pop)))*gxbest

But it did not work. The multiplication is not working also.

RuntimeError: inconsistent tensor size

Thank you all for your help!

Body:
1) How can I add/subtract a constant torch.FloatTensor of size 1 to all of the elements of a torch.FloatTensor of size 30?

You can do it directly in pytorch 0.2.

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a-b)

In case if you get any error due to size mismatch, you can make a small change as follows.

print(a-b.expand(a.size(0))) # to make both a and b tensor of same shape

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each)?

In pytorch 0.2, you can do it directly as well.

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a*b)

In case, if you get an error due to size mismatch, do as follows.

print(a*b.expand(a.size(0)))

So, in your case you can simply change the size of gxbest tensor from 1 to 30 as follows.

gxbest = gxbest.expand(30)


问:
Top ad banner Prestashop 1.7.1
I would like to understand how this top banner (SALE 70% OFF ALL PRODUCTS) included in this image can be done:

https://medias2.prestastore.com/906398-pbig/banner-manager.jpg

Is it needed an extra module for that?
If so, which one?
If not, how can you modify the theme to include it?

答: This is Banner Block (blocbanner in files) module, included by default, that you can manage in your backoffice.</p>

Title: Top ad banner Prestashop 1.7.1


问:
Difficulty extracting IMDb ratings by demographic (with IMDbpy)
I would like to collect the IMDb rating details by demographic (gender, age group).

When I try to use the get_movie_vote_details module in imdbpy, my output is empty.
Here is my code:

```<code> import imdb

 i =  imdb.IMDb(accessSystem='http')

 movie = i.get_movie('0780504')

 print(movie)

 votes = i.get_movie_vote_details('0780504')

 print(votes)
</code>```

and here is the output:

print(m)

Drive

print(votes)

{'charactersRefs': {}, 'data': {}, 'namesRefs': {}, 'titlesRefs': {}}

As you can see, the "votes" output is a little off. Is there a way I can extract rating details using imdbpy?

答:
You are not supposed to call the .get_movie_XYZ(...) methods directly: they are used internally to update a Movie instance using the IMDb().update(...) method.

For example:

```<code>import imdb

i = imdb.IMDb(accessSystem='http')

movie = i.get_movie('0780504')
i.update(movie, 'vote details')
print(movie.get('mean and median')
</code>```

If you want to know all the available info sets, call i.get_movie_infoset(); to see which keys of a Movie instance were added when a given info set was updated, use the movie.infoset2key mapping.

For more information, refer to the official documentation.

Regarding the format of the data, this code:

```<code>from imdb import IMDb
ia = IMDb()
m = ia.get_movie('0780504', 'vote details')
print('median', m.get('median'))
print('arithmetic mean', m.get('arithmetic mean'))
print('number of votes', m.get('number of votes'))
print('demographics', m.get('demographics'))
</code>```

will output something like this:

median 8
arithmetic mean 7.8
number of votes {1: 8626, 2: 4135, 3: 5762, 4: 9264, 5: 17595, 6: 39440, 7: 84746, 8: 133331, 9: 98870, 10: 75737}
demographics {'imdb staff': {'rating': 7.8, 'votes': 36}, 'aged under 18': {'rating': 8.5, 'votes': 844}, 'non us users': {'rating': 7.8, 'votes': 250586}, 'top 1000 voters': {'rating': 7.6, 'votes': 739}, 'males aged 45 plus': {'rating': 7.4, 'votes': 24213}, 'aged 45 plus': {'rating': 7.4, 'votes': 28779}, 'aged 18 29': {'rating': 7.9, 'votes': 183217}, 'us users': {'rating': 8.0, 'votes': 71299}, 'aged 30 44': {'rating': 7.7, 'votes': 181063}, 'males aged under 18': {'rating': 8.5, 'votes': 705}, 'males aged 30 44': {'rating': 7.8, 'votes': 152988}, 'females aged under 18': {'rating': 7.9, 'votes': 133}, 'males aged 18 29': {'rating': 8.0, 'votes': 148749}, 'females aged 45 plus': {'rating': 7.4, 'votes': 4004}, 'imdb users': {'rating': 7.8, 'votes': 477506}, 'females aged 18 29': {'rating': 7.6, 'votes': 32575}, 'females': {'rating': 7.6, 'votes': 65217}, 'males': {'rating': 7.9, 'votes': 341617}, 'females aged 30 44': {'rating': 7.5, 'votes': 25465}}

Body:
I would like to collect the IMDb rating details by demographic (gender, age group).

When I try to use the get_movie_vote_details module in imdbpy, my output is empty.
Here is my code:

 import imdb

 i =  imdb.IMDb(accessSystem='http')

 movie = i.get_movie('0780504')

 print(movie)

 votes = i.get_movie_vote_details('0780504')

 print(votes)

and here is the output:

print(m)

Drive

print(votes)

{'charactersRefs': {}, 'data': {}, 'namesRefs': {}, 'titlesRefs': {}}

As you can see, the "votes" output is a little off. Is there a way I can extract rating details using imdbpy?

Body:
You are not supposed to call the .get_movie_XYZ(...) methods directly: they are used internally to update a Movie instance using the IMDb().update(...) method.

For example:

import imdb

i = imdb.IMDb(accessSystem='http')

movie = i.get_movie('0780504')
i.update(movie, 'vote details')
print(movie.get('mean and median')

If you want to know all the available info sets, call i.get_movie_infoset(); to see which keys of a Movie instance were added when a given info set was updated, use the movie.infoset2key mapping.

For more information, refer to the official documentation.

Regarding the format of the data, this code:

from imdb import IMDb
ia = IMDb()
m = ia.get_movie('0780504', 'vote details')
print('median', m.get('median'))
print('arithmetic mean', m.get('arithmetic mean'))
print('number of votes', m.get('number of votes'))
print('demographics', m.get('demographics'))

will output something like this:

median 8
arithmetic mean 7.8
number of votes {1: 8626, 2: 4135, 3: 5762, 4: 9264, 5: 17595, 6: 39440, 7: 84746, 8: 133331, 9: 98870, 10: 75737}
demographics {'imdb staff': {'rating': 7.8, 'votes': 36}, 'aged under 18': {'rating': 8.5, 'votes': 844}, 'non us users': {'rating': 7.8, 'votes': 250586}, 'top 1000 voters': {'rating': 7.6, 'votes': 739}, 'males aged 45 plus': {'rating': 7.4, 'votes': 24213}, 'aged 45 plus': {'rating': 7.4, 'votes': 28779}, 'aged 18 29': {'rating': 7.9, 'votes': 183217}, 'us users': {'rating': 8.0, 'votes': 71299}, 'aged 30 44': {'rating': 7.7, 'votes': 181063}, 'males aged under 18': {'rating': 8.5, 'votes': 705}, 'males aged 30 44': {'rating': 7.8, 'votes': 152988}, 'females aged under 18': {'rating': 7.9, 'votes': 133}, 'males aged 18 29': {'rating': 8.0, 'votes': 148749}, 'females aged 45 plus': {'rating': 7.4, 'votes': 4004}, 'imdb users': {'rating': 7.8, 'votes': 477506}, 'females aged 18 29': {'rating': 7.6, 'votes': 32575}, 'females': {'rating': 7.6, 'votes': 65217}, 'males': {'rating': 7.9, 'votes': 341617}, 'females aged 30 44': {'rating': 7.5, 'votes': 25465}}


问:
Java Google Seehts API v4 get row column index by search value or append
Hi I'm using the Google Sheets API v4 for Java.
I want to make a Server List where I register up new Server IP's for my own small project. At the moment I can append a new Entry at a empty row using

```<code>AppendCellsRequest appendCellReq = new AppendCellsRequest();
appendCellReq.setSheetId(0);
appendCellReq.setRows(rowData);
appendCellReq.setFields("userEnteredValue");
</code>```

The Problem is now, that I want delete this row later, so I need to figure out how to find it later. My Idea was to add a UniqueID or to search for the exact added Values or to remember the row number. However a way would it be to find and replace all cells. But I would rather have a way to get the row number of my added data.
I'm very happy to hear some advices.

答:
Since long search I finaly found an answer. There are tutorials which indeed made it possible to append a row, but wasnt able to return in which Row they inserted. With this code its now possible. I found it after hours of searching somewhere. It is not the best code, but it works and can be modified.</p>

```<code>    String range = "A1"; // TODO: Update placeholder value.

    // How the input data should be interpreted.
    String valueInputOption = "RAW"; // TODO: Update placeholder value.

    // How the input data should be inserted.
    String insertDataOption = "INSERT_ROWS"; // TODO: Update placeholder value.

    // TODO: Assign values to desired fields of `requestBody`:
    ValueRange requestBody = new ValueRange();

    List<Object> data1 = new ArrayList<Object>();
    data1.addAll(Arrays.asList(dataArr));

    List<List<Object>> data2 = new ArrayList<List<Object>>();
    data2.add(data1);

    requestBody.setValues(data2);

    Sheets sheetsService;
    try {
        sheetsService = getSheetsService();
        Sheets.Spreadsheets.Values.Append request = sheetsService.spreadsheets().values().append(spreadSheetId,
                range, requestBody);

        request.setValueInputOption(valueInputOption);
        request.setInsertDataOption(insertDataOption);

        AppendValuesResponse response = request.execute();

        // TODO: Change code below to process the `response` object:

        Logger.println(response.getTableRange());

        String startCell = response.getTableRange().split(":")[1];
        String colString = startCell.replaceAll("\\d", "");
        String row = startCell.replaceAll(colString, "");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

Body:
Hi I'm using the Google Sheets API v4 for Java.
I want to make a Server List where I register up new Server IP's for my own small project. At the moment I can append a new Entry at a empty row using

AppendCellsRequest appendCellReq = new AppendCellsRequest();
appendCellReq.setSheetId(0);
appendCellReq.setRows(rowData);
appendCellReq.setFields("userEnteredValue");

The Problem is now, that I want delete this row later, so I need to figure out how to find it later. My Idea was to add a UniqueID or to search for the exact added Values or to remember the row number. However a way would it be to find and replace all cells. But I would rather have a way to get the row number of my added data.
I'm very happy to hear some advices.

Body:
Since long search I finaly found an answer. There are tutorials which indeed made it possible to append a row, but wasnt able to return in which Row they inserted. With this code its now possible. I found it after hours of searching somewhere. It is not the best code, but it works and can be modified.

    String range = "A1"; // TODO: Update placeholder value.

    // How the input data should be interpreted.
    String valueInputOption = "RAW"; // TODO: Update placeholder value.

    // How the input data should be inserted.
    String insertDataOption = "INSERT_ROWS"; // TODO: Update placeholder value.

    // TODO: Assign values to desired fields of `requestBody`:
    ValueRange requestBody = new ValueRange();

    List<Object> data1 = new ArrayList<Object>();
    data1.addAll(Arrays.asList(dataArr));

    List<List<Object>> data2 = new ArrayList<List<Object>>();
    data2.add(data1);

    requestBody.setValues(data2);

    Sheets sheetsService;
    try {
        sheetsService = getSheetsService();
        Sheets.Spreadsheets.Values.Append request = sheetsService.spreadsheets().values().append(spreadSheetId,
                range, requestBody);

        request.setValueInputOption(valueInputOption);
        request.setInsertDataOption(insertDataOption);

        AppendValuesResponse response = request.execute();

        // TODO: Change code below to process the `response` object:

        Logger.println(response.getTableRange());

        String startCell = response.getTableRange().split(":")[1];
        String colString = startCell.replaceAll("\\d", "");
        String row = startCell.replaceAll(colString, "");

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


问:
Android Studio 2.3.3; I can NOT DEBUG; hangs with “waiting for the debugger to attach” and "waiting for debugger response"
The past two days, for the first time in 3 years of using AS, I've been getting “waiting for the debugger to attach” and "waiting for debugger response" messages. The debugger isn't attaching or responding because it's hung.

It's that simple.

And as of an hour ago, stopping and restarting debugging from the Run menu no longer results in a debuggable process. NOTHING CAN BE DEBUGGED. And every time I do Run Stop, I get "waiting for debugger response." SURELY that tells Google SOMEthing.

I inadvertently had left an app in this hung state and went to a two-hour meeting. When I got back, Debug was still not responding to keypresses or mouse clicks. So I clicked Run Stop and immediately got the message "waiting for debugger response". I guess it would stay in this hung state until there was a stack overflow.

This is even happening with my PHONE. Problem not limited to emulators.

There are PLENTY of "Answers" to similar questions, BUT NOT ONE ANSWER IS A REAL SOLUTION ANYWHERE that I've looked. Just "restart AS" or "restart AS AND the emulator" or "upgrade" or "delete .idea folder for your project". Of course none of this works because IT'S GOOGLE'S PROBLEM.

No Gradle errors. Console's clean. So's terminal and event log.

Possibly related, I've been getting several "IDE errors" daily. I report each to Google.

Also today, in the Run menu, Debug was grayed out and Debug tab was missing. I clicked Run Debug and that problem went away. Whatever.

How do I fix "waiting for debugger to attach" and "waiting for debugger response" so I can debug again?

EDIT

Here's a telling bit I think:

It's said Collecting data... for a looooooooooooong time with the cursor at the first break point. Guess what happened when I hit F8. "Waiting for Debugger response."

Can you make anything out of this NOW?

答: I had the same problem with AS 3.0, but only with Oreo 8.0 virtual device (haven't tried on real device though). On older Android versions including Nougat 7.1 debugger was able to attach to the process running on the emulator. The reason was I had build version set to release instead of debug. When I changed it to debug (Build versions tab  is on the bottom of the left toolbar), I was able to debug the app on Oreo 8.0 as well. Hope this helps.</p>


问:
React Native : Arranging elements
I am building a very simple app with a picker and two inputs/labels.

It currently looks like this in my iphone.

This is my code

```<code>import React from 'react';
import { StyleSheet, Text, View, Button, Modal, TextInput, Picker } from 'react-native';

export default class App extends React.Component {

constructor(props) {
  super(props);

}

state = {
  b1text: 'Kg',
  b2text: 'Cm',
  weight: '',
  height: '',
  standard: 'Metric'
}

render() {
  return (

    <View style={styles.container}>
    <Picker
            selectedValue={this.state.standard}
            onValueChange={(itemValue, itemIndex) => {
                                                        this.setState({standard: itemValue});
                                                        if(itemValue === "Metric") {
                                                        this.setState({b1text: "Kg"});
                                                        this.setState({b2text: "Cm"});
                                                        }
                                                        if(itemValue === "Imperial") {
                                                          this.setState({b1text: "Lbs"});
                                                          this.setState({b2text: "Inches"});
                                                        }

                                                    } }
            style={{height: 100, width: 100 }}

        >
            <Picker.Item label="Metric" value="Metric" />
            <Picker.Item label="Imperial" value="Imperial" />
    </Picker>

    <TextInput
              style={{height: 40, width: 60, borderColor: 'gray', borderWidth: 1}}
            onChangeText={(text) => this.setState({text: weight})}
            value={this.state.weight}
          />
    <Text>{this.state.b1text}</Text>
    <TextInput
              style={{height: 40, width: 60, borderColor: 'gray', borderWidth: 1}}
            onChangeText={(text) => this.setState({text: height})}
            value={this.state.height}
          />

    <Text>{this.state.b2text}</Text>

    </View>

  );

}

}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'row',

  },
});
</code>```

But I want it to look something like this as shown below.

I have tried margin, padding etc. Still no luck.

Can someone tell me what css/flex property I can use to change the UI like how I want ?

答:
I've created an Expo Snack that has a closer example of the UI you want to achieve. But I'll leave it to you to work out the details.

```<code>import React from 'react';
import { StyleSheet, Text, View, TextInput, Picker } from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    b1text: 'Kg',
    b2text: 'Cm',
    weight: '',
    height: '',
    standard: 'Metric',
  };

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.top}>
          <Picker
            selectedValue={this.state.standard}
            onValueChange={itemValue => {
              this.setState({ standard: itemValue });
              if (itemValue === 'Metric') {
                this.setState({ b1text: 'Kg' });
                this.setState({ b2text: 'Cm' });
              }
              if (itemValue === 'Imperial') {
                this.setState({ b1text: 'Lbs' });
                this.setState({ b2text: 'Inches' });
              }
            }}>
            <Picker.Item label="Metric" value="Metric" />
            <Picker.Item label="Imperial" value="Imperial" />
          </Picker>
        </View>
        <View style={styles.bottom}>
          <TextInput
            style={{
              height: 40,
              width: 60,
              borderColor: 'gray',
              borderWidth: 1,
            }}
            onChangeText={() => this.setState({ text: weight })}
            value={this.state.weight}
          />
          <Text>{this.state.b1text}</Text>
          <TextInput
            style={{
              height: 40,
              width: 60,
              borderColor: 'gray',
              borderWidth: 1,
            }}
            onChangeText={() => this.setState({ text: height })}
            value={this.state.height}
          />
          <Text>{this.state.b2text}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  top: {
    width: '100%',
    flex: 1,
  },
  bottom: {
    flex: 1,
    alignItems: 'center',
  },
});
</code>```

One of the crucial things you need to is learn how to write styles with react-native. Here is a resource that has a guide of all of the style properties you can use with const {StyleSheet} from 'react-native'.

https://github.com/vhpoet/react-native-styling-cheat-sheet

Good luck :)

Title: React Native : Arranging elements

Body:
I am building a very simple app with a picker and two inputs/labels.

It currently looks like this in my iphone.

This is my code

import React from 'react';
import { StyleSheet, Text, View, Button, Modal, TextInput, Picker } from 'react-native';

export default class App extends React.Component {

constructor(props) {
  super(props);

}

state = {
  b1text: 'Kg',
  b2text: 'Cm',
  weight: '',
  height: '',
  standard: 'Metric'
}

render() {
  return (

    <View style={styles.container}>
    <Picker
            selectedValue={this.state.standard}
            onValueChange={(itemValue, itemIndex) => {
                                                        this.setState({standard: itemValue});
                                                        if(itemValue === "Metric") {
                                                        this.setState({b1text: "Kg"});
                                                        this.setState({b2text: "Cm"});
                                                        }
                                                        if(itemValue === "Imperial") {
                                                          this.setState({b1text: "Lbs"});
                                                          this.setState({b2text: "Inches"});
                                                        }

                                                    } }
            style={{height: 100, width: 100 }}

        >
            <Picker.Item label="Metric" value="Metric" />
            <Picker.Item label="Imperial" value="Imperial" />
    </Picker>

    <TextInput
              style={{height: 40, width: 60, borderColor: 'gray', borderWidth: 1}}
            onChangeText={(text) => this.setState({text: weight})}
            value={this.state.weight}
          />
    <Text>{this.state.b1text}</Text>
    <TextInput
              style={{height: 40, width: 60, borderColor: 'gray', borderWidth: 1}}
            onChangeText={(text) => this.setState({text: height})}
            value={this.state.height}
          />

    <Text>{this.state.b2text}</Text>

    </View>

  );

}

}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      backgroundColor: '#fff',
      alignItems: 'center',
      justifyContent: 'center',
      flexDirection: 'row',

  },
});

But I want it to look something like this as shown below.

I have tried margin, padding etc. Still no luck.

Can someone tell me what css/flex property I can use to change the UI like how I want ?

Body:
I've created an Expo Snack that has a closer example of the UI you want to achieve. But I'll leave it to you to work out the details.

import React from 'react';
import { StyleSheet, Text, View, TextInput, Picker } from 'react-native';

export default class App extends React.Component {
  constructor(props) {
    super(props);
  }

  state = {
    b1text: 'Kg',
    b2text: 'Cm',
    weight: '',
    height: '',
    standard: 'Metric',
  };

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.top}>
          <Picker
            selectedValue={this.state.standard}
            onValueChange={itemValue => {
              this.setState({ standard: itemValue });
              if (itemValue === 'Metric') {
                this.setState({ b1text: 'Kg' });
                this.setState({ b2text: 'Cm' });
              }
              if (itemValue === 'Imperial') {
                this.setState({ b1text: 'Lbs' });
                this.setState({ b2text: 'Inches' });
              }
            }}>
            <Picker.Item label="Metric" value="Metric" />
            <Picker.Item label="Imperial" value="Imperial" />
          </Picker>
        </View>
        <View style={styles.bottom}>
          <TextInput
            style={{
              height: 40,
              width: 60,
              borderColor: 'gray',
              borderWidth: 1,
            }}
            onChangeText={() => this.setState({ text: weight })}
            value={this.state.weight}
          />
          <Text>{this.state.b1text}</Text>
          <TextInput
            style={{
              height: 40,
              width: 60,
              borderColor: 'gray',
              borderWidth: 1,
            }}
            onChangeText={() => this.setState({ text: height })}
            value={this.state.height}
          />
          <Text>{this.state.b2text}</Text>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  top: {
    width: '100%',
    flex: 1,
  },
  bottom: {
    flex: 1,
    alignItems: 'center',
  },
});

One of the crucial things you need to is learn how to write styles with react-native. Here is a resource that has a guide of all of the style properties you can use with const {StyleSheet} from 'react-native'.

https://github.com/vhpoet/react-native-styling-cheat-sheet

Good luck :)


问:
How do I set up a div under the header which fills up the remaining space?
prnt.sc/ha3dag

The black div is the header, which is 40 pixels high. The blue div under it needs to fill up the remaining space without going over the screen height and causing an overflow-y.

答:
You are not giving us a lot to go on. When you post a question in the future, make sure you add a little code to give us a better idea of the issue. That being said, I think I can assist.

You have something like this:

```<code><div style="height:40px">
<h1>SomeContentHere</h1>
</div>
<div>
<h1>OtherContent</h1>
</div>
</code>```

but instead of setting a hard coded value, I like to do percentages.

```<code><div style="height:10%">
<h1>SomeContentHere</h1>
</div>
<div style="height:90%">
<h1>OtherContent</h1>
</div>
</code>```

This should change based on available screen size since it is a percentage and not a static value.

If you have a static value for your header, you could do something like this:

```<code>  <div style="height:40px">
    <h1>SomeContentHere</h1>
    </div>
    <div style="height: calc(100% - 40px)">
    <h1>OtherContent</h1>
    </div>
</code>```

Body:
You are not giving us a lot to go on. When you post a question in the future, make sure you add a little code to give us a better idea of the issue. That being said, I think I can assist.

You have something like this:

<div style="height:40px">
<h1>SomeContentHere</h1>
</div>
<div>
<h1>OtherContent</h1>
</div>

but instead of setting a hard coded value, I like to do percentages.

<div style="height:10%">
<h1>SomeContentHere</h1>
</div>
<div style="height:90%">
<h1>OtherContent</h1>
</div>

This should change based on available screen size since it is a percentage and not a static value.

If you have a static value for your header, you could do something like this:

  <div style="height:40px">
    <h1>SomeContentHere</h1>
    </div>
    <div style="height: calc(100% - 40px)">
    <h1>OtherContent</h1>
    </div>


问:
Upload files to same random folder in django
I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name.

So far I can upload both files to different random folders using the following:

```<code>from uuid import uuid4

def path_and_rename(path, dataset):
    def wrapper(instance, filename):
        main_folder = '{}/{}/'.format(path, uuid4().hex)
        name = '{}.csv'.format(dataset)

        return os.path.join(main_folder, name)
    return wrapper

class Dataset(Model):
    trainFile = FileField(null=False, blank=False,
                      validators=[FileExtensionValidator(['csv'])],
                      upload_to=path_and_rename('files/', 'train'))
    testFile = FileField(null=False, blank=False,
                     validators=[FileExtensionValidator(['csv'])],
                     upload_to=path_and_rename('files/', 'test'))

class DatasetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dataset
        fields = (
            'id',
            'trainFile',
            'testFile',
        )
        read_only_fields = ('created',)
</code>```

How could I get both files to be uploaded to the same random folder?

答:
Since the first FileField is required and the fields will be uploaded in order, you could use an alternate upload_to function for all of your fields apart from the first that relies on the initial upload path. Something like:

```<code>import posixpath

def dataset_file(dataset):
    def wrapper(instance, filename):
        main_folder = posixpath.split(instance.trainFile)[0]
        name = '{}.csv'.format(dataset)
        return posixpath.join(main_folder, name)
    return wrapper
</code>```

```

Body:
I am uploading two files using django rest framework, i want to upload these two files into the same folder and create said folder with a random name.

So far I can upload both files to different random folders using the following:

from uuid import uuid4

def path_and_rename(path, dataset):
    def wrapper(instance, filename):
        main_folder = '{}/{}/'.format(path, uuid4().hex)
        name = '{}.csv'.format(dataset)

        return os.path.join(main_folder, name)
    return wrapper

class Dataset(Model):
    trainFile = FileField(null=False, blank=False,
                      validators=[FileExtensionValidator(['csv'])],
                      upload_to=path_and_rename('files/', 'train'))
    testFile = FileField(null=False, blank=False,
                     validators=[FileExtensionValidator(['csv'])],
                     upload_to=path_and_rename('files/', 'test'))

class DatasetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dataset
        fields = (
            'id',
            'trainFile',
            'testFile',
        )
        read_only_fields = ('created',)

How could I get both files to be uploaded to the same random folder?

Body:
Since the first FileField is required and the fields will be uploaded in order, you could use an alternate upload_to function for all of your fields apart from the first that relies on the initial upload path. Something like:

import posixpath

def dataset_file(dataset):
    def wrapper(instance, filename):
        main_folder = posixpath.split(instance.trainFile)[0]
        name = '{}.csv'.format(dataset)
        return posixpath.join(main_folder, name)
    return wrapper

```


问:
How to change TabBarItem image and title-issue
I'm working with tabBar Based application with navigation controller. In my application I want to change the tabBarItem image and title. At the time of clicking the pariticular tabBarItem the control goes to viewWillAppear method of that particular view. In this time i want to change image and title of that particular tabBarItem.

I'm giving like this but,it's not working...

Code:

```<code>tabItem = [[UITabBarItem alloc] initWithTitle:@"Colors" image:[UIImage imageNamed:@"Colors.png"] tag:9];

self.tabBarController.tabBarItem = tabItem;
</code>```

Already I'm setting the tag value for that view is 9.

Please help me how can I change the image and title of that particular tabbarItem .

答:
There is a slight misconception in what you are attempting to do.  First of all, UITabBarController has no tabBarItem property, which is what you are attempting to set.  But, even if it did, the UITabBarController docs specifically state, in regards to UITabBarController's tabBar property:

You should never attempt to manipulate the UITabBar object itself stored in this property. If you attempt to do so, the tab bar view throws an exception.

So, the way to modify the items is not through the UITabBar itself.  In your situation, the UITabBar is getting its UITabBarItems from the UIViewControllers represented by each tab.  This is something you have control over.  Specifically, what you can do is:

```<code>- (void)viewWillAppear:(BOOL)animated {
    /* Modifies the UITabBarItem used by a UITabBarController to represent this
     * UIViewController in the tab bar.
     */

    UITabBarItem* tabBarItem =  [[UITabBarItem alloc] initWithTitle:@"Colors" image:[UIImage imageNamed:@"Colors.png"] tag:9];
    self.tabBarItem = tabBarItem;
    [tabBarItem release];
}
</code>```

Body:
I'm working with tabBar Based application with navigation controller. In my application I want to change the tabBarItem image and title. At the time of clicking the pariticular tabBarItem the control goes to viewWillAppear method of that particular view. In this time i want to change image and title of that particular tabBarItem.

I'm giving like this but,it's not working...

Code:

tabItem = [[UITabBarItem alloc] initWithTitle:@"Colors" image:[UIImage imageNamed:@"Colors.png"] tag:9];

self.tabBarController.tabBarItem = tabItem;

Already I'm setting the tag value for that view is 9.

Please help me how can I change the image and title of that particular tabbarItem .

Body:
There is a slight misconception in what you are attempting to do.  First of all, UITabBarController has no tabBarItem property, which is what you are attempting to set.  But, even if it did, the UITabBarController docs specifically state, in regards to UITabBarController's tabBar property:

You should never attempt to manipulate the UITabBar object itself stored in this property. If you attempt to do so, the tab bar view throws an exception.

So, the way to modify the items is not through the UITabBar itself.  In your situation, the UITabBar is getting its UITabBarItems from the UIViewControllers represented by each tab.  This is something you have control over.  Specifically, what you can do is:

- (void)viewWillAppear:(BOOL)animated {
    /* Modifies the UITabBarItem used by a UITabBarController to represent this
     * UIViewController in the tab bar.
     */

    UITabBarItem* tabBarItem =  [[UITabBarItem alloc] initWithTitle:@"Colors" image:[UIImage imageNamed:@"Colors.png"] tag:9];
    self.tabBarItem = tabBarItem;
    [tabBarItem release];
}


问:
Curl: could not resolve host using riak
I have this bash script that I'm using to read a csv file and insert my data in riak.

```<code>#!/bin/bash
# Set "," as the field separator using $IFS
# and read line by line using while read combo
while IFS=',' read -r Num_Acc senc catv occutc obs obsm choc manv num_veh
do
eval curl -i -X POST http://127.0.0.1:8098/riak/vehicule -H "Content-Type:application/json" -d {"Num_Acc":"$Num_Acc","senc":$senc,"catv":"$catv","occutc":"$occutc","obs":"$obs","obsm":$obsm,"choc":$choc,"manv":"$manv","num_veh":"$num_veh"}
done < vehicules_2016.csv
</code>```

The issue is that I have this error and I don't kown where it could come from :

```<code>curl: (6) Could not resolve host: senc
curl: (6) Could not resolve host: catv
curl: (6) Could not resolve host: occutc
curl: (6) Could not resolve host: obs
curl: (6) Could not resolve host: obsm
curl: (6) Could not resolve host: choc
curl: (6) Could not resolve host: manv
curl: (3) Illegal characters found in URL
HTTP/1.1 201 Created
Vary: Accept-Encoding
Server: MochiWeb/1.1 WebMachine/1.10.9 (cafe not found)
Location: /riak/vehicule/NiuPBkgCFBaqUNhorovnBvix2ED
Date: Mon, 13 Nov 2017 11:43:08 GMT
Content-Type: application/json
Content-Length: 0
</code>```

I think the problem might be the json syntax.

Thank you for your help.

答:
You have to enclose your data between either double quote " and escape inner double quote like \" or you can also use heredoc :

```<code>#!/bin/bash
while IFS=',' read -r Num_Acc senc catv occutc obs obsm choc manv num_veh
do
data=$(cat <<EOF
{
    "Num_Acc":"$Num_Acc",
    "senc": "$senc",
    "catv": "$catv",
    "occutc": "$occutc",
    "obs": "$obs",
    "obsm": "$obsm",
    "choc": "$choc",
    "manv": "$manv",
    "num_veh": "$num_veh"
}
EOF
)

curl -i http://127.0.0.1:8098/riak/vehicule \
     -H "Content-Type: application/json" \
     -d "$data"

done < vehicules_2016.csv
</code>```

check this post

Title: Curl: could not resolve host using riak

Body:
I have this bash script that I'm using to read a csv file and insert my data in riak.

#!/bin/bash
# Set "," as the field separator using $IFS
# and read line by line using while read combo
while IFS=',' read -r Num_Acc senc catv occutc obs obsm choc manv num_veh
do
eval curl -i -X POST http://127.0.0.1:8098/riak/vehicule -H "Content-Type:application/json" -d {"Num_Acc":"$Num_Acc","senc":$senc,"catv":"$catv","occutc":"$occutc","obs":"$obs","obsm":$obsm,"choc":$choc,"manv":"$manv","num_veh":"$num_veh"}
done < vehicules_2016.csv

The issue is that I have this error and I don't kown where it could come from :

curl: (6) Could not resolve host: senc
curl: (6) Could not resolve host: catv
curl: (6) Could not resolve host: occutc
curl: (6) Could not resolve host: obs
curl: (6) Could not resolve host: obsm
curl: (6) Could not resolve host: choc
curl: (6) Could not resolve host: manv
curl: (3) Illegal characters found in URL
HTTP/1.1 201 Created
Vary: Accept-Encoding
Server: MochiWeb/1.1 WebMachine/1.10.9 (cafe not found)
Location: /riak/vehicule/NiuPBkgCFBaqUNhorovnBvix2ED
Date: Mon, 13 Nov 2017 11:43:08 GMT
Content-Type: application/json
Content-Length: 0

I think the problem might be the json syntax.

Thank you for your help.

Body:
You have to enclose your data between either double quote " and escape inner double quote like \" or you can also use heredoc :

#!/bin/bash
while IFS=',' read -r Num_Acc senc catv occutc obs obsm choc manv num_veh
do
data=$(cat <<EOF
{
    "Num_Acc":"$Num_Acc",
    "senc": "$senc",
    "catv": "$catv",
    "occutc": "$occutc",
    "obs": "$obs",
    "obsm": "$obsm",
    "choc": "$choc",
    "manv": "$manv",
    "num_veh": "$num_veh"
}
EOF
)

curl -i http://127.0.0.1:8098/riak/vehicule \
     -H "Content-Type: application/json" \
     -d "$data"

done < vehicules_2016.csv

check this post


问:
Can I add an interface to a generated Service class via cxf-codegen-plugin
Here's my scenario: I am using the cxf-codegen-plugin to generate sources for a SOAP service client.  The generation and the service proxy are working fine however I would like my generated service class, which is currently extending javax.xml.ws.Service, to also implement a concretely defined interface.

I've been pouring over the JAXB and JAXWS docs but haven't quite found what I'm looking for.  Most examples I have found talk about applying bindings to complex types.

答:
To overcome the Unsupported binding interface issue you need to ensure your dependency for jaxb-basics is included in the configuration (as per lexicore's answer).

In addition, you should also include the -Xinheritance flag.

```<code>     </bindingFiles>
     <extraargs>
         <extraarg>-xjc-Xinheritance</extraarg>
     </extraargs>
</wsdlOption>
</code>```

Body:
To overcome the Unsupported binding interface issue you need to ensure your dependency for jaxb-basics is included in the configuration (as per lexicore's answer).

In addition, you should also include the -Xinheritance flag.

     </bindingFiles>
     <extraargs>
         <extraarg>-xjc-Xinheritance</extraarg>
     </extraargs>
</wsdlOption>


问:
assign function to object attribute
I'm building a draggable grid with grid-items generated out of the local storage. For the draggable grid I'm using the library Muuri.

Therefore I generate out of all my elements with the class .bookmark-container a Muuri Object and assign some attributes. The attribute dragSort includes all of the container elements in form of an array, which allows to drag elements from one container to an other.

This is my js code. gridObjects is globally defined and the function createbookmarkContainer is called on body.onload.

```<code>function createBookmarkContainer() {

  var bookmarkContainers = Array.prototype.slice.call($('.bookmark-container'));

  gridObjects = [];

  for(var i = 0; i < bookmarkContainers.length; i++) {
    gridObjects[i] = new Muuri(bookmarkContainers[i], {
      dragEnabled: true,
      dragSort: function () {
        return gridObjects
      }
    });
  }
}
</code>```

When I drag an item, it doesn't call my anonymous function within the dragSort attribute. However in my simplified codepen example it works.

Where is my fault? Is it because i call the anonymous function nested in an other function?

Thanks for your help!

答:
This is not an answer per-se but your code should run fine (as you can see in the running snippet below).

It seems that you are not calling the function correctly.

function createBookmarkContainer() {

  var bookmarkContainers = Array.prototype.slice.call($('.bookmark-container'));

  gridObjects = [];

  for(var i = 0; i < bookmarkContainers.length; i++) {
    gridObjects[i] = new Muuri(bookmarkContainers[i], {
      dragEnabled: true,
      dragSort: function () {
        return gridObjects
      }
    });
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto:400,700');

body {
 background-color: #2C3135;
 padding: 0;
 font-family: "roboto";
}

h1 {
 padding: 0;
 margin: 40px 0px 0px 20px;
 font-size: 18px;
 font-weight: 400;
 letter-spacing: 2px;
 color: rgba(255,255,255, .8);
}

.bookmark-container {
 position: relative;
 //background-color: rgba(255,255,255,.02);
 margin: 20px 0;
}
.item {
 position: absolute;
 width: 250px;
 height: 60px;
 line-height: 60px;
 margin: 15px;
 z-index: 1;
}

.item-content {
 position: relative;
 width: 100%;
 height: 100%;
 background-color: #3E444D;
 text-align: center;
 border-radius: 5px;
   box-shadow: 0px 10px 20px 0px rgba(47,47,47,0.03);
 font-size: 12px;
 color: white;
 cursor: pointer;
}

.item.muuri-dragging,
.item.muuri-releasing {
 z-index: 2;
}
.item.muuri-hidden {
 z-index: 0;
}</code>```

SECTION 1

1

2

3

4

5

6

7

8

9

10

SECTION 2

1

2

3

4

5

6

7

8

9

10

SECTION 3

1

2

3

4

5

6

7

8

9

10

SECTION 4

1

2

3

4

5

6

7

8

9

10

```

Title: assign function to object attribute

Body:
I'm building a draggable grid with grid-items generated out of the local storage. For the draggable grid I'm using the library Muuri.

Therefore I generate out of all my elements with the class .bookmark-container a Muuri Object and assign some attributes. The attribute dragSort includes all of the container elements in form of an array, which allows to drag elements from one container to an other.

This is my js code. gridObjects is globally defined and the function createbookmarkContainer is called on body.onload.

function createBookmarkContainer() {

  var bookmarkContainers = Array.prototype.slice.call($('.bookmark-container'));

  gridObjects = [];

  for(var i = 0; i < bookmarkContainers.length; i++) {
    gridObjects[i] = new Muuri(bookmarkContainers[i], {
      dragEnabled: true,
      dragSort: function () {
        return gridObjects
      }
    });
  }
}

When I drag an item, it doesn't call my anonymous function within the dragSort attribute. However in my simplified codepen example it works.

Where is my fault? Is it because i call the anonymous function nested in an other function?

Thanks for your help!

Body:
This is not an answer per-se but your code should run fine (as you can see in the running snippet below).

It seems that you are not calling the function correctly.

function createBookmarkContainer() {

  var bookmarkContainers = Array.prototype.slice.call($('.bookmark-container'));

  gridObjects = [];

  for(var i = 0; i < bookmarkContainers.length; i++) {
    gridObjects[i] = new Muuri(bookmarkContainers[i], {
      dragEnabled: true,
      dragSort: function () {
        return gridObjects
      }
    });
  }
}

@import url('https://fonts.googleapis.com/css?family=Roboto:400,700');

body {
 background-color: #2C3135;
 padding: 0;
 font-family: "roboto";
}

h1 {
 padding: 0;
 margin: 40px 0px 0px 20px;
 font-size: 18px;
 font-weight: 400;
 letter-spacing: 2px;
 color: rgba(255,255,255, .8);
}

.bookmark-container {
 position: relative;
 //background-color: rgba(255,255,255,.02);
 margin: 20px 0;
}
.item {
 position: absolute;
 width: 250px;
 height: 60px;
 line-height: 60px;
 margin: 15px;
 z-index: 1;
}

.item-content {
 position: relative;
 width: 100%;
 height: 100%;
 background-color: #3E444D;
 text-align: center;
 border-radius: 5px;
   box-shadow: 0px 10px 20px 0px rgba(47,47,47,0.03);
 font-size: 12px;
 color: white;
 cursor: pointer;
}

.item.muuri-dragging,
.item.muuri-releasing {
 z-index: 2;
}
.item.muuri-hidden {
 z-index: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-animations/2.3.1/web-animations.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/muuri/0.5.0/muuri.min.js"></script>

<body onload="createBookmarkContainer()">
<h1>SECTION 1</h1>
<div class="bookmark-container c1">
 <div class="item">
  <div class="item-content">1</div>
 </div>
 <div class="item">
  <div class="item-content">2</div>
 </div>
 <div class="item">
  <div class="item-content">3</div>
 </div>
 <div class="item">
  <div class="item-content">4</div>
 </div>
 <div class="item">
  <div class="item-content">5</div>
 </div>
 <div class="item">
  <div class="item-content">6</div>
 </div>
 <div class="item">
  <div class="item-content">7</div>
 </div>
 <div class="item">
  <div class="item-content">8</div>
 </div>
 <div class="item">
  <div class="item-content">9</div>
 </div>
 <div class="item">
  <div class="item-content">10</div>
 </div>
</div>

<h1>SECTION 2</h1>
<div class="bookmark-container c2">
 <div class="item">
  <div class="item-content">1</div>
 </div>
 <div class="item">
  <div class="item-content">2</div>
 </div>
 <div class="item">
  <div class="item-content">3</div>
 </div>
 <div class="item">
  <div class="item-content">4</div>
 </div>
 <div class="item">
  <div class="item-content">5</div>
 </div>
 <div class="item">
  <div class="item-content">6</div>
 </div>
 <div class="item">
  <div class="item-content">7</div>
 </div>
 <div class="item">
  <div class="item-content">8</div>
 </div>
 <div class="item">
  <div class="item-content">9</div>
 </div>
 <div class="item">
  <div class="item-content">10</div>
 </div>
</div>

<h1>SECTION 3</h1>
<div class="bookmark-container c3">
 <div class="item">
  <div class="item-content">1</div>
 </div>
 <div class="item">
  <div class="item-content">2</div>
 </div>
 <div class="item">
  <div class="item-content">3</div>
 </div>
 <div class="item">
  <div class="item-content">4</div>
 </div>
 <div class="item">
  <div class="item-content">5</div>
 </div>
 <div class="item">
  <div class="item-content">6</div>
 </div>
 <div class="item">
  <div class="item-content">7</div>
 </div>
 <div class="item">
  <div class="item-content">8</div>
 </div>
 <div class="item">
  <div class="item-content">9</div>
 </div>
 <div class="item">
  <div class="item-content">10</div>
 </div>
</div>

<h1>SECTION 4</h1>
<div class="bookmark-container c3">
 <div class="item">
  <div class="item-content">1</div>
 </div>
 <div class="item">
  <div class="item-content">2</div>
 </div>
 <div class="item">
  <div class="item-content">3</div>
 </div>
 <div class="item">
  <div class="item-content">4</div>
 </div>
 <div class="item">
  <div class="item-content">5</div>
 </div>
 <div class="item">
  <div class="item-content">6</div>
 </div>
 <div class="item">
  <div class="item-content">7</div>
 </div>
 <div class="item">
  <div class="item-content">8</div>
 </div>
 <div class="item">
  <div class="item-content">9</div>
 </div>
 <div class="item">
  <div class="item-content">10</div>
 </div>
</div>
</body>


问:
How to create library or framework for iPhone?
I want to create a library in Objective C in XCode, like the MKMapKit framework. How can I create this?

What type of project do I have to create for this?

答:
You can't make frameworks for the iPhone, you need to have a static library.

Jeffrey Sambells made a very good article how to do this.


问:
Substring on pandas dataframe column
I want to extract a substring (Titles - Mr. Mrs, Miss etc.) from a column (Name) in a pandas dataframe and then  write the new column (Title) back into the dataframe.

In the Name column of the dataframe I have a name such as "Brand, Mr. Owen Harris"  The two delimiters are the , and .

I have attempted to use a split method, but  this only splits the original string in two within a list. So I still send up ['Braund', ' Mr. Owen Harris'] in the list.

```<code>import pandas as pd
#import re
df_Train = pd.read_csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vTliZmavBsJCFDiEwxcSIIftu-0gR9p34n8Bq4OUNL4TxwHY-JMS6KhZEbWr1bp91UqHPkliZBBFgwh/pub?gid=1593012114&single=true&output=csv')
a= df_Train['Name'].str.split(',')
for i in a:
    print(i[1])
</code>```

I am thinking this might be situation where regex comes into play. My reading suggests a Lookahead (?=,)  and Lookbehind (?<='.') approach should do the trick. for example

```<code>import re
a= df_Train['Name'].str.split(r'(?=,)*(?<='.'))
for i in a:
    print(i)
    print(i[1])`
</code>```

But I am running into errors (EOL while scanning string literal) .  Can someone point me in the right direction?

Cheers
Mike

答:
You do it like this.

```<code>df_Train.Name.str.split(',').str[1].str.split('.').str[0].str.strip()
</code>```

Output head(5):

```<code>0       Mr
1      Mrs
2     Miss
3      Mrs
4       Mr
</code>```

Summation of results

```<code>df_Train.Name.str.split(',').str[1].str.split('.').str[0].str.strip()\
             .value_counts()
</code>```

Output

```<code>Mr              517
Miss            182
Mrs             125
Master           40
Dr                7
Rev               6
Mlle              2
Col               2
Major             2
Lady              1
Mme               1
Sir               1
Ms                1
the Countess      1
Jonkheer          1
Don               1
Capt              1
Name: Name, dtype: int64
</code>```

Title: Substring on pandas dataframe column

Body:
I want to extract a substring (Titles - Mr. Mrs, Miss etc.) from a column (Name) in a pandas dataframe and then  write the new column (Title) back into the dataframe.

In the Name column of the dataframe I have a name such as "Brand, Mr. Owen Harris"  The two delimiters are the , and .

I have attempted to use a split method, but  this only splits the original string in two within a list. So I still send up ['Braund', ' Mr. Owen Harris'] in the list.

import pandas as pd
#import re
df_Train = pd.read_csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vTliZmavBsJCFDiEwxcSIIftu-0gR9p34n8Bq4OUNL4TxwHY-JMS6KhZEbWr1bp91UqHPkliZBBFgwh/pub?gid=1593012114&single=true&output=csv')
a= df_Train['Name'].str.split(',')
for i in a:
    print(i[1])

I am thinking this might be situation where regex comes into play. My reading suggests a Lookahead (?=,)  and Lookbehind (?<='.') approach should do the trick. for example

import re
a= df_Train['Name'].str.split(r'(?=,)*(?<='.'))
for i in a:
    print(i)
    print(i[1])`

But I am running into errors (EOL while scanning string literal) .  Can someone point me in the right direction?

Cheers
Mike

Body:
You do it like this.

df_Train.Name.str.split(',').str[1].str.split('.').str[0].str.strip()

Output head(5):

0       Mr
1      Mrs
2     Miss
3      Mrs
4       Mr

Summation of results

df_Train.Name.str.split(',').str[1].str.split('.').str[0].str.strip()\
             .value_counts()

Output

Mr              517
Miss            182
Mrs             125
Master           40
Dr                7
Rev               6
Mlle              2
Col               2
Major             2
Lady              1
Mme               1
Sir               1
Ms                1
the Countess      1
Jonkheer          1
Don               1
Capt              1
Name: Name, dtype: int64


问:
Show Reviewing Pane in Word Client by default
What I want:
I'm editing a WordprocessingDocument, and adding some tracked changes in it. This part is done. Now, I want MS word to show all revisions by default, i.e., it shouldn't require user to click on the red side bar to open the tracked changes in the document.

What I did: For this, I found a class RevisionView, which adds the xml element <w:revisionView /> in settings.xml under w:settings element. The RevisionView has some properties like Comments, DisplayRevision, Formatting etc. I explicitly set them all to true.

```<code>RevisionView revView = new RevisionView();
revView.DisplayRevision = new OnOffValue(true);
revView.Formatting = new OnOffValue(true);
revView.InkAnnotations = new OnOffValue(true);
revView.Markup = new OnOffValue(true);
revView.Comments = new OnOffValue(true);
</code>```

and then I added this revView to the Settings:

```<code>Settings settings = wordprocessingDocument.MainDocumentPart.DocumentSettingsPart.Settings;
settings.RemoveAllChildren<RevisionView>();
settings.AppendChild(revView);
settings.Save();
</code>```

And then I reviewed the document xml explicitly, it is adding the following xml in the settings:

```<code><w:revisionView w:markup="true" w:comments="true" w:insDel="true" w:formatting="true" w:inkAnnotations="true" />
</code>```

But adding this element in settings doesn't affect the view. It isn't showing the revisions opened by default.

Then, for testing purpose, I changed the zoom element in the settings.xml by hand from <w:zoom w:percent="100" /> to <w:zoom w:percent="120" />. What I expected was: word would change the zoom for this document from 100 to 120 now. But it didn't do that, the zoom was 100 even after changing to 120 in settings.xml.

One more thing: I can't use interop as I have to deploy this to a server, that's why I'm doing all this using OpenXmlSdk.

What I'm asking:

Is it even possible to do what i want?

If it is, then what am I doing wrong? Is RevisionView the option, on what should I rely?

Is there a way to force word to apply (override the default application level settings) the settings provided in settings.xml?

Why isn't word changing the zoom from 100 to 120?

答:
Here are the answers to your questions:

Is it even possible to do what i want?

What you are trying to do is: Upon opening the docx file, have the Reviewing Pane be open automatically.  I could not find a way to force the Word client to do this with OpenXml.

If it is, then what am I doing wrong? Is RevisionView the option, on what should I rely?

Its not possible, so the answer here is also no.

Is there a way to force word to apply (override the default application level settings) the settings provided in settings.xml?

Yes using the OpenXml SDK.  The Settings Part has properties that you can control with code to alter the default Word client behavior.

Why isn't word changing the zoom from 100 to 120?

I can't answer this without seeing your file.  Perhaps you did not save the file back correctly when you edited the file manually.

I was able to build a simple console app with the following code.  The app will change the zoom level for any Word file to 120%.  You need to add your file path to the code.

I generated most of this code using the OpenXml Productivity Tool..

Note - When building this in Visual Studio, don't forget to add DocumentFormat.OpenXml and WindowsBase to your project references.

```<code>using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApp4
{
    class Program
    {

        private static WordprocessingDocument document;
        private static System.Collections.Generic.IDictionary<System.String, OpenXmlPart> UriPartDictionary = new System.Collections.Generic.Dictionary<System.String, OpenXmlPart>();
        private static System.Collections.Generic.IDictionary<System.String, DataPart> UriNewDataPartDictionary = new System.Collections.Generic.Dictionary<System.String, DataPart>();

        static void Main(string[] args)
        {

            using (document = WordprocessingDocument.Open("<DOCX FILE PATH HERE>", true))
            {
                BuildUriPartDictionary();
                ChangeParts();
            }

        }

        private static void BuildUriPartDictionary()
        {
            System.Collections.Generic.Queue<OpenXmlPartContainer> queue = new System.Collections.Generic.Queue<OpenXmlPartContainer>();
            queue.Enqueue(document);
            while (queue.Count > 0)
            {
                foreach (var part in queue.Dequeue().Parts)
                {
                    if (!UriPartDictionary.Keys.Contains(part.OpenXmlPart.Uri.ToString()))
                    {
                        UriPartDictionary.Add(part.OpenXmlPart.Uri.ToString(), part.OpenXmlPart);
                        queue.Enqueue(part.OpenXmlPart);
                    }
                }
            }
        }

        private static void ChangeParts()
        {
            ChangeDocumentSettingsPart1(((DocumentSettingsPart)UriPartDictionary["/word/settings.xml"]));
        }

        private static void ChangeDocumentSettingsPart1(DocumentSettingsPart documentSettingsPart)
        {
            Settings settings1 = documentSettingsPart.Settings;

            Zoom zoom1 = settings1.GetFirstChild<Zoom>();

            zoom1.Percent = "120";

        }
    }
}
</code>```

Body:
What I want:
I'm editing a WordprocessingDocument, and adding some tracked changes in it. This part is done. Now, I want MS word to show all revisions by default, i.e., it shouldn't require user to click on the red side bar to open the tracked changes in the document.

What I did: For this, I found a class RevisionView, which adds the xml element <w:revisionView /> in settings.xml under w:settings element. The RevisionView has some properties like Comments, DisplayRevision, Formatting etc. I explicitly set them all to true.

RevisionView revView = new RevisionView();
revView.DisplayRevision = new OnOffValue(true);
revView.Formatting = new OnOffValue(true);
revView.InkAnnotations = new OnOffValue(true);
revView.Markup = new OnOffValue(true);
revView.Comments = new OnOffValue(true);

and then I added this revView to the Settings:

Settings settings = wordprocessingDocument.MainDocumentPart.DocumentSettingsPart.Settings;
settings.RemoveAllChildren<RevisionView>();
settings.AppendChild(revView);
settings.Save();

And then I reviewed the document xml explicitly, it is adding the following xml in the settings:

<w:revisionView w:markup="true" w:comments="true" w:insDel="true" w:formatting="true" w:inkAnnotations="true" />

But adding this element in settings doesn't affect the view. It isn't showing the revisions opened by default.

Then, for testing purpose, I changed the zoom element in the settings.xml by hand from <w:zoom w:percent="100" /> to <w:zoom w:percent="120" />. What I expected was: word would change the zoom for this document from 100 to 120 now. But it didn't do that, the zoom was 100 even after changing to 120 in settings.xml.

One more thing: I can't use interop as I have to deploy this to a server, that's why I'm doing all this using OpenXmlSdk.

What I'm asking:

Is it even possible to do what i want?

If it is, then what am I doing wrong? Is RevisionView the option, on what should I rely?

Is there a way to force word to apply (override the default application level settings) the settings provided in settings.xml?

Why isn't word changing the zoom from 100 to 120?

Body:
Here are the answers to your questions:

Is it even possible to do what i want?

What you are trying to do is: Upon opening the docx file, have the Reviewing Pane be open automatically.  I could not find a way to force the Word client to do this with OpenXml.

If it is, then what am I doing wrong? Is RevisionView the option, on what should I rely?

Its not possible, so the answer here is also no.

Is there a way to force word to apply (override the default application level settings) the settings provided in settings.xml?

Yes using the OpenXml SDK.  The Settings Part has properties that you can control with code to alter the default Word client behavior.

Why isn't word changing the zoom from 100 to 120?

I can't answer this without seeing your file.  Perhaps you did not save the file back correctly when you edited the file manually.

I was able to build a simple console app with the following code.  The app will change the zoom level for any Word file to 120%.  You need to add your file path to the code.

I generated most of this code using the OpenXml Productivity Tool..

Note - When building this in Visual Studio, don't forget to add DocumentFormat.OpenXml and WindowsBase to your project references.

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApp4
{
    class Program
    {

        private static WordprocessingDocument document;
        private static System.Collections.Generic.IDictionary<System.String, OpenXmlPart> UriPartDictionary = new System.Collections.Generic.Dictionary<System.String, OpenXmlPart>();
        private static System.Collections.Generic.IDictionary<System.String, DataPart> UriNewDataPartDictionary = new System.Collections.Generic.Dictionary<System.String, DataPart>();

        static void Main(string[] args)
        {

            using (document = WordprocessingDocument.Open("<DOCX FILE PATH HERE>", true))
            {
                BuildUriPartDictionary();
                ChangeParts();
            }

        }

        private static void BuildUriPartDictionary()
        {
            System.Collections.Generic.Queue<OpenXmlPartContainer> queue = new System.Collections.Generic.Queue<OpenXmlPartContainer>();
            queue.Enqueue(document);
            while (queue.Count > 0)
            {
                foreach (var part in queue.Dequeue().Parts)
                {
                    if (!UriPartDictionary.Keys.Contains(part.OpenXmlPart.Uri.ToString()))
                    {
                        UriPartDictionary.Add(part.OpenXmlPart.Uri.ToString(), part.OpenXmlPart);
                        queue.Enqueue(part.OpenXmlPart);
                    }
                }
            }
        }

        private static void ChangeParts()
        {
            ChangeDocumentSettingsPart1(((DocumentSettingsPart)UriPartDictionary["/word/settings.xml"]));
        }

        private static void ChangeDocumentSettingsPart1(DocumentSettingsPart documentSettingsPart)
        {
            Settings settings1 = documentSettingsPart.Settings;

            Zoom zoom1 = settings1.GetFirstChild<Zoom>();

            zoom1.Percent = "120";

        }
    }
}


问:
What is the difference between starting Choregraphe application with a trigger sentence and starting in a different way?
I have a variety of apps that can be started in one of three ways:

1. from the robots's tablet - when the user clicks the icon I use runBehaviour or startBehaviour

2. from a dialog - trigger an event or start a behaviour

3. with trigger sentences

When the app runs, I want the robot to stay focused until it's over. That's why I stop modules such as the ALBasicAwarness and ALSpeechRecognition. However, if someone touches the robot on the head, the dialog_touch from the basic channel is triggered and Pepper begins to listen and answer questions, even though he has not left the application yet. Тhis happens if the app is started in a way (1) or (2) but if it is started in a way (3) (with trigger sentences) the robot remains focused at all times.

I want to know what is the difference between starting with a trigger sentence and other ways and how to run the application so the robot does not focus off.

答:
instead of runBehavior and startBehavior you should take advantage of the robots life cycle (see doc). Call ALAutonomousLife.switchFocus instead so the robot is 100% focused on your app (all the others will be stopped).

When the robot starts, Autonomous Life runs in "solitary" (no behavior is focused). It registers and listens to the launch trigger conditions for all the apps that are installed on the robot. When a behavior wants to start (i.e. its trigger condition is true), then the "Autonomous Life" will automatically call switchFocus.

Then depending on the behavior type:

if the behavior is "interactive" then autonomous life will also unregister the launch trigger conditions (i.e. an interactive behavior cannot be stopped by another behavior).

if the behavior is "solitary", then only interactive behaviors' trigger conditions will still be active (i.e. a solitary behavior can be stopped if an interactive behavior needs to start).

At the end of you application, then the robot goes back to the "solitary" state and resume watching the trigger conditions.

If you have "The Dialog" on your robot, then you have an interactive behavior that will start automatically (with trigger condition "user is in zone 1") and run all your "collaborative dialogs". In a dialog, you can use ^switchFocus to ask autonomousLife to start an app and stop any other thing it's doing.


问:
A formula to find the size of a matrix after convolution
If my input size is 5x5, the stride is 1x1, and the filter size is 3x3 then I can compute on paper that the final size of the convolved matrix will be 3x3.

But, when this input size changes to 28x28, or 50x50 then how can I compute the size of the convolved matrix on paper? Is there any formula or any trick to do that?

答:
Yes, there's a formula (see the details in cs231n class):

```<code>W2 = (W1 - F + 2*P) / S + 1
H2 = (H1 - F + 2*P) / S + 1
</code>```

where  W1xH1 is the original image size, F is the filter size, S is the stride and P is one more parameter - the padding size. Also note that result channel size equals to the number of filters.

Body:
Yes, there's a formula (see the details in cs231n class):

W2 = (W1 - F + 2*P) / S + 1
H2 = (H1 - F + 2*P) / S + 1

where  W1xH1 is the original image size, F is the filter size, S is the stride and P is one more parameter - the padding size. Also note that result channel size equals to the number of filters.


问:
activity onStop() and destroying process
I doubt in the meaning of this part of android "Activity lifecycle" tutorial:

It is also important that you use onStop() to release resources that might leak memory, because it is possible for the system to kill the process hosting your activity without calling the activity's final onDestroy() callback.

As I understand, when process is killed all memory associated with it is deallocated. A leak is a situation when a component with greater scope owns a reference to a component with a smaller scope (static reference to a context, handler, inner class etc). But if a process is dead, there are no components alive at all. Yes, some of them can be recreated later, but they will not hold a reference to some "old" components from past. Can anyone give an example of the scenario when killing  a process can lead to memory leaks? Or am I totally wrong in my (some of my) assumptions?

Thanks in advance!

答: The wording in the documentation is not good. When your OS process is killed, all memory is reclaimed. There are no memory leaks possible in this case.</p>


问:
Using numpy.fromregex on a text file with colon separated digits
I have a dataset that looks like this:

```<code># sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 12:1 13:1 14:1
</code>```

I want to create a matrix without colons which looks like this:

```<code># sparse2.txt
1 1 1 2 1 3 1
0 1 1 4 1
1 2 1 3 1 4 1
</code>```

I used online python regex to find the regex pattern to read the rows of the file.
https://pythex.org/

I used the pattern:

```<code>pat = [0-1]\s+([0-9]:1\s*)+
</code>```

Which satisfies the regex in online regexer, but, when I used it in np.fromregex
it does not work.

```<code>import numpy as np
pat = r'[0-1]\s+([0-9]:1\s*)+'

data = np.fromregex('sparse.txt', pat, dtype='str')
print("data = {}".format(data))
</code>```

How can we fix the error?

答:
What's wrong

[0-1]\s+([0-9]:1\s*)+

This will match the entire line instead of the each numerical number which you want.

How to fix it?

```<code>import numpy as np
pat = r'^\d|[^0-9\:\n][\d]?'

data = np.fromregex('sparse.txt', pat, [('num', np.int64)])
print("data = {}".format(data))
</code>```

Result

Suggestions

Use SublimeText to help you compose the regex pattern

numpy.fromregex official reference link

Body:
I have a dataset that looks like this:

# sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 12:1 13:1 14:1

I want to create a matrix without colons which looks like this:

# sparse2.txt
1 1 1 2 1 3 1
0 1 1 4 1
1 2 1 3 1 4 1

I used online python regex to find the regex pattern to read the rows of the file.
https://pythex.org/

I used the pattern:

pat = [0-1]\s+([0-9]:1\s*)+

Which satisfies the regex in online regexer, but, when I used it in np.fromregex
it does not work.

import numpy as np
pat = r'[0-1]\s+([0-9]:1\s*)+'

data = np.fromregex('sparse.txt', pat, dtype='str')
print("data = {}".format(data))

How can we fix the error?

Body:
What's wrong

[0-1]\s+([0-9]:1\s*)+

This will match the entire line instead of the each numerical number which you want.

How to fix it?

import numpy as np
pat = r'^\d|[^0-9\:\n][\d]?'

data = np.fromregex('sparse.txt', pat, [('num', np.int64)])
print("data = {}".format(data))

Result

Suggestions

Use SublimeText to help you compose the regex pattern

numpy.fromregex official reference link


问:
How do I store image sequence changes to a mysql database with php
I am trying to build a photo organization table and am looking for advice and/or examples of how to save the display sequence of photos to a database.
I'm using php and mysql

Example:
If I have 10 photos in an album and decide to change the sequence of images, so I move a photo from seq 2 to seq 7, then the sequence changes to the following.

1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Original Sequence

1, 7, 2, 3, 4, 5, 6, 8, 9, 10 New Sequence

How do I tell the database that the sequence column for all the affected rows has changed? ...in one operation.

Do I change multiple rows in the db at once?  Can I limit to just the affected rows

the photos table currently has   "rowID, sequence, URL...."

答:
```<code>UPDATE table SET display_order = CASE WHEN id=first_id THEN second_order ELSE first_order END WHERE id = first_id OR id = second_id LIMIT 2
</code>```

where you have first_id, first_order, second_id, second_order, this switches their display orders.

Body:
UPDATE table SET display_order = CASE WHEN id=first_id THEN second_order ELSE first_order END WHERE id = first_id OR id = second_id LIMIT 2

where you have first_id, first_order, second_id, second_order, this switches their display orders.


问:
Silence gdb "switching to thread" output messages
I am currently debugging a multi-threaded application in Linux using gdb.  I'm getting a lot of noise in the output and am wondering if there is anything I can do to silence it.

I'm getting a lot of these: "[Switching to Thread ~~ (LWP ~~)]"
I have used the 'set print thread-events off', but that only seems to catch the start/stop of the thread.

Does anyone know of a way that I can get gdb to stop showing these Switching thread messages?

答:
Does anyone know of a way that I can get gdb to stop showing these Switching thread messages?

There is no good way at present.

If you're desperate, one idea would be to write wrappers for commands like continue that work by redirecting output to /dev/null (and then undoing the redirection somewhere, like in a stop hook).  This will cause you to miss any other gdb output as well though.

It's worth filing a gdb bug report about this.


答:
The error is coming from the fact that you have single quotes around the period inside your single-quoted regex string-literal; this actually isn't the correct syntax, I think you mean to use an escaped-period i.e. r'(?=,)*(?<=\.). However you don't need to use lookahead/lookbehind here, it's more usual and simpler to use capture-groups to describe your regex; in this case the regex would be

```<code>df_Train['Name'].str.extract(", (\w*)\.")
</code>```

Title: Substring on pandas dataframe column

Body:
The error is coming from the fact that you have single quotes around the period inside your single-quoted regex string-literal; this actually isn't the correct syntax, I think you mean to use an escaped-period i.e. r'(?=,)*(?<=\.). However you don't need to use lookahead/lookbehind here, it's more usual and simpler to use capture-groups to describe your regex; in this case the regex would be

df_Train['Name'].str.extract(", (\w*)\.")


问:
is it possible to lock a user account (g suite) programmatically using google apps scripts
also is it possible to do that after a certain log-in attempts?

I'm trying to create a script that locks the user's account after a certain number of failed login attempts.

I tried to check if any functions can be used to access the account setting, or how many times this user failed to login, but I got nothing so far.

Gmail Service allows scripts to send email and access a user's Gmail account.
With only these Classes

Name            Brief description

GmailApp     : Provides access to Gmail threads, messages, and labels.

GmailAttachment   : An attachment from Gmail.

GmailDraft        : A user-created draft message in a user's Gmail account.

GmailLabel        :  A user-created label in a user's Gmail account.

GmailMessage       : A message in a user's Gmail account.

GmailThread         : A thread in a user's Gmail account.

also as far as I know the lock service allows scripts to prevents concurrent access to sections of code(e.g multiple users or processes modifying a shared resource to prevent collisions) but not locking an account .

any help would be appreciated .

Thanks

答:
Pretty sure it's not possible. Definitely not possible via the Gmail API. Your problem is getting the failed logins in real time, after that the reset is easy enough.

Have a look at the Admin SDK for the functions you need: in particular the Reports API for failed logins & the Directory API for managing user accounts.


问:
Show matlab figures automatically on the second monitor
I have a computer with a second monitor connected under "extended" mode.

When I start my matlab script it will show a figure. In a default mode, the figure always shows on the monitor of my computer. However, instead, I would like for the figure to show directly on the extended monitor. I'd also like for the figure to show with its maximum size.

I searched,  but did not get much luck to find a answer. Anyone here care to enlighten me? Thanks a lot.

答:
Open a new figure.  Place and resize it where you want on the second monitor.  Then do the following.  Now any new figure should be spawned there.

```<code>pos = get (gcf, 'position');
set(0, 'DefaultFigurePosition', pos)
</code>```

Note this will only keep for your current matlab session.  So if you want this behavior always you can add it to your startup.m file or create one if you dont have o e already.

Body:
Open a new figure.  Place and resize it where you want on the second monitor.  Then do the following.  Now any new figure should be spawned there.

pos = get (gcf, 'position');
set(0, 'DefaultFigurePosition', pos)

Note this will only keep for your current matlab session.  So if you want this behavior always you can add it to your startup.m file or create one if you dont have o e already.


问:
hibernate jpa unit tests autodection does not work
I have the following in persistence.xml

```<code><persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <class>com.merc.model.log.EventLogging</class>
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>
        <!-- Scan for annotated classes and Hibernate mapping XML files -->
        <property name="hibernate.archive.autodetection" value="class"/>
    </properties>
</persistence-unit>
</code>```

If I comment out com.merc.model.log.EventLogging, I get Unknown entity exception.

Any ideas as to why autodetection would not work

答:
This can be caused by the fact that by default autodetection works for classes inside the same classpath item where persistence.xml is located.

So, you have separate target folders for the code itself and for the tests (for example, if you use Maven with default configuration), and if this persistence.xml ends up in tests' target folder after compilation, classes from the main target folder wouldn't be detected.

You can use <jar-file> elements to point to other classpath items that should be searched for entities.

If you use Maven, you can do it in elegant way using resource filtering:

persistence.xml:

```<code><jar-file>${project.build.outputDirectory}</jar-file>
</code>```

pom.xml:

```<code><build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
            <filtering>true</filtering>
        </testResource>
    </testResources>
</build>
</code>```

Body:
I have the following in persistence.xml

<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <class>com.merc.model.log.EventLogging</class>
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    <properties>

        <property name="hibernate.archive.autodetection" value="class"/>
    </properties>
</persistence-unit>

If I comment out com.merc.model.log.EventLogging, I get Unknown entity exception.

Any ideas as to why autodetection would not work

Body:
This can be caused by the fact that by default autodetection works for classes inside the same classpath item where persistence.xml is located.

So, you have separate target folders for the code itself and for the tests (for example, if you use Maven with default configuration), and if this persistence.xml ends up in tests' target folder after compilation, classes from the main target folder wouldn't be detected.

You can use <jar-file> elements to point to other classpath items that should be searched for entities.

If you use Maven, you can do it in elegant way using resource filtering:

persistence.xml:

<jar-file>${project.build.outputDirectory}</jar-file>

pom.xml:

<build>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
            <filtering>true</filtering>
        </testResource>
    </testResources>
</build>


问:
How to concatenate multiple values to use in the select query in Oracle
I have the following query

```<code>set serveroutput on;
declare store_nbr number(9,0);
Begin
Select trim(NODE_ID) into store_nbr  from HOST_STORE_PROFILE
where sysdate between EFCV_DTE and EXPR_DTE and TO_CHAR(NODE_ID) in
('12175','22671','16449');
dbms_output.Put_line(store_nbr);
end;
</code>```

This works fine and prints a value(store_nbr).

But when I tried to replace the 'in' condition in the select statement with variable declaration, it is not working as desired.

I am doing like this:

```<code>declare store_nbr number(9,0);
ca_store_nbr varchar2(4096) := '(12175,22671,25519)';
begin
Select NODE_ID into store_nbr from HOST_STORE_PROFILE
where sysdate between EFCV_DTE and EXPR_DTE and TO_CHAR(NODE_ID) in ||
ca_store_nbr;
dbms_output.Put_line(store_nbr);
end;
</code>```

I don't get the value into store_nbr.

Whats wrong with the second query.

答:
This needs to be a dynamic sql statement.

make a string out of the whole statement and execute with something like

```<code>EXECUTE IMMEDIATE <sql statement>
</code>```

Body:
I have the following query

set serveroutput on;
declare store_nbr number(9,0);
Begin
Select trim(NODE_ID) into store_nbr  from HOST_STORE_PROFILE
where sysdate between EFCV_DTE and EXPR_DTE and TO_CHAR(NODE_ID) in
('12175','22671','16449');
dbms_output.Put_line(store_nbr);
end;

This works fine and prints a value(store_nbr).

But when I tried to replace the 'in' condition in the select statement with variable declaration, it is not working as desired.

I am doing like this:

declare store_nbr number(9,0);
ca_store_nbr varchar2(4096) := '(12175,22671,25519)';
begin
Select NODE_ID into store_nbr from HOST_STORE_PROFILE
where sysdate between EFCV_DTE and EXPR_DTE and TO_CHAR(NODE_ID) in ||
ca_store_nbr;
dbms_output.Put_line(store_nbr);
end;

I don't get the value into store_nbr.

Whats wrong with the second query.

Body:
This needs to be a dynamic sql statement.

make a string out of the whole statement and execute with something like

EXECUTE IMMEDIATE <sql statement>


问:
How do I call one constructor from another in Java?
Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?</p>

答:
There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

```<code>class LambdaInitedClass {

   public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
       init.accept(this);
   }
}
</code>```

Call it with...

```<code> new LambdaInitedClass(l -> { // init l any way you want });
</code>```

OwnerDisplayName: askgelal

LastEditorDisplayName: Gaius

Body:
There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

class LambdaInitedClass {

   public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
       init.accept(this);
   }
}

Call it with...

 new LambdaInitedClass(l -> { // init l any way you want });