问:
How to know jedis message has been pushed or not
I am using jedis as my Java Redis Client and using BinaryJedis class's method for lpush and rpop. I am pushing message in a queue from Jedis client and there is another redis client in nodejs which executes blocking pop to this same queue. I am not able to get all data from this pop. I want to make sure that records are successfully pushed from jedis client, how can I do that with jedis?

答: The return value from the lpush and rpush commands is the size of the list after the push is performed.  You could use a combination of the llen call (wrapped in a transaction to ensure correctness) to validate that the list is the right size after the push operation.


来源: stackexchange

问:
Paperclip video attachment error using paperclip-av-transcoder
I am making a Ruby on Rails application and am trying to allow video files to be uploaded through the application.

I'm using the paperclip gem to handle the attachment of files, paperclip-av-transcoder gem (as suggested) to handle the transcoding. I also have the aws-sdk gem installed, but that's irrelevant at the moment because I can't even get the uploading to work on my local system.

I've followed all the instructions to prepare the application to handle video uploading: I've installed necessary gems, created the actual paperclip for the Video model (I named the paperclip "film"), ran the migration, and added the association to my Video model itself. I also whitelisted the :film attribute in my video controller parameters, and I have the correct field for :film in my new video form.

When I run my local server I go to my videos#new page and fill out the form, attach the file for :film, and submit the form. It takes about 10 seconds until it loads the following error:

```<code>Av::UnableToDetect in VideosController#create
Unable to detect any supported library

Extracted source (around line #10):
  @video = Video.new(video_params)
</code>```

I have no idea what's going on here. When I look at other people who have had the exact same error message "Unable to detect any supported library", they always simply forgot to run the paperclip migration or something like that. I've followed all of those necessary steps.

Here is my :film related code in my Video.rb model

```<code>has_attached_file :film, styles: {
    :medium => {
      :geometry => "640x480",
      :format => 'mp4'
    },
    :thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}
}, :processors => [:transcoder]
validates_attachment_content_type :film, content_type: /\Avideo\/.*\Z/
</code>```

and here's my strong parameters in my videos_controller

```<code>def video_params
  params.require(:video).permit(:title, :description, :film, :preview_image,
                          award_attributes: [:id, :title, :body, :award_image])
end
</code>```

And here is the database schema relevant to my video model. Preview image is a separate paperclip (its an image), which I've had for a few weeks and it works completely fine.

```<code>create_table "videos", force: :cascade do |t|
    t.string   "title"
    t.string   "description"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.string   "preview_image_file_name"
    t.string   "preview_image_content_type"
    t.integer  "preview_image_file_size"
    t.datetime "preview_image_updated_at"
    t.string   "film_file_name"
    t.string   "film_content_type"
    t.integer  "film_file_size"
    t.datetime "film_updated_at"
  end
</code>```

I also have a feeling it may have something to do with my gems, here's my gemfile:

```<code>gem 'paperclip', :git=> 'https://github.com/thoughtbot/paperclip', :ref => '523bd46c768226893f23889079a7aa9c73b57d68'
gem 'aws-sdk'
gem 'paperclip-av-transcoder'
</code>```

I've already tried it with just the plain 'paperclip' gem, with no reference to git. It still doesn't work

Thanks in advance for any help you all can give me!

答:
```<code>Av::UnableToDetect in VideosController#create
Unable to detect any supported library
</code>```

Means you don't have ffmpeg installed. This library is used by paperclip-av to transcode your vide.
If you're on macOS, go to your terminal and install it (I'm using homebrew):

```<code>brew install ffmpeg
</code>```

--

Chances are that you will encounter the same problem when deploying to remote server, such as Heroku... If that is the case, then you have to add ffmepg using buildpacks. Make sure to read how to do so in the Heroku Devcenter

ContentLicense: CC BY-SA 3.0

Body:
I am making a Ruby on Rails application and am trying to allow video files to be uploaded through the application.

I'm using the paperclip gem to handle the attachment of files, paperclip-av-transcoder gem (as suggested) to handle the transcoding. I also have the aws-sdk gem installed, but that's irrelevant at the moment because I can't even get the uploading to work on my local system.

I've followed all the instructions to prepare the application to handle video uploading: I've installed necessary gems, created the actual paperclip for the Video model (I named the paperclip "film"), ran the migration, and added the association to my Video model itself. I also whitelisted the :film attribute in my video controller parameters, and I have the correct field for :film in my new video form.

When I run my local server I go to my videos#new page and fill out the form, attach the file for :film, and submit the form. It takes about 10 seconds until it loads the following error:

Av::UnableToDetect in VideosController#create
Unable to detect any supported library

Extracted source (around line #10):
  @video = Video.new(video_params)

I have no idea what's going on here. When I look at other people who have had the exact same error message "Unable to detect any supported library", they always simply forgot to run the paperclip migration or something like that. I've followed all of those necessary steps.

Here is my :film related code in my Video.rb model

has_attached_file :film, styles: {
    :medium => {
      :geometry => "640x480",
      :format => 'mp4'
    },
    :thumb => { :geometry => "160x120", :format => 'jpeg', :time => 10}
}, :processors => [:transcoder]
validates_attachment_content_type :film, content_type: /\Avideo\/.*\Z/

and here's my strong parameters in my videos_controller

def video_params
  params.require(:video).permit(:title, :description, :film, :preview_image,
                          award_attributes: [:id, :title, :body, :award_image])
end

And here is the database schema relevant to my video model. Preview image is a separate paperclip (its an image), which I've had for a few weeks and it works completely fine.

create_table "videos", force: :cascade do |t|
    t.string   "title"
    t.string   "description"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
    t.string   "preview_image_file_name"
    t.string   "preview_image_content_type"
    t.integer  "preview_image_file_size"
    t.datetime "preview_image_updated_at"
    t.string   "film_file_name"
    t.string   "film_content_type"
    t.integer  "film_file_size"
    t.datetime "film_updated_at"
  end

I also have a feeling it may have something to do with my gems, here's my gemfile:

gem 'paperclip', :git=> 'https://github.com/thoughtbot/paperclip', :ref => '523bd46c768226893f23889079a7aa9c73b57d68'
gem 'aws-sdk'
gem 'paperclip-av-transcoder'

I've already tried it with just the plain 'paperclip' gem, with no reference to git. It still doesn't work

Thanks in advance for any help you all can give me!

Body:
Av::UnableToDetect in VideosController#create
Unable to detect any supported library

Means you don't have ffmpeg installed. This library is used by paperclip-av to transcode your vide.
If you're on macOS, go to your terminal and install it (I'm using homebrew):

brew install ffmpeg

--

Chances are that you will encounter the same problem when deploying to remote server, such as Heroku... If that is the case, then you have to add ffmepg using buildpacks. Make sure to read how to do so in the Heroku Devcenter


问:
How to capture windows command result from Start-Process?

$features = Start-Process powershell -Verb runAs -ArgumentList "Get-WindowsOptionalFeature –Online"
$features

How can I get the result back into my $feature variable?

答:
Quick & dirty workaround: you can use temporary clixml file to store results of Get-WindowsOptionalFeature cmdlet:</p>

```<code>$tempFile = [System.IO.Path]::GetTempFileName()
try
{
    Start-Process powershell -Wait -Verb runAs -ArgumentList "-Command Get-WindowsOptionalFeature -Online | Export-Clixml -Path $tempFile"

    $features = Import-Clixml -Path $tempFile

    # Use $features
}
finally
{
    if (Test-Path $tempFile)
    {
        Remove-Item -Path $tempFile -Force -ErrorAction Ignore
    }
}
</code>```

Body:
Quick & dirty workaround: you can use temporary clixml file to store results of Get-WindowsOptionalFeature cmdlet:

$tempFile = [System.IO.Path]::GetTempFileName()
try
{
    Start-Process powershell -Wait -Verb runAs -ArgumentList "-Command Get-WindowsOptionalFeature -Online | Export-Clixml -Path $tempFile"

    $features = Import-Clixml -Path $tempFile

    # Use $features
}
finally
{
    if (Test-Path $tempFile)
    {
        Remove-Item -Path $tempFile -Force -ErrorAction Ignore
    }
}


问:
How to animate a floating UIView in ObjectiveC
I am trying to have a UIView animate as a floating object, or as a Balloon :D
The UIView is in the middle of the screen, and I want it to keep floating randomly around its first initiated spot. Not across the screen or anything like that, just floating in the area of 5 pixels around it.

Any suggestions? :D

I tried this:

```<code>[UIView animateWithDuration:0.1
                      delay:0.0
                    options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]);
                 }
                 completion:NULL];
</code>```

randomFloatingGenerator generates a number between -5 and 5. Problem is, it only executes once, and keeps repeating with the same random values.

EDIT1:
Now I have tried This

```<code>-(void)animationLoop{

[UIView animateWithDuration:1.0
                     animations: ^{ myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]); }
                     completion:
     ^(BOOL finished) {
         [UIView animateWithDuration:1.0
                          animations:^{ myCircleUIView.transform = CGAffineTransformMakeTranslation(0,0);
                          }
                          completion:
          ^(BOOL finished) {[self animationLoop];}];
     }];
</code>```

But it is still not working, the animation is.... Cracky... I think I am doing some stupid mistake that I need a second set of eyes to help me with.

EDIT2:
Fixed it.

```<code> -(void)animationLoop{
    CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
    [UIView animateWithDuration:1.0
                     animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
                     completion:
     ^(BOOL finished) {
         [UIView animateWithDuration:1.0
                          animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
                          completion:
          ^(BOOL finished) {[self animationLoop];}];
     }];
}
</code>```

Thanks for the help anyone.

EDIT 3:

Someone posted an enhanced code.

答:
Swift 3.1:

