问:
How to extract multiple words from a line using shell script
I need to extract the name of root CN of a website stored inside a file as shown below.

```<code>google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2
</code>```

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

```<code>cat RootCertificates | tr -d '*CN='  | sort | uniq -c
</code>```

答:
You can use sed instead.

```<code>sed 's/^.*CN=//' < RootCertificates | sort | ..
</code>```

.. also, try to avoid cat if you can. In this can you can redirect the input of sed from your file.

Body:
I need to extract the name of root CN of a website stored inside a file as shown below.

google.com   CN=Google Internet Authority G2
youtube.com   CN=Google Internet Authority G2

I want to extract this portion from the line "Google Internet Authority G2" and count the occurrence in the file.

I tried using this command, but I don't know the proper regex to be used for it. Can somebody help?

cat RootCertificates | tr -d '*CN='  | sort | uniq -c

Body:
You can use sed instead.

sed 's/^.*CN=//' < RootCertificates | sort | ..

.. also, try to avoid cat if you can. In this can you can redirect the input of sed from your file.


来源: stackexchange

问:
In linux how to archive and compress multiple files into one and remove source files?
I have below files in a directory.

```<code>file001
file002
.
.
file009
</code>```

I need to compress them into one and remove original/source files (file001 .. file009) so I can free up some disk space.

This is what I did:
Archived all files into one using below command

```<code>tar -cvf file00.tar file00*
</code>```

Then compressed the archived file using below command

```<code>xz file00.tar
</code>```

previously I had archived and compressed using single command

```<code>tar -cJvf file00.tar.xz file00*
</code>```

xz has done a fine job, compressed 10GB file into less than 400MB but I have several problems with these methods:

Old/source files are not removed

xz takes huge time

My question is, is there any way I can archive and compress multiple files into one using single command that'll also remove source files? Is there any other compression tool that's efficient as xz but works faster?

I've seen in some other sites that I can use multiple cores/threads to boost xz process but haven't tried myself.

Thanks in advance.

答:
You may try pixz which is parallel variant of xz tool (or pxz parallel variant of xz)):

```<code>tar -Ipixz -cf foo.tpxz foo/`
</code>```

There is -I compressor option of tar to select non-standard compressor, and it should be before f option as f option requires the string argument.

And for deletion there is option in GNU Tar https://www.gnu.org/software/tar/manual/html_node/remove-files.html (why it is in the "4.4 Options Used by --extract" section??)

Removing Files

See The section is too terse. Something more to add? An example, maybe?

--remove-files

Remove files after adding them to the archive.

I didn't test it, but it was listed in https://serverfault.com/questions/283355/correct-way-of-using-the-remove-files-option-with-tar (and https://superuser.com/questions/96860)  again used before -f option:

```<code>tar --remove-files -cvfj archive.tar.bz2 archive/
</code>```

So, combining both options (after installation of pixz; this is still can be opened by classic xz tool, and can be renamed as archive.tar.xz too):

```<code>tar  -Ipixz --remove-files -cJvf file00.tpxz file00*
</code>```

or with xz:

```<code>tar  -Ixz --remove-files -cJvf file00.tar.xz file00*
</code>```

PS: There are other parallel compressors: pigz (gzip format), pbzip2 and lbzip2 (bzip2 format, not so compact and slower than xz and gzip). There are also fast compressors like lz4/lz5 or facebook's zstd. And there is lrzip which can use several threads for compression and can find repetitions of data over long distance, and then compress using lzma (by default, xz-like method) or classic gz or faster LZO or very slow and effective ZPAQ.

ContentLicense: CC BY-SA 3.0

Body:
I have below files in a directory.

file001
file002
.
.
file009

I need to compress them into one and remove original/source files (file001 .. file009) so I can free up some disk space.

This is what I did:
Archived all files into one using below command

tar -cvf file00.tar file00*

Then compressed the archived file using below command

xz file00.tar

previously I had archived and compressed using single command

tar -cJvf file00.tar.xz file00*

xz has done a fine job, compressed 10GB file into less than 400MB but I have several problems with these methods:

Old/source files are not removed

xz takes huge time

My question is, is there any way I can archive and compress multiple files into one using single command that'll also remove source files? Is there any other compression tool that's efficient as xz but works faster?

I've seen in some other sites that I can use multiple cores/threads to boost xz process but haven't tried myself.

Thanks in advance.

Body:
You may try pixz which is parallel variant of xz tool (or pxz parallel variant of xz)):

tar -Ipixz -cf foo.tpxz foo/`

There is -I compressor option of tar to select non-standard compressor, and it should be before f option as f option requires the string argument.

And for deletion there is option in GNU Tar https://www.gnu.org/software/tar/manual/html_node/remove-files.html (why it is in the "4.4 Options Used by --extract" section??)

Removing Files

See The section is too terse. Something more to add? An example, maybe?

--remove-files

Remove files after adding them to the archive.

I didn't test it, but it was listed in https://serverfault.com/questions/283355/correct-way-of-using-the-remove-files-option-with-tar (and https://superuser.com/questions/96860)  again used before -f option:

tar --remove-files -cvfj archive.tar.bz2 archive/

So, combining both options (after installation of pixz; this is still can be opened by classic xz tool, and can be renamed as archive.tar.xz too):

tar  -Ipixz --remove-files -cJvf file00.tpxz file00*

or with xz:

tar  -Ixz --remove-files -cJvf file00.tar.xz file00*

PS: There are other parallel compressors: pigz (gzip format), pbzip2 and lbzip2 (bzip2 format, not so compact and slower than xz and gzip). There are also fast compressors like lz4/lz5 or facebook's zstd. And there is lrzip which can use several threads for compression and can find repetitions of data over long distance, and then compress using lzma (by default, xz-like method) or classic gz or faster LZO or very slow and effective ZPAQ.


问:
maven testCompile error: java 6 vs java 8
I created a few Mock classes that implement java.sql interfaces (ResultSet, Connection etc.)
When i run maven (3.3.9) test on my classes, i get a compilation failure (e.g. Class is not abstract and doesn't override abstract method getNetworkTimeout()) which is due to methods added in java 8.
I have JAVA_HOME set to Java 8.
I'm trying to compile my source and tests with java 6 and i have tried different methods:

adding properties for maven.compiler.source and maven.compiler.target to be 1.6

adding source and target configuration of 1.6 for maven-compiler-plugin

adding an executable for my 1.6 installation

None of them make any difference, which tells me i'm barking up the wrong tree.

Any ideas?

Thanks,
Nilesh

答: You need to set the boot class path to use the 1.6 JRE; setting the language level only controls language features, not the classpath.</p>


问:
Prism for Xamarin Forms - Navigating from a tabbedpage
(Using Prism 6.1.0-pre6 and XF 2.3.0.107)

Summary: Navigating to a ContentPage from a TabbedPage doesn't show the toolbar/actionbar.

I navigate to a TabbedPage (MainPage.xaml) from another page.  This looks like this:

```<code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Or.Console.Views"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Or.Console.Views.MainPage">
  <local:APage/>
  <local:BPage/>
  <local:CPage/>
</TabbedPage>
</code>```

And in the ViewModel for APage, I'm calling

```<code>_navigationService.NavigateAsync("DetailsPage");
</code>```

The DetailsPage is just a ContentPage, and I would expect that it would show with the back button and action bar at the top, but it doesn't.

I'm guessing this is because Prism doesn't know about the tab child pages, only the TabbedPage itself.

I've tried registering the tab child pages with Prism, but this doesn't seem to work.  Also tried wrapping each tab child in a NavigationPage, but this brings on some strange behavior with duplicate toolbars.

What's the right way to navigate from within tabbed content?

EDIT:
In response to Brian Lagunas answer, I tried wrapping the TabbedPage in a NavigationPage, so when I navigate to it, I'm calling

```<code> _navigationService.NavigateAsync("DeviceNavWrapper/MainPage");
</code>```

But this gives an odd result:

EDIT2: Solution in my case ended up that I needed to call NavigateAsync from APage with the useModalNavigation set to false. So now APage has this:

```<code>_navigationService.NavigateAsync("DetailsPage", null, false);
</code>```

答:
To eliminate duplicate Toolbar, I found out that settting

```<code>   NavigationPage.HasNavigationBar="False"
</code>```

of the NavigationPage Wrapper easier

Body:
(Using Prism 6.1.0-pre6 and XF 2.3.0.107)

Summary: Navigating to a ContentPage from a TabbedPage doesn't show the toolbar/actionbar.

I navigate to a TabbedPage (MainPage.xaml) from another page.  This looks like this:

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Or.Console.Views"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="Or.Console.Views.MainPage">
  <local:APage/>
  <local:BPage/>
  <local:CPage/>
</TabbedPage>

And in the ViewModel for APage, I'm calling

_navigationService.NavigateAsync("DetailsPage");

The DetailsPage is just a ContentPage, and I would expect that it would show with the back button and action bar at the top, but it doesn't.

I'm guessing this is because Prism doesn't know about the tab child pages, only the TabbedPage itself.

I've tried registering the tab child pages with Prism, but this doesn't seem to work.  Also tried wrapping each tab child in a NavigationPage, but this brings on some strange behavior with duplicate toolbars.

What's the right way to navigate from within tabbed content?

EDIT:
In response to Brian Lagunas answer, I tried wrapping the TabbedPage in a NavigationPage, so when I navigate to it, I'm calling

 _navigationService.NavigateAsync("DeviceNavWrapper/MainPage");

But this gives an odd result:

EDIT2: Solution in my case ended up that I needed to call NavigateAsync from APage with the useModalNavigation set to false. So now APage has this:

_navigationService.NavigateAsync("DetailsPage", null, false);

Body:
To eliminate duplicate Toolbar, I found out that settting

   NavigationPage.HasNavigationBar="False"

of the NavigationPage Wrapper easier


问:
Boost:asio time taken for socket read/write
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ? </p>

```<code>  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }
</code>```

答:
Does this ensure that - this time is the actual "network time" for the data transfer?

No. It measures the time to transfer the data into the socket send buffer. If the socket send buffer was full enough such that not all the data fitted into it immediately, it also measures the time to drain the socket send buffer sufficiently to accomodate all the new data. It does not measure time to send all this data to the server in any way.

assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)

