问:
Linux script for probing ssh connection in a loop and start log command after connect
I have a host machine that gets rebooted or reconnected quite a few times.
I want to have a script running on my dev machine that continuously tries to log into that machine and if successful runs a specific command (tailing the log data).
Edit: To clarify, the connection needs to stay open. The log command keeps tailing until I stop it manually.

What I have so far

```<code>#!/bin/bash

IP=192.168.178.1

if (("$#" >= 1))
then
  IP=$1
fi

LOOP=1

trap 'echo "stopping"; LOOP=0' INT

while (( $LOOP==1 ))
do
if ping -c1 $IP
then
  echo "Host $IP reached"
  sshpass -p 'password' ssh -o ConnectTimeout=10 -q user@$IP '<command would go here>'
else
  echo "Host $IP unreachable"
fi
sleep 1

done
</code>```

The LOOP flag is not really used. The script is ended via CTRL-C.
Now this works if I do NOT add a command to be executed after the ssh and instead start the log output manually. On a disconnect the script keeps probing the connection and logs back in once the host is available again.
Also when I disconnect from the host (CTRL-D) the script will log right back into the host if CTRL-C is not pressed fast enough.
When I add a command to be executed after ssh the loop is broken. So pressing (CTRL-C) does not only stop the log but also disconnects and ends the script on the dev machine.

I guess I have to spawn another shell somewhere or something like that?

1) I want the script to keep probing, log in and run a command completely automatically and fall back to probing when the connection breaks.
2) I want to be able to stop the log on the host (CTRL-C) and thereby fall back to a logged in ssh connection to use it manually.

How do I fix this?

答:
Maybe best approach on "fixing" would be fixing requirements.

The problematic part is number "2)".
The problem is from how SIGINT works.

When triggered, it is sent to the current control group related to your terminal. Mostly this is the shell and any process started from there. With more modern shells (you seem to use bash), the shell manages control groups such that programs started in the background are disconnected (by having been assigned a different control group).

In your case the ssh is started in the foreground (from a script executed in the foreground), so it will receive the interrupt, forward it to the remote and terminate as soon as the remote end terminated. As by that time the script shell has processed its signal handler (specified by trap) it is going to exit the loop and terminate itself.

So, as you can see, you have overloaded CTRL-C to mean two things:

terminate the monitoring script

terminate the remote command and continue with whatever is specified for the remote side.

You might get closer to what you want if you drop the first effect (or at least make it more explicit). Then, calling a script on the remote side that does not terminate itself but just the tail command, will be step. In that case you will likely need to use -t switch on ssh to get a terminal allocated for allowing normal shell operation later.

This, will not allow for terminating the remote side with just CTRL-C. You always will need to exit the remote shell that is going to be run.

The essence of such a remote script might look like:

```<code>tail command
shell
</code>```

of course you would need to add whatever parts will be necessary for your shell or coding style.

An alternate approach would be to keep the current remote command being terminated and add another ssh call for the case of being interrupted that is spanning the shell for interactive use. But in that case, also `CTRL-C will not be available for terminating the minoring altogether.

To achieve this you might try changing active interrupt handler with your monitoring script to trigger termination as soon as the remote side returns. However, this will cause a race condition between the user being able to recognize remote command terminated (and control has been returned to local script) and the proper interrupt handler being in place. You might be able to sufficiently lower that risk be first activating the new trap handler and then echoing the fact and maybe add a sleep to allow the user to react.

Body:
I have a host machine that gets rebooted or reconnected quite a few times.
I want to have a script running on my dev machine that continuously tries to log into that machine and if successful runs a specific command (tailing the log data).
Edit: To clarify, the connection needs to stay open. The log command keeps tailing until I stop it manually.

What I have so far

#!/bin/bash

IP=192.168.178.1

if (("$#" >= 1))
then
  IP=$1
fi

LOOP=1

trap 'echo "stopping"; LOOP=0' INT

while (( $LOOP==1 ))
do
if ping -c1 $IP
then
  echo "Host $IP reached"
  sshpass -p 'password' ssh -o ConnectTimeout=10 -q user@$IP '<command would go here>'
else
  echo "Host $IP unreachable"
fi
sleep 1

done

The LOOP flag is not really used. The script is ended via CTRL-C.
Now this works if I do NOT add a command to be executed after the ssh and instead start the log output manually. On a disconnect the script keeps probing the connection and logs back in once the host is available again.
Also when I disconnect from the host (CTRL-D) the script will log right back into the host if CTRL-C is not pressed fast enough.
When I add a command to be executed after ssh the loop is broken. So pressing (CTRL-C) does not only stop the log but also disconnects and ends the script on the dev machine.

I guess I have to spawn another shell somewhere or something like that?

1) I want the script to keep probing, log in and run a command completely automatically and fall back to probing when the connection breaks.
2) I want to be able to stop the log on the host (CTRL-C) and thereby fall back to a logged in ssh connection to use it manually.

How do I fix this?

Body:
Maybe best approach on "fixing" would be fixing requirements.

The problematic part is number "2)".
The problem is from how SIGINT works.

When triggered, it is sent to the current control group related to your terminal. Mostly this is the shell and any process started from there. With more modern shells (you seem to use bash), the shell manages control groups such that programs started in the background are disconnected (by having been assigned a different control group).

In your case the ssh is started in the foreground (from a script executed in the foreground), so it will receive the interrupt, forward it to the remote and terminate as soon as the remote end terminated. As by that time the script shell has processed its signal handler (specified by trap) it is going to exit the loop and terminate itself.

So, as you can see, you have overloaded CTRL-C to mean two things:

terminate the monitoring script

terminate the remote command and continue with whatever is specified for the remote side.

You might get closer to what you want if you drop the first effect (or at least make it more explicit). Then, calling a script on the remote side that does not terminate itself but just the tail command, will be step. In that case you will likely need to use -t switch on ssh to get a terminal allocated for allowing normal shell operation later.

This, will not allow for terminating the remote side with just CTRL-C. You always will need to exit the remote shell that is going to be run.

The essence of such a remote script might look like:

tail command
shell

of course you would need to add whatever parts will be necessary for your shell or coding style.

An alternate approach would be to keep the current remote command being terminated and add another ssh call for the case of being interrupted that is spanning the shell for interactive use. But in that case, also `CTRL-C will not be available for terminating the minoring altogether.

To achieve this you might try changing active interrupt handler with your monitoring script to trigger termination as soon as the remote side returns. However, this will cause a race condition between the user being able to recognize remote command terminated (and control has been returned to local script) and the proper interrupt handler being in place. You might be able to sufficiently lower that risk be first activating the new trap handler and then echoing the fact and maybe add a sleep to allow the user to react.


来源: stackexchange

问:
Create new thread if last thread is finished [Python 2.7]
I am new to Python threads. Basically, I have a QT based application designed in Python. The application has a button "Follow Trajectory", whenever I press this button, the robot starts moving. I noticed that robot is not following the exact trajectory.

The move command is being overwritten and robot receives only a few points. Below is the function, which gets executed when the button is pressed:

```<code>def move_robot(self):
    # points is an array of point
    for point in points:
        start_new_thread(self.robot.move, (point,))
</code>```

Below is the move function from the controller:

```<code>def move(self, point):
    while True:
        self._robot_controller.move(point)
        current_location = self._robot_controller.location()
        if current_location - point < 0.0001:
            break
</code>```

My question is that how to create a new thread only if last thread is finished?

Below is the complete code:

```<code>class RobotControllerWrapper():
    def __init__(self):
        self._robot_controller = RobotController()

    def move(self, point):
        while True:
            self._robot_controller.move(point)
            current_location = self._robot_controller.location()
            if current_location - point < 0.0001:
                break

from thread import start_new_thread
from qt_gui.plugin import Plugin
from python_qt_binding.QtGui import QWidget, QPushButton

class MyPlugin(Plugin):
    def __init__(self, context):

        super(MyPlugin, self).__init__(context)
        self.setObjectName('MyPlugin')

        self._widget = QWidget()
        self._vertical_layout = QVBoxLayout()
        self._move_robot_button = QPushButton('Follow Trajectory')
        self._move_robot_button.clicked.connect(self.move_robot)
        self._vertical_layout.addWidget(self._move_robot_button)
        self._widget.setLayout(self._vertical_layout)
        self._widget.setObjectName('MyPluginUi')

        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        self.robot = RobotControllerWrapper()

    def move_robot(self):
        # points is an array of point
        for point in points:
            start_new_thread(self.robot.move, (point,))
</code>```

Apologize for the long post. Thank you very much.

答:
In the definition in the methode move robot, you should add a "thread controller" to check if last running thread is over, before starting a new one.
Here is maybe a good tutorial, Python: is thread still running

In particular the method:

```<code>if last_thread.isAlive() ==  False:
    new_thread = start_new_thread(self.robot.move, (point,))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Python threads. Basically, I have a QT based application designed in Python. The application has a button "Follow Trajectory", whenever I press this button, the robot starts moving. I noticed that robot is not following the exact trajectory.

The move command is being overwritten and robot receives only a few points. Below is the function, which gets executed when the button is pressed:

def move_robot(self):
    # points is an array of point
    for point in points:
        start_new_thread(self.robot.move, (point,))

Below is the move function from the controller:

def move(self, point):
    while True:
        self._robot_controller.move(point)
        current_location = self._robot_controller.location()
        if current_location - point < 0.0001:
            break

My question is that how to create a new thread only if last thread is finished?

Below is the complete code:

class RobotControllerWrapper():
    def __init__(self):
        self._robot_controller = RobotController()

    def move(self, point):
        while True:
            self._robot_controller.move(point)
            current_location = self._robot_controller.location()
            if current_location - point < 0.0001:
                break

from thread import start_new_thread
from qt_gui.plugin import Plugin
from python_qt_binding.QtGui import QWidget, QPushButton

class MyPlugin(Plugin):
    def __init__(self, context):

        super(MyPlugin, self).__init__(context)
        self.setObjectName('MyPlugin')

        self._widget = QWidget()
        self._vertical_layout = QVBoxLayout()
        self._move_robot_button = QPushButton('Follow Trajectory')
        self._move_robot_button.clicked.connect(self.move_robot)
        self._vertical_layout.addWidget(self._move_robot_button)
        self._widget.setLayout(self._vertical_layout)
        self._widget.setObjectName('MyPluginUi')

        if context.serial_number() > 1:
            self._widget.setWindowTitle(self._widget.windowTitle() + (' (%d)' % context.serial_number()))
        context.add_widget(self._widget)

        self.robot = RobotControllerWrapper()

    def move_robot(self):
        # points is an array of point
        for point in points:
            start_new_thread(self.robot.move, (point,))

Apologize for the long post. Thank you very much.

Body:
In the definition in the methode move robot, you should add a "thread controller" to check if last running thread is over, before starting a new one.
Here is maybe a good tutorial, Python: is thread still running

In particular the method:

if last_thread.isAlive() ==  False:
    new_thread = start_new_thread(self.robot.move, (point,))


问:
Rails: Param problems with delete button
index.html:

```<code>  <% @partners.each do |j| %>
            <% if j.link == nil %>
                <div class="column_left"><%= j.name %></div>
            <% else %>
                <div class="column_left"><%= image_tag("#{j.link}") %></div>
            <% end %>
            <div class="column_right"><%= j.description %></div>
            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>