```<code>func animateFloatView(_ view: UIView?) {
    guard let view = view else { return }
    let oldYCoordinate = view.center.y

    UIView.animate(withDuration: 0.6, animations: {
        view.center.y -= 15
    }, completion: { _ in
        UIView.animate(withDuration: 0.6, animations: {
            view.center.y = oldYCoordinate
        }, completion: { _ in
            self.animateFloatView(view)
        })
    })
}
</code>```

Body:
I am trying to have a UIView animate as a floating object, or as a Balloon :D
The UIView is in the middle of the screen, and I want it to keep floating randomly around its first initiated spot. Not across the screen or anything like that, just floating in the area of 5 pixels around it.

Any suggestions? :D

I tried this:

[UIView animateWithDuration:0.1
                      delay:0.0
                    options: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse | UIViewAnimationOptionAllowUserInteraction
                 animations:^{
                     myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]);
                 }
                 completion:NULL];

randomFloatingGenerator generates a number between -5 and 5. Problem is, it only executes once, and keeps repeating with the same random values.

EDIT1:
Now I have tried This

-(void)animationLoop{

[UIView animateWithDuration:1.0
                     animations: ^{ myCircleUIView.transform = CGAffineTransformMakeTranslation([self randomFloatingGenerator], [self randomFloatingGenerator]); }
                     completion:
     ^(BOOL finished) {
         [UIView animateWithDuration:1.0
                          animations:^{ myCircleUIView.transform = CGAffineTransformMakeTranslation(0,0);
                          }
                          completion:
          ^(BOOL finished) {[self animationLoop];}];
     }];

But it is still not working, the animation is.... Cracky... I think I am doing some stupid mistake that I need a second set of eyes to help me with.

EDIT2:
Fixed it.

 -(void)animationLoop{
    CGPoint oldPoint = CGPointMake(myCircleUIView.frame.origin.x, myCircleUIView.frame.origin.y);
    [UIView animateWithDuration:1.0
                     animations: ^{ myCircleUIView.frame = CGRectMake(myCircleUIView.frame.origin.x + [self randomFloatingGenerator], myCircleUIView.frame.origin.y + [self randomFloatingGenerator], myCircleUIView.frame.size.width, myCircleUIView.frame.size.height); }
                     completion:
     ^(BOOL finished) {
         [UIView animateWithDuration:1.0
                          animations:^{ myCircleUIView.frame = CGRectMake(oldPoint.x, oldPoint.y, myCircleUIView.frame.size.width, myCircleUIView.frame.size.height);}
                          completion:
          ^(BOOL finished) {[self animationLoop];}];
     }];
}

Thanks for the help anyone.

EDIT 3:

Someone posted an enhanced code.

Body:
Swift 3.1:

func animateFloatView(_ view: UIView?) {
    guard let view = view else { return }
    let oldYCoordinate = view.center.y

    UIView.animate(withDuration: 0.6, animations: {
        view.center.y -= 15
    }, completion: { _ in
        UIView.animate(withDuration: 0.6, animations: {
            view.center.y = oldYCoordinate
        }, completion: { _ in
            self.animateFloatView(view)
        })
    })
}


问:
julia floating point compare for zero
```<code>julia> r
3×3 Array{Float64,2}:
 -1.77951  -0.79521   -2.57472
  0.0       0.630793   0.630793
  0.0       0.0       -1.66533e-16

julia> sort(abs(diag(r)))[1]
1.6653345369377348e-16

julia> isequal(floor(sort(abs(diag(r)))[1]),0)
true
</code>```

But this is not right

```<code>julia> isequal(sort(abs(diag(r)))[1],convert(AbstractFloat,0.0))
false
</code>```

Is there a function in Julia to check for floating point equivalent to zero?

答:
-1.66533e-16 is not equivalent to zero. It is, however, approximately equivalent to zero (with respect to a particular tolerance), and julia does provide just such a function:

```<code>isapprox(1e-16, 0.0; atol=1e-15, rtol=0)
</code>```

edit: or as Chris pointed out, a good choice for atol is eps() which corresponds to machine precision for that particular type:

```<code>julia> isapprox(1e-20, 0.0; atol=eps(Float64), rtol=0)
true
</code>```

Do read the description for isapprox to see what the default arguments mean, and to see if you prefer an "absolute" or "relative" tolerance approach (or a mixed approach). Though for a comparison to zero specifically, using an absolute tolerance is fine and probably more intuitive.

Title: julia floating point compare for zero

Body:
julia> r
3×3 Array{Float64,2}:
 -1.77951  -0.79521   -2.57472
  0.0       0.630793   0.630793
  0.0       0.0       -1.66533e-16

julia> sort(abs(diag(r)))[1]
1.6653345369377348e-16

julia> isequal(floor(sort(abs(diag(r)))[1]),0)
true

But this is not right

julia> isequal(sort(abs(diag(r)))[1],convert(AbstractFloat,0.0))
false

Is there a function in Julia to check for floating point equivalent to zero?

Body:
-1.66533e-16 is not equivalent to zero. It is, however, approximately equivalent to zero (with respect to a particular tolerance), and julia does provide just such a function:

isapprox(1e-16, 0.0; atol=1e-15, rtol=0)

edit: or as Chris pointed out, a good choice for atol is eps() which corresponds to machine precision for that particular type:

julia> isapprox(1e-20, 0.0; atol=eps(Float64), rtol=0)
true

Do read the description for isapprox to see what the default arguments mean, and to see if you prefer an "absolute" or "relative" tolerance approach (or a mixed approach). Though for a comparison to zero specifically, using an absolute tolerance is fine and probably more intuitive.


问:
Only prints the last server in the list, I want all servers
This only prints the last server in the list, I'm looking to get all servers and print to screen </p>

```<code>$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status
</code>```

答:
Here is a more PowerShell-like approach (not tested):</p>

```<code>Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | ForEach-Object {
  $machineName = $_.DNSName
  [PSCustomObject] @{
    "MachineName"     = $machineName
    "MaintenanceMode" = (Get-BrokerMachine -HostedMachineName $machine).InMaintenanceMode
  }
} | Export-Csv "C:\whatever\results.csv" -NoTypeInformation
</code>```

Body:
This only prints the last server in the list, I'm looking to get all servers and print to screen

$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status

Body:
Here is a more PowerShell-like approach (not tested):

Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | ForEach-Object {
  $machineName = $_.DNSName
  [PSCustomObject] @{
    "MachineName"     = $machineName
    "MaintenanceMode" = (Get-BrokerMachine -HostedMachineName $machine).InMaintenanceMode
  }
} | Export-Csv "C:\whatever\results.csv" -NoTypeInformation


问:
How can below template class be generalized to call any function?
```<code>#include <map>
#include <functional>

template<typename... Args>
class Listner {
public:
    template<typename T>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(reinterpret_cast<void*>(t), [&t](Args... args){t->callback(args...); }));
    }

    template<typename T>
    void detachListner(T *t) {
        m_listenerCallbacks.erase(reinterpret_cast<void*>(t));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }
private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};
</code>```

Using above Listner class I am able to register objects which has a public method named callback. Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

答:
Here is a possible solution based on the example code that might work for you:

```<code>#include <map>
#include <functional>

template<typename>
struct Listner;

template<typename R, typename... Args>
struct Listner<R(Args...)> {
    template<typename T, R(T::*M)(Args...) = &T::callback>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(static_cast<void*>(t), [t](Args... args){ (t->*M)(args...); }));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }

private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};

struct A {
    void f(int, char) {}
    void f(int, double) {}
    void f(int) {}
};

int main() {
    A a;
    Listner<void(int, char)> l;
    l.attachListner<A, &A::f>(&a);
    l.notify(0, 'c');
}
</code>```

The basic idea is that you must specify the function type entirely (see Listner<void(int, char)>). The sole parameters list isn't enough.

We can do it with a partial specialization of a class template as:

```<code>template<typename>
struct Listner;

template<typename R, typename... Args>
struct Listner<R(Args...)> {
    // ...
};
</code>```

Once you did it, we can use that type to detect the right overload as a template parameter:

```<code>template<typename T, R(T::*M)(Args...) = &T::callback>
void attachListner(T *t) {
    // ...
}
</code>```

Note that I put a default (&T::callback) so that you can invoke it either as:

```<code>l.attachListner<A, &A::f>(&a);
</code>```

If you want to use a different member function, or as:

```<code>l.attachListner(&a);
</code>```

If A has a member method named callback and you want to use it as it was before.

Body:
#include <map>
#include <functional>

template<typename... Args>
class Listner {
public:
    template<typename T>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(reinterpret_cast<void*>(t), [&t](Args... args){t->callback(args...); }));
    }

    template<typename T>
    void detachListner(T *t) {
        m_listenerCallbacks.erase(reinterpret_cast<void*>(t));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }
private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};

Using above Listner class I am able to register objects which has a public method named callback. Is it possible to generalize Listner class in such a way that the method name (callback) can also passed as template argument.

Body:
Here is a possible solution based on the example code that might work for you:

#include <map>
#include <functional>

template<typename>
struct Listner;

template<typename R, typename... Args>
struct Listner<R(Args...)> {
    template<typename T, R(T::*M)(Args...) = &T::callback>
    void attachListner(T *t) {
        m_listenerCallbacks.insert(std::make_pair(static_cast<void*>(t), [t](Args... args){ (t->*M)(args...); }));
    }

    void notify(Args... args) {
        for (auto l : m_listenerCallbacks)
            l.second(args...);
    }

private:
    std::map<void*, std::function<void(Args...)>> m_listenerCallbacks;
};

struct A {
    void f(int, char) {}
    void f(int, double) {}
    void f(int) {}
};

int main() {
    A a;
    Listner<void(int, char)> l;
    l.attachListner<A, &A::f>(&a);
    l.notify(0, 'c');
}

The basic idea is that you must specify the function type entirely (see Listner<void(int, char)>). The sole parameters list isn't enough.