It isn't. It is called when all the data has been transferred into the socket send buffer.

Body:
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ?

  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }


问:
How to get the value of a selected radio button and checkbox using its class in jQuery?
I have a laravel form which uses a JSON object as it's source for questions and answer choices. This form allows for text answers, radio buttons and checkboxes. Upon submission, I use jQuery to obtain the value of all the responses which have a class=>response. Those responses/answers are then appended to a hidden textarea field.
I am able to retrieve all the text type responses correctly, however the radio and checkbox responses are incorrect. Instead of capturing the actual radio/checkbox selected, I am returning the final JSON index value from each radio/checkbox. For example, if there are 3 radio button options for a question, the value returned for the answer selected is '2' even if '0' was chosen.  How do I get the actual radio button/checkbox value clicked? It'd be great if I could actually store the text value of each index instead of the index number checked.

I included the jQuery first, then followed it with the portion of the form.

```<code> /*Script for collecting all patient data; script for collecting questionnaire answers and submitting as JSON string*/
$("#formq").submit(function(){
    $("#formq").append("<textarea name='answers' id='answers' hidden='hidden'></textarea>");
    var answers = new Object();
    $(".response").each(function(){
        answers[$(this).attr('name')] = $(this).val();
    });
//Change answers object into json string; place answers into textarea and submit form
    $("#answers").text(JSON.stringify(answers));

<div class="form-group">
     @foreach($jsonObject['questions']['english'] as $key =>$question)
       {{ Form::label('questions', $question['question'], array('class' => 'col-sm-9 display-label')) }}
         @if(($jsonObject['question_metadata'][$key]['multi_value']) == false)
           @if(($jsonObject['question_metadata'][$key]['text_value']) == true)
              <div class="col-sm-8" style="padding-bottom: 15px;">
                  {{ Form::text($key, null, array('class' => 'form-control response')) }}
              </div>
           @elseif(($jsonObject['question_metadata'][$key]['text_value']) == false)
              <div class="col-sm-9" style="padding-right: 15px">
                  @foreach($question['choices'] as $key2 => $choice)
                    <div class="col-sm-9 radio" style="padding-bottom: 15px">
                       {{ Form::radio($key, $key2, null, array('class' => 'response')) }} {{$choice}}
                   </div>
                  @endforeach
              </div>
           @endif
        @elseif(($jsonObject['question_metadata'][$key]['multi_value']) == true)
           <div class="col-sm-9" style="padding-right: 15px">
              @foreach($question['choices'] as $key3 => $choice)
                <div class="col-sm-9 checkbox" style="padding-bottom: 15px">
                  {{ Form::checkbox($key, $key3, null, array('class' => 'response')) }} {{ $choice }}
                </div>
              @endforeach
           </div>
        @endif
   @endforeach
</code>```

```<code>JSON snippet
{
  "questions": {
    "english": [
    {
        "question": "5. This question will provide a text box:"
    },
  {
    "question": "6. Another text box question:"
  },
  {
    "question": "7. This question will provide checkboxes so multiple items can be chosen:",
    "choices": {
      "0": "Option1",
      "1": "Option 2",
      "2": "Option 3",
      "3": "Option 4",
      "4": "Option 5",
      "5": "Option 6",
      "6": "Other"
    }
  },
  {
    "question": "8. This question will provide radio buttons:",
    "choices": {
      "0": "No",
      "1": "Yes"
    }
  },
</code>```

答:
You can change your jQuery code as below which is simply assigning the value if the element is textbox otherwise checked or not for radio and checkboxes.

```<code>var answers = new Object();
$(".response").each(function(){
   if($(this).is('[type="text"]') || $(this).is(':checked')) {
      answers[$(this).attr('name')] = $(this).val();
   }
});
</code>```

The above code will replace the previous value when multiple checkboxes selected, so you can check if value exists for checkbox and append the value as comma (,) separated as below.

```<code>var answers = new Object();
$(".response").each(function(){
   if($(this).is('[type="text"]') || $(this).is(':checked')) {
      if(answers[$(this).attr('name')]) {
         answers[$(this).attr('name')] += ', ';
      } else {
         answers[$(this).attr('name')] = '';
      }

      answers[$(this).attr('name')] += $(this).val();
   }
});
</code>```

Body:
I have a laravel form which uses a JSON object as it's source for questions and answer choices. This form allows for text answers, radio buttons and checkboxes. Upon submission, I use jQuery to obtain the value of all the responses which have a class=>response. Those responses/answers are then appended to a hidden textarea field.
I am able to retrieve all the text type responses correctly, however the radio and checkbox responses are incorrect. Instead of capturing the actual radio/checkbox selected, I am returning the final JSON index value from each radio/checkbox. For example, if there are 3 radio button options for a question, the value returned for the answer selected is '2' even if '0' was chosen.  How do I get the actual radio button/checkbox value clicked? It'd be great if I could actually store the text value of each index instead of the index number checked.

I included the jQuery first, then followed it with the portion of the form.

 /*Script for collecting all patient data; script for collecting questionnaire answers and submitting as JSON string*/