</code>```

controller:

```<code>    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end
</code>```

routes.rb:

```<code>  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]
</code>```

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

答:
If you want to delete an entry then you need to send a id of partner

```<code>        <%if logged_in? %>
          <%= button_to "Delete", partner_path(id: j.id), :method => :delete %>
        <% end %>
</code>```

Controller: -

```<code>def destroy
    Partner.find(params[:id]).destroy_all
    redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
end
</code>```

Routes: -

```<code> Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partners' => 'partner#index'
  post '/partners' => 'partner#addPartner'
  delete '/partner/:id' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]
</code>```

Body:
index.html:

  <% @partners.each do |j| %>
            <% if j.link == nil %>

<%= j.name %>

            <% else %>

<%= image_tag("#{j.link}") %>

            <% end %>

<%= j.description %>

            <%if logged_in? %>
                <%= button_to "-", j, :method => :destroy , data: { confirm: "Sind Sie sich sicher, dass sie den Partner #{j.name} löschen wollen?" } %>
            <% end %>

controller:

    def delete
        Partner.find(partner_params).destroy_all
        redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
    end

    def addPartner
        @partner = Partner.new(partner_params)
        if !Partner.exists?(:name => partner_params[:name])
            uploaded_io = params[:partner][:logo]
            File.open(Rails.root.join('app', 'assets', 'images', 'partner', uploaded_io.original_filename), 'wb') do |file|
              file.write(uploaded_io.read)
            @partner[:link] = "partner/#{uploaded_io.original_filename}"
            params[:partner].delete :logo
            @partner.save
            redirect_to partner_path, notice: "#{@partner.name} wurde modifiziert!"

            end
        else
          @partner = Partner.where(:name => partner_params[:name])
          if @partner.update_all(partner_params)
            flash[:notice] = "#{@partner.name} wurde geändert!"
          end
        end
      end

    private
       def partner_params
          params.require(:partner).permit(:name, :link, :description)
       end

routes.rb:

  Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partner' => 'partner#index'
  post '/partner' => 'partner#addPartner'
  delete '/partner' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]

I want to delete an entry from my database by clicking on a button. But there must be a conflict with the "private_params".
I always got this problem:

param is missing or the value is empty: partner

I searched for similiar problems, but nothing seems to fit really.

Body:
If you want to delete an entry then you need to send a id of partner

        <%if logged_in? %>
          <%= button_to "Delete", partner_path(id: j.id), :method => :delete %>
        <% end %>

Controller: -

def destroy
    Partner.find(params[:id]).destroy_all
    redirect_to partner_path, notice: "#Eintrag wurde gelöscht!"
end

Routes: -

 Rails.application.routes.draw do

  get '/login' => 'sessions#new'
  post '/login' => 'sessions#create'
  delete '/logout' => 'sessions#destroy'

  resources :users
  get '/home' => 'main#home'
  get '/impressum' => 'main#impressum'
  post '/impressum' => 'main#updateImpressumById'
  get '/partners' => 'partner#index'
  post '/partners' => 'partner#addPartner'
  delete '/partner/:id' => 'partner#delete'
  get '/jobs' => 'jobs#index'
  post '/jobs' => 'jobs#index'
  get '/kontakt' => 'contacts#new'
  post '/home' => 'main#updateText'
  get '/referenzen' => 'reference#index'
  post '/referenzen' => 'reference#index'

  resources "contacts", only: [:new, :create]


问:
Cant post to Azure storage? Invalid Path error
I am trying to add an image I am receiving like this.

[FunctionName("Imageupload")]
public static async System.Threading.Tasks.Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
{
    //Check if the request contains multipart/form-data.
    if (!req.Content.IsMimeMultipartContent())
    {
        return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    var storageConnectionString = "XXXXXXXXXXXXXXXXXXX";

    var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        log.Info(storageConnectionString);
    var blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("temporary-images");

    // Create the container if it doesn't already exist.
    container.CreateIfNotExists();

    //Retrieve reference to a blob named "myblob".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("images");

    try
    {
        string root = blockBlob.Uri.AbsoluteUri;
        var provider2 = new MultipartFormDataStreamProvider(root);
        await req.Content.ReadAsMultipartAsync(provider);
    }
    catch (StorageException e)
    {
        return req.CreateErrorResponse(HttpStatusCode.NotFound,e.Message);
    }
}
```

The path I am using is right as I checked it and it points to the storage container.

How Can I send the images I receive to Azure storage?

I recieve the error that the path's format is not supported.

My path looks like this : "https://XXXXXXXXXXX.blob.core.windows.net/temporary-images/images"

答:
I recieve the error that the path's format is not supported.

As MultipartFormDataStreamProvider requests local file path as parameter, so blob address http/https is not valid.

If you want to upload mutiple files to Azure storage container, please have try to use req.Content.ReadAsMultipartAsync(); and blockBlob.UploadFromStream(stream); to upload file to azure storage blob. I do a demo, it works correctly on my side.

```<code> if (!req.Content.IsMimeMultipartContent())
 {
     return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
 }
 var storageConnectionString = "connection string";
 var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
 log.Info(storageConnectionString);
 var blobClient = storageAccount.CreateCloudBlobClient();
 CloudBlobContainer container = blobClient.GetContainerReference("temporary-images");
 container.CreateIfNotExists();
 try
 {
    var filesReadToProvider = await req.Content.ReadAsMultipartAsync();
    foreach (var stream in filesReadToProvider.Contents)
    {
       var blobName = stream.Headers.ContentDisposition.FileName.Trim('"');
       CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
       blockBlob.UploadFromStream(stream.ReadAsStreamAsync().Result);

    }

 }
 catch (StorageException e)
 {
        return req.CreateErrorResponse(HttpStatusCode.NotFound, e.Message);
 }
</code>```

Body:
I am trying to add an image I am receiving like this.

[FunctionName("Imageupload")]
public static async System.Threading.Tasks.Task<HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = "HttpTriggerCSharp/name/{name}")]HttpRequestMessage req, string name, TraceWriter log)
{
    //Check if the request contains multipart/form-data.
    if (!req.Content.IsMimeMultipartContent())
    {
        return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    var storageConnectionString = "XXXXXXXXXXXXXXXXXXX";

    var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
        log.Info(storageConnectionString);
    var blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("temporary-images");

    // Create the container if it doesn't already exist.
    container.CreateIfNotExists();

    //Retrieve reference to a blob named "myblob".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("images");

    try
    {
        string root = blockBlob.Uri.AbsoluteUri;
        var provider2 = new MultipartFormDataStreamProvider(root);
        await req.Content.ReadAsMultipartAsync(provider);
    }
    catch (StorageException e)
    {
        return req.CreateErrorResponse(HttpStatusCode.NotFound,e.Message);
    }
}

The path I am using is right as I checked it and it points to the storage container.

How Can I send the images I receive to Azure storage?

I recieve the error that the path's format is not supported.

My path looks like this : "https://XXXXXXXXXXX.blob.core.windows.net/temporary-images/images"

Body:
I recieve the error that the path's format is not supported.

As MultipartFormDataStreamProvider requests local file path as parameter, so blob address http/https is not valid.

If you want to upload mutiple files to Azure storage container, please have try to use req.Content.ReadAsMultipartAsync(); and blockBlob.UploadFromStream(stream); to upload file to azure storage blob. I do a demo, it works correctly on my side.

 if (!req.Content.IsMimeMultipartContent())
 {
     return req.CreateResponse(HttpStatusCode.UnsupportedMediaType);
 }
 var storageConnectionString = "connection string";
 var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
 log.Info(storageConnectionString);
 var blobClient = storageAccount.CreateCloudBlobClient();
 CloudBlobContainer container = blobClient.GetContainerReference("temporary-images");
 container.CreateIfNotExists();
 try
 {
    var filesReadToProvider = await req.Content.ReadAsMultipartAsync();
    foreach (var stream in filesReadToProvider.Contents)
    {
       var blobName = stream.Headers.ContentDisposition.FileName.Trim('"');
       CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
       blockBlob.UploadFromStream(stream.ReadAsStreamAsync().Result);

    }

 }
 catch (StorageException e)
 {
        return req.CreateErrorResponse(HttpStatusCode.NotFound, e.Message);
 }


问:
Error message displayed when opening Eclipse: "An error has occurred. See the log file null"
I use Windows 10 and jre1.8.0_51. I don't know why when I start Eclipse it always displays an alert message "An error has occurred. See the log file null."

And I cannot open Eclipse thereafter. I tried to search Google and have no best solution. I uninstalled JRE and installed it again, but it still produces the same problem.

答: Remove the .snap file from <WORKSPACE-DIRECTORY>\.metadata\.plugins\org.eclipse.core.resources

ContentLicense: CC BY-SA 4.0


问:
Set the button to Done instead of Go in EditText
I'm trying to switch the button in the softkey from "Go" to "Done" and vice-versa.
If I just set the imeoption

```<code>private fun showDoneOnSoftKeyboard() {
    setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_DONE)
}

private fun showGoOnSoftKeyboard() {
    setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_GO)
}

private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
    contractIdInput.imeOptions = imeOptions
}
</code>```

the button is not changed. I've found that by doing:

```<code>private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
    val inputType = contractIdInput.inputType
    contractIdInput.inputType = InputType.TYPE_NULL
    contractIdInput.imeOptions = imeOptions
    contractIdInput.inputType = inputType
}
</code>```

the button is changed. The problem is though that the keyboard settings are reset that means that if I have for example the capslock set after I switch between states (for example from Done to Go) then the capslock is reset.

I have also tried

```<code>contractIdInput.imeOptions = imeOptions
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.restartInput(contractIdInput)
</code>```

but this has the same effect.

I tried this one as well:

```<code>contractIdInput.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER)
</code>```

but it does not work either.

Is there any other way to do the same?

答: It looks like this can't be done. The IME-options are thought to be set statically in the XML or programmatically but they can't be modified dynamically while the user is typing.</p>

Body:
I'm trying to switch the button in the softkey from "Go" to "Done" and vice-versa.
If I just set the imeoption

private fun showDoneOnSoftKeyboard() {
    setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_DONE)
}