We can do it with a partial specialization of a class template as:

template<typename>
struct Listner;

template<typename R, typename... Args>
struct Listner<R(Args...)> {
    // ...
};

Once you did it, we can use that type to detect the right overload as a template parameter:

template<typename T, R(T::*M)(Args...) = &T::callback>
void attachListner(T *t) {
    // ...
}

Note that I put a default (&T::callback) so that you can invoke it either as:

l.attachListner<A, &A::f>(&a);

If you want to use a different member function, or as:

l.attachListner(&a);

If A has a member method named callback and you want to use it as it was before.


问:
(Android) Camera Capture not saving, can't load bitmap of image
I'm trying to write code that launches the camera app, saves the image, and then displays a bitmap of the captured image.

This is the relevant code, which was adapted from https://guides.codepath.com/android/Accessing-the-Camera-and-Stored-Media:

```<code>    public static final int PICTURE_REQUEST_CODE = 1034;
    public static final String FILE_BEGIN = "note";
    private int note_id = 4;
    public static final String FILE_END = ".jpg";
    private static final String APP_TAG = "School_App";

    private void takePicture() {
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri(FILE_BEGIN + note_id + FILE_END));
    if (i.resolveActivity(getPackageManager()) != null){
        startActivityForResult(i, PICTURE_REQUEST_CODE);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICTURE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Uri takenPhotoUri = getPhotoFileUri(FILE_BEGIN + note_id + FILE_END);
            Log.d("NotesDetail", takenPhotoUri.toString());
            // by this point we have the camera photo on disk
            Bitmap takenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
            // RESIZE BITMAP, see section below
            // Load the taken image into a preview
            ImageView ivPreview = (ImageView) findViewById(R.id.iv_notes_picture);
            ivPreview.setImageBitmap(takenImage);
        } else { // Result was a failure
            Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
        }
    }
}

private Uri getPhotoFileUri(String fileName) {
    if(isSpaceAvailable()){
        File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);

        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
           Log.d(APP_TAG, "Failed to make directory");
        }

        File file = new File(mediaStorageDir.getPath() + File.separator + fileName);

        Uri uri = FileProvider.getUriForFile(NotesDetail.this, "com.kfode.schoolapp.fileprovider", file);
        Log.d("getPhotoFileUri", uri.toString());
        return uri;
    }
    return null;
}

private boolean isSpaceAvailable() {
    String state = Environment.getExternalStorageState();
    return state.equals(Environment.MEDIA_MOUNTED);
}
</code>```

I also have the following permissions set:

```<code>    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</code>```

Within the application tag of the manifest...

```<code>    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.kfode.schoolapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"
            />
    </provider>
</code>```

And within the file_paths.xml

```<code>    <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="images"
    path="Pictures"/>
</code>```

When I run the app, I get the following log messages and exception:

```<code>D/getPhotoFileUri: content://com.kfode.schoolapp.fileprovider/images/School_App/note4.jpg
D/NotesDetail: content://com.kfode.schoolapp.fileprovider/images/School_App/note4.jpg
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /images/School_App/note4.jpg: open failed: ENOENT (No such file or directory)
</code>```

Not sure what is going on here. Help please?

答:
```<code>Bitmap takenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
</code>```

This will not work. A Uri is not a File.

Refactor getPhotoFileUri() into two methods:

getPhotoFile() that generates your File

getPhotoFileUri() that obtains the FileProvider Uri for that File

Then, use an image-loading library (Glide, Picasso, etc.) to populate your ImageView from the file returned by getPhotoFile(). This not only will handle all the BitmapFactory stuff for you, but it will also do that work on a background thread, so you do not freeze your UI the way you are in your current code.

Body:
I'm trying to write code that launches the camera app, saves the image, and then displays a bitmap of the captured image.

This is the relevant code, which was adapted from https://guides.codepath.com/android/Accessing-the-Camera-and-Stored-Media:

    public static final int PICTURE_REQUEST_CODE = 1034;
    public static final String FILE_BEGIN = "note";
    private int note_id = 4;
    public static final String FILE_END = ".jpg";
    private static final String APP_TAG = "School_App";

    private void takePicture() {
    Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri(FILE_BEGIN + note_id + FILE_END));
    if (i.resolveActivity(getPackageManager()) != null){
        startActivityForResult(i, PICTURE_REQUEST_CODE);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICTURE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Uri takenPhotoUri = getPhotoFileUri(FILE_BEGIN + note_id + FILE_END);
            Log.d("NotesDetail", takenPhotoUri.toString());
            // by this point we have the camera photo on disk
            Bitmap takenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
            // RESIZE BITMAP, see section below
            // Load the taken image into a preview
            ImageView ivPreview = (ImageView) findViewById(R.id.iv_notes_picture);
            ivPreview.setImageBitmap(takenImage);
        } else { // Result was a failure
            Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
        }
    }
}

private Uri getPhotoFileUri(String fileName) {
    if(isSpaceAvailable()){
        File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);

        if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
           Log.d(APP_TAG, "Failed to make directory");
        }

        File file = new File(mediaStorageDir.getPath() + File.separator + fileName);

        Uri uri = FileProvider.getUriForFile(NotesDetail.this, "com.kfode.schoolapp.fileprovider", file);
        Log.d("getPhotoFileUri", uri.toString());
        return uri;
    }
    return null;
}

private boolean isSpaceAvailable() {
    String state = Environment.getExternalStorageState();
    return state.equals(Environment.MEDIA_MOUNTED);
}

I also have the following permissions set:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Within the application tag of the manifest...

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.kfode.schoolapp.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"
            />
    </provider>

And within the file_paths.xml

    <paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="images"
    path="Pictures"/>

When I run the app, I get the following log messages and exception:

D/getPhotoFileUri: content://com.kfode.schoolapp.fileprovider/images/School_App/note4.jpg
D/NotesDetail: content://com.kfode.schoolapp.fileprovider/images/School_App/note4.jpg
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /images/School_App/note4.jpg: open failed: ENOENT (No such file or directory)

Not sure what is going on here. Help please?

Body:
Bitmap takenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());

This will not work. A Uri is not a File.

Refactor getPhotoFileUri() into two methods:

getPhotoFile() that generates your File

getPhotoFileUri() that obtains the FileProvider Uri for that File

Then, use an image-loading library (Glide, Picasso, etc.) to populate your ImageView from the file returned by getPhotoFile(). This not only will handle all the BitmapFactory stuff for you, but it will also do that work on a background thread, so you do not freeze your UI the way you are in your current code.


问:
how do I move html pages to a new project/war file?
Suppose my existing Java project (that also has some JavaScript code) is named UI and has subdirs Func1 and Func2, each of which have some JavaScript files containing functions with parameters named 'url' and values of webpages within the UI project called things like 'resources/html/docs/myPage1.html' etc.  ie, each of Func1 and Func2 have a resources/html subdirs with lots of different directories to organize their various webdocs.

Now suppose that I want to create a new project (at the UI) level called something like DOCS in which to consolidate all of the various html pages.  ie, my project has grown to the point where I want to deploy a separate war in Tomcat to just warehouse all my html pages so that I can manage the documentation separately from the actual source code files that point to them.

How can I do this?  I created a new DOCS project in my git repo and moved over all of the html pages from, say, UI/Func1/resources/html/docs/page1.html to the new location of DOCS/Func1/resources/html/docs/page1.html.  But, how can the JavaScript programs that still live in places like UI/Func1/src/main/webapp/view/MyJS1.js be updated to cross a project domain boundary so that Tomcat can find the page pointed to in various function's url parameters in the new war file I'll build and deploy?  Is there some maven pom magic to help make this happen?

TIA,

答:
It turns out that there is some maven magic to make this work.  In the new project's pom:

```<code><plugin>
   <artifactId>maven-war-plugin</artifcatId>
   <version>2.4</version>
   <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      <webResources>
         <resource>
            <directory>webapp</directory>
         </resource>
      </webResources>
   </configuration>
</plugin>
</code>```

The JavaScript parameters were thus changed to http://localhost:8555/webdocs-0.0.1-SNAPSHOT/resources/html/docs/myPage1.html.  And, setting a JS property for the prefix of these url's cleans things up nicely once the new warfile is built and tossed in the webapp directory.

Body:
It turns out that there is some maven magic to make this work.  In the new project's pom:

<plugin>
   <artifactId>maven-war-plugin</artifcatId>
   <version>2.4</version>
   <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      <webResources>
         <resource>
            <directory>webapp</directory>
         </resource>
      </webResources>
   </configuration>
</plugin>

The JavaScript parameters were thus changed to http://localhost:8555/webdocs-0.0.1-SNAPSHOT/resources/html/docs/myPage1.html.  And, setting a JS property for the prefix of these url's cleans things up nicely once the new warfile is built and tossed in the webapp directory.


问:
Remove duplicates from array, convert to array of objects and add duplicate count property
I have an array of strings:

```<code>var array = ['bob', 'charlie', 'bob', 'bob'];
</code>```

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

```<code>var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];
</code>```

How can I do that?

答:
Ecmascript5 solution using Array.prototype.reduce() function:

var arr = ['bob', 'charlie', 'bob', 'bob'],
    counts = arr.reduce(function(r,s){
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}),
    result = Object.keys(counts).map(function(k){ return counts[k]; });

console.log(result);```
</div>
</div>
</p>

<hr>

<p><strong><em>Ecmascript6</em></strong> version (with Object.values() function):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ['bob', 'charlie', 'bob', 'bob'],
    result = Object.values(arr.reduce((r,s) => {
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}));

console.log(result);</code>```

Body:
I have an array of strings:

var array = ['bob', 'charlie', 'bob', 'bob'];

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];

How can I do that?

Body:
Ecmascript5 solution using Array.prototype.reduce() function:

var arr = ['bob', 'charlie', 'bob', 'bob'],
    counts = arr.reduce(function(r,s){
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}),
    result = Object.keys(counts).map(function(k){ return counts[k]; });

console.log(result);

Ecmascript6 version (with Object.values() function):

var arr = ['bob', 'charlie', 'bob', 'bob'],
    result = Object.values(arr.reduce((r,s) => {
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}));

console.log(result);


问:
ExtJS 6 Use custom filter function within memory proxy
I have a store configured with memory proxy with enablePaging: true. Store's remoteFilter and remoteSort set to true so filtering and sorting requests handled by proxy.

When I filter my store by multiple fields I want to use OR condition, not AND.

Without memory proxy paging I could use remoteFilter: false and custom filter function like:

```<code>store.filterBy(function (record)
{
    for (var i = 0; i < searchFields.length; ++i) {
        if (record.get(searchFields[i]).toLowerCase().indexOf(searchText) !== -1) {
            return true;
        }
    }
    return false;
});
</code>```

But how I can achieve this with enabled paging? Override memory proxy?

答:
Ext.data.proxy.Memory.read use Ext.util.Filter.createFilterFn to create a filter function based on passed Ext.util.Filter[] (with property-value configs):

```<code>// Filter the resulting array of records
if (filters && filters.length) {
    // Total will be updated by setting records
    resultSet.setRecords(records = Ext.Array.filter(records, Ext.util.Filter.createFilterFn(filters)));
    resultSet.setTotal(records.length);
}
</code>```

So, if you want to use different filter logic, you can override memroy proxy read method and use custom function to create filter function:

```<code>Ext.define('MyApp.extensions.FilterMemoryProxy', {
    extend: 'Ext.data.proxy.Memory',
    alias: 'proxy.filtermemory',

    createCustomFilterFn: function (filters)
    {
        if (!filters) {
            return Ext.returnTrue;
        }
        return function (candidate)
        {
            var items = filters.isCollection ? filters.items : filters,
                length = items.length,
                i, filter;
            for (i = 0; i < length; i++) {
                filter = items[i];
                if (!filter.getDisabled() && candidate.get(filter.getProperty()).toLowerCase().indexOf(
                        filter.getValue().toLowerCase()) !== -1) {
                    return true;
                }
            }
            return false;
        };
    },

    read: function (operation)
    {

        ...

        if (operation.process(resultSet, null, null, false) !== false) {
            // Filter the resulting array of records
            if (filters && filters.length) {
                // Total will be updated by setting records
                resultSet.setRecords(records = Ext.Array.filter(records, me.createCustomFilterFn(filters)));
                resultSet.setTotal(records.length);
            }

        ...

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

Body:
I have a store configured with memory proxy with enablePaging: true. Store's remoteFilter and remoteSort set to true so filtering and sorting requests handled by proxy.

When I filter my store by multiple fields I want to use OR condition, not AND.

Without memory proxy paging I could use remoteFilter: false and custom filter function like:

store.filterBy(function (record)
{
    for (var i = 0; i < searchFields.length; ++i) {
        if (record.get(searchFields[i]).toLowerCase().indexOf(searchText) !== -1) {
            return true;
        }
    }
    return false;
});

But how I can achieve this with enabled paging? Override memory proxy?

Body:
Ext.data.proxy.Memory.read use Ext.util.Filter.createFilterFn to create a filter function based on passed Ext.util.Filter[] (with property-value configs):

// Filter the resulting array of records
if (filters && filters.length) {
    // Total will be updated by setting records
    resultSet.setRecords(records = Ext.Array.filter(records, Ext.util.Filter.createFilterFn(filters)));
    resultSet.setTotal(records.length);
}

So, if you want to use different filter logic, you can override memroy proxy read method and use custom function to create filter function:

Ext.define('MyApp.extensions.FilterMemoryProxy', {
    extend: 'Ext.data.proxy.Memory',
    alias: 'proxy.filtermemory',

    createCustomFilterFn: function (filters)
    {
        if (!filters) {
            return Ext.returnTrue;
        }
        return function (candidate)
        {
            var items = filters.isCollection ? filters.items : filters,
                length = items.length,
                i, filter;
            for (i = 0; i < length; i++) {
                filter = items[i];
                if (!filter.getDisabled() && candidate.get(filter.getProperty()).toLowerCase().indexOf(
                        filter.getValue().toLowerCase()) !== -1) {
                    return true;
                }
            }
            return false;
        };
    },

    read: function (operation)
    {

        ...

        if (operation.process(resultSet, null, null, false) !== false) {
            // Filter the resulting array of records
            if (filters && filters.length) {
                // Total will be updated by setting records
                resultSet.setRecords(records = Ext.Array.filter(records, me.createCustomFilterFn(filters)));
                resultSet.setTotal(records.length);
            }

        ...

        }
    }
});


问:
Converting HTML content to PDF file using jsPDF
Trying to automatically convert this  content to a pdf file. Based on how the rest of my code is setup, I have to have the button to click INSIDE the div that I want to export to pdf. Is this a problem? Here's what I have so far. When I click the button, it does nothing.

JS:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>

<script>
jQuery('#generatereport').click(function () {
    doc.fromHTML(jQuery('#lppresults').html(), 15, 15, {
        'width': 170
    });
    doc.save('sample-file.pdf');
});
</script>
</code>```

HTML:

```<code><div class="survey-results" style="display: none;" id="lppresults">
   <button id="generatereport">Download Report</button>
   TEST CONTENT
</div>
</code>```

答:
No, this is not a problem. You can have the button inside the div element. Though you have some other issues. Here is the revised version of your code ...