$("#formq").submit(function(){
    $("#formq").append("<textarea name='answers' id='answers' hidden='hidden'></textarea>");
    var answers = new Object();
    $(".response").each(function(){
        answers[$(this).attr('name')] = $(this).val();
    });
//Change answers object into json string; place answers into textarea and submit form
    $("#answers").text(JSON.stringify(answers));

     @foreach($jsonObject['questions']['english'] as $key =>$question)
       {{ Form::label('questions', $question['question'], array('class' => 'col-sm-9 display-label')) }}
         @if(($jsonObject['question_metadata'][$key]['multi_value']) == false)
           @if(($jsonObject['question_metadata'][$key]['text_value']) == true)

                  {{ Form::text($key, null, array('class' => 'form-control response')) }}

           @elseif(($jsonObject['question_metadata'][$key]['text_value']) == false)

                  @foreach($question['choices'] as $key2 => $choice)

                       {{ Form::radio($key, $key2, null, array('class' => 'response')) }} {{$choice}}

                  @endforeach

           @endif
        @elseif(($jsonObject['question_metadata'][$key]['multi_value']) == true)

              @foreach($question['choices'] as $key3 => $choice)

                  {{ Form::checkbox($key, $key3, null, array('class' => 'response')) }} {{ $choice }}

              @endforeach

        @endif
   @endforeach

JSON snippet
{
  "questions": {
    "english": [
    {
        "question": "5. This question will provide a text box:"
    },
  {
    "question": "6. Another text box question:"
  },
  {
    "question": "7. This question will provide checkboxes so multiple items can be chosen:",
    "choices": {
      "0": "Option1",
      "1": "Option 2",
      "2": "Option 3",
      "3": "Option 4",
      "4": "Option 5",
      "5": "Option 6",
      "6": "Other"
    }
  },
  {
    "question": "8. This question will provide radio buttons:",
    "choices": {
      "0": "No",
      "1": "Yes"
    }
  },

Body:
You can change your jQuery code as below which is simply assigning the value if the element is textbox otherwise checked or not for radio and checkboxes.

var answers = new Object();
$(".response").each(function(){
   if($(this).is('[type="text"]') || $(this).is(':checked')) {
      answers[$(this).attr('name')] = $(this).val();
   }
});

The above code will replace the previous value when multiple checkboxes selected, so you can check if value exists for checkbox and append the value as comma (,) separated as below.

var answers = new Object();
$(".response").each(function(){
   if($(this).is('[type="text"]') || $(this).is(':checked')) {
      if(answers[$(this).attr('name')]) {
         answers[$(this).attr('name')] += ', ';
      } else {
         answers[$(this).attr('name')] = '';
      }

      answers[$(this).attr('name')] += $(this).val();
   }
});


问:
Google App Engine - Datastore get_or_insert key_name confusion
I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:

```<code>class Person(db.model)
    name = db.StringProperty(required=True)
</code>```

Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement look like?

Cheers,

Pete

答:
You can think of key_name like a primary key.  Look at the docs for get_or_insert(...), there is an example of what the back-end code looks like.

If name is a unique field, you might want to use that as the key name too.  Although I would suggest stripping white-space and normalizing case.

ContentLicense: CC BY-SA 2.5

Body:
I am confused by get_or_insert(..). What should I pass as the key_name? Consider the following example:

class Person(db.model)
    name = db.StringProperty(required=True)

Assume that no two people can have the same name. Say I want to get or insert a new Person with name Peter, what would my get_or_insert statement look like?

Cheers,

Pete


问:
Is there any way to get specific range of words?
```<code>time='2017-03-29 08:28:55'
</code>```

I hope this str make like below with something. such as split or something

```<code>new_time='2017-03-29 08:28'
</code>```

How would I do?

答:
Split the time on the colon then remove the last element with an array slicing operation. Then rejoin it back together with colons. All one line.</p>

```<code>new_time = ":".join(time.split(":")[:-1])
</code>```

Body:
time='2017-03-29 08:28:55'

I hope this str make like below with something. such as split or something

new_time='2017-03-29 08:28'

How would I do?

Body:
Split the time on the colon then remove the last element with an array slicing operation. Then rejoin it back together with colons. All one line.

new_time = ":".join(time.split(":")[:-1])


问:
How to solve # 7 in SQLZOO select names section
All:

I am learnig SQL now, but stuck at   #7   of

http://sqlzoo.net/wiki/SELECT_names

```<code>Bahamas has three a - who else?

Find the countries that have three or more a in the name
</code>```

Thanks

答:
```<code>SELECT name
FROM world
WHERE LENGTH(name) - LENGTH(REPLACE(lower(name),'a', '')) >= 3
</code>```

Body:
All:

I am learnig SQL now, but stuck at   #7   of

http://sqlzoo.net/wiki/SELECT_names

Bahamas has three a - who else?

Find the countries that have three or more a in the name

Thanks


问:
Reading in files stored in a dataframe in R
I have three directories that each contain about 2,000 files - the files have the same exact format but they are from 3 different sources. For each set of 3 files, I need to read in the data, merge them, and do some calculations and store the output.  I've already got my script running for a test case; now I'm trying to loop it over all the files (so, 2000 sets of 3 files of each).

I only want to read in 3 at a time, of course. I thought of this approach: create a dataframe of files where the columns represent the 3 types and the rows represent files. I do that here:

```<code>type1Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)
type2Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)
type3Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)

enter files.df <- cbind.data.frame(type1=type1Files,type2=type2Files,type3=type3Files)
</code>```

Now I need to read these files by column, looping over rows so only 3 files get opened in one loop.  The issue is that I cannot read in a file using read.table, and I think it's because of the format of the filename (read.table() is not being fed the right format).

```<code>head(files.df) #confirms that each file is not surrounded by double quotes as required by read.table
</code>```

My read.table statement:

```<code>type1.df <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)
</code>```

Where, for x, I have tried the following:

```<code>shQuote(files.df[1,"type1"])
dQuote(files.df[1,"type1"])

file.t <- files.df[1,"type1"]
paste0('"',file.t,'"')
</code>```

I've tried them all directly in read.table() as well as saving to objects and naming the object in read.table().  I even trying using cat() because I thought the escaped quotes might be the problem.  Nothing works. I either get "unexpected input" as the error, or the typical error: "Error in file(file, "rt") : cannot open the connection."  Furthermore, if I paste that exact filename that is printed in the error into my read.table() statement, it runs just fine.  So, after many hours, I am stumped.

Can this be done in this way?
Thank you all for your advice.

答:
Consider iterating directly from the lists without using an intermediary dataframe. With Map, you can pass each list of 2,000 dataframes for iterative cbind calls across all three types. Below cbind.data.frame prefixes columns with type1, type2, and type3.

```<code>bind_dfs <- function(x,y,z) {
  xdf <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  ydf <- read.table(y, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  zdf <- read.table(z, header=FALSE, sep="\t", stringsAsFactors=FALSE)

  cbind.data.frame(type1=xdf, type2=ydf, type3=zdf)
}

dfList <- Map(bind_dfs, type1Files, type2Files, type3Files)
</code>```

Also, to run your calculations, you can either extend the bind_dfs method

```<code>bind_dfs <- function(x,y,z) {
  xdf <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  ydf <- read.table(y, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  zdf <- read.table(z, header=FALSE, sep="\t", stringsAsFactors=FALSE)

  df <- cbind(xdf, ydf, zdf)
  df <- #... other calculations
  return(df)
}
</code>```

Or use another loop on dataframe list:

```<code>newdfList <- lapply(dfList, function(df){
   df <- # ... other calculations
   return(df)
})
</code>```

Body:
I have three directories that each contain about 2,000 files - the files have the same exact format but they are from 3 different sources. For each set of 3 files, I need to read in the data, merge them, and do some calculations and store the output.  I've already got my script running for a test case; now I'm trying to loop it over all the files (so, 2000 sets of 3 files of each).

I only want to read in 3 at a time, of course. I thought of this approach: create a dataframe of files where the columns represent the 3 types and the rows represent files. I do that here:

type1Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)
type2Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)
type3Files <- list.files(path="path_to_dir", pattern="*.tsv", full.names=TRUE, recursive=FALSE)

enter files.df <- cbind.data.frame(type1=type1Files,type2=type2Files,type3=type3Files)

Now I need to read these files by column, looping over rows so only 3 files get opened in one loop.  The issue is that I cannot read in a file using read.table, and I think it's because of the format of the filename (read.table() is not being fed the right format).

head(files.df) #confirms that each file is not surrounded by double quotes as required by read.table

My read.table statement:

type1.df <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)

Where, for x, I have tried the following:

shQuote(files.df[1,"type1"])
dQuote(files.df[1,"type1"])

file.t <- files.df[1,"type1"]
paste0('"',file.t,'"')

I've tried them all directly in read.table() as well as saving to objects and naming the object in read.table().  I even trying using cat() because I thought the escaped quotes might be the problem.  Nothing works. I either get "unexpected input" as the error, or the typical error: "Error in file(file, "rt") : cannot open the connection."  Furthermore, if I paste that exact filename that is printed in the error into my read.table() statement, it runs just fine.  So, after many hours, I am stumped.

Can this be done in this way?
Thank you all for your advice.

Body:
Consider iterating directly from the lists without using an intermediary dataframe. With Map, you can pass each list of 2,000 dataframes for iterative cbind calls across all three types. Below cbind.data.frame prefixes columns with type1, type2, and type3.

bind_dfs <- function(x,y,z) {
  xdf <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  ydf <- read.table(y, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  zdf <- read.table(z, header=FALSE, sep="\t", stringsAsFactors=FALSE)

  cbind.data.frame(type1=xdf, type2=ydf, type3=zdf)
}

dfList <- Map(bind_dfs, type1Files, type2Files, type3Files)

Also, to run your calculations, you can either extend the bind_dfs method

bind_dfs <- function(x,y,z) {
  xdf <- read.table(x, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  ydf <- read.table(y, header=FALSE, sep="\t", stringsAsFactors=FALSE)
  zdf <- read.table(z, header=FALSE, sep="\t", stringsAsFactors=FALSE)

  df <- cbind(xdf, ydf, zdf)
  df <- #... other calculations
  return(df)
}

Or use another loop on dataframe list:

newdfList <- lapply(dfList, function(df){
   df <- # ... other calculations
   return(df)
})


问:
How to route Matlab input to specific DOS cmd input?
I have a Matlab script that uses the dos command to open an exe.  This exe pauses awaiting user input.  For this project I need everything to be scripted and dynamic, so matlab has to be able to continue running its script, dynamically determine what to input to the running exe, and then input it.

So far, I have been able to get the exe to run in the background and let the matlab script continue by using dos('test.exe &'), but I cant get then get matlab to send inputs to the running exe.  I have tried batch files and I still run into the same issue, which is how do I automate the sending of inputs to the cmd line when the cmd line exe running is paused awaiting user input?

My best guess would be that I need to reroute the standard output of matlab to the standard input of a specific, already open instance of cmd, but I have no idea how to do that and have been unable to find anything so far on the internet.  Any insight would be greatly appreciated, thanks.

答:
There is a way. It's just not elegant.

When you call a program with &, its window appears in the foreground and has focus (at least on my system). So you can send it keyboard events from Matlab using the java.awt.Robot class.

If you need to automatize the conversion from characters to key presses, you probably need a big switch statement along these lines. The following example defines the events manually, which is only practical for small inputs.

```<code>robot = java.awt.Robot;
dos('copy con &'); % open MS-DOS Window that will just echo the input text
pause(1) % allow some time for the external program to start up
robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
  robot.keyPress(java.awt.event.KeyEvent.VK_H);
  robot.keyRelease(java.awt.event.KeyEvent.VK_H);
robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
robot.keyPress(java.awt.event.KeyEvent.VK_E);
robot.keyRelease(java.awt.event.KeyEvent.VK_E);
robot.keyPress(java.awt.event.KeyEvent.VK_L);
robot.keyRelease(java.awt.event.KeyEvent.VK_L);
robot.keyPress(java.awt.event.KeyEvent.VK_L);
robot.keyRelease(java.awt.event.KeyEvent.VK_L);
robot.keyPress(java.awt.event.KeyEvent.VK_O);
robot.keyRelease(java.awt.event.KeyEvent.VK_O);
robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
  robot.keyPress(java.awt.event.KeyEvent.VK_1);
  robot.keyRelease(java.awt.event.KeyEvent.VK_1);
robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);
</code>```

Here's an example run:

Body:
There is a way. It's just not elegant.

When you call a program with &, its window appears in the foreground and has focus (at least on my system). So you can send it keyboard events from Matlab using the java.awt.Robot class.

If you need to automatize the conversion from characters to key presses, you probably need a big switch statement along these lines. The following example defines the events manually, which is only practical for small inputs.

robot = java.awt.Robot;
dos('copy con &'); % open MS-DOS Window that will just echo the input text
pause(1) % allow some time for the external program to start up
robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
  robot.keyPress(java.awt.event.KeyEvent.VK_H);
  robot.keyRelease(java.awt.event.KeyEvent.VK_H);
robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
robot.keyPress(java.awt.event.KeyEvent.VK_E);
robot.keyRelease(java.awt.event.KeyEvent.VK_E);
robot.keyPress(java.awt.event.KeyEvent.VK_L);
robot.keyRelease(java.awt.event.KeyEvent.VK_L);
robot.keyPress(java.awt.event.KeyEvent.VK_L);
robot.keyRelease(java.awt.event.KeyEvent.VK_L);
robot.keyPress(java.awt.event.KeyEvent.VK_O);
robot.keyRelease(java.awt.event.KeyEvent.VK_O);
robot.keyPress(java.awt.event.KeyEvent.VK_SHIFT);
  robot.keyPress(java.awt.event.KeyEvent.VK_1);
  robot.keyRelease(java.awt.event.KeyEvent.VK_1);
robot.keyRelease(java.awt.event.KeyEvent.VK_SHIFT);
robot.keyPress(java.awt.event.KeyEvent.VK_ENTER);
robot.keyRelease(java.awt.event.KeyEvent.VK_ENTER);

Here's an example run:


问:
Mysql query - how to do this?
I have a table in mysql and I want to calculate the sum of column ss.

If (id and ss) repeats it will take only one.

See image:

enter image description here

thank you

答:
Try -

```<code>SELECT id,
       SUM( DISTINCT ss ) AS "Sum (ss)"
FROM tblData
GROUP BY id;
</code>```

Note : Without GROUP BY SUM() will try to add up all values of ss, even with the DISTINCT qualifier.  If you use GROUP BY but not DISTINCT then SUM() will add up all the values of ss for a particular value of id, even if they are repeated.  Using DISTINCT in conjunction with GROUP BY here removes any repeated combinations before SUM() goes to work.

Title: Mysql query - how to do this?

Body:
Try -

SELECT id,
       SUM( DISTINCT ss ) AS "Sum (ss)"
FROM tblData
GROUP BY id;

Note : Without GROUP BY SUM() will try to add up all values of ss, even with the DISTINCT qualifier.  If you use GROUP BY but not DISTINCT then SUM() will add up all the values of ss for a particular value of id, even if they are repeated.  Using DISTINCT in conjunction with GROUP BY here removes any repeated combinations before SUM() goes to work.


问:
Linq-to-Entities/Linq-to-SQL, Is One Data Polling Method More Efficient?
Are the following two examples different and if so, which is more efficient?

```<code>var user = (from u in db.Users where u.Id == userId select u).Single();
</code>```

and

```<code>var user = db.Users.Single(p => p.Id == userId);
</code>```

答: They will both wind up being identical (SQL and Efficiency wise).</p>

Body:
Are the following two examples different and if so, which is more efficient?

var user = (from u in db.Users where u.Id == userId select u).Single();

and

var user = db.Users.Single(p => p.Id == userId);


问:
Simple way to count number of specific elements in 2D array Python
I'm looking for a way to count how many instances of a specific character there are in a 2D array that I'm working with. For example, when I print the array out, it can look like this:

```<code>[['.', '.'], ['.', 'R']]
</code>```

Occasionally this array will be much larger, and I'm looking for a nice way to get the number of instances of something like 'R' for example, so that I can use it in a future if statement.

答:
A more condensed way would be:

```<code>def countChar(char, list):
    return sum([i.count(char) for i in list])
</code>```

This doesn't need to be a function, you could use it like:

```<code>test=[['x','r','a'],['r','t','u'],['r','r','R']]
sum([i.count('r') for i in test])
</code>```

Which returns 4.

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to count how many instances of a specific character there are in a 2D array that I'm working with. For example, when I print the array out, it can look like this:

[['.', '.'], ['.', 'R']]

Occasionally this array will be much larger, and I'm looking for a nice way to get the number of instances of something like 'R' for example, so that I can use it in a future if statement.

Body:
A more condensed way would be:

def countChar(char, list):
    return sum([i.count(char) for i in list])

This doesn't need to be a function, you could use it like:

test=[['x','r','a'],['r','t','u'],['r','r','R']]
sum([i.count('r') for i in test])

Which returns 4.


问:
X Path Python Error- 'list' object has no attribute 'xpath'
I am trying to do a Web-Crawling project, and I am keep on getting an error code called "'list' object has no attribute 'xpath'"/

This is the code so far:

```<code>import requests
from lxml import html
import pandas

url = "http://www.cnbc.com/"
response = requests.get(url)
doc = html.fromstring(response.text)

headlineNode = doc.xpath('//div[@class="headline"]')
len(headlineNode)

headlines = headlineNode.xpath('/a')
len(headlines)
</code>```

I want to extraxt the headlines from CNBC Home, but I am keep on getting an error saying

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-d9f54582133c> in <module>()
----> 1 headlines = headlineNode.xpath('/a')
      2 len(headlines)

AttributeError: 'list' object has no attribute 'xpath'
</code>```

Is there anyway to fix this?

答:
As your error says, you are trying to invoke .xpath(..) on a list

```<code>headlineNode = doc.xpath('//div[@class="headline"]')
len(headlineNode)
# ^ headlineNode is a list, I guess you know this.
</code>```

Now,

```<code>headlines = headlineNode.xpath('/a')
                       #^ and you are invoking .xpath on a list.
</code>```

Fix:

You need to say:

```<code>headlines = headlineNode[0].xpath('/a')
</code>```

Consider renaming your variable name to headlineNodes to avoid confusion, or say: headlineNode = doc.xpath(..)[0] (this might raise an Exception though).

Body:
I am trying to do a Web-Crawling project, and I am keep on getting an error code called "'list' object has no attribute 'xpath'"/

This is the code so far:

import requests
from lxml import html
import pandas

url = "http://www.cnbc.com/"
response = requests.get(url)
doc = html.fromstring(response.text)

headlineNode = doc.xpath('//div[@class="headline"]')
len(headlineNode)

headlines = headlineNode.xpath('/a')
len(headlines)

I want to extraxt the headlines from CNBC Home, but I am keep on getting an error saying

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-d9f54582133c> in <module>()
----> 1 headlines = headlineNode.xpath('/a')
      2 len(headlines)

AttributeError: 'list' object has no attribute 'xpath'

Is there anyway to fix this?

Body:
As your error says, you are trying to invoke .xpath(..) on a list

headlineNode = doc.xpath('//div[@class="headline"]')
len(headlineNode)
# ^ headlineNode is a list, I guess you know this.

Now,

headlines = headlineNode.xpath('/a')
                       #^ and you are invoking .xpath on a list.

Fix:

You need to say:

headlines = headlineNode[0].xpath('/a')

Consider renaming your variable name to headlineNodes to avoid confusion, or say: headlineNode = doc.xpath(..)[0] (this might raise an Exception though).


问:
How do I inline fields when marshalling JSON?
I have a type MonthYear defined like

```<code>type MonthYear time.Time

func (my *MonthYear) MarshalJSON() ([]byte, error) {
    t := time.Time(*my)

    return json.Marshal(&struct {
        Month int `json:"month"`
        Year  int `json:"year"`
    }{
        Month: int(t.Month()) - 1,
        Year:  t.Year(),
    })
}
</code>```

I'm including it a lot of different structs like

```<code>type Event struct {
    Name string `json:"name"`
    Date MonthYear
}

type Item struct {
    Category string `json:"category"`
    Date     MonthYear
}
</code>```

How do I inline the MonthYear type so that the resulting JSON does not have any embedded objects?

I want the result to look like { "name": "party", "month": 2, "year": 2017 } and { "category": "art", "month": 3, "year": 2016 } without having to write the MarshalJSON for each of the structs.

答:
I know this is not the answer you wish to receive, but until inline support is added to the encoding/json package, you may use the following workaround:

Make your MonthYear a struct, e.g.:

```<code>type MonthYear struct {
    t     time.Time
    Month int `json:"month"`
    Year  int `json:"year"`
}
</code>```

An optional, constructor function for easy creation:

```<code>func NewMonthYear(t time.Time) MonthYear {
    return MonthYear{
        t:     t,
        Month: int(t.Month()) - 1,
        Year:  t.Year(),
    }
}
</code>```

And use embedding (anonymous field) instead of a regular (named) field to get "flattened" / inlined in the JSON representation:

```<code>type Event struct {
    Name string `json:"name"`
    MonthYear
}

type Item struct {
    Category string `json:"category"`
    MonthYear
}
</code>```

As an extra, you'll be able to refer to fields directly like Event.Year or Event.Month which is nice.

Testing it:

```<code>evt := Event{Name: "party", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(evt), evt.Year)

itm := Item{Category: "Tool", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(itm))
</code>```

Output (try it on the Go Playground):

```<code>{"name":"party","month":10,"year":2009}
<nil> 2009
{"category":"Tool","month":10,"year":2009}
<nil>
</code>```

Note: The MonthYear.t time field does not play a role here (it is not marshaled either). You can remove it if the original time.Time is not needed.

Body:
I have a type MonthYear defined like

type MonthYear time.Time

func (my *MonthYear) MarshalJSON() ([]byte, error) {
    t := time.Time(*my)

    return json.Marshal(&struct {
        Month int `json:"month"`
        Year  int `json:"year"`
    }{
        Month: int(t.Month()) - 1,
        Year:  t.Year(),
    })
}

I'm including it a lot of different structs like

type Event struct {
    Name string `json:"name"`
    Date MonthYear
}

type Item struct {
    Category string `json:"category"`
    Date     MonthYear
}

How do I inline the MonthYear type so that the resulting JSON does not have any embedded objects?

I want the result to look like { "name": "party", "month": 2, "year": 2017 } and { "category": "art", "month": 3, "year": 2016 } without having to write the MarshalJSON for each of the structs.

Body:
I know this is not the answer you wish to receive, but until inline support is added to the encoding/json package, you may use the following workaround:

Make your MonthYear a struct, e.g.:

type MonthYear struct {
    t     time.Time
    Month int `json:"month"`
    Year  int `json:"year"`
}

An optional, constructor function for easy creation:

func NewMonthYear(t time.Time) MonthYear {
    return MonthYear{
        t:     t,
        Month: int(t.Month()) - 1,
        Year:  t.Year(),
    }
}

And use embedding (anonymous field) instead of a regular (named) field to get "flattened" / inlined in the JSON representation:

type Event struct {
    Name string `json:"name"`
    MonthYear
}

type Item struct {
    Category string `json:"category"`
    MonthYear
}

As an extra, you'll be able to refer to fields directly like Event.Year or Event.Month which is nice.

Testing it:

evt := Event{Name: "party", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(evt), evt.Year)

itm := Item{Category: "Tool", MonthYear: NewMonthYear(time.Now())}
fmt.Println(json.NewEncoder(os.Stdout).Encode(itm))

Output (try it on the Go Playground):

{"name":"party","month":10,"year":2009}
<nil> 2009
{"category":"Tool","month":10,"year":2009}
<nil>

Note: The MonthYear.t time field does not play a role here (it is not marshaled either). You can remove it if the original time.Time is not needed.


问:
Sublime will not run my code in chrome
When I try to run my html on chrome using sublime 2 I get this alert: Error trying to parse build system: Unexpected character, expected a comma or closing bracket in ~/Library/Application Support/Sublime Text 2/Packages/User/Chrome.sublime-build:2:17. What does this mean?</p>

答: Write your HTML code in Sublime, save as .html file and then right click said file and select "Open With" then select chrome.</p>

Title: Sublime will not run my code in chrome


问:
Can you run GUI applications in a Linux Docker container?
How can you run GUI applications in a Linux Docker container?

Are there any images that set up vncserver or something so that you can - for example - add an extra speedbump sandbox around say Firefox?

答:
This is not lightweight but is a nice solution that gives docker feature parity with full desktop virtualization. Both Xfce4 or IceWM for Ubuntu and CentOS work, and the noVNC option makes for an easy access through a browser.

https://github.com/ConSol/docker-headless-vnc-container

It runs noVNC as well as tigerVNC's vncserver. Then it calls startx for given Window Manager. In addition, libnss_wrapper.so is used to emulate password management for the users.


问:
Redirect user to login if not logged in ASP.NET web form using C#
I'm trying to develop  web app in ASP.NET web forms using C# and I've looked everywhere I could on the internet, but I found no solution to the problem. I've tried editing the default Web app template, to restrict a user from accessing any page if the user is not logged in. The default page should be the log in page and if the user clicks on anything else, he/she must be redirected to login page. Using MVC is easier, with just one bit of code on web.config but I've no idea what to do here in the web form

This is currently what my web.config contains.

```<code><?xml version="1.0"?>
<configuration>

  <location path="Manage.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>
</code>```

Where exactly I need to change?

答:
The shortest path to what you want is to use forms authentication with a login  URL, where you'd add something like this to your web.config:

```<code><authentication mode="Forms">
    <forms loginUrl="login.aspx" />
</authentication>
</code>```

The forms authentication mechanism will issue a cookie to a user when they log in.  If they attempt to access a page without the cookie, or with a cookie that has expired, the site will detect this via the FormsAuthenticationModule, which inspects each and every request that hits the site.  If the user isn't authenticated, it'll automatically issue a redirect to the loginUrl that you have specified (login.aspx in my example).

You can use a similar approach if you are using other authentication methods. In pretty much all cases there will be some mechanism that looks for a cookie indicating that the user has signed on.

Body:
I'm trying to develop  web app in ASP.NET web forms using C# and I've looked everywhere I could on the internet, but I found no solution to the problem. I've tried editing the default Web app template, to restrict a user from accessing any page if the user is not logged in. The default page should be the log in page and if the user clicks on anything else, he/she must be redirected to login page. Using MVC is easier, with just one bit of code on web.config but I've no idea what to do here in the web form

This is currently what my web.config contains.

<?xml version="1.0"?>
<configuration>

  <location path="Manage.aspx">
    <system.web>
      <authorization>
        <deny users="?"/>
      </authorization>
    </system.web>
  </location>

</configuration>

Where exactly I need to change?

Body:
The shortest path to what you want is to use forms authentication with a login  URL, where you'd add something like this to your web.config:

<authentication mode="Forms">
    <forms loginUrl="login.aspx" />
</authentication>

The forms authentication mechanism will issue a cookie to a user when they log in.  If they attempt to access a page without the cookie, or with a cookie that has expired, the site will detect this via the FormsAuthenticationModule, which inspects each and every request that hits the site.  If the user isn't authenticated, it'll automatically issue a redirect to the loginUrl that you have specified (login.aspx in my example).

You can use a similar approach if you are using other authentication methods. In pretty much all cases there will be some mechanism that looks for a cookie indicating that the user has signed on.


问:
What is the difference between Skip_build and test_without_building on Fastlane/Scanfile
What is the difference between Skip_build and test_without_building on Fastlane/Scanfile?

I would really execute my test cases without building everytime, I have several schemes that are executed on a shell script in a loop.   I don't want to build for every iteration.

Does anybody tried those parameters before?

答:
The skip_build parameter will omit the build command from the generated xcodebuild command that ultimately gets executed by scan. This means that if there is a built product in DerivedData, it will use it instead of recompiling your app. If there is no build product in DerivedData, it will rebuild the product.

The test_without_building parameter is the equivalent of the --test-without-building flag that you can pass to xcodebuild. This allows you to pass other flags to the command to point to the product under test.

Hope this helps!


问:
How to display the list from database using selected value in drop down
manage_bank

Hi everyone,

Can someone help me, How to display the bank name based on selected drop down, when we choose

for example:- 50 records

then it will display 50 records of the bank name from database.

When we logout the value still remain the same 50 records.

```<code><?php
// Includes the required files
include ("../ecompany/terms_includes.php");
?>
<?php
// Check user authority for this page
$ModuleName = "Manage Banks";
$ModuleAction = "view";
base_checkAuthority($ModuleName,$ModuleAction)
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php
include PATH_INC_HEAD;
?>
<?php
//get page number
$page = $_GET["page"];
$record = $_GET["record"];
//get Miscellaneous detail
$MiscellaneousDetail = base_getMiscellaneousDetail();
?>
<?php
if(!isset($page))
{
    $page = 1;
}
if(!isset($record))
{
    $record = $MiscellaneousDetail['base_mis_default'];
}

//go to reload page
if(isset($_POST['load']))
    {
        $page = 1;
        $record = $_POST['records_per_page'];
    }

//go to add profile page
if(isset($_POST['add']))
    {
        echo '<script type="text/javascript">' . "\n";
        echo 'window.location="../ecompany/add_bank.php";';
        echo '</script>';
    }

//go to home page
if(isset($_POST['cancel']))
    {
        echo '<script type="text/javascript">' . "\n";
        echo 'window.location="../terms_base/home.php";';
        echo '</script>';
    }
?>
</head>
<body>

<div class="container">
<?php
include PATH_INC_HEADER;
?>
<div class="main_body1">

<div id="update_category"></div>

<div style="width:800px; margin:auto">

<?php
include PATH_INC_DESC;
?>
<div style="clear:both"></div>
<form name="bank_list_form" id="bank_list_form" method="post" action="">
<div style="width:800px; margin:auto; text-align:left">
 <select name="records_per_page" id="records_per_page"  >
 <option value="<?php echo $record; ?>">Default Records/Page :</option>
 <option value="1" title="1" >1</option>
 <option value="3" title="3" >3</option>
 <option value="5" title="5" >5</option>
 <option value="10" title="10" >10</option>
 <option value="20" title="20" >20</option>
 <option value="30" title="30" >30</option>
 <option value="50" title="50" >50</option>
 <option value="100" title="100" >100</option>
 <option value="200" title="200" >200</option>
 <option value="500" title="500" >500</option>
 <option value="1000" title="1000" >1000</option>
 </select>
  <input type="" size="4" style="width:25px" name="record"

  id="record"value="<?php echo $record; ?>" readonly="readonly" />
  <div id="searchbutton">
  <input type="submit" id="load" name="load" value="Refresh">
  </div>
  </div>
 <table cellspacing="1" class="tablesorter">
 <thead>
    <tr>
        <th></th>
        <th>Code</th>
        <th>Name</th>
        <th>Description</th>
        <th>Remark</th>
        <th></th>
        <th></th>
    </tr>
 </thead>
 <tbody>
   <?php ecoy_listBank($page, $record) ?>
 </tbody>
   <tr>
        <td align="center" colspan="8"><input type="submit" id="add"

  name="add" value="Add Bank" /><input type="submit" id="cancel"
  name="cancel" value="Cancel" /></td>
   </tr>
  </tfoot>
  </table>
  </form>
  <br />
  </div>

    <div class="clearboth"></div>
  </div>
  <?php
  include PATH_INC_FOOTER;
  ?>

  </div>

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

Much appreciate, Thanks.

答:
The title of your question is misleading. But if I got it right you actually succeed in querying your data correctly and refreshing the number of records with your refresh button.

You real question is how to persist the default value of the dropdown after a logout.

By mentioning your logout feature I assume you have users and a user table in your database.

From here you have two solutions I can think of:

1. Save the users preferences like the default value of your dropdown within your users table or create a separated table dedicated for this purpose.

2. Store users preferences in cookies

Body:
manage_bank

Hi everyone,

Can someone help me, How to display the bank name based on selected drop down, when we choose

for example:- 50 records

then it will display 50 records of the bank name from database.

When we logout the value still remain the same 50 records.

<?php
// Includes the required files
include ("../ecompany/terms_includes.php");
?>
<?php
// Check user authority for this page
$ModuleName = "Manage Banks";
$ModuleAction = "view";
base_checkAuthority($ModuleName,$ModuleAction)
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php
include PATH_INC_HEAD;
?>
<?php
//get page number
$page = $_GET["page"];
$record = $_GET["record"];
//get Miscellaneous detail
$MiscellaneousDetail = base_getMiscellaneousDetail();
?>
<?php
if(!isset($page))
{
    $page = 1;
}
if(!isset($record))
{
    $record = $MiscellaneousDetail['base_mis_default'];
}

//go to reload page
if(isset($_POST['load']))
    {
        $page = 1;
        $record = $_POST['records_per_page'];
    }

//go to add profile page
if(isset($_POST['add']))
    {
        echo '';
    }

//go to home page
if(isset($_POST['cancel']))
    {
        echo '';
    }
?>

<?php
include PATH_INC_HEADER;
?>

<?php
include PATH_INC_DESC;
?>

<form name="bank_list_form" id="bank_list_form" method="post" action="">

 <select name="records_per_page" id="records_per_page"  >
 <option value="<?php echo $record; ?>">Default Records/Page :</option>
 <option value="1" title="1" >1</option>
 <option value="3" title="3" >3</option>
 <option value="5" title="5" >5</option>
 <option value="10" title="10" >10</option>
 <option value="20" title="20" >20</option>
 <option value="30" title="30" >30</option>
 <option value="50" title="50" >50</option>
 <option value="100" title="100" >100</option>
 <option value="200" title="200" >200</option>
 <option value="500" title="500" >500</option>
 <option value="1000" title="1000" >1000</option>
 </select>
  <input type="" size="4" style="width:25px" name="record"

  id="record"value="<?php echo $record; ?>" readonly="readonly" />

  <input type="submit" id="load" name="load" value="Refresh">

        Code
        Name
        Description
        Remark

   <?php ecoy_listBank($page, $record) ?>

        <input type="submit" id="add"

  name="add" value="Add Bank" /><input type="submit" id="cancel"
  name="cancel" value="Cancel" />

  </form>

  <?php
  include PATH_INC_FOOTER;
  ?>

Much appreciate, Thanks.


问:
MVC project complaining it is unable to find Nhibernate.dll version 2.1.0.4000
In my MVC project, I am trying to use the latest Fluent Nhibernate, and NHibernate.linq.  I am using the Nhibernate.dll that came with the latest Fluent Nhibernate released build.  However, I have only been able to find NHibernate.linq 1.0.

When attempting to run I get the error:

```<code>Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's
manifest definition does not match the assembly reference. (Exception from HRESULT:
0x80131040)
</code>```

I see at SourceForge in the NHibernate project, they have a NHibernate.Linq 2.1.2 version under the NHibernate 2.1.2 project, but if you download this zip, it is empty.

My thoughts is that Linq is referencing the older NHibernate.dll, but how can I get the NHibernate.linq.dll 2.1.2 version?

There is another question with this same error, and I tried all their suggestions with making sure that all the other NHibernate.dll's are included.  I didn't rebuild the NHibernate.linq project with the same NHibernate.dll that Fluent uses, since I was hoping to get a newer version of NHibernate.linq.

答:
As James wrote, you should download the 2.1.2 zip and extract it with 7-Zip. Version number should be 1.1.0.1001.

However... NHibernate 3.0 is about to be released. It contains an integrated Linq provider which is much more complete, powerful and extensible.

I wouldn't use the old provider (which is not completely compatible with the new one) in a new project.

Body:
In my MVC project, I am trying to use the latest Fluent Nhibernate, and NHibernate.linq.  I am using the Nhibernate.dll that came with the latest Fluent Nhibernate released build.  However, I have only been able to find NHibernate.linq 1.0.

When attempting to run I get the error:

Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral,
PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's
manifest definition does not match the assembly reference. (Exception from HRESULT:
0x80131040)

I see at SourceForge in the NHibernate project, they have a NHibernate.Linq 2.1.2 version under the NHibernate 2.1.2 project, but if you download this zip, it is empty.

My thoughts is that Linq is referencing the older NHibernate.dll, but how can I get the NHibernate.linq.dll 2.1.2 version?

There is another question with this same error, and I tried all their suggestions with making sure that all the other NHibernate.dll's are included.  I didn't rebuild the NHibernate.linq project with the same NHibernate.dll that Fluent uses, since I was hoping to get a newer version of NHibernate.linq.


问:
Techniques other than RegEx to discover 'intent' in sentences
I'm embarking on a project for a non-profit organization to help process and classify 1000's of reports annually from their field workers / contractors the world over. I'm relatively new to NLP and as such wanted to seek the group's guidance on the approach to solve our problem.

I'll highlight the current process, and our challenges and would love your help on the best way to solve our problem.

Current process: Field officers submit reports from locally run projects in the form of best practices. These reports are then processed by a full-time team of curators who (i) ensure they adhere to a best-practice template and (ii) edit the documents to improve language/style/grammar.

Challenge: As the number of field workers increased the volume of reports being generated has grown and our editors are now becoming the bottle-neck.

Solution: We would like to automate the 1st step of our process i.e., checking the document for compliance to the organizational best practice template

Basically, we need to ensure every report has 3 components namely:
1. States its purpose: What topic / problem does this best practice address?
2. Identifies Audience: Who is this for?
3. Highlights Relevance: What can the reader do after reading it?

Here's an example of a good report submission.

"This document introduces techniques for successfully applying best practices across developing countries. This study is intended to help low-income farmers identify a set of best practices for pricing agricultural products in places where there is no price transparency. By implementing these processes, farmers will be able to get better prices for their produce and raise their household incomes."

As of now, our approach has been to use RegEx and check for keywords. i.e., to check for compliance we use the following logic:
1 To check "states purpose" =  we do a regex to match 'purpose', 'intent'
2 To check "identifies audience" = we do a regex to match with 'identifies', 'is for'
3 To check "highlights relevance" = we do a regex to match with 'able to', 'allows', 'enables'

The current approach of RegEx seems very primitive and limited so I wanted to ask the community if there is a better way to solving this problem using something like NLTK, CoreNLP.

Thanks in advance.

答:
I've been trying to do something very similar with clinical trials, where most of the data is again written in natural language.

If you do not care about past data, and have control over what the field officers write, maybe you can have them provide these 3 extra fields in their reports, and you would be done.

Otherwise; CoreNLP and OpenNLP, the libraries that I'm most familiar with, have some tools that can help you with part of the task. For example; if your Regex pattern matches a word that starts with the prefix "inten", the actual word could be "intention", "intended", "intent", "intentionally" etc., and you wouldn't necessarily know if the word is a verb, a noun, an adjective or an adverb. POS taggers and the parsers in these libraries would be able to tell you the type (POS) of the word and maybe you only care about the verbs that start with "inten", or more strictly, the verbs spoken by the 3rd person singular.

CoreNLP has another tool called OpenIE, which attempts to extract relations in a sentence. For example, given the following sentence

Born in a small town, she took the midnight train going anywhere

CoreNLP can extract the triple

she, took, midnight train

Combined with the POS tagger for example; you would also know that "she" is a personal pronoun and "took" is a past tense verb.

These libraries can accomplish many other tasks such as tokenization, sentence splitting, and named entity recognition and it would be up to you to combine all of these tools with your domain knowledge and creativity to come up with a solution that works for your case.


问:
Visual C++ get string from Cedit
This is probably a pretty basic question, but I can't seem to get it.  I am working on a visualC++ project and I basically want to get a string from a GUI and then use that as a filename.  I have written the following thus far, where IDC_FILE_NAME is the ID of the edit control box but I'm not sure if that is even the way to accomplish this.</p>

```<code>m_pFileName = (CEdit*)GetDlgItem( IDC_FILE_NAME );

CString fName =_T(" ");
GetDlgItemTextA(IDC_FILE_NAME, fName);
</code>```

答:
This has been tested with VS2015:</p>

```<code>//
// Get string from CEdit m_ceDate;
// where
// DDX_Control(pDX, IDC_EDIT_DATE, m_ceDate);

char cdateBuf[128];
UINT nCountOfCharacters = GetDlgItemText(IDC_EDIT_DATE, cdateBuf, 16);
CString csDate = cdateBuf;
</code>```

Title: Visual C++ get string from Cedit

Body:
This is probably a pretty basic question, but I can't seem to get it.  I am working on a visualC++ project and I basically want to get a string from a GUI and then use that as a filename.  I have written the following thus far, where IDC_FILE_NAME is the ID of the edit control box but I'm not sure if that is even the way to accomplish this.

m_pFileName = (CEdit*)GetDlgItem( IDC_FILE_NAME );

CString fName =_T(" ");
GetDlgItemTextA(IDC_FILE_NAME, fName);

Body:
This has been tested with VS2015:

//
// Get string from CEdit m_ceDate;
// where
// DDX_Control(pDX, IDC_EDIT_DATE, m_ceDate);

char cdateBuf[128];
UINT nCountOfCharacters = GetDlgItemText(IDC_EDIT_DATE, cdateBuf, 16);
CString csDate = cdateBuf;


问:
Soot android-jars error
I am trying to analyze android apk's using Soot. However, I get an an error saying invalid option: android-jars along with a CompilationDeathException: Option parse error. Is this due to the wrong path of android jars or soot(2.5.0)?

To launch soot, I am using the script found here: http://www.abartel.net/dexpler/

答: Yes. The command-line option -android-jars was not included in soot-2.5. Use the latest nightly version instead.</p>

Title: Soot android-jars error


问:
Tkinter checkbox with command attached
I would like some help with something simple: A tkinter checkbox that does have a command attached <--this simple example is always mentioned but never shown in tutorials on the web.

I have:

```<code>from tkinter import *

def activateMotors(active):
    scale.config(state=active)

root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,text="Motors ON(checked)/OFF(unchecked)", variable=motorsOn, command=activateMotors)
motorsCheck.pack()
scale = Scale(root, from_=0, to=180,
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()
</code>```

This does not work. Sure the window comes up but when I click on the checkbox I get "TypeError activateMotors() missing 1 required positional argument 'active' "

Can anybody correct this so that we can have one operational checkbox example with commands?

答:
The callback must not have arguments, we must use the get() function of IntVar

```<code>from tkinter import *

def activateMotors():
    if motorsOn.get() == 1:
        scale.config(state=ACTIVE)
    elif motorsOn.get() == 0:
        scale.config(state=DISABLED)

root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,
    text="Motors ON(checked)/OFF(unchecked)",
    variable=motorsOn,
    command=activateMotors)
motorsCheck.pack()

scale = Scale(root, from_=0, to=180,
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()
</code>```

Title: Tkinter checkbox with command attached

Body:
I would like some help with something simple: A tkinter checkbox that does have a command attached <--this simple example is always mentioned but never shown in tutorials on the web.

I have:

from tkinter import *

def activateMotors(active):
    scale.config(state=active)

root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,text="Motors ON(checked)/OFF(unchecked)", variable=motorsOn, command=activateMotors)
motorsCheck.pack()
scale = Scale(root, from_=0, to=180,
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()

This does not work. Sure the window comes up but when I click on the checkbox I get "TypeError activateMotors() missing 1 required positional argument 'active' "

Can anybody correct this so that we can have one operational checkbox example with commands?

Body:
The callback must not have arguments, we must use the get() function of IntVar

from tkinter import *

def activateMotors():
    if motorsOn.get() == 1:
        scale.config(state=ACTIVE)
    elif motorsOn.get() == 0:
        scale.config(state=DISABLED)

root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,
    text="Motors ON(checked)/OFF(unchecked)",
    variable=motorsOn,
    command=activateMotors)
motorsCheck.pack()

scale = Scale(root, from_=0, to=180,
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()


问:
Data update error with SharePoint 2010 and MS Access 2010
I've encountered a strange error when attempting to update a SharePoint 2010 list that I have linked to via Microsoft Access 2010.

Error: Data cannot be inserted because there is no matching record.

This occurs in 2 scenarios:

I attempt to run any UPDATE query against the list in MS Access

I attempt to update a record from the list if the list view is filtered

The second item might need an explanation. If I simply open the linked list in Access, scroll down to a record I want to edit, and edit it, it works. If I filter that view first (for example, showing only records with a checkbox field checked), I cannot edit any records and get the error.

This only happens in one particular environment; others work fine with either approach. I've checked permissions (I have full control of the list, I am a Site Collection Administrator, etc.). I have tried linking to the list in various ways: from within Access, from the "Open with Access" ribbon button in SharePoint. I've deleted and recreated the Access DB file... no luck.

Also, Google has no knowledge of this particular error: searches for the exact error text come up with 0 results.

Any idea what to check? Running SQL-style queries against this SharePoint list is the only viable option for maintaining it.

答: I had a similar issue, linking to a Sharepoint List (List1) that I'd just exported from Access to Sharepoint. When I linked to List1, I also found that 'UserInfo' was added as a linked list. I deleted that UserInfo link believing it to be unnecessary, but then found that I generated validation errors when trying to update List1 with an append query. Restoring the link to UserInfo fixed those errors; presumably the 'Created By' and 'Modified By' columns added by Sharepoint to List1 require the Lookup to UserInfo. The answers above pointed me in the right direction, so thank you.</p>


问:
Selenium 3.3.1: NoDefClassFound (com.google.common.base.Function)
I have the strangest problem, with Selenium 3.3.1, when trying to start a ChromeDriver (or FirefoxDriver), with the simplest code:

Edit: added the full class

```<code>import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class App {
    public static void main(String[] args) {
        // testCrawl();
        seleniumGetDoc();
    }

    public static void seleniumGetDoc() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver(); //here something goes terribly wrong
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("https://google.com/");
        String htmlContent = driver.getPageSource();
        System.out.println(driver.getCurrentUrl());
    }
}
</code>```

With the following dependencies in my pom:

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-server -->
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.3.1</version>
    </dependency>
</code>```

I obtain the following output:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
    at my.package.MyClass.seleniumGetDoc(CrawlerMain.java:28)
    at  my.package.MyClass.main(CrawlerMain.java:22)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code>```

Nonetheless when downgrading my selenium versions, it works properly with the following dependencies:

```<code>   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.45.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.0.1</version>
    </dependency>
</code>```

Does anyone knows why apparently in the 3.3.1 version some guava library is missing? Or have I missed something in setting up Selenium?

I have looked at several posts on StackOverflow, however the problem is either linked to the missing installation of external jars (which maven should handle) or to the dependency missing of selenium-server.

Edit my list of dependencies:

```<code><dependencies>
    <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.10.2</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</code>```

Also when running mvn dependency:tree, maven indicates that only selenium-java depends on com.google.guava:guava:jar:21.0:compile

Edit adding my dependency tree:

```<code>[INFO] org.linkedin.crawler:main:jar:0.0.1-SNAPSHOT
[INFO] +- org.jsoup:jsoup:jar:1.10.2:compile
[INFO] +- org.seleniumhq.selenium:selenium-java:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-chrome-driver:jar:3.3.1:compile
[INFO] |  |  \- org.seleniumhq.selenium:selenium-remote-driver:jar:3.3.1:compile
[INFO] |  |     +- org.seleniumhq.selenium:selenium-api:jar:3.3.1:compile
[INFO] |  |     +- cglib:cglib-nodep:jar:3.2.4:compile
[INFO] |  |     +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO] |  |     +- com.google.code.gson:gson:jar:2.8.0:compile
[INFO] |  |     +- com.google.guava:guava:jar:21.0:compile
[INFO] |  |     +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] |  |     |  \- org.apache.httpcomponents:httpcore:jar:4.4.4:compile
[INFO] |  |     \- net.java.dev.jna:jna-platform:jar:4.1.0:compile
[INFO] |  |        \- net.java.dev.jna:jna:jar:4.1.0:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-edge-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-ie-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-opera-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-safari-driver:jar:3.3.1:compile
[INFO] |  +- com.codeborne:phantomjsdriver:jar:1.4.0:compile
[INFO] |  \- org.seleniumhq.selenium:htmlunit-driver:jar:2.24:compile
[INFO] |     +- org.seleniumhq.selenium:selenium-support:jar:3.3.1:compile (version selected from constraint [2.53.0,4.0.0))
[INFO] |     |  \- org.hamcrest:hamcrest-library:jar:1.3:compile
[INFO] |     \- net.sourceforge.htmlunit:htmlunit:jar:2.24:compile
[INFO] |        +- xalan:xalan:jar:2.7.2:compile
[INFO] |        |  \- xalan:serializer:jar:2.7.2:compile
[INFO] |        +- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] |        +- org.apache.httpcomponents:httpmime:jar:4.5.2:compile
[INFO] |        +- commons-codec:commons-codec:jar:1.10:compile
[INFO] |        +- net.sourceforge.htmlunit:htmlunit-core-js:jar:2.23:compile
[INFO] |        +- net.sourceforge.htmlunit:neko-htmlunit:jar:2.24:compile
[INFO] |        |  \- xerces:xercesImpl:jar:2.11.0:compile
[INFO] |        |     \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |        +- net.sourceforge.cssparser:cssparser:jar:0.9.21:compile
[INFO] |        |  \- org.w3c.css:sac:jar:1.3:compile
[INFO] |        +- commons-io:commons-io:jar:2.5:compile
[INFO] |        +- commons-logging:commons-logging:jar:1.2:compile
[INFO] |        \- org.eclipse.jetty.websocket:websocket-client:jar:9.2.20.v20161216:compile
[INFO] |           +- org.eclipse.jetty:jetty-util:jar:9.2.20.v20161216:compile
[INFO] |           +- org.eclipse.jetty:jetty-io:jar:9.2.20.v20161216:compile
[INFO] |           \- org.eclipse.jetty.websocket:websocket-common:jar:9.2.20.v20161216:compile
[INFO] |              \- org.eclipse.jetty.websocket:websocket-api:jar:9.2.20.v20161216:compile
[INFO] +- org.seleniumhq.selenium:selenium-server:jar:3.3.1:compile
[INFO] |  +- com.beust:jcommander:jar:1.48:compile
[INFO] |  +- net.jcip:jcip-annotations:jar:1.0:compile
[INFO] |  +- org.seleniumhq.selenium:jetty-repacked:jar:9.4.1.v20170120:compile
[INFO] |  |  \- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.15:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.8:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.8:compile
[INFO] \- junit:junit:jar:4.12:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:compile
</code>```

Update: It works with selenium-server with version 3.3.1 and selenium-java version 3.0.1, from selenium-java version >3.1.x it starts breaking with the same afore mentioned error

Edit Adding my full pom:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.main.groupid</groupId>
    <artifactId>main</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>main</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib/</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>my.main.Class</mainClass>
                        </manifest>
                    </archive>
                    <excludes>
                        <exclude>**/*log4j*</exclude>
                    </excludes>
                </configuration>
            </plugin>

        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

答:
I was having similar issues, and narrowed it down to including both Selenium 3.3.1 Standalone and HTMLUnit-driver-standalone 2.21.  Turns out I didn't need the HTMLUnit jar at all.  It's already included in 3.3.1 dependencies.  (If I remember right the last version did not include HTMLUnit which is why I had added it separately before... this may explain the > 3.01 part.)

Now, I don't use the Selenium-java part... just the standalone server, but it looks like you have 2 HTMLUnit versions... 2.24 and 2.23 in your dep list so it could be a similar issue.

Body:
I have the strangest problem, with Selenium 3.3.1, when trying to start a ChromeDriver (or FirefoxDriver), with the simplest code:

Edit: added the full class

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class App {
    public static void main(String[] args) {
        // testCrawl();
        seleniumGetDoc();
    }

    public static void seleniumGetDoc() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver(); //here something goes terribly wrong
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.get("https://google.com/");
        String htmlContent = driver.getPageSource();
        System.out.println(driver.getCurrentUrl());
    }
}

With the following dependencies in my pom:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.3.1</version>
    </dependency>

I obtain the following output:

Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
    at my.package.MyClass.seleniumGetDoc(CrawlerMain.java:28)
    at  my.package.MyClass.main(CrawlerMain.java:22)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Nonetheless when downgrading my selenium versions, it works properly with the following dependencies:

   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.45.0</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.0.1</version>
    </dependency>

Does anyone knows why apparently in the 3.3.1 version some guava library is missing? Or have I missed something in setting up Selenium?

I have looked at several posts on StackOverflow, however the problem is either linked to the missing installation of external jars (which maven should handle) or to the dependency missing of selenium-server.

Edit my list of dependencies:

<dependencies>

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.10.2</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.3.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.8</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Also when running mvn dependency:tree, maven indicates that only selenium-java depends on com.google.guava:guava:jar:21.0:compile

Edit adding my dependency tree:

[INFO] org.linkedin.crawler:main:jar:0.0.1-SNAPSHOT
[INFO] +- org.jsoup:jsoup:jar:1.10.2:compile
[INFO] +- org.seleniumhq.selenium:selenium-java:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-chrome-driver:jar:3.3.1:compile
[INFO] |  |  \- org.seleniumhq.selenium:selenium-remote-driver:jar:3.3.1:compile
[INFO] |  |     +- org.seleniumhq.selenium:selenium-api:jar:3.3.1:compile
[INFO] |  |     +- cglib:cglib-nodep:jar:3.2.4:compile
[INFO] |  |     +- org.apache.commons:commons-exec:jar:1.3:compile
[INFO] |  |     +- com.google.code.gson:gson:jar:2.8.0:compile
[INFO] |  |     +- com.google.guava:guava:jar:21.0:compile
[INFO] |  |     +- org.apache.httpcomponents:httpclient:jar:4.5.2:compile
[INFO] |  |     |  \- org.apache.httpcomponents:httpcore:jar:4.4.4:compile
[INFO] |  |     \- net.java.dev.jna:jna-platform:jar:4.1.0:compile
[INFO] |  |        \- net.java.dev.jna:jna:jar:4.1.0:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-edge-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-firefox-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-ie-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-opera-driver:jar:3.3.1:compile
[INFO] |  +- org.seleniumhq.selenium:selenium-safari-driver:jar:3.3.1:compile
[INFO] |  +- com.codeborne:phantomjsdriver:jar:1.4.0:compile
[INFO] |  \- org.seleniumhq.selenium:htmlunit-driver:jar:2.24:compile
[INFO] |     +- org.seleniumhq.selenium:selenium-support:jar:3.3.1:compile (version selected from constraint [2.53.0,4.0.0))
[INFO] |     |  \- org.hamcrest:hamcrest-library:jar:1.3:compile
[INFO] |     \- net.sourceforge.htmlunit:htmlunit:jar:2.24:compile
[INFO] |        +- xalan:xalan:jar:2.7.2:compile
[INFO] |        |  \- xalan:serializer:jar:2.7.2:compile
[INFO] |        +- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] |        +- org.apache.httpcomponents:httpmime:jar:4.5.2:compile
[INFO] |        +- commons-codec:commons-codec:jar:1.10:compile
[INFO] |        +- net.sourceforge.htmlunit:htmlunit-core-js:jar:2.23:compile
[INFO] |        +- net.sourceforge.htmlunit:neko-htmlunit:jar:2.24:compile
[INFO] |        |  \- xerces:xercesImpl:jar:2.11.0:compile
[INFO] |        |     \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |        +- net.sourceforge.cssparser:cssparser:jar:0.9.21:compile
[INFO] |        |  \- org.w3c.css:sac:jar:1.3:compile
[INFO] |        +- commons-io:commons-io:jar:2.5:compile
[INFO] |        +- commons-logging:commons-logging:jar:1.2:compile
[INFO] |        \- org.eclipse.jetty.websocket:websocket-client:jar:9.2.20.v20161216:compile
[INFO] |           +- org.eclipse.jetty:jetty-util:jar:9.2.20.v20161216:compile
[INFO] |           +- org.eclipse.jetty:jetty-io:jar:9.2.20.v20161216:compile
[INFO] |           \- org.eclipse.jetty.websocket:websocket-common:jar:9.2.20.v20161216:compile
[INFO] |              \- org.eclipse.jetty.websocket:websocket-api:jar:9.2.20.v20161216:compile
[INFO] +- org.seleniumhq.selenium:selenium-server:jar:3.3.1:compile
[INFO] |  +- com.beust:jcommander:jar:1.48:compile
[INFO] |  +- net.jcip:jcip-annotations:jar:1.0:compile
[INFO] |  +- org.seleniumhq.selenium:jetty-repacked:jar:9.4.1.v20170120:compile
[INFO] |  |  \- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.15:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.8:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.8:compile
[INFO] \- junit:junit:jar:4.12:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:compile

Update: It works with selenium-server with version 3.3.1 and selenium-java version 3.0.1, from selenium-java version >3.1.x it starts breaking with the same afore mentioned error

Edit Adding my full pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.main.groupid</groupId>
    <artifactId>main</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>main</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib/</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>false</overWriteSnapshots>
                            <overWriteIfNewer>true</overWriteIfNewer>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>my.main.Class</mainClass>
                        </manifest>
                    </archive>
                    <excludes>
                        <exclude>**/*log4j*</exclude>
                    </excludes>
                </configuration>
            </plugin>

        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-server</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


问:
How to get text from CEdit control
I'm a new guy with ATL. So forgive me to ask this question.

Problem description:
One CEdit control is added into a ATL dialog class. It's attached in the dialog initialize function.

```<code>//Define the edit control
ATLControls::CEdit  m_txtInput;

//In the OnInitDialog function
m_txtInput.Attach(GetDlgItem(IDC_INPUT_LINE));

m_txtInput.SetWindowText(_T("New directory"));

//In the public memeber function of the dialog GetInput()
//I have tried three kinds of method to get the text. But all of them are throw an
//assert exception, IsWindow() failed.
//1.
GetDlgItemText(IDC_INPUT_LINE, input);
//2.
ZeroMemory(m_lptstrInput, MAX_PATH);
m_txtInput.GetLine(0, m_lptstrInput, MAX_PATH);
//3.
BSTR input;
m_txtInput.GetWindowText(input);
</code>```

Here is a topic about how to get text from CEdit but it is not working.

Why the CEdit control could be set text with the function SetWindowText() but can't get the text by the function GetWindowText()? It's really confuse me. Thanks a lot if someone could explain it for me.

答:
This has been tested with MFC & VS2015:</p>

```<code>//
// Get char string/CString from CEdit m_ceDate;
// where
// DDX_Control(pDX, IDC_EDIT_DATE, m_ceDate);

char cdateBuf[128];
UINT nCountOfCharacters = GetDlgItemText(IDC_EDIT_DATE, cdateBuf, 16);
CString csDate = cdateBuf;
</code>```

Title: How to get text from CEdit control

Body:
I'm a new guy with ATL. So forgive me to ask this question.

Problem description:
One CEdit control is added into a ATL dialog class. It's attached in the dialog initialize function.

//Define the edit control
ATLControls::CEdit  m_txtInput;

//In the OnInitDialog function
m_txtInput.Attach(GetDlgItem(IDC_INPUT_LINE));

m_txtInput.SetWindowText(_T("New directory"));

//In the public memeber function of the dialog GetInput()
//I have tried three kinds of method to get the text. But all of them are throw an
//assert exception, IsWindow() failed.
//1.
GetDlgItemText(IDC_INPUT_LINE, input);
//2.
ZeroMemory(m_lptstrInput, MAX_PATH);
m_txtInput.GetLine(0, m_lptstrInput, MAX_PATH);
//3.
BSTR input;
m_txtInput.GetWindowText(input);

Here is a topic about how to get text from CEdit but it is not working.

Why the CEdit control could be set text with the function SetWindowText() but can't get the text by the function GetWindowText()? It's really confuse me. Thanks a lot if someone could explain it for me.

Body:
This has been tested with MFC & VS2015:

//
// Get char string/CString from CEdit m_ceDate;
// where
// DDX_Control(pDX, IDC_EDIT_DATE, m_ceDate);

char cdateBuf[128];
UINT nCountOfCharacters = GetDlgItemText(IDC_EDIT_DATE, cdateBuf, 16);
CString csDate = cdateBuf;