private fun showGoOnSoftKeyboard() {
    setImeOptionsOnSoftKeyboard(EditorInfo.IME_ACTION_GO)
}

private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
    contractIdInput.imeOptions = imeOptions
}

the button is not changed. I've found that by doing:

private fun setImeOptionsOnSoftKeyboard(imeOptions: Int) {
    val inputType = contractIdInput.inputType
    contractIdInput.inputType = InputType.TYPE_NULL
    contractIdInput.imeOptions = imeOptions
    contractIdInput.inputType = inputType
}

the button is changed. The problem is though that the keyboard settings are reset that means that if I have for example the capslock set after I switch between states (for example from Done to Go) then the capslock is reset.

I have also tried

contractIdInput.imeOptions = imeOptions
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.restartInput(contractIdInput)

but this has the same effect.

I tried this one as well:

contractIdInput.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER)

but it does not work either.

Is there any other way to do the same?


问:
Remove duplicates within Spark array column
I have a given DataSet :

```<code>+-------------------+--------------------+
|               date|            products|
+-------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|
|2017-09-21 22:00:00|[361, 361, 361, 3...|
|2017-09-28 22:00:00|[360, 361, 361, 3...|
</code>```

where products column is an array of strings with possible duplicated items.

I would like to remove this duplication (within one row)

What I did is basically write an UDF function like that

```<code> val removeDuplicates: WrappedArray[String] => WrappedArray[String] = _.distinct
 val udfremoveDuplicates = udf(removeDuplicates)
</code>```

This solution gives me a proper results :

```<code>+-------------------+--------------------+--------------------+
|               date|            products|       rm_duplicates|
+-------------------+--------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|[361, 362, 363, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|[361, 362, 363, 3...|
</code>```

My questions are  :

Do Spark provides a better/more efficient way of getting this result ?

I was thinking about using a map - but how to get desired column as a List to be able to use 'distinct' method  like in my removeDuplicates lambda ?

Edit: I marked this topic with java tag, because it does not matter to me in which language (scala or java) I will get an answear :)
Edit2: typos

Body:
I have a given DataSet :