var doc = new jsPDF();
$('#generatereport').click(function() {
   doc.fromHTML($('#lppresults')[0], 15, 15, {
      width: 170
   }, function() {
      doc.save('sample-file.pdf');
   });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

<div class="survey-results" id="lppresults">
  <button id="generatereport">Download Report</button> TEST CONTENT
</div></code>```

Body:
Trying to automatically convert this  content to a pdf file. Based on how the rest of my code is setup, I have to have the button to click INSIDE the div that I want to export to pdf. Is this a problem? Here's what I have so far. When I click the button, it does nothing.

JS:

HTML:

   <button id="generatereport">Download Report</button>
   TEST CONTENT

Body:
No, this is not a problem. You can have the button inside the div element. Though you have some other issues. Here is the revised version of your code ...

var doc = new jsPDF();
$('#generatereport').click(function() {
   doc.fromHTML($('#lppresults')[0], 15, 15, {
      width: 170
   }, function() {
      doc.save('sample-file.pdf');
   });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

<div class="survey-results" id="lppresults">
  <button id="generatereport">Download Report</button> TEST CONTENT
</div>


问:
[Ruby on Rails]Redirect to RESTful URL
I am working on a movie rails project and I have to redirect the url to be RESTful, but I have no idea how to make it done. The following information may be useful:

I fail to: GET /movies when selecting a movie rating should redirect to a RESTful route

rake routes:

Prefix Verb   URI Pattern                Controller#Action
      root GET    /                          movies#index
    movies GET    /movies(.:format)          movies#index
           POST   /movies(.:format)          movies#create
 new_movie GET    /movies/new(.:format)      movies#new
edit_movie GET    /movies/:id/edit(.:format) movies#edit
     movie GET    /movies/:id(.:format)      movies#show
           PATCH  /movies/:id(.:format)      movies#update
           PUT    /movies/:id(.:format)      movies#update
           DELETE /movies/:id(.:format)      movies#destroy

The UI of the webpage

Some descriptions of what I have to do: (generally saying if the user intentionally deletes some attributes from the url, I have redirect it to the correct url):

To be RESTful, we want to preserve the property that a URI that results in a sorted/filtered view always contains the corresponding sorting/filtering parameters.

The code I have implemented to do the task:

```<code>if !(params.has_key?(:sort_by))  #check the url has this parameter
  if session[:sort_by]           #has cookie
    redirect_to movies_path(:sort_by => session[:sort_by]) #redirect using cookie, not sure need to add :ratings
  else
    session[:sort_by] = "id"    # default sorting
  end
end

if !(params.has_key?(:ratings))
  if session[:ratings]
    redirect_to movies_path(:ratings => session[:ratings]) # error: AbstractController::DoubleRenderError
  else
    session[:rating] = {"G"=>"1", "PG"=>"1", "PG-13"=>"1", "R"=>"1"}
  end
end
</code>```

:sort_by is the attribute to control how is the movies sorted, e.g. session[:sort_by] = "date" means sorted on the release date.

:ratings is something like: "ratings"=>{"G"=>"1", "PG-13"=>"1", "R"=>"1"}

An example of URL: /movies?ratings%5BG%5D=1&ratings%5BPG%5D=1&ratings%5BPG-13%5D=1&ratings%5BR%5D=1&sort_by=title

if I type something like .../movies, the url should be generated from cookie(if any). But I am having some problems:

for example we check that sort_by is missing, and there is session for sort_by, do we still need to supply session[:ratings] to movies_path()? And what to do if it is the first time I come to this website (no session[:ratings]/session[:sort_by]) but I still need the RESTful URL(all checked boxes are 'clicked' by default)

Some more instructions:

So you should redirect when parameters are missing in URL, instead of in URL + session.
It means that when ‘sort_by’ is not in the URL, but in the session, you should complete this URL with session data, and redirect to the complete URL (so fill in if ‘ratings’ is also missing).
Now what if a parameter is missing in both URL and session? You should rely on some initialization rules. For ‘ratings’, you should check all ratings; and for ‘sort_by’, you can set the keyword to ‘id’, which is how items are sorted by default (the order of movies in the array returned by Movie.all).

答:
Something like this should work

```<code>def index
  session[:sort_by] = if params[:sort_by].present?
                        params[:sort_by]
                      else
                        session[:sort_by] || 'id'
                      end
  session[:rating] = if params[:rating].present?
                       params[:rating]
                     else
                       session[:rating] || { 'G' => '1', 'PG' => '1', 'PG-13' => '1', 'R' => '1' }
                     end

  if !(params[:sort_by].present? && params[:rating].present?)
    redirect_to movies_path(sort_by: session[:sort_by], rating: session[:rating])

    return
  end
end
</code>```

First couple lines set up the session to the parameter value if one was passed in, otherwise checks for an existing session value, and then falls back to the default.

Then, we look to see if either the sort_by or the rating parameter were missing, we'll redirect to include both of them from the new values in the session.

I believe this hits all your criteria. The main problem you were having is that as soon as you call redirect_to, it's going to try and redirect, it doesn't like having code (especially other redirect or render calls) after it. So you need to check any conditions you need and then lump it all into one redirect call and then return from the method so it doesn't try to also render.

Title: [Ruby on Rails]Redirect to RESTful URL

Body:
I am working on a movie rails project and I have to redirect the url to be RESTful, but I have no idea how to make it done. The following information may be useful:

I fail to: GET /movies when selecting a movie rating should redirect to a RESTful route

rake routes:

Prefix Verb   URI Pattern                Controller#Action
      root GET    /                          movies#index
    movies GET    /movies(.:format)          movies#index
           POST   /movies(.:format)          movies#create
 new_movie GET    /movies/new(.:format)      movies#new
edit_movie GET    /movies/:id/edit(.:format) movies#edit
     movie GET    /movies/:id(.:format)      movies#show
           PATCH  /movies/:id(.:format)      movies#update
           PUT    /movies/:id(.:format)      movies#update
           DELETE /movies/:id(.:format)      movies#destroy

The UI of the webpage

Some descriptions of what I have to do: (generally saying if the user intentionally deletes some attributes from the url, I have redirect it to the correct url):

To be RESTful, we want to preserve the property that a URI that results in a sorted/filtered view always contains the corresponding sorting/filtering parameters.

The code I have implemented to do the task:

if !(params.has_key?(:sort_by))  #check the url has this parameter
  if session[:sort_by]           #has cookie
    redirect_to movies_path(:sort_by => session[:sort_by]) #redirect using cookie, not sure need to add :ratings
  else
    session[:sort_by] = "id"    # default sorting
  end
end

if !(params.has_key?(:ratings))
  if session[:ratings]
    redirect_to movies_path(:ratings => session[:ratings]) # error: AbstractController::DoubleRenderError
  else
    session[:rating] = {"G"=>"1", "PG"=>"1", "PG-13"=>"1", "R"=>"1"}
  end
end

:sort_by is the attribute to control how is the movies sorted, e.g. session[:sort_by] = "date" means sorted on the release date.

:ratings is something like: "ratings"=>{"G"=>"1", "PG-13"=>"1", "R"=>"1"}

An example of URL: /movies?ratings%5BG%5D=1&ratings%5BPG%5D=1&ratings%5BPG-13%5D=1&ratings%5BR%5D=1&sort_by=title

if I type something like .../movies, the url should be generated from cookie(if any). But I am having some problems:

for example we check that sort_by is missing, and there is session for sort_by, do we still need to supply session[:ratings] to movies_path()? And what to do if it is the first time I come to this website (no session[:ratings]/session[:sort_by]) but I still need the RESTful URL(all checked boxes are 'clicked' by default)

Some more instructions:

So you should redirect when parameters are missing in URL, instead of in URL + session.
It means that when ‘sort_by’ is not in the URL, but in the session, you should complete this URL with session data, and redirect to the complete URL (so fill in if ‘ratings’ is also missing).
Now what if a parameter is missing in both URL and session? You should rely on some initialization rules. For ‘ratings’, you should check all ratings; and for ‘sort_by’, you can set the keyword to ‘id’, which is how items are sorted by default (the order of movies in the array returned by Movie.all).

Body:
Something like this should work

def index
  session[:sort_by] = if params[:sort_by].present?
                        params[:sort_by]
                      else
                        session[:sort_by] || 'id'
                      end
  session[:rating] = if params[:rating].present?
                       params[:rating]
                     else
                       session[:rating] || { 'G' => '1', 'PG' => '1', 'PG-13' => '1', 'R' => '1' }
                     end

  if !(params[:sort_by].present? && params[:rating].present?)
    redirect_to movies_path(sort_by: session[:sort_by], rating: session[:rating])

    return
  end
end

First couple lines set up the session to the parameter value if one was passed in, otherwise checks for an existing session value, and then falls back to the default.

Then, we look to see if either the sort_by or the rating parameter were missing, we'll redirect to include both of them from the new values in the session.

I believe this hits all your criteria. The main problem you were having is that as soon as you call redirect_to, it's going to try and redirect, it doesn't like having code (especially other redirect or render calls) after it. So you need to check any conditions you need and then lump it all into one redirect call and then return from the method so it doesn't try to also render.


问:
Get a font and font size from text?
I want to make an application for auto finding font.

Therefore, I try to get a font and font size from PDF text with Acrobat SDK.

I examined samples and documents, but I could not find it.

```<code> CAcroPDDoc pdDoc = new AcroPDDocClass();
 pdDoc.Open(filename);
 Object jsObj = pdDoc.GetJSObject();
 Type T = jsObj.GetType();

 // no idea for getting font and font size...
</code>```

My tools : Visual Studio, C#, Acrobat DC, Acrobat DC SDK

For example PDF text, font and font size on Acrobat DC

Best regards

答:
Acrobat JavaScript and, therefore, the JSO doesn't have access to the properties of text in the page content. The best you're going to be able to do is infer the size from the bounding box height but that won't be accurate since the bbox includes the leading. You can't get the font name at all.

You can get that information if you create a plugin but that would require C++ which you don't have listed as an option in your question.

Title: Get a font and font size from text?

Body:
I want to make an application for auto finding font.

Therefore, I try to get a font and font size from PDF text with Acrobat SDK.

I examined samples and documents, but I could not find it.

 CAcroPDDoc pdDoc = new AcroPDDocClass();
 pdDoc.Open(filename);
 Object jsObj = pdDoc.GetJSObject();
 Type T = jsObj.GetType();

 // no idea for getting font and font size...

My tools : Visual Studio, C#, Acrobat DC, Acrobat DC SDK

For example PDF text, font and font size on Acrobat DC

Best regards


问:
Java: make a function not virtual - call parent method on parent reference
I would think this question has been asked before, but was not immediately able to find an answer.

Say, somehow, a Pet reference is assigned a Dog object:

```<code>Pet pet = new Dog();
</code>```

If I write

```<code>pet.attackInvader();
</code>```

The child class (Dog)'s method is called by virtue that all functions in Java are virtual.

Is it possible to invoke Pet's attackInvader() instead?

(I know I can edit Dog's method to call super, but, in this case, assume I cannot change Dog's implementation.)

答:
Without overriding the method in Dog and without changing the instantiated object from Dog to Pet, it is not possible as the polymorphism works in this way :

the method invoked at runtime is always the method of the runtime object.

Now as alternative, you could provide a method in Dog that convert it into a Pet instance :

```<code>  public Pet toPet(){
      return new Pet(...);
 }
</code>```

and then invoke attackInvader() :

```<code>myDog.toPet().attackInvader();
</code>```

Or by creating a new method in Dog that offers this specific behavior :

```<code>  public void attackInvaderPet(){
      super.attackInvader();
  }
</code>```

Body:
I would think this question has been asked before, but was not immediately able to find an answer.

Say, somehow, a Pet reference is assigned a Dog object:

Pet pet = new Dog();

If I write

pet.attackInvader();

The child class (Dog)'s method is called by virtue that all functions in Java are virtual.

Is it possible to invoke Pet's attackInvader() instead?

(I know I can edit Dog's method to call super, but, in this case, assume I cannot change Dog's implementation.)

Body:
Without overriding the method in Dog and without changing the instantiated object from Dog to Pet, it is not possible as the polymorphism works in this way :

the method invoked at runtime is always the method of the runtime object.

Now as alternative, you could provide a method in Dog that convert it into a Pet instance :

  public Pet toPet(){
      return new Pet(...);
 }

and then invoke attackInvader() :

myDog.toPet().attackInvader();

Or by creating a new method in Dog that offers this specific behavior :

  public void attackInvaderPet(){
      super.attackInvader();
  }


问:
How can I add waitbar in the current GUI window MATLAB?
I am having a GUI figure, which contains some buttons, I want to show waitbar on the same GUI window on which buttons are placed, I tried different solutions but in vain. e.g when user clicks on button it starts showing me waitbar on left bottom side of the figure.</p>

答:
You could try to add a java waitbar in your figure.

Put this in the OpeningFcn

```<code>PB=javaObjectEDT(javax.swing.JProgressBar);
javacomponent(PB,[10,10,200,20],gcf); %put at bottom part of the current figure
set(handles.output.Children(1),'Tag','first_bar'); %make sure you can find it back
</code>```

In the callback of any function you can then set the bar to a value between 0 and 100 using this code:

```<code>h=findobj(handles.output.Children,'Tag','first_bar');
set(h.JavaPeer,'Value',rand(1)*100)
</code>```

You can make it visible or invisible just as you would any GUI object in Matlab using

```<code>h=findobj(handles.output.Children,'Tag','first_bar');
set(h,'visible','off');
</code>```

Here you can find details about the JProgressBar . For example using this you get a string with the progress inside the bar.

```<code>h=findobj(handles.output.Children,'Tag','first_bar');
set(h.JavaPeer,'StringPainted',1)
</code>```

Body:
You could try to add a java waitbar in your figure.

Put this in the OpeningFcn

PB=javaObjectEDT(javax.swing.JProgressBar);
javacomponent(PB,[10,10,200,20],gcf); %put at bottom part of the current figure
set(handles.output.Children(1),'Tag','first_bar'); %make sure you can find it back

In the callback of any function you can then set the bar to a value between 0 and 100 using this code:

h=findobj(handles.output.Children,'Tag','first_bar');
set(h.JavaPeer,'Value',rand(1)*100)

You can make it visible or invisible just as you would any GUI object in Matlab using

h=findobj(handles.output.Children,'Tag','first_bar');
set(h,'visible','off');

Here you can find details about the JProgressBar . For example using this you get a string with the progress inside the bar.

h=findobj(handles.output.Children,'Tag','first_bar');
set(h.JavaPeer,'StringPainted',1)


问:
Consul TLS CRL checking
We're implementing consul with TLS security enabled, but it doesn't look like the consul agent performs any revocation lookup on the incoming (or local) certificates. Is this expected behavior? We'd like to be able to lock rogue/expired agents out.</p>

答:
By default, Consul does not verify incoming certificates. You can enable this behavior by setting verify_incoming in your configuration:

```<code>{
  "verify_incoming": true,
  "verify_incoming_rpc": true,
  "verify_incoming_https": true,
}
</code>```

You can also tell Consul to verify outgoing connections via TLS:

```<code>{
  "verify_outgoing": true,
}
</code>```

In these situations, it may be necessary to set the ca_file and ca_path arguments as well.

Title: Consul TLS CRL checking

Body:
By default, Consul does not verify incoming certificates. You can enable this behavior by setting verify_incoming in your configuration:

{
  "verify_incoming": true,
  "verify_incoming_rpc": true,
  "verify_incoming_https": true,
}

You can also tell Consul to verify outgoing connections via TLS:

{
  "verify_outgoing": true,
}

In these situations, it may be necessary to set the ca_file and ca_path arguments as well.


问:
How do I get the current username in Windows PowerShell?
How do I get the current username in Windows PowerShell?</p>

答:
If you're used to batch, you can call

```<code>$user=$(cmd.exe /c echo %username%)
</code>```

This basically steals the output from what you would get if you had a batch file with just "echo %username%".

ContentLicense: CC BY-SA 4.0

Body:
If you're used to batch, you can call

$user=$(cmd.exe /c echo %username%)

This basically steals the output from what you would get if you had a batch file with just "echo %username%".


问:
AWS + MongoDB : How to connect to mongo server on AWS linux instance?
I launched an AWS linux instance and installed and ran mongo as instructed here. The mongo service is running and accepting connections on 27017. However, when I go to the server publik dns with port 27017 the server does not respond and I don't see the default mongo message.

I am trying to run a Python(Flask) server on another instance and trying to connect to the mongo server using the private ip, but the connection does not happen. I get this error message on the terminal :

pymongo.errors.ServerSelectionTimeoutError: xxx.xx.xx.xx:27017: [Errno
  111] Connection refused

Is this not the right way to use mongo db on aws ? If this approach is feasible, what is causing the connection to not happen ?

All inputs appreciated, much thanks!

答:
It is possible that your mongodb is configured to only accept connection from local host. Edit /etc/mongod.conf file to comment out the line that bindIP like in the example below -

```<code># network interfaces
net:
  port: 27017
#  bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.
</code>```

Body:
It is possible that your mongodb is configured to only accept connection from local host. Edit /etc/mongod.conf file to comment out the line that bindIP like in the example below -

# network interfaces
net:
  port: 27017
#  bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.


问:
How to set the window decorator color on an Android app in Chromebook?
There are many "default" apps that have the window decorator matching the app color theme such as the Youtube or Google Play apps.

My app otherwise has a gray bar (the bottom one in the pic) as most of the apps one can download from Google Play that aren't from Google.
How can I change the color of it?

答:
The window decoration color roughly follows the status bar color. You can set it at runtime via Window#setStatusBarColor

If you do not set it specifically, the color will be derived from your theme colors.

So setting ColorPrimaryDark or ColorPrimary would define your decorations color.

The color can't be transparent, if it is, you might get the grey color you are seeing.

If you are still not seeing the right color, you are hitting a bug that should be fixed in ChromeOS 60.


问:
Authorization with Node JS application
I have an Angular 2 app with node js as back end. I am wondering, how to authenticate user when I for example want to restrict access. Now, I am using bearer token and keeping users' sessions in dictionary [token] => user object. I am not sure if this is a good solution because if someone will steal token, then could use particular users' account.

Regards

答:
You can set expiration duration for your JWT tokens.

Avoid updating credentials(email,password etc) only on the basis of Token.

 More

Title: Authorization with Node JS application


问:
Looping over one pandas column to match values with index of another dataframe
Exp is one DataFrame with datetime object

```<code>           Exp
0   1989-06-01
1   1989-07-01
2   1989-08-01
3   1989-09-01
4   1989-10-01
</code>```

CL is the Dataframe with Index as DateTime Object

```<code>                    CL
1989-06-01   68.800026
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023
</code>```

I want to add new column R into CL dataframe which have will have date from Exp matching with CL Index.

This what my desired output should look like

```<code>                   CL          R

1989-06-01   68.800026   1989-06-01
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023
</code>```

This is what I tried doing:

```<code>for m in Exp.iloc[:,0]:
if m == CL.index:
    CL['R'] = m
</code>```

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

Can someone please help me ? I keep getting this ValueError a lot of times

Body:
Exp is one DataFrame with datetime object

           Exp
0   1989-06-01
1   1989-07-01
2   1989-08-01
3   1989-09-01
4   1989-10-01

CL is the Dataframe with Index as DateTime Object

                    CL
1989-06-01   68.800026
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023

I want to add new column R into CL dataframe which have will have date from Exp matching with CL Index.

This what my desired output should look like

                   CL          R

1989-06-01   68.800026   1989-06-01
1989-06-04   68.620026
1989-06-05   68.930023
1989-06-06   68.990021
1989-06-09   69.110023

This is what I tried doing:

for m in Exp.iloc[:,0]:
if m == CL.index:
    CL['R'] = m

ValueError: The truth value of an array with more than one element is
  ambiguous. Use a.any() or a.all()

Can someone please help me ? I keep getting this ValueError a lot of times

Body:
pd.DataFrame.join

join focuses on combining dataframes/series via the index.

Use set_index on Exp with drop=False to keep the same information in the dataframe proper and the index.  We put it in the index to make join convenient.

CL.join(Exp.set_index('Exp', drop=False)).rename(columns=dict(Exp='R'))

                   CL          R
1989-06-01  68.800026 1989-06-01
1989-06-04  68.620026        NaT
1989-06-05  68.930023        NaT
1989-06-06  68.990021        NaT
1989-06-09  69.110023        NaT

Setup

Exp = pd.DataFrame(dict(
        Exp=pd.to_datetime(
            ['1989-06-01', '1989-07-01', '1989-08-01', '1989-09-01', '1989-10-01'])
    ))

CL = pd.DataFrame(dict(
        CL=[68.800026, 68.620026, 68.930023, 68.990021, 69.110023],
    ), pd.to_datetime(
        ['1989-06-01', '1989-06-04', '1989-06-05', '1989-06-06', '1989-06-09']))


问:
How to efficiently swap elements in a dataframe?
Suppose that we have the following dataframe:

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D
</code>```

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

```<code>for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E
</code>```

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

```<code>tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

How to go about this case? Thanks!

答:
```<code>#Find out the indices where difference is odd
inds = abs(as.numeric(tmp$R1) - as.numeric(tmp$R2)) %% 2 != 0

#create new columns where values for the appropriate inds are from relevant columns
tmp$R1_new = replace(tmp$R1, inds, tmp$R2[inds])
tmp$R2_new = replace(tmp$R2, inds, tmp$R1[inds])

tmp
#    x R1 R2 R1_new R2_new
#1   1  B  B      B      B
#2   2  B  A      A      B
#3   3  C  D      D      C
#4   4  E  B      B      E
#5   5  B  D      B      D
#6   6  E  C      E      C
#7   7  E  D      D      E
#8   8  D  E      E      D
#9   9  D  B      D      B
#10 10  A  D      D      A
</code>```

Delete the old R1 and R2 if necessary

Body:
Suppose that we have the following dataframe:

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

How to go about this case? Thanks!

Body:
#Find out the indices where difference is odd
inds = abs(as.numeric(tmp$R1) - as.numeric(tmp$R2)) %% 2 != 0

#create new columns where values for the appropriate inds are from relevant columns
tmp$R1_new = replace(tmp$R1, inds, tmp$R2[inds])
tmp$R2_new = replace(tmp$R2, inds, tmp$R1[inds])

tmp
#    x R1 R2 R1_new R2_new
#1   1  B  B      B      B
#2   2  B  A      A      B
#3   3  C  D      D      C
#4   4  E  B      B      E
#5   5  B  D      B      D
#6   6  E  C      E      C
#7   7  E  D      D      E
#8   8  D  E      E      D
#9   9  D  B      D      B
#10 10  A  D      D      A

Delete the old R1 and R2 if necessary


问:
How to find the real size ("logical area") of a TScrollBox
I need to find the entire size (also called "logical area") of a TScrollBox - as opposite to visible area that you get via Width and Height property (or ClientWidth ClientHeight).

I want to create some controls inside that TScrollBox. One of them (called TViewer) needs to be as high as the TScrollBox itself. The thing is that during creation, the TScrollBox is scrolled down to show last created control. So, using Top=1 will not work because my control will have top=1 which is not the top of the logical area.

Delphi 7

答:
Im not sure i understand exactly what you want to do, but to get the complete area defined as "scrollable" you would have to write ScrollBox.HorScrollBar.Range + ScrollBox.Clientwidth (and the same thing for the vertical section). The scrollbox always deducts the visible "page" size from the total. So if you define a height of 1000 pixels, with 100 pixels showing - it will have a scrolling range of 900. You have to add the clientheight to get the rest.

Also, to get the correct "top" position you will have to read Canvas.Cliprect.Top, since a scrolling window does not change the top position of sub-controls. Windows handles this for you and only tells you what to re-draw once the scrollbars are initialized.

Since you want to create a control that is just as high as the complete scrollable area, i presume you are creating an editor of sorts?

If so you would probably get better results taking a look at SynEdit and extract the base-class that adds scrollbars to a normal TCustomControl (it's quite easy). That way you can control both the painting and the layout of your controls.

Here is one I wrote for Lazarus and FreePascal a while back. If you add messages to the uses clause and prefix the message handlers with WM rather than TLM it will compile under Delphi.

(code to long, had to use external link): http://delphimax.wordpress.com/2010/09/20/platform-independent-image-component-for-lazarus/

ContentLicense: CC BY-SA 2.5


问:
Cartesian Product of Sets where No Elements are Identical under Permutations in Python
I have some sets I would like to take the Cartesian product of, which is working well. However, I want to remove all elements of this new set which are identical under a permutation of the elements.

For example, take the following code:

```<code>import itertools as ittools
x = 2
y = 3
z = 5

flist = list(ittools.product([x,y,z],repeat=3))

for f in flist:
    print reduce(lambda a,b: a*b, f)
</code>```

This code find the Cartesian product of the set {2,3,5} and returns the product of all three components of each element in the resulting set. However, some numbers appear multiple times, i.e. 12 can be written as 2*2*3, 2*3*2, or 3*2*2. I would like to remove all but one instance of these duplicates.

I know that this fundamentally a combinatorics problem, but this seems like there is probably a nice solution in Python that doesn't involve doing an extra pass over the list like I did here to compute some identifier for each element of the Cartesian product.

答:
You want combinations_with_replacement, not product:

```<code>itertools.combinations_with_replacement([x, y, z], 3)
</code>```

Body:
I have some sets I would like to take the Cartesian product of, which is working well. However, I want to remove all elements of this new set which are identical under a permutation of the elements.

For example, take the following code:

import itertools as ittools
x = 2
y = 3
z = 5

flist = list(ittools.product([x,y,z],repeat=3))

for f in flist:
    print reduce(lambda a,b: a*b, f)

This code find the Cartesian product of the set {2,3,5} and returns the product of all three components of each element in the resulting set. However, some numbers appear multiple times, i.e. 12 can be written as 2*2*3, 2*3*2, or 3*2*2. I would like to remove all but one instance of these duplicates.

I know that this fundamentally a combinatorics problem, but this seems like there is probably a nice solution in Python that doesn't involve doing an extra pass over the list like I did here to compute some identifier for each element of the Cartesian product.

Body:
You want combinations_with_replacement, not product:

itertools.combinations_with_replacement([x, y, z], 3)


答:
Using Map with Array#reduce:

const array = ['bob', 'charlie', 'bob', 'bob'];

const result = [...array.reduce((map, name) => {
  const current = map.get(name) || { name, count: 0 };

  current.count++;

  return map.set(name, current);
}, new Map()).values()];

console.log(result);```

Title: Remove duplicates from array, convert to array of objects and add duplicate count property

Body:
I have an array of strings:

var array = ['bob', 'charlie', 'bob', 'bob'];

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];

How can I do that?


问:
Local Player Bukkit/Spigot Development
Are there commands to get the display name of the local player.
So if I create a chat message, all players seen their own name in the chat. Is it possible and how? </p>

答:
No, you can't get the "local" player name, because who will run the code is the server, not the client, so you can't get it because there is no local player. However, you can still send a custom message for different people with different names to simulate this effect.

Based in this example, you can simply send a message through the /tellraw command to the players that you want to send the message, example:

```<code>public static void sendMessage(String playerName, String msg) {
        Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(),
                "/tellraw " + playerName + " {\"text\":\"" + msg.replaceAll("<playername>", playerName) + "\"}");
}
</code>```

In this case, I've used <playername> as a keyword to reference the player, so Hello <playername> should return Hello yourname...
However, this solution is better when you don't have the Player object, and to not waste your machine's time to create it, you can simply use the tellraw... But to simplify the answer, you can use the Player::sendMessage method (quoted by bcsb1001).:

```<code>public static void sendMessage(Player player, String msg){
    player.sendMessage(msg.replaceAll("<playername>", player.getName()));
}
</code>```

Okay, but how can I send it to every person in a group, or in an Array?

In this case, you can use a for each loop for every single player.

Here is the full code to send a hello message to every single player online:

```<code>public static void sayHelloToEveryone() {
    String msg = "Hello <playername>!";
    for (Player p : Bukkit.getServer().getOnlinePlayers()) {
        p.sendMessage(msg.replaceAll("<playername>", p.getName()));
    }
}
</code>```

Therefore, when you use sayHelloToEveryone(), it will send a message to everyone based on their name:

If there are Steve and Ruben online, the server will send a different message to both users:

Steve's chat: Hello Steve!

Ruben's chat: Hello Ruben!

Title: Local Player Bukkit/Spigot Development

Body:
No, you can't get the "local" player name, because who will run the code is the server, not the client, so you can't get it because there is no local player. However, you can still send a custom message for different people with different names to simulate this effect.

Based in this example, you can simply send a message through the /tellraw command to the players that you want to send the message, example:

public static void sendMessage(String playerName, String msg) {
        Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(),
                "/tellraw " + playerName + " {\"text\":\"" + msg.replaceAll("<playername>", playerName) + "\"}");
}

In this case, I've used <playername> as a keyword to reference the player, so Hello <playername> should return Hello yourname...
However, this solution is better when you don't have the Player object, and to not waste your machine's time to create it, you can simply use the tellraw... But to simplify the answer, you can use the Player::sendMessage method (quoted by bcsb1001).:

public static void sendMessage(Player player, String msg){
    player.sendMessage(msg.replaceAll("<playername>", player.getName()));
}

Okay, but how can I send it to every person in a group, or in an Array?

In this case, you can use a for each loop for every single player.

Here is the full code to send a hello message to every single player online:

public static void sayHelloToEveryone() {
    String msg = "Hello <playername>!";
    for (Player p : Bukkit.getServer().getOnlinePlayers()) {
        p.sendMessage(msg.replaceAll("<playername>", p.getName()));
    }
}

Therefore, when you use sayHelloToEveryone(), it will send a message to everyone based on their name:

If there are Steve and Ruben online, the server will send a different message to both users:

Steve's chat: Hello Steve!

Ruben's chat: Hello Ruben!


问:
PrimeNG DataTable multiselect filter with dynamic values
I am using PrimeNG 4.x.x supporting Angular 4. I want to provide values dynamically to multiselect filter in DataTable column.

As shown below I am creating table columns dynamically from 'clientcolumnDefs' and now I want to provide values dynamically to multiselect filter Option .

    <ng-template pTemplate="filter" let-col>

    </ng-template>