+-------------------+--------------------+
|               date|            products|
+-------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|
|2017-09-21 22:00:00|[361, 361, 361, 3...|
|2017-09-28 22:00:00|[360, 361, 361, 3...|

where products column is an array of strings with possible duplicated items.

I would like to remove this duplication (within one row)

What I did is basically write an UDF function like that

 val removeDuplicates: WrappedArray[String] => WrappedArray[String] = _.distinct
 val udfremoveDuplicates = udf(removeDuplicates)

This solution gives me a proper results :

+-------------------+--------------------+--------------------+
|               date|            products|       rm_duplicates|
+-------------------+--------------------+--------------------+
|2017-08-31 22:00:00|[361, 361, 361, 3...|[361, 362, 363, 3...|
|2017-09-22 22:00:00|[361, 362, 362, 3...|[361, 362, 363, 3...|

My questions are  :

Do Spark provides a better/more efficient way of getting this result ?

I was thinking about using a map - but how to get desired column as a List to be able to use 'distinct' method  like in my removeDuplicates lambda ?

Edit: I marked this topic with java tag, because it does not matter to me in which language (scala or java) I will get an answear :)
Edit2: typos

Body:
Given your current dataframe schema as

root
 |-- date: string (nullable = true)
 |-- products: array (nullable = true)
 |    |-- element: integer (containsNull = false)

You can use following method for removing the duplicates.

df.map(row => DuplicateRemoved(row(0).toString, row(1).asInstanceOf[mutable.WrappedArray[Int]], row(1).asInstanceOf[mutable.WrappedArray[Int]].distinct)).toDF()

Of course you need a case class for this

case class DuplicateRemoved(date: String, products: mutable.WrappedArray[Int], rm_duplicates: mutable.WrappedArray[Int])

You should be getting following output

+-------------------+------------------------------+-------------------------+
|date               |products                      |rm_duplicates            |
+-------------------+------------------------------+-------------------------+
|2017-08-31 22:00:00|[361, 361, 361, 362, 363, 364]|[361, 362, 363, 364]     |
|2017-09-22 22:00:00|[361, 362, 362, 362, 363, 364]|[361, 362, 363, 364]     |
|2017-09-21 22:00:00|[361, 361, 361, 362, 363, 364]|[361, 362, 363, 364]     |
|2017-09-28 22:00:00|[360, 361, 361, 362, 363, 364]|[360, 361, 362, 363, 364]|
+-------------------+------------------------------+-------------------------+

I hope the answer is helpful


问:
How do i read image using PILLOW image?
I wanted read a image using PIL.Image.open().But I've image in different path.
The following is the path I've the python script

```<code>"D:\YY_Aadhi\holy-edge-master\hed\test.py"
</code>```

The following is the path I've the image file.

```<code>"D:\YY_Aadhi\HED-BSDS\test\2018.jpg"

from PIL import Image
'''some code here'''
image = Image.open(????)
</code>```

How should I fill the question mark to access the image file.

答: Does this image = Image.open("D:\YY_Aadhi\HED-BSDS\test\2018.jpg") not do the trick?

Title: How do i read image using PILLOW image?

Body:
I wanted read a image using PIL.Image.open().But I've image in different path.
The following is the path I've the python script

"D:\YY_Aadhi\holy-edge-master\hed\test.py"

The following is the path I've the image file.

"D:\YY_Aadhi\HED-BSDS\test\2018.jpg"

from PIL import Image
'''some code here'''
image = Image.open(????)

How should I fill the question mark to access the image file.


问:
How to calculate the run time of a nested loop theoretically?
I have a nested for loop in c++:

```<code>for(i=0;i<10000000;i++)
{
for(j=0;j<999999;j++)
    {
        //execute something
    }
}
</code>```

I want to know:

the number of hours this code will take to finish running.

Will using a machine with more RAM and cores improve the run-time?

How does my choice of language (MATLAB, Python, C/C++) will affect the run-time?

答:
if you are just asking for measuring the time you could use

```<code>#include <ctime>

int start_s=clock();
    // code
int stop_s=clock();
cout << "time (in milis): " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000;
</code>```

but if you wonder if this runtime would be better if got more ram or more cpu cores here is what you need :

short answer : it depends on "//execute something" block

long answer :
it doesn't depend directly on what the loop boundaries are, it just depend on what you do inside the nested loop
here are a few double loop examples to demonstrate this

if you are dealing with formulas then using a higher cpu frequency would be better

note that number of cores have nothing to do with running time as the code is not parallelized by default

```<code>sum = 0;
for(i=0;i<10000000;i++)
    for(j=0;j<999999;j++)
        sum+=1;
</code>```

if you are dealing with arrays then your RAM can make use of spatial/temporal locality but the portion of your array saved in memory is limited by other parameters so bigger RAM wouldn't do much but using a higher RAM frequency would be better

```<code>int arr[10000000][999999];
arr[0][0] = 0;
for(i=1;i<10000000;i++)
    for(j=1;j<999999;j++)
        arr[i][j]=arr[i-1][j-1];
</code>```

if you are dealing with disk/buffer operation then neither your RAM or cpu can optimize it more than some level -hardware is the bottleneck-

```<code>    for(i=0;i<10000000;i++)
        for(j=0;j<999999;j++)
            cout << "yes";

    ofstream file;
    file.open ("out.txt");
    for(i=0;i<10000000;i++)
        for(j=0;j<999999;j++)
            file << "Writing to the file.\n";
</code>```

Body:
I have a nested for loop in c++:

for(i=0;i<10000000;i++)
{
for(j=0;j<999999;j++)
    {
        //execute something
    }
}

I want to know:

the number of hours this code will take to finish running.

Will using a machine with more RAM and cores improve the run-time?

How does my choice of language (MATLAB, Python, C/C++) will affect the run-time?

Body:
if you are just asking for measuring the time you could use

#include <ctime>

int start_s=clock();
    // code
int stop_s=clock();
cout << "time (in milis): " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000;

but if you wonder if this runtime would be better if got more ram or more cpu cores here is what you need :

short answer : it depends on "//execute something" block

long answer :
it doesn't depend directly on what the loop boundaries are, it just depend on what you do inside the nested loop
here are a few double loop examples to demonstrate this

if you are dealing with formulas then using a higher cpu frequency would be better

note that number of cores have nothing to do with running time as the code is not parallelized by default

sum = 0;
for(i=0;i<10000000;i++)
    for(j=0;j<999999;j++)
        sum+=1;

if you are dealing with arrays then your RAM can make use of spatial/temporal locality but the portion of your array saved in memory is limited by other parameters so bigger RAM wouldn't do much but using a higher RAM frequency would be better

int arr[10000000][999999];
arr[0][0] = 0;
for(i=1;i<10000000;i++)
    for(j=1;j<999999;j++)
        arr[i][j]=arr[i-1][j-1];

if you are dealing with disk/buffer operation then neither your RAM or cpu can optimize it more than some level -hardware is the bottleneck-

    for(i=0;i<10000000;i++)
        for(j=0;j<999999;j++)
            cout << "yes";

    ofstream file;
    file.open ("out.txt");
    for(i=0;i<10000000;i++)
        for(j=0;j<999999;j++)
            file << "Writing to the file.\n";


问:
Django error templates in custom path
I have dir template with all templates, and I have dir errors, with all templates with errors 404.html.
I found the following old solution:

In urls.py my app I wrote

```<code>from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found'
</code>```

And in view my app

```<code>from django.shortcuts import (render_to_response)
from django.template import RequestContext

def page_not_found(request):
    response = render_to_response(
    'errors/404.html',
    context_instance=RequestContext(request))

    response.status_code = 404
    return response
</code>```

But I use Django 1.11 and this doesn't work.

答:
If you follow the docs

You should return HttpResponseNotFound which is the same as HttpResonse except for status code. It worked for me.

```<code>def bad_request(request):
    response = render_to_response(
        'errors/404.html'
    )

    return HttpResponseNotFound(response.content)
</code>```

Title: Django error templates in custom path

Body:
I have dir template with all templates, and I have dir errors, with all templates with errors 404.html.
I found the following old solution:

In urls.py my app I wrote

from django.conf.urls import (handler400, handler403, handler404, handler500)
handler404 = 'my_app.views.page_not_found'

And in view my app

from django.shortcuts import (render_to_response)
from django.template import RequestContext

def page_not_found(request):
    response = render_to_response(
    'errors/404.html',
    context_instance=RequestContext(request))

    response.status_code = 404
    return response

But I use Django 1.11 and this doesn't work.

Body:
If you follow the docs

You should return HttpResponseNotFound which is the same as HttpResonse except for status code. It worked for me.

def bad_request(request):
    response = render_to_response(
        'errors/404.html'
    )

    return HttpResponseNotFound(response.content)


问:
Unable to run java applet in web browser
I have added one class file and one zip file into html file and some html tags like bgcolor,title,center and so on my point is that the web browser runs html code only but unable to run applet without any error how can i do that very succesfully

[Translation attempt: I have created a simple HTML page with one java applet, a zip download link and some basic HTML formatting 'bgcolor, title, center'.  My applet does not run, and no error is displayed]

and one thing also a single event like one click button it runs but multiple events doesn't run please answer me

[Translation attempt: Upon clicking on the applet once (?) it works as intended, however it does not run fully to completion (?)]

i currently use Mozilla Firefox, no ad remover is installed and there is currently no error message simply a blank box with some html (code?) features that i have used in html file

================================================================================
now after enabling console and refreshing it gives window and it contain following:-\

```<code>Java Plug-in 1.6.0_22
Using JRE version 1.6.0_22-b04 Java HotSpot(TM) Client VM
User home directory = C:\Users\HONEY
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
APPLET tag missing CODE parameter.**
</code>```

答:
APPLET tag missing CODE parameter.**

Is the message in the console, which suggests to me that the "APPLET tag missing CODE parameter.**".  Which is bad grammar, but means something like..

Wrong!

```<code><applet
  width="400"
  height="300"
>
</applet>
</code>```

Right/Corrrect

```<code><applet
  code="my.own.MyClass"
  width="400"
  height="300"
>
</applet>
</code>```

Body:
I have added one class file and one zip file into html file and some html tags like bgcolor,title,center and so on my point is that the web browser runs html code only but unable to run applet without any error how can i do that very succesfully

[Translation attempt: I have created a simple HTML page with one java applet, a zip download link and some basic HTML formatting 'bgcolor, title, center'.  My applet does not run, and no error is displayed]

and one thing also a single event like one click button it runs but multiple events doesn't run please answer me

[Translation attempt: Upon clicking on the applet once (?) it works as intended, however it does not run fully to completion (?)]

i currently use Mozilla Firefox, no ad remover is installed and there is currently no error message simply a blank box with some html (code?) features that i have used in html file

================================================================================
now after enabling console and refreshing it gives window and it contain following:-\

Java Plug-in 1.6.0_22
Using JRE version 1.6.0_22-b04 Java HotSpot(TM) Client VM
User home directory = C:\Users\HONEY
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
l:   dump classloader list
m:   print memory usage
o:   trigger logging
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
x:   clear classloader cache
0-5: set trace level to <n>
----------------------------------------------------
APPLET tag missing CODE parameter.**

Body:
APPLET tag missing CODE parameter.**

Is the message in the console, which suggests to me that the "APPLET tag missing CODE parameter.**".  Which is bad grammar, but means something like..

Wrong!

<applet
  width="400"
  height="300"
>
</applet>

Right/Corrrect

<applet
  code="my.own.MyClass"
  width="400"
  height="300"
>
</applet>

ContentLicense: CC BY-SA 2.5


问:
how to pass variable inside replace java-script function
I'm using the below code to trim the string based on the condition like 15 characters per line, in this below code, 15 was hard-coded.But I need to make it dynamic like defining variable and pass into replace function.

```<code>var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,15})(?:\n|$| )/g, "$1|\n");
console.log(result);
</code>```

How I need

```<code>var trim_val =15;
var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,trim_val})(?:\n|$| )/g, "$1|\n"); //here i have to pass that variable
console.log(result);
</code>```

Thanks in Advance

答:
You need to use the RegExp constructor, to create a new Regex instance with your trim_val variable and use it in your replace() call.

This is how should be your code:

```<code>var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", "g");
var result = str.replace(reg, "$1|\n");
</code>```

Demo:

var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", 'g');
var result = str.replace(reg, "$1|\n"); //here i have to pass that variable
console.log(result);```

Body:
I'm using the below code to trim the string based on the condition like 15 characters per line, in this below code, 15 was hard-coded.But I need to make it dynamic like defining variable and pass into replace function.

var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,15})(?:\n|$| )/g, "$1|\n");
console.log(result);

How I need

var trim_val =15;
var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,trim_val})(?:\n|$| )/g, "$1|\n"); //here i have to pass that variable
console.log(result);

Thanks in Advance

Body:
You need to use the RegExp constructor, to create a new Regex instance with your trim_val variable and use it in your replace() call.

This is how should be your code:

var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", "g");
var result = str.replace(reg, "$1|\n");

Demo:

var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", 'g');
var result = str.replace(reg, "$1|\n"); //here i have to pass that variable
console.log(result);


问:
subquery inside WHERE statement
I have some trouble inserting subquery inside WHERE statement. Code that I have so far is :

```<code>    select * from (
    SELECT 'P_' dmnsn  AS partition_name,
    decode(dmnsn,'PROMO','CMBD_PROMO',dmnsn_code) AS high_value,
    dmnsn AS part_pre
    FROM
       (select to_char(to_clob(COLUMN_VALUE)) as dmnsn
    from XMLTABLE(to_clob('"CLSTR","CUSTOMER","CALENDAR","TYPE",
    "PROMO","PRODUCT","PRODUCTION","STORE","WAREHOUSE","SALES","PRICE"')))
    )
    where ( select count(*) 'TEST_' || substr( partition_name,3) || '_VIEW' ) > 0
</code>```

Obviously it doesn't work. ( I've just put it here to give you a glimps of what I'm trying to do)
All the views from XMLTABLE actually exist and look like this "TEST_CLSTR_VIEW".
What I'm aiming for is selecting from XMLTABLE only those values that create a view which is not empty ( contains some records )

答:
You have   several  problem in your query

1 - the use on var of database object as table or columns name is noit allowed  in SQL .. so you should build your query using another tecnique eg: building dinamically server side  the  string for your query avoinding var

2 - you missed  the FROM clause in you subselect .

3 -  the 'P_'   dmnsn   AS partition_name,  is sintactically wrong

```<code>select * from (
    SELECT 'P_'   dmnsn  AS partition_name,
    decode(dmnsn,'PROMO','CMBD_PROMO',dmnsn_code) AS high_value,
    dmnsn AS part_pre
    FROM
       (select to_char(to_clob(COLUMN_VALUE)) as dmnsn
    from XMLTABLE(to_clob('"CLSTR","CUSTOMER","CALENDAR","TYPE",
    "PROMO","PRODUCT","PRODUCTION","STORE","WAREHOUSE","SALES","PRICE"')))
    )
    where ( select count(*) FROM  YOUR_VIEW ) > 0
</code>```

Title: subquery inside WHERE statement

Body:
I have some trouble inserting subquery inside WHERE statement. Code that I have so far is :

    select * from (
    SELECT 'P_' dmnsn  AS partition_name,
    decode(dmnsn,'PROMO','CMBD_PROMO',dmnsn_code) AS high_value,
    dmnsn AS part_pre
    FROM
       (select to_char(to_clob(COLUMN_VALUE)) as dmnsn
    from XMLTABLE(to_clob('"CLSTR","CUSTOMER","CALENDAR","TYPE",
    "PROMO","PRODUCT","PRODUCTION","STORE","WAREHOUSE","SALES","PRICE"')))
    )
    where ( select count(*) 'TEST_' || substr( partition_name,3) || '_VIEW' ) > 0

Obviously it doesn't work. ( I've just put it here to give you a glimps of what I'm trying to do)
All the views from XMLTABLE actually exist and look like this "TEST_CLSTR_VIEW".
What I'm aiming for is selecting from XMLTABLE only those values that create a view which is not empty ( contains some records )

Body:
You have   several  problem in your query

1 - the use on var of database object as table or columns name is noit allowed  in SQL .. so you should build your query using another tecnique eg: building dinamically server side  the  string for your query avoinding var

2 - you missed  the FROM clause in you subselect .

3 -  the 'P_'   dmnsn   AS partition_name,  is sintactically wrong

select * from (
    SELECT 'P_'   dmnsn  AS partition_name,
    decode(dmnsn,'PROMO','CMBD_PROMO',dmnsn_code) AS high_value,
    dmnsn AS part_pre
    FROM
       (select to_char(to_clob(COLUMN_VALUE)) as dmnsn
    from XMLTABLE(to_clob('"CLSTR","CUSTOMER","CALENDAR","TYPE",
    "PROMO","PRODUCT","PRODUCTION","STORE","WAREHOUSE","SALES","PRICE"')))
    )
    where ( select count(*) FROM  YOUR_VIEW ) > 0


问:
How to identify an element in Selenium WebDriver that does not have any unique identifier/property?
There are two buttons on application named as "download" & "upload" with same properties/identifiers. Can someone help me how to click on button & how to handle such objects. I have tried CSS Selector, XPath other combinations as well, nothing worked for me. looking for Java code.
below is the HTML for those buttons:</p>

```<code><div class="control-label col-md-6 control-label-left"> <button class="btn blue form-control-btn" ngf-select="vm.uploadDemographic($file)"> <i class="fa fa-upload"/> Upload Template </button> </div> 2nd Button <div class="control-label col-md-6 control-label-left"> <button class="btn blue form-control-btn" ng-click="vm.downloadTemplate('demographic')"> <i class="fa fa-download"/> Download Template </button> </div>
</code>```

答:
Try to use the following CSS Selector: .btn.blue.form-control-btn. It must help you.

Code:

```<code>buttons = driver.findElements(By.cssSelector(".btn.blue.form-control-btn"));
buttons.get(0).click(); // Click on the first button.
</code>```

Body:
There are two buttons on application named as "download" & "upload" with same properties/identifiers. Can someone help me how to click on button & how to handle such objects. I have tried CSS Selector, XPath other combinations as well, nothing worked for me. looking for Java code.
below is the HTML for those buttons:

 <button class="btn blue form-control-btn" ngf-select="vm.uploadDemographic($file)">  Upload Template </button>
 2nd Button
 <button class="btn blue form-control-btn" ng-click="vm.downloadTemplate('demographic')">  Download Template </button>

Body:
Try to use the following CSS Selector: .btn.blue.form-control-btn. It must help you.

Code:

buttons = driver.findElements(By.cssSelector(".btn.blue.form-control-btn"));
buttons.get(0).click(); // Click on the first button.


问:
The required anti-forgery form field "__RequestVerificationToken" is not present on $.post
Currently I am having a problem with my AntiForgeryToken not being present in my post call but for all I know, it is actually there.

Since I don't use a form to get the data from my HTML but just input fields I made a empty form on the bottom of my page using:

```<code>@using (Html.BeginForm(null, null, FormMethod.Post, new { id =
"__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}
</code>```

This results in a AntiForgeryToken that I can get using jQuery.

so in my Javascript I do:

```<code>                        var LoginData = {
                            EmailAddress: currentMail,
                            Password: password
                        }
                        var form = $('#__AjaxAntiForgeryForm');
                        var token = $('input[name="__RequestVerificationToken"]', form).val();

                        data = {
                            __RequestVerificationToken: token,
                            LoginData: LoginData
                        }

                        $.post(window.location,
                            {
                                scController: '*Controller*',
                                scAction: 'ValidateLogin',
                                data: data
                            }).done(function (d, e) {
                                console.log("done");
                                console.log(d);
                                console.log(e);
                            }).fail(function (d, e) {
                                console.log("error");
                                console.log(d);
                                console.log(e);
                            });
</code>```

The data object that I create results in:

```<code>{LoginData: {EmailAddress: "********", Password: "*******"}, __RequestVerificationToken: "Imagine a token here"}
</code>```

And then my controller action:

```<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public ResultMessage ValidateLogin(LoginData login)
    {
        return _userRepository.Login(login);
    }
</code>```

For some reason when I try to do this post I get this error:

"The required anti-forgery form field "__RequestVerificationToken" is not present."

What am I doing wrong?

EDIT 1:
I see that the __RequestVerificationToken in the Cookie header is different than the one I send with the data. How can this be?

答:
As stated here https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks, when used with ajax, the anti-forgery token must be sent in the headers like this:</p>

```<code>$.ajax("api/values", {
    type: "post",
    contentType: "application/json",
    data: {  }, // JSON data goes here
    dataType: "json",
    headers: {
        'RequestVerificationToken': <Token>
    }
});
</code>```

Body:
Currently I am having a problem with my AntiForgeryToken not being present in my post call but for all I know, it is actually there.

Since I don't use a form to get the data from my HTML but just input fields I made a empty form on the bottom of my page using:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id =
"__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

This results in a AntiForgeryToken that I can get using jQuery.

so in my Javascript I do:

                        var LoginData = {
                            EmailAddress: currentMail,
                            Password: password
                        }
                        var form = $('#__AjaxAntiForgeryForm');
                        var token = $('input[name="__RequestVerificationToken"]', form).val();

                        data = {
                            __RequestVerificationToken: token,
                            LoginData: LoginData
                        }

                        $.post(window.location,
                            {
                                scController: '*Controller*',
                                scAction: 'ValidateLogin',
                                data: data
                            }).done(function (d, e) {
                                console.log("done");
                                console.log(d);
                                console.log(e);
                            }).fail(function (d, e) {
                                console.log("error");
                                console.log(d);
                                console.log(e);
                            });

The data object that I create results in:

{LoginData: {EmailAddress: "********", Password: "*******"}, __RequestVerificationToken: "Imagine a token here"}

And then my controller action:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ResultMessage ValidateLogin(LoginData login)
    {
        return _userRepository.Login(login);
    }

For some reason when I try to do this post I get this error:

"The required anti-forgery form field "__RequestVerificationToken" is not present."

What am I doing wrong?

EDIT 1:
I see that the __RequestVerificationToken in the Cookie header is different than the one I send with the data. How can this be?

Body:
As stated here https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks, when used with ajax, the anti-forgery token must be sent in the headers like this:

$.ajax("api/values", {
    type: "post",
    contentType: "application/json",
    data: {  }, // JSON data goes here
    dataType: "json",
    headers: {
        'RequestVerificationToken': <Token>
    }
});


问:
Two-Way Binding Of VerticalOffset Property on ScrollViewer?
I have a View and a ViewModel in Silverlight 3.0.

The view contains a standard ScrollViewer, which contains dynamic content.

Depending on the content within the ScrollViewer, the user could have scrolled half way down the content, and then performed an action that causes the ScrollViewer to load new content, but the ScrollViewer does not automatically scroll to the top.

I want to be able to bind to the VerticalOffset property, but it is read-only.  Any ideas on attachable behavior?
Any ideas?

Thanks.

答:
I've simplified the @ColinE's solution. Instead of hooking to the ScrollBar.ValueChanged event, I hook to the ScrollViewer.ScrollChanged event. So, 1. it is not necessary to find the ScrollBar in the visual tree and 2. ScrollBar.ValueChanged is called in some transition states when the content of the ScrollViewer changes and I do not want to catch these states.

I post my code for the VerticalOffset, the HorizontalOffset is similar:

///
/// VerticalOffset attached property
///
public static readonly DependencyProperty VerticalOffsetProperty =
    DependencyProperty.RegisterAttached("VerticalOffset", typeof(double),
    typeof(ScrollViewerBinding), new FrameworkPropertyMetadata(double.NaN,
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        OnVerticalOffsetPropertyChanged));

///
/// Just a flag that the binding has been applied.
///
private static readonly DependencyProperty VerticalScrollBindingProperty =
    DependencyProperty.RegisterAttached("VerticalScrollBinding", typeof(bool?), typeof(ScrollViewerBinding));

public static double GetVerticalOffset(DependencyObject depObj)
{
    return (double)depObj.GetValue(VerticalOffsetProperty);
}

public static void SetVerticalOffset(DependencyObject depObj, double value)
{
    depObj.SetValue(VerticalOffsetProperty, value);
}

private static void OnVerticalOffsetPropertyChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    ScrollViewer scrollViewer = d as ScrollViewer;
    if (scrollViewer == null)
        return;

    BindVerticalOffset(scrollViewer);
    scrollViewer.ScrollToVerticalOffset((double)e.NewValue);
}

public static void BindVerticalOffset(ScrollViewer scrollViewer)
{
    if (scrollViewer.GetValue(VerticalScrollBindingProperty) != null)
        return;

    scrollViewer.SetValue(VerticalScrollBindingProperty, true);
    scrollViewer.ScrollChanged += (s, se) =>
    {
        if (se.VerticalChange == 0)
            return;
        SetVerticalOffset(scrollViewer, se.VerticalOffset);
    };
}
```

<p>And use it in the XAML:</p>

<pre class="lang-xml prettyprint-override"><code><ScrollViewer local:ScrollViewerBinding.VerticalOffset="{Binding ScrollVertical}">
    <!-- content ... -->
</ScrollViewer>
</code>```

Body:
I've simplified the @ColinE's solution. Instead of hooking to the ScrollBar.ValueChanged event, I hook to the ScrollViewer.ScrollChanged event. So, 1. it is not necessary to find the ScrollBar in the visual tree and 2. ScrollBar.ValueChanged is called in some transition states when the content of the ScrollViewer changes and I do not want to catch these states.

I post my code for the VerticalOffset, the HorizontalOffset is similar:

/// <summary>
/// VerticalOffset attached property
/// </summary>
public static readonly DependencyProperty VerticalOffsetProperty =
    DependencyProperty.RegisterAttached("VerticalOffset", typeof(double),
    typeof(ScrollViewerBinding), new FrameworkPropertyMetadata(double.NaN,
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        OnVerticalOffsetPropertyChanged));

/// <summary>
/// Just a flag that the binding has been applied.
/// </summary>
private static readonly DependencyProperty VerticalScrollBindingProperty =
    DependencyProperty.RegisterAttached("VerticalScrollBinding", typeof(bool?), typeof(ScrollViewerBinding));

public static double GetVerticalOffset(DependencyObject depObj)
{
    return (double)depObj.GetValue(VerticalOffsetProperty);
}

public static void SetVerticalOffset(DependencyObject depObj, double value)
{
    depObj.SetValue(VerticalOffsetProperty, value);
}

private static void OnVerticalOffsetPropertyChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    ScrollViewer scrollViewer = d as ScrollViewer;
    if (scrollViewer == null)
        return;

    BindVerticalOffset(scrollViewer);
    scrollViewer.ScrollToVerticalOffset((double)e.NewValue);
}

public static void BindVerticalOffset(ScrollViewer scrollViewer)
{
    if (scrollViewer.GetValue(VerticalScrollBindingProperty) != null)
        return;

    scrollViewer.SetValue(VerticalScrollBindingProperty, true);
    scrollViewer.ScrollChanged += (s, se) =>
    {
        if (se.VerticalChange == 0)
            return;
        SetVerticalOffset(scrollViewer, se.VerticalOffset);
    };
}

And use it in the XAML:

<ScrollViewer local:ScrollViewerBinding.VerticalOffset="{Binding ScrollVertical}">
    <!-- content ... -->
</ScrollViewer>


问:
Manifest-declared broadcast receiver does not receive custom broadcast on Android 8
First, I created a BroadcastReceiver with empty body. Then, I added it to the AndroidManifest.xml. But I found out that BroadcastReceiver declared in manifest does not receive any broadcast. I sent broadcast by

```<code>sendOrderedBroadcast(new Intent("com.example.action"), null)
</code>```

or

```<code>adb shell am broadcast -a com.example.action
</code>```

Both methods works on Android 7 but it does not work on Android 8. However, if the BroadcastReceiver is declared through registerReceiver, then it can still receive the broadcast.

On the other hand, android.hardware.usb.action.USB_DEVICE_ATTACHED works fine on both Android 7 and 8.

I want to ask why does it happen? I have tested it in both emulator and a physical device. They have the same behavior.

AndroidManifest.xml

```<code>...
<receiver
    android:name=".device.UsbBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        <action android:name="com.example.action" />
    </intent-filter>
    <meta-data
        android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        android:resource="@xml/device_filter" />
</receiver>
...
</code>```

答:
As part of the Android 8.0 (API level 26) Background Execution Limits, apps that target the API level 26 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest.

Read this

Body:
First, I created a BroadcastReceiver with empty body. Then, I added it to the AndroidManifest.xml. But I found out that BroadcastReceiver declared in manifest does not receive any broadcast. I sent broadcast by

sendOrderedBroadcast(new Intent("com.example.action"), null)

or

adb shell am broadcast -a com.example.action

Both methods works on Android 7 but it does not work on Android 8. However, if the BroadcastReceiver is declared through registerReceiver, then it can still receive the broadcast.

On the other hand, android.hardware.usb.action.USB_DEVICE_ATTACHED works fine on both Android 7 and 8.

I want to ask why does it happen? I have tested it in both emulator and a physical device. They have the same behavior.

AndroidManifest.xml

...
<receiver
    android:name=".device.UsbBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
        <action android:name="com.example.action" />
    </intent-filter>
    <meta-data
        android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
        android:resource="@xml/device_filter" />
</receiver>
...


问:
How to remove link tab in images for CKEditor?
I am able to remove other tabs like Advanced in images and and another tab in links but, I the same method is not working for link tab.

I edited config.js file like this and it worked for advanced tab:
config.removeDialogTabs = 'image:advanced';

But when I edited config.js file for link tab then it didn't work:
config.removeDialogTabs = 'image:advanced';'image:link';!

enter image description here

答:
Please take a look at config.removeDialogTabs docs. This config is case sensitive as described there, so the proper form should be:

config.removeDialogTabs = 'image:advanced;image:Link';


问:
Linking video to an HTML anchor tag
I am trying to make a website that has an anchor link to "watch the video", what I want to do is to link a video to the anchor tag and when someone clicks on the link, the video appears on the same webpage but upon webpage and behind the video, page should be lightened. Help me to figure this out.

  Watch Video
  Explore More

```

答:
You do need a video tag and also use some JavaScript.

Not sure if that what you meant, but here is a simple implemnation of what I think you meant.
href="javascript:openVideo()"

```<code>https://jsfiddle.net/awkbawgs/2/
</code>```

Title: Linking video to an HTML anchor tag

Body:
You do need a video tag and also use some JavaScript.

Not sure if that what you meant, but here is a simple implemnation of what I think you meant.
<a href="javascript:openVideo()"

https://jsfiddle.net/awkbawgs/2/


问:
Different GNU ABI Tag for same C library version?
I have two ELF binaries on my Linux machine. When I run file on them I receive the following:

File#1: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.2.0, not stripped

File#2: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.2.5, stripped

Now as far as I understand it, the for GNU/Linux 2.2.X part stems from the .note.ABI-tag section of the binary and is added by the linker. The resulting value of 2.2.X depends on the version of the C library that is linked to the binary and describes the lowest ABI version that this C library version supports - meaning that File #1 will be supported on machines with a Linux kernel >= 2.2.0 and File #2 on machines with a Linux kernel >= 2.2.5. (Is that correct, or am I already wrong here?)

I would suppose that the differences in the ABI tag would stem from two different C library versions contained in the two binaries. But when I examine the strings of the binaries, both of them contain the string glibc 2.3.2.

How is this possible? It seems unreasonable to me, that a patch of some sort to the GNU C Library which didn't result in a version number change would change the supported ABI version...

答:
The glibc ABI is supposed to be independent of the kernel version it is built for, and the test suite attempts to verify that a newly built glibc conforms to the official ABI.

The minimum kernel version required by a glibc release can be specified at glibc configure time, and this is what ends up in the .note.ABI-tag section.  No patching of the glibc sources is needed.  I'm not entirely sure whether it is correct that the configured minimum kernel version ends up in dynamically linked binaries (because it should be possible to run the binaries on older kernels with a differently built glibc).

However, for statically linked binaries, this is certainly correct because configuring a higher minimum kernel version will make the program fail to run on older kernels.


问:
jQuery - How to detect if an item is currently outside of the viewport?
I'm building a page that will be using ajax to update a main content area.  Users will be clicking on items from a left hand menu bar to update a div to the right with search results.

I want to detect if a user has scrolled down so far causing the right-hand-side results div to moved outside the viewport -- but has does one detect that?

答:
No testing/cross browser assurances/example code but take a look at $elem.offset().top vs the $(document).scrollTop() - Might be your solution.

You might need the .height() of the element and the window as well.

Brodingo in #jQuery on freenode just linked me to a Viewport Selectors plugin that might simplify it.


问:
group day of the year data by month
I have a data frame called "fish" which contains variables such as mass, length and day of the year. I need to make a boxplot of fish length by month but there is no month variable, only day of the year (i.e 1:365). How can I group days by 30 to represent month and then name them so I can make a boxplot? I have attached a screenshot of the data.

答:
I would add a new column with the full date:

```<code>as.Date(104, origin = "2014-01-01")
</code>```

and from that you can group by month.

```<code>months(as.Date(104, origin = "2014-01-01"))
</code>```

put together:

```<code>df %>% mutate(date = as.Date(day_of_the_year, origin = "2014-01-01"),
month = months(date))
</code>```

Title: group day of the year data by month

Body:
I would add a new column with the full date:

as.Date(104, origin = "2014-01-01")

and from that you can group by month.

months(as.Date(104, origin = "2014-01-01"))

put together:

df %>% mutate(date = as.Date(day_of_the_year, origin = "2014-01-01"),
month = months(date))


问:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views
I have an issue with the following error in Android:

CalledFromWrongThreadException;: Only
  the original thread that created a
  view hierarchy can touch its views

It appears to happen when I try to update a Textview in my Activity, the call to update the TextView is from within my Activity but I still get the above error.

I have it like this:

onCreate()
-sets up the buttons and the text view.

onStateChange() - a listener for notifications about state changes, when this gets notification if changes the TextView to say some different text.

When I get notification of a new text I try to change the TextView as so:

```<code>((TextView)findViewById(R.id.title)).setText("Some Text");
</code>```

But I get the above Error.

From googling it, it appears I should use a handler to change the TextView or maybe use AsyncTask?

Could anyone explain which one would be better to use and why?

EDIT: ADDED CODE SNIPPETS:

```<code>     public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

            setContentView(R.layout.my);

            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_title);

            ((TextView)findViewById(R.id.time)).setText("Hello Text");

            findViewById(R.id.keyboardimage).setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"));
                    startActivity(dialIntent);

                        dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.FLAG_SOFT_KEYBOARD));
                        dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
                }
        });

     }
</code>```

```<code>//CallBacks from running Service

private final ICallDialogActivity.Stub iCallDialogActivity = new ICallDialogActivity.Stub(){

@Override
public void onStateChanged(int callState)
                throws RemoteException {
            switch(callState){
            case GlobalData.CALL_STATUS_IDLE:

                break;

            case GlobalData.CALL_STATUS_DISCONNECTING:
                byeSetup();
                break;
    }

};
</code>```

```<code>public void byeSetup(){

            ((TextView)findViewById(R.id.time)).setText("Bye Text");

            findViewById(R.id.keyboardimage).setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    //Void the Button
                }});
}
</code>```

答:
when the change involves to the main thread (UiThread). Use it inside of another Thread to changes any view.

```<code>runOnUiThread(new Runnable() {
    @Override
    public void run() {

      // TODO your Code
        et_Pass.setText("");
    }
});
</code>```

Body:
I have an issue with the following error in Android:

CalledFromWrongThreadException;: Only
  the original thread that created a
  view hierarchy can touch its views

It appears to happen when I try to update a Textview in my Activity, the call to update the TextView is from within my Activity but I still get the above error.

I have it like this:

onCreate()
-sets up the buttons and the text view.

onStateChange() - a listener for notifications about state changes, when this gets notification if changes the TextView to say some different text.

When I get notification of a new text I try to change the TextView as so:

((TextView)findViewById(R.id.title)).setText("Some Text");

But I get the above Error.

From googling it, it appears I should use a handler to change the TextView or maybe use AsyncTask?

Could anyone explain which one would be better to use and why?

EDIT: ADDED CODE SNIPPETS:

     public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

            setContentView(R.layout.my);

            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.my_title);

            ((TextView)findViewById(R.id.time)).setText("Hello Text");

            findViewById(R.id.keyboardimage).setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"));
                    startActivity(dialIntent);

                        dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.FLAG_SOFT_KEYBOARD));
                        dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
                }
        });

     }

//CallBacks from running Service

private final ICallDialogActivity.Stub iCallDialogActivity = new ICallDialogActivity.Stub(){

@Override
public void onStateChanged(int callState)
                throws RemoteException {
            switch(callState){
            case GlobalData.CALL_STATUS_IDLE:

                break;

            case GlobalData.CALL_STATUS_DISCONNECTING:
                byeSetup();
                break;
    }

};

public void byeSetup(){

            ((TextView)findViewById(R.id.time)).setText("Bye Text");

            findViewById(R.id.keyboardimage).setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    //Void the Button
                }});
}

Body:
when the change involves to the main thread (UiThread). Use it inside of another Thread to changes any view.

runOnUiThread(new Runnable() {
    @Override
    public void run() {

      // TODO your Code
        et_Pass.setText("");
    }
});


问:
In python with pywin32, win32job, the CreateJobObject function, how do I pass NULL for the name parameter?
I'm trying to use the win32job API that is part of the PyWin32 package.  I want to do this:

```<code>win32job.CreateJobObject(None, NULL)
</code>```

I want to pass NULL as the second parameter as documented here:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682409(v=vs.85).aspx

If lpName is NULL, the job is created without a name.

How do I pass in NULL?

Here's what I hoped would work, but doesn't:

```<code>win32job.CreateJobObject(None, None)
</code>```

Error:

```<code>TypeError: None is not a valid string in this context
</code>```

(Side question... if anyone knows how to view JobObjects associated with a process in Windows, that would be helpful.)

答:
You can use win32job.CreateJobObject(None, ""). Although it isn't specified on [MS.Docs]: CreateJobObjectA function, the empty string acts just like NULL.

According to the link above:

If the function succeeds, the return value is a handle to the job object. The handle has the JOB_OBJECT_ALL_ACCESS access right. If the object existed before the function call, the function returns a handle to the existing job object and GetLastError returns ERROR_ALREADY_EXISTS.

I wrote a small C program for demonstrating purposes:

#include <Windows.h>
#include <stdio.h>

#define EMPTY_TEXT ""
#define DUMMY0_TEXT "dummy0"
#define DUMMY1_TEXT "dummy1"

#define DIM 12

int main() {
    char* names[DIM] = { NULL, NULL, EMPTY_TEXT, EMPTY_TEXT, DUMMY0_TEXT,
                         DUMMY0_TEXT, EMPTY_TEXT, DUMMY0_TEXT, DUMMY1_TEXT,
                         NULL, DUMMY0_TEXT, DUMMY1_TEXT };
    HANDLE jobs[DIM] = { NULL };
    for (int i = 0; i < DIM; i++) {
        jobs[i] = CreateJobObjectA(NULL, names[i]);
        printf("%02d [%6s] CreateJobObject: %08X - GetLastError: %d\n", i, names[i], (long)jobs[i], GetLastError());
    }
    for (int i = 0; i < DIM; i++)
        CloseHandle(jobs[i]);
    return 0;
}
```

<p><strong>Output</strong> (built and ran with <em>VStudio 2015 Community Edition</em>):</p>

<blockquote>
<pre class="lang-bat prettyprint-override"><code>00 [(null)] CreateJobObject: 000000D8 - GetLastError: 0
01 [(null)] CreateJobObject: 000000E0 - GetLastError: 0
02 [      ] CreateJobObject: 00000088 - GetLastError: 0
03 [      ] CreateJobObject: 000000F0 - GetLastError: 0
04 [dummy0] CreateJobObject: 000000F4 - GetLastError: 0
05 [dummy0] CreateJobObject: 000000F8 - GetLastError: 183
06 [      ] CreateJobObject: 000000E8 - GetLastError: 0
07 [dummy0] CreateJobObject: 000000FC - GetLastError: 183
08 [dummy1] CreateJobObject: 00000100 - GetLastError: 0
09 [(null)] CreateJobObject: 000000DC - GetLastError: 0
10 [dummy0] CreateJobObject: 000000E4 - GetLastError: 183
11 [dummy1] CreateJobObject: 00000104 - GetLastError: 183
</code>```

You can see that for "dummy0" and "dummy", every time (excepting the 1st) when creating a new object, the function does return a new HANDLE, but fails (GetLastError returns 183 (which is ERROR_ALREADY_EXISTS)). This doesn't happen for NULL and the empty string names (from here I understand that a new object is created with every call instead of incrementing an existing object's reference).

Python "translation" (code.py):

#!/usr/bin/env python3

import win32job
import win32api

DUMMY0 = "dummy00"
DUMMY1 = "dummy11"

JOB_NAMES = ["", "", DUMMY0, DUMMY0, "", DUMMY1, DUMMY0, "", DUMMY1]

if __name__ == "__main__":
    handles = list()
    for i, name in enumerate(JOB_NAMES):
        h = win32job.CreateJobObject(None, name)
        print("{} [{:10}] {} - GetLastError: {}".format(i, name, h, win32api.GetLastError()))
        handles.append(h)

    for h in handles:
        win32api.CloseHandle(h)
```

<p><strong>Output</strong> (same result as in <em>C</em>'s case - which is natural since <em>Python</em> functions only wrap the lower level <em>C</em> ones):</p>

<blockquote>
<pre class="lang-bat prettyprint-override"><code>(py35x64_test) e:\Work\Dev\StackOverflow\q046800142>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
0 [          ] <PyHANDLE:300> - GetLastError: 0
1 [          ] <PyHANDLE:308> - GetLastError: 0
2 [dummy00   ] <PyHANDLE:580> - GetLastError: 0
3 [dummy00   ] <PyHANDLE:584> - GetLastError: 183
4 [          ] <PyHANDLE:588> - GetLastError: 0
5 [dummy11   ] <PyHANDLE:592> - GetLastError: 0
6 [dummy00   ] <PyHANDLE:596> - GetLastError: 183
7 [          ] <PyHANDLE:600> - GetLastError: 0
8 [dummy11   ] <PyHANDLE:604> - GetLastError: 183
</code>```

Regarding the "side" question: unfortunately, I'm not familiar with that topic.

Body:
I'm trying to use the win32job API that is part of the PyWin32 package.  I want to do this:

win32job.CreateJobObject(None, NULL)

I want to pass NULL as the second parameter as documented here:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682409(v=vs.85).aspx

If lpName is NULL, the job is created without a name.

How do I pass in NULL?

Here's what I hoped would work, but doesn't:

win32job.CreateJobObject(None, None)

Error:

TypeError: None is not a valid string in this context

(Side question... if anyone knows how to view JobObjects associated with a process in Windows, that would be helpful.)

Body:
You can use win32job.CreateJobObject(None, ""). Although it isn't specified on [MS.Docs]: CreateJobObjectA function, the empty string acts just like NULL.

According to the link above:

If the function succeeds, the return value is a handle to the job object. The handle has the JOB_OBJECT_ALL_ACCESS access right. If the object existed before the function call, the function returns a handle to the existing job object and GetLastError returns ERROR_ALREADY_EXISTS.

I wrote a small C program for demonstrating purposes:

#include <Windows.h>
#include <stdio.h>

#define EMPTY_TEXT ""
#define DUMMY0_TEXT "dummy0"
#define DUMMY1_TEXT "dummy1"

#define DIM 12

int main() {
    char* names[DIM] = { NULL, NULL, EMPTY_TEXT, EMPTY_TEXT, DUMMY0_TEXT,
                         DUMMY0_TEXT, EMPTY_TEXT, DUMMY0_TEXT, DUMMY1_TEXT,
                         NULL, DUMMY0_TEXT, DUMMY1_TEXT };
    HANDLE jobs[DIM] = { NULL };
    for (int i = 0; i < DIM; i++) {
        jobs[i] = CreateJobObjectA(NULL, names[i]);
        printf("%02d [%6s] CreateJobObject: %08X - GetLastError: %d\n", i, names[i], (long)jobs[i], GetLastError());
    }
    for (int i = 0; i < DIM; i++)
        CloseHandle(jobs[i]);
    return 0;
}

Output (built and ran with VStudio 2015 Community Edition):

00 [(null)] CreateJobObject: 000000D8 - GetLastError: 0
01 [(null)] CreateJobObject: 000000E0 - GetLastError: 0
02 [      ] CreateJobObject: 00000088 - GetLastError: 0
03 [      ] CreateJobObject: 000000F0 - GetLastError: 0
04 [dummy0] CreateJobObject: 000000F4 - GetLastError: 0
05 [dummy0] CreateJobObject: 000000F8 - GetLastError: 183
06 [      ] CreateJobObject: 000000E8 - GetLastError: 0
07 [dummy0] CreateJobObject: 000000FC - GetLastError: 183
08 [dummy1] CreateJobObject: 00000100 - GetLastError: 0
09 [(null)] CreateJobObject: 000000DC - GetLastError: 0
10 [dummy0] CreateJobObject: 000000E4 - GetLastError: 183
11 [dummy1] CreateJobObject: 00000104 - GetLastError: 183

You can see that for "dummy0" and "dummy", every time (excepting the 1st) when creating a new object, the function does return a new HANDLE, but fails (GetLastError returns 183 (which is ERROR_ALREADY_EXISTS)). This doesn't happen for NULL and the empty string names (from here I understand that a new object is created with every call instead of incrementing an existing object's reference).

Python "translation" (code.py):

#!/usr/bin/env python3

import win32job
import win32api

DUMMY0 = "dummy00"
DUMMY1 = "dummy11"

JOB_NAMES = ["", "", DUMMY0, DUMMY0, "", DUMMY1, DUMMY0, "", DUMMY1]

if __name__ == "__main__":
    handles = list()
    for i, name in enumerate(JOB_NAMES):
        h = win32job.CreateJobObject(None, name)
        print("{} [{:10}] {} - GetLastError: {}".format(i, name, h, win32api.GetLastError()))
        handles.append(h)

    for h in handles:
        win32api.CloseHandle(h)

Output (same result as in C's case - which is natural since Python functions only wrap the lower level C ones):

(py35x64_test) e:\Work\Dev\StackOverflow\q046800142>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" code.py
0 [          ] <PyHANDLE:300> - GetLastError: 0
1 [          ] <PyHANDLE:308> - GetLastError: 0
2 [dummy00   ] <PyHANDLE:580> - GetLastError: 0
3 [dummy00   ] <PyHANDLE:584> - GetLastError: 183
4 [          ] <PyHANDLE:588> - GetLastError: 0
5 [dummy11   ] <PyHANDLE:592> - GetLastError: 0
6 [dummy00   ] <PyHANDLE:596> - GetLastError: 183
7 [          ] <PyHANDLE:600> - GetLastError: 0
8 [dummy11   ] <PyHANDLE:604> - GetLastError: 183

Regarding the "side" question: unfortunately, I'm not familiar with that topic.


问:
Jquery valid() always returns true
I am usind jquery validator to perform validation of my form. This is validator and its call:

```<code>$(document).ready(function() {
    $("#search_form").validate({
        rules:{
            templateName:{
                required: true,
            },
        },
        errorElement: "div"
    });

  $('#templateConfirmDialog').on('show.bs.modal', function (event) {
    $(this).find('.modal-yes').click(function(){
        $("#search_form").validate();
        if($("#search_form").valid()){
            alert('aaa');
        }
    })
  })

});
</code>```

This is element for validation:

```<code><input name="createTemplate.templateName" type="text" id="templateName" class="ui-widget-content ui-corner-all сriteria"/>
</code>```

Debugger goes into click() function. If I call  $("#search_form").validate() in the console, I see right parameters of my validator, but error list is empty (in case I entered nothing into attribute wit id=templateName). What is the mistake?

答:
Replace your code

```<code><input name="createTemplate.templateName" type="text" id="templateName" class="ui-widget-content ui-corner-all сriteria"/>
</code>```

to

```<code><input type="text" name="templateName" class="ui-widget-content ui-corner-all сriteria"/>
</code>```

If your code need to have same name attribute as you have in your question then try quoting your name in single quotes.

Title: Jquery valid() always returns true

Body:
I am usind jquery validator to perform validation of my form. This is validator and its call:

$(document).ready(function() {
    $("#search_form").validate({
        rules:{
            templateName:{
                required: true,
            },
        },
        errorElement: "div"
    });

  $('#templateConfirmDialog').on('show.bs.modal', function (event) {
    $(this).find('.modal-yes').click(function(){
        $("#search_form").validate();
        if($("#search_form").valid()){
            alert('aaa');
        }
    })
  })

});

This is element for validation:

<input name="createTemplate.templateName" type="text" id="templateName" class="ui-widget-content ui-corner-all сriteria"/>

Debugger goes into click() function. If I call  $("#search_form").validate() in the console, I see right parameters of my validator, but error list is empty (in case I entered nothing into attribute wit id=templateName). What is the mistake?

Body:
Replace your code

<input name="createTemplate.templateName" type="text" id="templateName" class="ui-widget-content ui-corner-all сriteria"/>

to

<input type="text" name="templateName" class="ui-widget-content ui-corner-all сriteria"/>

If your code need to have same name attribute as you have in your question then try quoting your name in single quotes.


问:
how to format time with jquery/javascript
I have a JSON feed that drupal spits out time in this format:   2010-12-16T04:41:35Z

How do I go about formating it to X minutes/hours ago?

答:
does the 04:41:35 part is correct? or do you need like to take into consideration time zones and stuff?

because basically this can work:

```<code>var str = "2010-12-16T04:41:35Z"
var arr = str.split("T")
arr[0] = arr[0].split("-")
arr[1] = (arr[1].replace(/Z/ig,"")).split(":")
var year = arr[0][0]
var month = parseInt(arr[0][1],10)-1
var day = arr[0][2]
var hours = arr[1][0]
var minutes = arr[1][1]
var seconds = arr[1][2]
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var now = (new Date())
var diffMS = now.getTime() - d.getTime()
//alert ("difference in milliseconds: " + diffMS)

var hoursago = diffMS/1000/60
var ANDminutes = (diffMS - Math.floor(hoursago) * 1000*60)/1000

alert (Math.floor(hoursago) + " hours and " + ANDminutes + " minutes ago")
</code>```

Body:
does the 04:41:35 part is correct? or do you need like to take into consideration time zones and stuff?

because basically this can work:

var str = "2010-12-16T04:41:35Z"
var arr = str.split("T")
arr[0] = arr[0].split("-")
arr[1] = (arr[1].replace(/Z/ig,"")).split(":")
var year = arr[0][0]
var month = parseInt(arr[0][1],10)-1
var day = arr[0][2]
var hours = arr[1][0]
var minutes = arr[1][1]
var seconds = arr[1][2]
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var now = (new Date())
var diffMS = now.getTime() - d.getTime()
//alert ("difference in milliseconds: " + diffMS)

var hoursago = diffMS/1000/60
var ANDminutes = (diffMS - Math.floor(hoursago) * 1000*60)/1000

alert (Math.floor(hoursago) + " hours and " + ANDminutes + " minutes ago")


问:
Smallest range of substring in string
I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ?

For example,

Input:
S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox
Q: lazy brown dog

Output: [11,15]

My code:

```<code>S = raw_input().strip().split(' ')
Q = raw_input().strip().split(' ')

count = [0 for x in range(len(Q))]
smallest_index = [0 for x in range(len(Q))]
largest_index = [0 for x in range(len(Q))]

for i in range(len(S)):
    for j in range(len(Q)):
        if S[i] == Q[j]:
            count[j] += 1
            if count[j] <= 1:
                smallest_index[j] = i
                largest_index[j] = i
            if count[j] > 1:
                largest_index[j] = i

largest_index.sort()
print "[%d," % largest_index[0],
print "%d]" % largest_index[len(Q)-1]
</code>```

答:
This code isn't particular efficient, but it does work correctly. Perhaps someone will devise a better way of processing the position information than using product. In the mean time you can use this code to test other algorithms against.

```<code>from itertools import product

def words_range(src, query):
    # Create a dict to store the word positions in src of each query word
    pos = {s: [] for s in query}
    for i, s in enumerate(src):
        if s in pos:
            pos[s].append(i)
    print(pos)

    # Find all the ranges that hold all the query word
    ranges = ((min(t), max(t)) for t in product(*pos.values()))
    # Find the smallest range
    return min(ranges, key=lambda t:t[1] - t[0])

# Test

src = '''what about the lazy brown fox that jumped over the other
brown one which lazy dog ate the food of the fox'''.split()
for i, s in enumerate(src):
    print(i, s)

query = 'lazy brown dog'.split()
print(words_range(src, query))

query = 'the lazy brown fox'.split()
print(words_range(src, query))
</code>```

output

```<code>0 what
1 about
2 the
3 lazy
4 brown
5 fox
6 that
7 jumped
8 over
9 the
10 other
11 brown
12 one
13 which
14 lazy
15 dog
16 ate
17 the
18 food
19 of
20 the
21 fox
{'lazy': [3, 14], 'brown': [4, 11], 'dog': [15]}
(11, 15)
{'the': [2, 9, 17, 20], 'lazy': [3, 14], 'brown': [4, 11], 'fox': [5, 21]}
(2, 5)
</code>```

Title: Smallest range of substring in string

Body:
I have a string S (with words indexed from 0) and a substring Q. I wish to find the smallest range [L, R] in S which contains all words in Q. There are no duplicate words in Q. How do I approach this ?

For example,

Input:
S: what about the lazy brown fox that jumped over the other brown one which lazy dog ate the food of the fox
Q: lazy brown dog

Output: [11,15]

My code:

S = raw_input().strip().split(' ')
Q = raw_input().strip().split(' ')

count = [0 for x in range(len(Q))]
smallest_index = [0 for x in range(len(Q))]
largest_index = [0 for x in range(len(Q))]

for i in range(len(S)):
    for j in range(len(Q)):
        if S[i] == Q[j]:
            count[j] += 1
            if count[j] <= 1:
                smallest_index[j] = i
                largest_index[j] = i
            if count[j] > 1:
                largest_index[j] = i

largest_index.sort()
print "[%d," % largest_index[0],
print "%d]" % largest_index[len(Q)-1]

Body:
This code isn't particular efficient, but it does work correctly. Perhaps someone will devise a better way of processing the position information than using product. In the mean time you can use this code to test other algorithms against.

from itertools import product

def words_range(src, query):
    # Create a dict to store the word positions in src of each query word
    pos = {s: [] for s in query}
    for i, s in enumerate(src):
        if s in pos:
            pos[s].append(i)
    print(pos)

    # Find all the ranges that hold all the query word
    ranges = ((min(t), max(t)) for t in product(*pos.values()))
    # Find the smallest range
    return min(ranges, key=lambda t:t[1] - t[0])

# Test

src = '''what about the lazy brown fox that jumped over the other
brown one which lazy dog ate the food of the fox'''.split()
for i, s in enumerate(src):
    print(i, s)

query = 'lazy brown dog'.split()
print(words_range(src, query))

query = 'the lazy brown fox'.split()
print(words_range(src, query))

output

0 what
1 about
2 the
3 lazy
4 brown
5 fox
6 that
7 jumped
8 over
9 the
10 other
11 brown
12 one
13 which
14 lazy
15 dog
16 ate
17 the
18 food
19 of
20 the
21 fox
{'lazy': [3, 14], 'brown': [4, 11], 'dog': [15]}
(11, 15)
{'the': [2, 9, 17, 20], 'lazy': [3, 14], 'brown': [4, 11], 'fox': [5, 21]}
(2, 5)


问:
Block commenting VB/VB.NET code
How to comment multiple lines of code/block of code in VB?</p>

答:
Select the lines you need to comment and press keys CTRL+K+C.

If you need to uncomment use CTRL+K+U

OwnerDisplayName: Pradeep

Title: Block commenting VB/VB.NET code


问:
Get values without using sessions
I am using a payment portal in which i need to define a request url in their admin panel. For eg, I need to log in their admin panel and then set my url in which the pay from xyz is. As of now my url is project/:id/contribution/id/payment_method/:type. Since my url is dynamic, i cant use this url in the admin panel but have to set some static url like domain/contirbute

The easy part of having dynamic url is i can fetch project or contribtion from params but if i have a staic url like /contribute I will have to depend upon session.

Is there a to get this done without using session?

The funny thing is that , I tired making req with my dynamic url but only after changing the url in the url bar with js but that did nt work too lol.

In the dynamic url page, i have a form which makes a post req to the url given by the payment portal. How does they know form which url is the req comming from?

答:
one way we can solve this problem is by creating two routes. One will be used to render the page which is the static url and the next one will be dynamic url. So when user submits the btn, the user will use ajax to make req with the dynamic url and the origin in the header is still preserved.

I called those payment portal and they had  a checkbox in their own admin panel which could allow to make req from dynamic url

Title: Get values without using sessions