```

How do i populate my dynamicFilters in typescript , so that it works for all the columns.

The filters should be of this type but the values will be dynamic for each column.

filter image

答:
dynamicaFilters should be a multi dimensional array. In your ts file you need to fetch the distinct values per column and insert them into a temp array and then insert that temp array into dynamicaFilters.

Your html code will also change to be -

```<code><p-column *ngFor="let col of clientcolumnDefs; let i= index" [field]="col.field" [header]="col.header" sortable="true" [filter]="true" filterMatchMode="in" [style]="{'overflow':'visible'}">
            <ng-template pTemplate="filter" let-col>
                <p-multiSelect  [options]="dynamicaFilters[i]" defaultLabel="All" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-multiSelect>
            </ng-template>
        </p-column>
</code>```

I did not get a chance to try this myself, let me know if you have any questions.

Body:
I am using PrimeNG 4.x.x supporting Angular 4. I want to provide values dynamically to multiselect filter in DataTable column.

As shown below I am creating table columns dynamically from 'clientcolumnDefs' and now I want to provide values dynamically to multiselect filter Option .

    <ng-template pTemplate="filter" let-col>

    </ng-template>

How do i populate my dynamicFilters in typescript , so that it works for all the columns.

The filters should be of this type but the values will be dynamic for each column.

filter image

Body:
dynamicaFilters should be a multi dimensional array. In your ts file you need to fetch the distinct values per column and insert them into a temp array and then insert that temp array into dynamicaFilters.

Your html code will also change to be -

<p-column *ngFor="let col of clientcolumnDefs; let i= index" [field]="col.field" [header]="col.header" sortable="true" [filter]="true" filterMatchMode="in" [style]="{'overflow':'visible'}">
            <ng-template pTemplate="filter" let-col>
                <p-multiSelect  [options]="dynamicaFilters[i]" defaultLabel="All" (onChange)="dt.filter($event.value,col.field,col.filterMatchMode)" styleClass="ui-column-filter"></p-multiSelect>
            </ng-template>
        </p-column>

I did not get a chance to try this myself, let me know if you have any questions.


问:
Insert data to a SQL Server database that contains apostrophes
I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.

One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'

When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.

```<code>CMD.CommandText =
"INSERT INTO Table_ARTICLES
 (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
 VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
  '" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
  '" & txtMin.Text & "', '" & cmbUnidad.Text & "')"
</code>```

Does anybody know how to make this query accept those characters on the query?

答:
As @pmbAustin pointed out, is a terrible idea to build sql statements via string concatenation due to SQL Injection attacks and other problems. The approach you should use is called a parametrized query:

```<code>CMD.CommandText = "INSERT INTO (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL,
MIN, Unidad_de_medida)
VALUES (@NUMPART, @DESCRIPTION,@LOCATION,@MAX,@ACTUAL,@MIN,@UNIDAD_DE_MEDIDA)"
</code>```

And then:

```<code>CMD.Parameters.Add("@NUMPART",txtNumParte.Text);
CMD.Parameters.Add("@DESCRIPTION",txtDescripcion.Text);
//...and so on
CMD.ExecuteNonQuery();
</code>```

Body:
I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.

One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'

When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.

CMD.CommandText =
"INSERT INTO Table_ARTICLES
 (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
 VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
  '" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
  '" & txtMin.Text & "', '" & cmbUnidad.Text & "')"

Does anybody know how to make this query accept those characters on the query?

Body:
As @pmbAustin pointed out, is a terrible idea to build sql statements via string concatenation due to SQL Injection attacks and other problems. The approach you should use is called a parametrized query:

CMD.CommandText = "INSERT INTO (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL,
MIN, Unidad_de_medida)
VALUES (@NUMPART, @DESCRIPTION,@LOCATION,@MAX,@ACTUAL,@MIN,@UNIDAD_DE_MEDIDA)"

And then:

CMD.Parameters.Add("@NUMPART",txtNumParte.Text);
CMD.Parameters.Add("@DESCRIPTION",txtDescripcion.Text);
//...and so on
CMD.ExecuteNonQuery();


问:
segmentation fault in binary tree in C
I was trying to implement my code to create a binary tree in C language.The code doesn't give out any errors but during runtime it results in segmentation fault .Couldn't figure out the reason why. please help.</p>

```<code>#include<stdio.h>
#include<malloc.h>

struct node{
    int value;
    struct node *left;
    struct node *right;
}*root = NULL;

struct node* create(int val)
{
    struct node *ptr;
    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->value = val;
    ptr->left = NULL;
    ptr->right = NULL;
    return ptr;
}

void insert(int val)
{
    if(root == NULL)
    {
        root=create(val);
    }
    else if(val < (root)->value)
    {
        (root)->left = create(val);
    }
    else
    {
        (root)->right = create(val);
    }
}

void traverse(struct node** root)
{
    if(*root==NULL)
        printf("TREE EMPTY");
        return 0;
    while((*root)!=NULL)
    {
        printf("%d",(*root)->value);
        traverse((*root)->left);
        traverse((*root)->right);
    }
}

int main()
{
    int val;
    char ch='y';
    while(ch=='y')
    {
        scanf("%d",&val);
        insert(val);
        printf("Want to insert more elements ?(y or n) =");
        scanf("%c",ch);
    }
    traverse(&root);
    free(root);
    return 0;
}
</code>```

答:
As described by @BLUEPIXY the segmentation fault is caused by parsing the value of the variable ch instead of the address of ch. In addition to this you code appears to have some logical errors.

Your implementation of insert only looks at the root node and adds the new value its left or right child, depending on the root value. The desired behaviour is for insert to search down through the tree structure until it reaches a leaf node, and insert the new value here.

As indicated by @BLUEPIXY the while ((*root)!=NULL) in the traverse function is equal to while (true), as the root element is never updated. Here, again, the desired behaviour is for the traverse function to navigate the tree structure (usually from left to right) and recursively visit the children of the current node. The code below implements a simple way to achieve this by simply calling traverse on each child, without the while-loop.

Finally, as @BLUEPIXY also points out, your call to free with root as argument does not release the entire tree. Free only releases the memory block pointed to by its argument. It does not recursively follow pointers within that memory block. In order to release all resources held by the tree structure you need to traverse the tree again and call free on every node.

The following code, based on your code, implements binary tree. Note that the tree is not likely to remain balanced, as it grows. To achieve a balanced binary tree you need to remodel the tree when inserting a new node.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int value;
    struct node *left;
    struct node *right;
} node;

node *root = NULL;

node* create(int val)
{

    node *ptr;
    ptr = (node*)malloc(sizeof(node));
    ptr->value = val;
    ptr->left = NULL;
    ptr->right = NULL;
    return ptr;
}

void insert_(node *root, int val)
{
  if (val < root->value)
  {
    if (root->left != NULL)
    {
        insert_(root->left, val);
        } else {
        root->left = create(val);
        }
    }
    else
    {
        if (root->right != NULL)
        {
            insert_(root->right, val);
        } else {
            root->right = create(val);
        }
    }
}

void insert(int val)
{
    if(root == NULL)
    {
        root = create(val);
    }
    else
    {
        insert_(root, val);
    }
}

void traverse(node *root)
{
    if(root == NULL)
    {
        printf("E");
        return;
    }
    printf("%d (", root->value);
    traverse(root->left);
    printf( ") (");
    traverse(root->right);
    printf( ")");
}

void free_tree(node *root)
{
      if (root == NULL) {
            return;
      }
      free_tree(root->left);
      free_tree(root->right);
      free(root);
}

int main()
{
      int val;
      char ch='y';
      while(ch=='y')
      {
            scanf("%d",&val);
            insert(val);
            printf("Want to insert more elements ?(y or n) =");
            scanf(" %s", &ch);
      }
      traverse(root);
      free_tree(root);
      return 0;
}
</code>```

Title: segmentation fault in binary tree in C

Body:
I was trying to implement my code to create a binary tree in C language.The code doesn't give out any errors but during runtime it results in segmentation fault .Couldn't figure out the reason why. please help.

#include<stdio.h>
#include<malloc.h>

struct node{
    int value;
    struct node *left;
    struct node *right;
}*root = NULL;

struct node* create(int val)
{
    struct node *ptr;
    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->value = val;
    ptr->left = NULL;
    ptr->right = NULL;
    return ptr;
}

void insert(int val)
{
    if(root == NULL)
    {
        root=create(val);
    }
    else if(val < (root)->value)
    {
        (root)->left = create(val);
    }
    else
    {
        (root)->right = create(val);
    }
}

void traverse(struct node** root)
{
    if(*root==NULL)
        printf("TREE EMPTY");
        return 0;
    while((*root)!=NULL)
    {
        printf("%d",(*root)->value);
        traverse((*root)->left);
        traverse((*root)->right);
    }
}

int main()
{
    int val;
    char ch='y';
    while(ch=='y')
    {
        scanf("%d",&val);
        insert(val);
        printf("Want to insert more elements ?(y or n) =");
        scanf("%c",ch);
    }
    traverse(&root);
    free(root);
    return 0;
}

Body:
As described by @BLUEPIXY the segmentation fault is caused by parsing the value of the variable ch instead of the address of ch. In addition to this you code appears to have some logical errors.

Your implementation of insert only looks at the root node and adds the new value its left or right child, depending on the root value. The desired behaviour is for insert to search down through the tree structure until it reaches a leaf node, and insert the new value here.

As indicated by @BLUEPIXY the while ((*root)!=NULL) in the traverse function is equal to while (true), as the root element is never updated. Here, again, the desired behaviour is for the traverse function to navigate the tree structure (usually from left to right) and recursively visit the children of the current node. The code below implements a simple way to achieve this by simply calling traverse on each child, without the while-loop.

Finally, as @BLUEPIXY also points out, your call to free with root as argument does not release the entire tree. Free only releases the memory block pointed to by its argument. It does not recursively follow pointers within that memory block. In order to release all resources held by the tree structure you need to traverse the tree again and call free on every node.

The following code, based on your code, implements binary tree. Note that the tree is not likely to remain balanced, as it grows. To achieve a balanced binary tree you need to remodel the tree when inserting a new node.

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int value;
    struct node *left;
    struct node *right;
} node;

node *root = NULL;

node* create(int val)
{

    node *ptr;
    ptr = (node*)malloc(sizeof(node));
    ptr->value = val;
    ptr->left = NULL;
    ptr->right = NULL;
    return ptr;
}

void insert_(node *root, int val)
{
  if (val < root->value)
  {
    if (root->left != NULL)
    {
        insert_(root->left, val);
        } else {
        root->left = create(val);
        }
    }
    else
    {
        if (root->right != NULL)
        {
            insert_(root->right, val);
        } else {
            root->right = create(val);
        }
    }
}

void insert(int val)
{
    if(root == NULL)
    {
        root = create(val);
    }
    else
    {
        insert_(root, val);
    }
}

void traverse(node *root)
{
    if(root == NULL)
    {
        printf("E");
        return;
    }
    printf("%d (", root->value);
    traverse(root->left);
    printf( ") (");
    traverse(root->right);
    printf( ")");
}

void free_tree(node *root)
{
      if (root == NULL) {
            return;
      }
      free_tree(root->left);
      free_tree(root->right);
      free(root);
}

int main()
{
      int val;
      char ch='y';
      while(ch=='y')
      {
            scanf("%d",&val);
            insert(val);
            printf("Want to insert more elements ?(y or n) =");
            scanf(" %s", &ch);
      }
      traverse(root);
      free_tree(root);
      return 0;
}


问:
How to avoid "show all content" msg on HTTPS site in IE9?
We have an a HTTPS site that brings up a page from a different site of ours that’s HTTP.

In IE (9), we get the message at the bottom of the page:
“Only secure content is displayed. What’s the risk? [Show all content]”.

When the button is clicked, it closes the lightbox-ish control that's open and returns to the page it was overlaid on.

Does anyone know how to avoid this?

In the HTTP site’s page, one guy here had the idea to add, at the end of On_Load, the following to turn off cross-site scripting protection:
    this.Response.Headers.Add("X-XSS-Protection", "0");

Both sites are C# / ASP.NET 4.0.

Thanks in advance!

答:
The real setting to enable here is to "Display mixed content" for the zone of the site you want.  If the site is on your Intranet, you select Intranet zone in the Security settings, then Custom level.  If it's an Internet site, you go there and go to Custom level.

There, you should see the "Display mixed content" setting, and simply select "Enable", then "OK" your way out of the dialogs.

Reference:  https://www.mydigitallife.net/how-to-disable-only-secure-content-is-displayed-in-ie-always-show-all-mixed-content/