问:
Should I choose cloud?
I'm about to start development on a project with very uncertain load/traffic specifics. When it will be released there will certainly be very low load that can easily be handled by a single desktop quad code machine.

The problem is that there will be (after some invite-only period) a strong publicity for the product so I expect considerable traffic/load peaks.

I haven't read enough about cloud providers and I'm mostly leaning toward Amazon or Azure for the credibility these two companies have without checking them out as I should with others (ie. Rackspace that I suppose is also a cloud service provider).

What I want

I would like to create a normal Asp.net MVC web application that can be run on in-house single machine low-cost server. It would run web server along with database (relational and maybe also document) and fulltext search (not SQL FTS but rather high speed separate product like Lucene or Sphinx). But after initial invite-only period I'd like to move this app to the cloud to make it more traffic/load demand-friendly.

As much as I know Amazon offers a sort of virtual machine hosting which I understand you setup as a normal server but has possible flexible resources in terms of load power. I'm not sure if that can be accomplished on Azure as well.

Questions

What is your experience with application transition to cloud and which one did you choose and why?

What would you recommend I should think about when designing/developing the solution to make the transition as painless as possible.

Based on your experience is it better to move to the cloud (financial wise) or is it better to buy your own servers and load balance application yourself and maybe save money on the long run?

答: I have just migrated an MVC-based application from a dedicated server to Azure. When migrating the MSSQl-database, I first tried importing .bacpak files but some of the tables failed because of their size. I then used the SQL Database migratio wizard which worked fine for small tables but failed for tables with BLOB-fields. For these tables I had to use temporary intermediate tables. Then after a while after all the data was transferred setting up the Webapp was a breeze and we went in production. At first, everything seemed to work just fine, but after a couple of hours when the load got heavier, all kind of errors occurred. I went into the Azure portal and it was really easy to see the </p>

Title: Should I choose cloud?


来源: stackexchange

问:
Apache Derby: how can I do "insert if not exists"?
I'm giving Apache Derby, aka JavaDB a spin.  I can't seem to get around duplicate key issues when inserting records that may already exist.  Is there a Derby equivalent to "insert if not exists", or "merge" ?

Similarly, is there a way to do something like "drop table foo if exists"?

答:
I've never used apache derby, but a general solution that is fairly database independent is as follows:

To insert the values 'a' and 'b' into table foo (with columns named A, B), but only where the values are not already there, try something like

```<code>INSERT INTO foo (
  SELECT 'a' as A, 'b' as B
  FROM foo
  WHERE
    A = 'a' AND B = 'b'
  HAVING count(*)=0
 )
</code>```

This may need tweaking for a particular dbms, but the idea is to insert the result of a select that only returns values when there are non.

This is a useful trick for creating an idempotent sql script (one that does nothing the second time it is run). However, be careful when using this in production code as the HAVING count(*)=0 may be very slow on large tables.

OwnerDisplayName: Limbic System

ContentLicense: CC BY-SA 2.5

Body:
I've never used apache derby, but a general solution that is fairly database independent is as follows:

To insert the values 'a' and 'b' into table foo (with columns named A, B), but only where the values are not already there, try something like

INSERT INTO foo (
  SELECT 'a' as A, 'b' as B
  FROM foo
  WHERE
    A = 'a' AND B = 'b'
  HAVING count(*)=0
 )

This may need tweaking for a particular dbms, but the idea is to insert the result of a select that only returns values when there are non.

This is a useful trick for creating an idempotent sql script (one that does nothing the second time it is run). However, be careful when using this in production code as the HAVING count(*)=0 may be very slow on large tables.

OwnerDisplayName: Snukker


问:
Why is there a warning on this Java generic method definition?
I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

```<code>interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}
</code>```

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked conversion. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

It makes little sense to me, and Google didn't bring up anything useful.  Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

```<code>interface Car {
    Car getCar();
}
</code>```

答:
Short answer: it doesn't work that way, and is extremely dangerous to do what you are proposing since there is no way for the compiler to deduce what should be "correct" there. Generic methods usually have the type passed into them by the method parameters, here you don't pass anything in parameterized so T could be anything that extends Car.

Long answer: Look to this question for the answer.

Body:
I noticed that if I use generics on a method signature to accomplish something similar to co-variant return types, it works like I think it would, except it generates a warning:

interface Car {
    <T extends Car> T getCar();
}

class MazdaRX8 implements Car {
    public MazdaRX8 getCar() { // "Unchecked overriding" warning
        return this;
    }
}

With the code above, my IDE gives the warning: "Unchecked overriding: return type requires unchecked conversion. Found: 'MazdaRX8', required 'T'"

What does this warning mean?

It makes little sense to me, and Google didn't bring up anything useful.  Why doesn't this serve as a warning-free replacement for the following interface (which is also warning free, as co-variant return types are allowed by Java)?

interface Car {
    Car getCar();
}


问:
Get file duration uploaded from custom field wordpress
I want to get the duration of audio file when uploaded through custom field and save it in the post meta.</p>

答:
WordPress has built in audio functions using the ID3 library that will help you achieve this.

First you will hook into ACF using the acf/save_post hook. Then you will use the WP function wp_read_audio_metadata() to get the meta data of the audio file. Lastly you will use the update_post_meta() function to save the data to the post. Something like this:

```<code>function save_audio_duration($post_id) {
    // Get the WP Uploads Directory (where ACF saves files)
    $uploads = wp_upload_dir();
    $uploads_dir = ( $uploads['baseurl'] . $uploads['subdir'] );

    // Get the file name from ACF & create the file string
    $file_obj = get_field('audio_file', $post_id);
    $file = $uploads_dir . '/' . $file_obj['filename'];

    // Use the wp_read_audio_metadata() function to get data
    $metadata = wp_read_audio_metadata( $file );

    // Save the file length to the post meta
    update_post_meta($post_id, 'audio_length', $metadata['length']);
}

// Will execute AFTER post has been saved (change "20" to "1" to execute before)
add_action('acf/save_post', 'save_audio_duration', 20);
</code>```

Note: $metadata['length'] will return the time in seconds while $metadata['length_formatted'] will return the time in a formatted string.

Note x2: If you change the "20" to "1" in the action to execute this BEFORE the fields are saved to the post you will need to change the get_field() function to $_POST['audio_file'] as the function will be executed before ACF saves the fields to the DB.

ContentLicense: CC BY-SA 3.0

Body:
WordPress has built in audio functions using the ID3 library that will help you achieve this.

First you will hook into ACF using the acf/save_post hook. Then you will use the WP function wp_read_audio_metadata() to get the meta data of the audio file. Lastly you will use the update_post_meta() function to save the data to the post. Something like this:

function save_audio_duration($post_id) {
    // Get the WP Uploads Directory (where ACF saves files)
    $uploads = wp_upload_dir();
    $uploads_dir = ( $uploads['baseurl'] . $uploads['subdir'] );

    // Get the file name from ACF & create the file string
    $file_obj = get_field('audio_file', $post_id);
    $file = $uploads_dir . '/' . $file_obj['filename'];

    // Use the wp_read_audio_metadata() function to get data
    $metadata = wp_read_audio_metadata( $file );

    // Save the file length to the post meta
    update_post_meta($post_id, 'audio_length', $metadata['length']);
}

// Will execute AFTER post has been saved (change "20" to "1" to execute before)
add_action('acf/save_post', 'save_audio_duration', 20);

Note: $metadata['length'] will return the time in seconds while $metadata['length_formatted'] will return the time in a formatted string.

Note x2: If you change the "20" to "1" in the action to execute this BEFORE the fields are saved to the post you will need to change the get_field() function to $_POST['audio_file'] as the function will be executed before ACF saves the fields to the DB.


问:
Stuck on an older version after installed a new one
```<code>node --version
v4.5.0

npm --version
2.15.9

node-gyp --version
v3.4.0

which node
/home/admin/.nvm/versions/node/v4.5.0/bin/node
</code>```

For some reason, after running sudo npm install -g node-gyp - node-gyp installs with node v0.10.25:

```<code>npm WARN engine cryptiles@2.0.5: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine boom@2.10.1: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine hoek@2.16.3: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
</code>```

I've accessed /home/admin/.nvm/versions/node/ and found those folders: v4.4.4, v4.4.7, v4.5.0.

Can someone trigger the issue ? Where is that v0.10.25 version and how do I get rid of it ?

答: I had the same problem. i found that i had a node.exe file with old version, and in the PATH (environment variables) i had a link to this old node.exe folder. once removing it from the path (and restarting cmd) the problem was fixed</p>

Body:
node --version
v4.5.0

npm --version
2.15.9

node-gyp --version
v3.4.0

which node
/home/admin/.nvm/versions/node/v4.5.0/bin/node

For some reason, after running sudo npm install -g node-gyp - node-gyp installs with node v0.10.25:

npm WARN engine cryptiles@2.0.5: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine boom@2.10.1: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})
npm WARN engine hoek@2.16.3: wanted: {"node":">=0.10.40"} (current: {"node":"v0.10.25","npm":"1.3.10"})

I've accessed /home/admin/.nvm/versions/node/ and found those folders: v4.4.4, v4.4.7, v4.5.0.

Can someone trigger the issue ? Where is that v0.10.25 version and how do I get rid of it ?


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
You don't "go one line up".  You output the first line and then output the second line.  So first you'd output your whole a array, then output a line of hyphens the length of that array.  Maybe something like this:

```<code>Console.WriteLine(string.Join("", a));
Console.WriteLine(string.Join("", a.Select(_ => "-")));
</code>```

The first line would join all elements of the a array into a single string, the second line uses kind of a trick with LINQ to "query" the a array but return a hyphen instead of anything from that array, then outputs the same way.

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----

Body:
You don't "go one line up".  You output the first line and then output the second line.  So first you'd output your whole a array, then output a line of hyphens the length of that array.  Maybe something like this:

Console.WriteLine(string.Join("", a));
Console.WriteLine(string.Join("", a.Select(_ => "-")));

The first line would join all elements of the a array into a single string, the second line uses kind of a trick with LINQ to "query" the a array but return a hyphen instead of anything from that array, then outputs the same way.


问:
How to write multiline macro with continue or break expression
In our recent project i write a macro that will continue on given condition and as explained here C multi-line macro: do/while(0) vs scope block I tried to use do--while to achieve that.
Below is sample code to illustrate that :

```<code>#define PRINT_ERROR_AND_CONTINUE_IF_EMPTY(dummy,dummystream,symbol,errorString) \
  do{ \
    if(dummy.empty())\
    {\
        dummyStream<<symbol<<",Failed,"<<errorString<<std::endl;\
        continue;\
    }\
  }while(0)
int main()
{
  int x =9;
  std::ofstream& ofsReportFile;
  while(x>5)
  {
      std::string str;
      PRINT_ERROR_AND_CONTINUE_IF_EMPTY(str,ofsReportFile,"Test","Test String is Empty");
      std::cout<<x<<std::endl;
      x--;
  }
  return 0;
}
</code>```

However this is not working as expected and the reason may be continue statement inside do while so question how to write multi-line macro with continue statement and also user of that macro can call it like CONTINUE_IF_EMPTY(str);

答:
How about a lambda? This looks like a good replacement for that macro that is both global (as all macros are) and oddly specific. Plus, you get captures to help whittling down the repeated parameters.</p>

```<code>int main()
{
    int x = 9;
    std::ofstream& ofsReportFile = /* ... */;

    auto const reportEmpty = [&](std::string const &str) {
        if(str.empty()) {
            ofsReportFile << "Test, Failed, Test String is Empty" << std::endl;
            return true;
        }
        return false;
    };

    while(x > 5)
    {
        std::string str;

        if(reportEmpty(str))
            continue;

        std::cout << x << std::endl;
        x--;
    }
}
</code>```

Body:
In our recent project i write a macro that will continue on given condition and as explained here C multi-line macro: do/while(0) vs scope block I tried to use do--while to achieve that.
Below is sample code to illustrate that :

#define PRINT_ERROR_AND_CONTINUE_IF_EMPTY(dummy,dummystream,symbol,errorString) \
  do{ \
    if(dummy.empty())\
    {\
        dummyStream<<symbol<<",Failed,"<<errorString<<std::endl;\
        continue;\
    }\
  }while(0)
int main()
{
  int x =9;
  std::ofstream& ofsReportFile;
  while(x>5)
  {
      std::string str;
      PRINT_ERROR_AND_CONTINUE_IF_EMPTY(str,ofsReportFile,"Test","Test String is Empty");
      std::cout<<x<<std::endl;
      x--;
  }
  return 0;
}

However this is not working as expected and the reason may be continue statement inside do while so question how to write multi-line macro with continue statement and also user of that macro can call it like CONTINUE_IF_EMPTY(str);

Body:
How about a lambda? This looks like a good replacement for that macro that is both global (as all macros are) and oddly specific. Plus, you get captures to help whittling down the repeated parameters.

int main()
{
    int x = 9;
    std::ofstream& ofsReportFile = /* ... */;

    auto const reportEmpty = [&](std::string const &str) {
        if(str.empty()) {
            ofsReportFile << "Test, Failed, Test String is Empty" << std::endl;
            return true;
        }
        return false;
    };

    while(x > 5)
    {
        std::string str;

        if(reportEmpty(str))
            continue;

        std::cout << x << std::endl;
        x--;
    }
}


问:
Omniauth: callback not firing, returns failure with "invalid credentials"
The facebook authentication in my Rails application, implemented with the Omniauth gem has stopped working recently.

The problem is that the controller action, that should be used by the callback is not getting fired, and the process immediately skips to failure with "invalid credentials" message.

log:

```<code>Started GET "/auth/facebook" for ::ffff:127.0.0.1 at 2017-03-29 11:12:29 +0200
Started GET "/auth/facebook/callback?code=<<code>>&state=<<state>" for ::ffff:127.0.0.1 at 2017-03-29 11:12:30 +0200
Started GET "/auth/failure?message=invalid_credentials&origin=<<origin>>&strategy=facebook" for ::ffff:127.0.0.1 at 2017-03-29 11:12:31 +0200
Started GET "/login" for ::ffff:127.0.0.1 at 2017-03-29 11:12:31 +0200
Processing by UserSessionsController#new as HTML
</code>```

routes:

```<code>  match "/auth/failure" => redirect("/login"), :via => [:get, :post]
  match '/auth/:provider/callback' => 'user_sessions#create_omniauth', :via => [:get, :post]
  match '/auth/:provider/disconnect' => 'user_sessions#destroy_omniauth', :as => :destroy_auth, :via => :delete
</code>```

Any ideas what could be wrong?

Edit:
I had the same problem with Google authorization.

答:
Updating gems to their newest versions (omniauth 1.6.1 and omniauth-facebook 4.0.0) with:

```<code>bundle update omniauth
bundle update omniauth-facebook
</code>```

solved the issue. I am leaving this for future reference.

Edit:

Same thing worked for google authorization:

```<code>bundle update omniauth-google-oauth2
</code>```

Body:
The facebook authentication in my Rails application, implemented with the Omniauth gem has stopped working recently.

The problem is that the controller action, that should be used by the callback is not getting fired, and the process immediately skips to failure with "invalid credentials" message.

log:

Started GET "/auth/facebook" for ::ffff:127.0.0.1 at 2017-03-29 11:12:29 +0200
Started GET "/auth/facebook/callback?code=<>&state=<<state>" for ::ffff:127.0.0.1 at 2017-03-29 11:12:30 +0200
Started GET "/auth/failure?message=invalid_credentials&origin=<<origin>>&strategy=facebook" for ::ffff:127.0.0.1 at 2017-03-29 11:12:31 +0200
Started GET "/login" for ::ffff:127.0.0.1 at 2017-03-29 11:12:31 +0200
Processing by UserSessionsController#new as HTML

routes:

  match "/auth/failure" => redirect("/login"), :via => [:get, :post]
  match '/auth/:provider/callback' => 'user_sessions#create_omniauth', :via => [:get, :post]
  match '/auth/:provider/disconnect' => 'user_sessions#destroy_omniauth', :as => :destroy_auth, :via => :delete

Any ideas what could be wrong?

Edit:
I had the same problem with Google authorization.

Body:
Updating gems to their newest versions (omniauth 1.6.1 and omniauth-facebook 4.0.0) with:

bundle update omniauth
bundle update omniauth-facebook

solved the issue. I am leaving this for future reference.

Edit:

Same thing worked for google authorization:

bundle update omniauth-google-oauth2


问:
I don't understand why is this step necessary to count the number of chars in text document
```<code>lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

```<code>no_of_chars = lines.length
</code>```

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

答:
What I do not understand is why is there a need to lines.join?

To get a full text(all items in the array) in one string

And what is the program doing when you lines.join?

Check the documentation.

Because when I puts lines or puts lines.join the program prints out
  the exact same thing.

Because lines is an array when you run puts lines it is shows an array as string, join() merge all array items to one string.

```<code>>> puts "fooo"
#> fooo
=> nil
>> puts ["fooo"].join
#> fooo
=> nil
</code>```

Therefore to get the number of chars in the text, why am I unable to
  just use no_of_chars = lines.length?

Becase when you use lines.length it's show the length of an array.

Body:
lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

no_of_chars = lines.length

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

Body:
What I do not understand is why is there a need to lines.join?

To get a full text(all items in the array) in one string

And what is the program doing when you lines.join?

Check the documentation.

Because when I puts lines or puts lines.join the program prints out
  the exact same thing.

Because lines is an array when you run puts lines it is shows an array as string, join() merge all array items to one string.

>> puts "fooo"
#> fooo
=> nil
>> puts ["fooo"].join
#> fooo
=> nil

Therefore to get the number of chars in the text, why am I unable to
  just use no_of_chars = lines.length?

Becase when you use lines.length it's show the length of an array.


问:
how to make np.where work in this example
I want the variable b, when the b is between (-2,2) , the output is b; when is beyond the domain (-2 ,2),the output is 0. I try a lot of times. The problem is it can not work continuously, for the first few lines, 0 is output. However, there still some value smaller than- 2, and the output is b itself, it should be 0.</p>

```<code>for k in range (nz):
    b = xg- nl*z[k]
    c = xg- nt*z[k]
    b = np.array(b)
    c = np.array(c)
    np.where((b > -2)&(b<2) ,b,0)
    np.where(( c >-2) & (c < 2),c,0)
</code>```

答:
What about if you multiply the masking arrays?</p>

```<code>import numpy as np

a = np.arange(-5,5)
# [-5 -4 -3 -2 -1  0  1  2  3  4]

cond = (a>-2)*(a<2)
b = np.where(cond,a,0)
# [ 0  0  0  0 -1  0  1  0  0  0]
</code>```

Body:
I want the variable b, when the b is between (-2,2) , the output is b; when is beyond the domain (-2 ,2),the output is 0. I try a lot of times. The problem is it can not work continuously, for the first few lines, 0 is output. However, there still some value smaller than- 2, and the output is b itself, it should be 0.

for k in range (nz):
    b = xg- nl*z[k]
    c = xg- nt*z[k]
    b = np.array(b)
    c = np.array(c)
    np.where((b > -2)&(b<2) ,b,0)
    np.where(( c >-2) & (c < 2),c,0)

Body:
What about if you multiply the masking arrays?

import numpy as np

a = np.arange(-5,5)
# [-5 -4 -3 -2 -1  0  1  2  3  4]

cond = (a>-2)*(a<2)
b = np.where(cond,a,0)
# [ 0  0  0  0 -1  0  1  0  0  0]


问:
Clear Cache in Android Application programmatically
what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

```<code>@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}
</code>```

答:
The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

```<code>import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());
</code>```

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

```<code>compile 'commons-io:commons-io:2.4'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Body:
The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'


问:
jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval In file: inline evaluation of: '' Encountered "," at line 1, column 9
I have a CSV file on a location from which i am reading the contents in a file.
Thats why i have added Jmeter Bean shell Post processor and checking values of variable in debug sampler.

There is no error coming in sccript and thread is successfully getting executed and values are properly coming in variable.
Hiwever, in Jmeter logs, i am getting error -

ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method:
  eval  In file: inline evaluation of:
  ``Location,Advertiser,Product,Campaign,Supplier,Insertion order
  ID,Invoice number, . . . '' Encountered "," at line 1, column 9.

I am having below code in my BeanShell PostProcessor -

```<code>${__FileToString(${InvoiceDataFile},UTF-8,CheckInvoice)}
</code>```

${InvoiceDataFile} is a variable which i defined in the user defined variable and its value is the path of the directory where my CSV file is present.

eg:
${__P(includecontroller.prefix)}/Reporting/Prisma/Prisma US/properties/ReportsVerificationUS-${__P(test.environment)}/invoice_report.csv

Please suggest.

Regards.

答:
Don't inline JMeter Variables like ${InvoiceDataFile} or functions into Beanshell script body, they may resolve into something which will cause syntax errors. The correct Beanshell equivalent function will look like:

```<code>vars.put("CheckInvoice", org.apache.commons.io.FileUtils.readFileToString(new File(vars.get("InvoiceDataFile")),"UTF-8"));
</code>```

Going forward you can take the next steps in order to get to the bottom of your Beanshell script failure:

Add debug(); directive at the beginning of your script. This way you will be able to see debugging output in STDOUT

Put your code inside try block like

```<code>try {
   //your code here
}
catch (Throwable ex) {
   log.error("Failed in Beanshell", ex);
   throw ex;
}
</code>```

This way you will see a "good" error stacktrace in the jmeter.log file.

See How to Use BeanShell: JMeter's Favorite Built-in Component for more information on Beanshell scripting in JMeter

Body:
I have a CSV file on a location from which i am reading the contents in a file.
Thats why i have added Jmeter Bean shell Post processor and checking values of variable in debug sampler.

There is no error coming in sccript and thread is successfully getting executed and values are properly coming in variable.
Hiwever, in Jmeter logs, i am getting error -

ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method:
  eval  In file: inline evaluation of:
  ``Location,Advertiser,Product,Campaign,Supplier,Insertion order
  ID,Invoice number, . . . '' Encountered "," at line 1, column 9.

I am having below code in my BeanShell PostProcessor -

${__FileToString(${InvoiceDataFile},UTF-8,CheckInvoice)}

${InvoiceDataFile} is a variable which i defined in the user defined variable and its value is the path of the directory where my CSV file is present.

eg:
${__P(includecontroller.prefix)}/Reporting/Prisma/Prisma US/properties/ReportsVerificationUS-${__P(test.environment)}/invoice_report.csv

Please suggest.

Regards.

Body:
Don't inline JMeter Variables like ${InvoiceDataFile} or functions into Beanshell script body, they may resolve into something which will cause syntax errors. The correct Beanshell equivalent function will look like:

vars.put("CheckInvoice", org.apache.commons.io.FileUtils.readFileToString(new File(vars.get("InvoiceDataFile")),"UTF-8"));

Going forward you can take the next steps in order to get to the bottom of your Beanshell script failure:

Add debug(); directive at the beginning of your script. This way you will be able to see debugging output in STDOUT

Put your code inside try block like

try {
   //your code here
}
catch (Throwable ex) {
   log.error("Failed in Beanshell", ex);
   throw ex;
}

This way you will see a "good" error stacktrace in the jmeter.log file.

See How to Use BeanShell: JMeter's Favorite Built-in Component for more information on Beanshell scripting in JMeter


问:
How to obtain the scale and rotation angle from LogPolar transform
I'm trying to use LogPolar transform to obtain the scale and the rotation angle from two images. Below are two 300x300 sample images. The first rectangle is 100x100, and the second rectangle is 150x150, rotated by 45 degree.

The algorithm:

Convert both images to LogPolar.

Find the translational shift using Phase Correlation.

Convert the translational shift to scale and rotation angle (how to do this?).

My code:

```<code>#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

int main()
{
    cv::Mat a = cv::imread("rect1.png", 0);
    cv::Mat b = cv::imread("rect2.png", 0);
    if (a.empty() || b.empty())
        return -1;

    cv::imshow("a", a);
    cv::imshow("b", b);

    cv::Mat pa = cv::Mat::zeros(a.size(), CV_8UC1);
    cv::Mat pb = cv::Mat::zeros(b.size(), CV_8UC1);
    IplImage ipl_a = a, ipl_pa = pa;
    IplImage ipl_b = b, ipl_pb = pb;
    cvLogPolar(&ipl_a, &ipl_pa, cvPoint2D32f(a.cols >> 1, a.rows >> 1), 40);
    cvLogPolar(&ipl_b, &ipl_pb, cvPoint2D32f(b.cols >> 1, b.rows >> 1), 40);

    cv::imshow("logpolar a", pa);
    cv::imshow("logpolar b", pb);

    cv::Mat pa_64f, pb_64f;
    pa.convertTo(pa_64f, CV_64F);
    pb.convertTo(pb_64f, CV_64F);

    cv::Point2d pt = cv::phaseCorrelate(pa_64f, pb_64f);

    std::cout << "Shift = " << pt
              << "Rotation = " << cv::format("%.2f", pt.y*180/(a.cols >> 1))
              << std::endl;

    cv::waitKey(0);

    return 0;
}
</code>```

The log polar images:

For the sample image images above, the translational shift is (16.2986, 36.9105). I have successfully obtain the rotation angle, which is 44.29. But I have difficulty in calculating the scale. How to convert the given translational shift to obtain the scale?

答:
This thread was helpful in getting me started on rotation-invariant phase correlation, so I hope my input will help resolve any lingering issues.

We aim to calculate the scale and rotation (which is incorrectly calculated in the code). Let's start by gathering the equations from the logPolar docs. There they state the following:

```<code>(1) I = (dx,dy) = (x-center.x, y-center.y)
(2) rho = M * ln(magnitude(I))
(3) phi = Ky * angle(I)_0..360
</code>```

Note: rho is pt.x and phi is pt.y in the code above

We also know that

```<code>(4) M = src.cols/ln(maxRadius)
(5) Ky = src.rows/360
</code>```

First, let's solve for scale. Solving for magnitude(I) (i.e. scale) in equation 2, we get

```<code>(6) magnitude(I) = scale = exp(rho/M)
</code>```

Then we substitute for M and simplify to get

```<code>(7) magnitude(I) = scale = exp(rho*ln(maxRadius)/src.cols) = pow(maxRadius, rho/src.cols)
</code>```

Now let's solve for rotation. Solving for angle(I) (i.e. rotation) in equation 3, we get

```<code>(8) angle(I) = rotation = phi/Ky
</code>```

Then we substitute for Ky and simplify to get

```<code>(9) angle(I) = rotation = phi*360/src.rows
</code>```

So, scale and rotation can be calculated using equations 7 and 9, respectively. It might be worth noting that you should use equation 4 for calculation M and Point2f center( (float)a.cols/2, (float)a.rows/2 ) for calculating center as opposed to what is in the code above. There are good bits of info in this logpolar example opencv code.

Body:
I'm trying to use LogPolar transform to obtain the scale and the rotation angle from two images. Below are two 300x300 sample images. The first rectangle is 100x100, and the second rectangle is 150x150, rotated by 45 degree.

The algorithm:

Convert both images to LogPolar.

Find the translational shift using Phase Correlation.

Convert the translational shift to scale and rotation angle (how to do this?).

My code:

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/imgproc/imgproc_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

int main()
{
    cv::Mat a = cv::imread("rect1.png", 0);
    cv::Mat b = cv::imread("rect2.png", 0);
    if (a.empty() || b.empty())
        return -1;

    cv::imshow("a", a);
    cv::imshow("b", b);

    cv::Mat pa = cv::Mat::zeros(a.size(), CV_8UC1);
    cv::Mat pb = cv::Mat::zeros(b.size(), CV_8UC1);
    IplImage ipl_a = a, ipl_pa = pa;
    IplImage ipl_b = b, ipl_pb = pb;
    cvLogPolar(&ipl_a, &ipl_pa, cvPoint2D32f(a.cols >> 1, a.rows >> 1), 40);
    cvLogPolar(&ipl_b, &ipl_pb, cvPoint2D32f(b.cols >> 1, b.rows >> 1), 40);

    cv::imshow("logpolar a", pa);
    cv::imshow("logpolar b", pb);

    cv::Mat pa_64f, pb_64f;
    pa.convertTo(pa_64f, CV_64F);
    pb.convertTo(pb_64f, CV_64F);

    cv::Point2d pt = cv::phaseCorrelate(pa_64f, pb_64f);

    std::cout << "Shift = " << pt
              << "Rotation = " << cv::format("%.2f", pt.y*180/(a.cols >> 1))
              << std::endl;

    cv::waitKey(0);

    return 0;
}

The log polar images:

For the sample image images above, the translational shift is (16.2986, 36.9105). I have successfully obtain the rotation angle, which is 44.29. But I have difficulty in calculating the scale. How to convert the given translational shift to obtain the scale?

Body:
This thread was helpful in getting me started on rotation-invariant phase correlation, so I hope my input will help resolve any lingering issues.

We aim to calculate the scale and rotation (which is incorrectly calculated in the code). Let's start by gathering the equations from the logPolar docs. There they state the following:

(1) I = (dx,dy) = (x-center.x, y-center.y)
(2) rho = M * ln(magnitude(I))
(3) phi = Ky * angle(I)_0..360

Note: rho is pt.x and phi is pt.y in the code above

We also know that

(4) M = src.cols/ln(maxRadius)
(5) Ky = src.rows/360

First, let's solve for scale. Solving for magnitude(I) (i.e. scale) in equation 2, we get

(6) magnitude(I) = scale = exp(rho/M)

Then we substitute for M and simplify to get

(7) magnitude(I) = scale = exp(rho*ln(maxRadius)/src.cols) = pow(maxRadius, rho/src.cols)

Now let's solve for rotation. Solving for angle(I) (i.e. rotation) in equation 3, we get

(8) angle(I) = rotation = phi/Ky

Then we substitute for Ky and simplify to get

(9) angle(I) = rotation = phi*360/src.rows

So, scale and rotation can be calculated using equations 7 and 9, respectively. It might be worth noting that you should use equation 4 for calculation M and Point2f center( (float)a.cols/2, (float)a.rows/2 ) for calculating center as opposed to what is in the code above. There are good bits of info in this logpolar example opencv code.


问:
Symfony 3: Passing variables into forms
I'm building using the Symfony 3 Forms, and need to retrieve a collection which is dependant on the current user, within the form to render in a dropdown.

Using the EntityType I can retrieve a list of all entities, but I want to be able to run a custom query which only retrieves those which have a relationship with the current user object.

I've read the documentation on forms and the EntityType, and it explains custom queries and mentions passing in a collection as an argument. But I cannot find instructions on how this is achieved anywhere.

Ideally, I'd like to either pass in a collection I've curated in the Controller, pass in the User object to run the query inside the Form, or otherwise access the user id in the form to run the query on.

Has anyone found a solution to anything similar?

答:
Here is how you can pass custom collection into the form.

For ex: Product entity;

inside controller

```<code>$form = $this->createForm(ProductType::class, $product, array('recommended_product' => $recommendedProduct));
</code>```

inside FormType

```<code> $builder
   ->add('recommended_product', EntityType::class, array(
            'class' => 'AppBundle\Entity\Product',
            'choices' => $options['recommended_product'],
            'choice_label' => function (Product $user) {
                return $user->getProduct();
            }
        ));

 public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Product',
        'recommended_product' => array()
    ));
}
</code>```

Title: Symfony 3: Passing variables into forms

Body:
Here is how you can pass custom collection into the form.

For ex: Product entity;

inside controller

$form = $this->createForm(ProductType::class, $product, array('recommended_product' => $recommendedProduct));

inside FormType

 $builder
   ->add('recommended_product', EntityType::class, array(
            'class' => 'AppBundle\Entity\Product',
            'choices' => $options['recommended_product'],
            'choice_label' => function (Product $user) {
                return $user->getProduct();
            }
        ));

 public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Product',
        'recommended_product' => array()
    ));
}


问:
Manually raising (throwing) an exception in Python
How do I raise an exception in Python so that it can later be caught via an except block?

答:
Read the existing answers first, this is just an addendum.

Notice that you can raise exceptions with or without arguments.

Example:

```<code>raise SystemExit
</code>```

exits the program, but you might want to know what happened. So you can use this.

```<code>raise SystemExit("program exited")
</code>```

This will print "program exited" to standard error before closing the program.

Body:
Read the existing answers first, this is just an addendum.

Notice that you can raise exceptions with or without arguments.

Example:

raise SystemExit

exits the program, but you might want to know what happened. So you can use this.

raise SystemExit("program exited")

This will print "program exited" to standard error before closing the program.


问:
java.io.FileNotFoundException:/BOOT-inf/classes!/templates/
i am useing springboot create a project ,it's no error run idea,but, run app.jar file ,it's run Exception like this

```<code>java.io.FileNotFoundException: class path resource [templates/] cannot be resol
ed to absolute file path because it does not reside in the file system: jar:fil
:/E:/projects/help/target/zhx-help-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/templa
es/
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:21
)
    at org.springframework.core.io.AbstractFileResolvingResource.getFile(Ab
tractFileResolvingResource.java:52)
    at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.get
emplateLoaderForPath(FreeMarkerConfigurationFactory.java:338)
    at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.cre
teConfiguration(FreeMarkerConfigurationFactory.java:290)
    at org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer
   afterPropertiesSet(FreeMarkerConfigurer.java:116)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getO
ject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegist
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetB
an(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBea
(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory
</code>```

springboot version :1.5.2

useing spring-data-jpa

答:
FreeMarkerConfigurationFactory.class

```<code>protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) {
    if(this.isPreferFileSystemAccess()) {
        try {
            Resource ex = this.getResourceLoader().getResource(templateLoaderPath);
            File file = ex.getFile();
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Template loader path [" + ex + "] resolved to file path [" + file.getAbsolutePath() + "]");
            }

            return new FileTemplateLoader(file);
        } catch (IOException var4) {
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Cannot resolve template loader path [" + templateLoaderPath + "] to [java.io.File]: using SpringTemplateLoader as fallback", var4);
            }

            return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
        }
    } else {
        this.logger.debug("File system access not preferred: using SpringTemplateLoader");
        return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
    }
}
</code>```

so make log lever info

```<code><logger name="org.springframework.web" level="INFO"/>
</code>```

Body:
i am useing springboot create a project ,it's no error run idea,but, run app.jar file ,it's run Exception like this

java.io.FileNotFoundException: class path resource [templates/] cannot be resol
ed to absolute file path because it does not reside in the file system: jar:fil
:/E:/projects/help/target/zhx-help-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/templa
es/
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:21
)
    at org.springframework.core.io.AbstractFileResolvingResource.getFile(Ab
tractFileResolvingResource.java:52)
    at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.get
emplateLoaderForPath(FreeMarkerConfigurationFactory.java:338)
    at org.springframework.ui.freemarker.FreeMarkerConfigurationFactory.cre
teConfiguration(FreeMarkerConfigurationFactory.java:290)
    at org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer
   afterPropertiesSet(FreeMarkerConfigurer.java:116)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBea
Factory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getO
ject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegist
y.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetB
an(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBea
(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory

springboot version :1.5.2

useing spring-data-jpa

Body:
FreeMarkerConfigurationFactory.class

protected TemplateLoader getTemplateLoaderForPath(String templateLoaderPath) {
    if(this.isPreferFileSystemAccess()) {
        try {
            Resource ex = this.getResourceLoader().getResource(templateLoaderPath);
            File file = ex.getFile();
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Template loader path [" + ex + "] resolved to file path [" + file.getAbsolutePath() + "]");
            }

            return new FileTemplateLoader(file);
        } catch (IOException var4) {
            if(this.logger.isDebugEnabled()) {
                this.logger.debug("Cannot resolve template loader path [" + templateLoaderPath + "] to [java.io.File]: using SpringTemplateLoader as fallback", var4);
            }

            return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
        }
    } else {
        this.logger.debug("File system access not preferred: using SpringTemplateLoader");
        return new SpringTemplateLoader(this.getResourceLoader(), templateLoaderPath);
    }
}

so make log lever info

<logger name="org.springframework.web" level="INFO"/>


问:
Create PushButtons in QTableView with QStyledItemDelegate subclass
I have the exact same problem, but I will use the QTableView widget. I read this and was wondering if I can override the createEditor function to use for instance QFileDialog to get the new data.

If this is possible, can anyone provide me with an example to implement such a subclass to QItemDelegate.

And if not, can anyone provide me with an example to implement a subclass to QItemDelegate, witch can draw a button next to a QLineEdit to get the functionality here.

Edit: Maybe this question is really stupid and i dont realize, because I left the project for around half a year.

Second: Is it safe to update from Qt 5.7 to 5.8?

答:
Use QStyledItemDelegate, not QItemDelegate.

Read the Qt Manual

QStyledItemDelegate class

Spinboxdelegate Example

Code example of subclassed QStyledItemDelegate (trimmed down):

Header file

```<code>#ifndef MYITEMDELEGATE_H
#define MYITEMDELEGATE_H

#include <QStyledItemDelegate>

class KontaktForm;

class MyItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT

    mutable SubscriberForm *subscriberForm;

public:
    explicit MyItemDelegate(QObject *parent = 0);
    ~MyItemDelegate();

////////!Methods - You don't need all of them
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);

};

#endif // MYITEMDELEGATE_H
</code>```

Source file

```<code>#include "myitemdelegate.h"

#include "mytreeview.h"
#include <QModelIndex>
#include <QSize>

MyItemDelegate::MyItemDelegate(QObject *parent) : QStyledItemDelegate(parent),
    subscriberForm(Q_NULLPTR),
{
}

QSize MyItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    //// return the QSize of the item in Your view
}

void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    ////optional : implement custom painting - text, images, drawings, and such
}

QWidget *MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    subscriberForm = new SubscriberForm(parent);
    ////optional additional settings for Your editor
    return subscriberForm;
}

void MyItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void MyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    ////setup the editor - your data are in index.data(Qt::DataRoles) - stored in a QVariant;
    QString value = index.model()->data(index,Qt::EditRole).toString();
    SubscriberForm *subscriberForm =  static_cast<SubscriberForm*>(editor);
}

void MyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    ////optional - if needed - return changed data, from editor to the model in a custom matter

    SubscriberForm *subscriberForm =  static_cast<SubscriberForm*>(editor);
    model->setData(index,QVariant(subscriberForm->getData()),Qt::EditRole);

}
</code>```

Body:
Use QStyledItemDelegate, not QItemDelegate.

Read the Qt Manual

QStyledItemDelegate class

Spinboxdelegate Example

Code example of subclassed QStyledItemDelegate (trimmed down):

Header file

#ifndef MYITEMDELEGATE_H
#define MYITEMDELEGATE_H

#include <QStyledItemDelegate>

class KontaktForm;

class MyItemDelegate : public QStyledItemDelegate
{
    Q_OBJECT

    mutable SubscriberForm *subscriberForm;

public:
    explicit MyItemDelegate(QObject *parent = 0);
    ~MyItemDelegate();

////////!Methods - You don't need all of them
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setEditorData(QWidget *editor, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
    void editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index);

};

#endif // MYITEMDELEGATE_H

Source file

#include "myitemdelegate.h"

#include "mytreeview.h"
#include <QModelIndex>
#include <QSize>

MyItemDelegate::MyItemDelegate(QObject *parent) : QStyledItemDelegate(parent),
    subscriberForm(Q_NULLPTR),
{
}

QSize MyItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    //// return the QSize of the item in Your view
}

void MyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    ////optional : implement custom painting - text, images, drawings, and such
}

QWidget *MyItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    subscriberForm = new SubscriberForm(parent);
    ////optional additional settings for Your editor
    return subscriberForm;
}

void MyItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    editor->setGeometry(option.rect);
}

void MyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    ////setup the editor - your data are in index.data(Qt::DataRoles) - stored in a QVariant;
    QString value = index.model()->data(index,Qt::EditRole).toString();
    SubscriberForm *subscriberForm =  static_cast<SubscriberForm*>(editor);
}

void MyItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    ////optional - if needed - return changed data, from editor to the model in a custom matter

    SubscriberForm *subscriberForm =  static_cast<SubscriberForm*>(editor);
    model->setData(index,QVariant(subscriberForm->getData()),Qt::EditRole);

}


问:
Make matrix out of the dictionary in Python
I have this data (taken part of random data coming from some server):

```<code> data={2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 3: [9,
 ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 5: [5, ['c', 'b', 'a',
 'b', 'b']], 7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}
</code>```

In this data, first number is the key, second value is the number of entries in the bracket following it. eg:-
For data

2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]

2 is the key. 9 is the total number of entries in the bracket which follows it.

Also, for keys having second value less than 9 are to be discarded.
I got that data.values() can give me the value as

[[9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [9, ['c',
  'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [5, ['c', 'b', 'a', 'b',
  'b']], [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

But I am not able to find any way to index within the matrix.

I need to make matrix out of this data as follows:

```<code>     a    b    c
2    4    5    0
3    4    4    1
7    4    3    2
</code>```

The matrix value [1][1] is the sum of a's in key value 2, [1][2] is the sum of b's in key value 2 and [1][3] is the sum of c's in key value 2, [2][1] is the sum of a's in key value 3, and so on..

答:
Probably Reut Sharabani's answer is better and faster, but here's how I would do it :

```<code>data = {
    2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    3: [9, ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    5: [5, ['c', 'b', 'a', 'b', 'b']],
    7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]
}

matrix = {key: {k: val[1].count(k) for k in set(val[1])} for key, val in data.iteritems() if val[0] >=9}
</code>```

Which will give you :

```<code>{2: {'a': 4, 'b': 5},
 3: {'a': 4, 'b': 4, 'c': 1},
 5: {'a': 1, 'b': 3, 'c': 1},
 7: {'a': 4, 'b': 3, 'c': 2}}
</code>```

And, of course, use the .get('c', 0) so you get 0's for values which are 0.

*Edited to adapt to original question, keys below 9 must be discarded.

Body:
I have this data (taken part of random data coming from some server):

 data={2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 3: [9,
 ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], 5: [5, ['c', 'b', 'a',
 'b', 'b']], 7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

In this data, first number is the key, second value is the number of entries in the bracket following it. eg:-
For data

2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]

2 is the key. 9 is the total number of entries in the bracket which follows it.

Also, for keys having second value less than 9 are to be discarded.
I got that data.values() can give me the value as

[[9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [9, ['c',
  'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']], [5, ['c', 'b', 'a', 'b',
  'b']], [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]}

But I am not able to find any way to index within the matrix.

I need to make matrix out of this data as follows:

     a    b    c
2    4    5    0
3    4    4    1
7    4    3    2

The matrix value [1][1] is the sum of a's in key value 2, [1][2] is the sum of b's in key value 2 and [1][3] is the sum of c's in key value 2, [2][1] is the sum of a's in key value 3, and so on..

Body:
Probably Reut Sharabani's answer is better and faster, but here's how I would do it :

data = {
    2: [9, ['b', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    3: [9, ['c', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']],
    5: [5, ['c', 'b', 'a', 'b', 'b']],
    7: [9, ['c', 'c', 'a', 'b', 'a', 'b', 'a', 'b', 'a']]
}

matrix = {key: {k: val[1].count(k) for k in set(val[1])} for key, val in data.iteritems() if val[0] >=9}

Which will give you :

{2: {'a': 4, 'b': 5},
 3: {'a': 4, 'b': 4, 'c': 1},
 5: {'a': 1, 'b': 3, 'c': 1},
 7: {'a': 4, 'b': 3, 'c': 2}}

And, of course, use the .get('c', 0) so you get 0's for values which are 0.

*Edited to adapt to original question, keys below 9 must be discarded.


问:
Xamarin.Droid - Get device phone number
I'm currently working on a Xamarin forms project in which I need to be able to get the user's phone number from device. It figured out that it was not possible to do that on iOS and Windows Phone, but I still want to do that for Android, that's why I've found on the Internet a piece of code that should be working on Android. I'm using MVVM pattern.

In my ViewModel, I try to get the phone number this way :

```<code>   string phoneNumber = DependencyService.Get<IPhoneNumber>().GetPhoneNumber();
</code>```

Which calls this method from this class :

```<code> public class PhoneNumber : IPhoneNumber
    {
        public string GetPhoneNumber()
        {
            TelephonyManager mTelephonyMgr;
            mTelephonyMgr = (TelephonyManager)Application.Context.GetSystemService(Context.TelephonyService);
            return mTelephonyMgr.Line1Number;
        }
    }
</code>```

When I run my app on Android Emulator for visual studio, it works, I get a phone number made up of 11 digits. But when I'm on a real device, the method returns an empty string (""). I've put the READ_PHONE_STATE permission in my AndroidManifest.xml file. Oh also, of course, my real device has a SIM card plugged in, and it has only one SIM slot.

Did I miss something ? I'll try to test it on another device as soon as I can, but it is currently not possible.

Thanks for your help !

答:
So, as Emad said in a comment of my question :

I tried this long ago using native android programs and it was shown that many operators don't give this information. Especially in Iran non of the active operators do that. I've heard it's even illegal! That's why apps like Telegram and Viber ask your number.

So, after a few more research, it is indeed not possible to get the phone number for sure without asking the user.

Hope it helped !

Title: Xamarin.Droid - Get device phone number

Body:
I'm currently working on a Xamarin forms project in which I need to be able to get the user's phone number from device. It figured out that it was not possible to do that on iOS and Windows Phone, but I still want to do that for Android, that's why I've found on the Internet a piece of code that should be working on Android. I'm using MVVM pattern.

In my ViewModel, I try to get the phone number this way :

   string phoneNumber = DependencyService.Get<IPhoneNumber>().GetPhoneNumber();

Which calls this method from this class :

 public class PhoneNumber : IPhoneNumber
    {
        public string GetPhoneNumber()
        {
            TelephonyManager mTelephonyMgr;
            mTelephonyMgr = (TelephonyManager)Application.Context.GetSystemService(Context.TelephonyService);
            return mTelephonyMgr.Line1Number;
        }
    }

When I run my app on Android Emulator for visual studio, it works, I get a phone number made up of 11 digits. But when I'm on a real device, the method returns an empty string (""). I've put the READ_PHONE_STATE permission in my AndroidManifest.xml file. Oh also, of course, my real device has a SIM card plugged in, and it has only one SIM slot.

Did I miss something ? I'll try to test it on another device as soon as I can, but it is currently not possible.

Thanks for your help !


问:
Timeout exception in sqlite
Error: java.util.concurrent.TimeoutException: android.database.sqlite.SQLiteConnection.finalize() timed out after 10 seconds

I get this error but didn't find any specific line in project.Below is my logcat output:

```<code>    java.util.concurrent.TimeoutException: android.database.sqlite.SQLiteConnection.finalize() timed out after 10 seconds
    at android.database.sqlite.SQLiteConnection.nativeClose(Native Method)
    at android.database.sqlite.SQLiteConnection.dispose(SQLiteConnection.java:238)
    at android.database.sqlite.SQLiteConnection.finalize(SQLiteConnection.java:178)
    at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202)
    at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185)
    at java.lang.Thread.run(Thread.java:818)
</code>```

答: Garbage collector tries to clear your SQLiteConnection instance, which you have forgot to close yourself. Take care of close()ing db instance.

Title: Timeout exception in sqlite

Body:
Error: java.util.concurrent.TimeoutException: android.database.sqlite.SQLiteConnection.finalize() timed out after 10 seconds

I get this error but didn't find any specific line in project.Below is my logcat output:

    java.util.concurrent.TimeoutException: android.database.sqlite.SQLiteConnection.finalize() timed out after 10 seconds
    at android.database.sqlite.SQLiteConnection.nativeClose(Native Method)
    at android.database.sqlite.SQLiteConnection.dispose(SQLiteConnection.java:238)
    at android.database.sqlite.SQLiteConnection.finalize(SQLiteConnection.java:178)
    at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:202)
    at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:185)
    at java.lang.Thread.run(Thread.java:818)


问:
git status does not work properly with Virtualbox Shared Folders

Details

Host Machine:  macOS Sierra

Guest Machine: Ubuntu 64bits 16.04 LTS

Virtualbox:    5.1.14

On the host the repository is only local for now. Initialized and have several [local] commits without a single push to remote.

Symptoms

On my host machine I have parent folder with a Git repository on it.
I have shared parent folder with the guest machine, after login on the VM the folder is in /media/sf_parent.

In a terminal I do cd /media/sf_parent at the moment the content seems to be properly shared.
But when I change to the repo folder I tried to do a git status and the output is as everything single file in the repository is tracked but modified.

The strange part is that the git log delivers the last commit I have made on host.
I tried to visually compare both "versions" of the repository folder with ls and they the same value for "update date" and "file size" but have different values for "owner", "group" and "permissions".

What could be the problem?

Maybe Virtualbox somehow does not support this?

Might be the conflict on filesystem level with "owner" and "permissions"?

答:
With the help of git config I was able to resolve this problem as I suspected and @g19fanatic suggested this problem seems to be related with "user permissions".

After reading a lot of the properties on the page I tested this two:

```<code>git config core.filemode false
git config core.ignorecase false
</code>```

PS: Their are both true as default.

Restarted the VM and it worked, now working tree is synced between host and guest.

Body:
With the help of git config I was able to resolve this problem as I suspected and @g19fanatic suggested this problem seems to be related with "user permissions".

After reading a lot of the properties on the page I tested this two:

git config core.filemode false
git config core.ignorecase false

PS: Their are both true as default.

Restarted the VM and it worked, now working tree is synced between host and guest.


问:
SWRevealViewController: Change color of frontview when rearview(menu) is open
I am using Swift 3 with SWRevealViewController to create side bar menu app.

How do I control the color of front view when rear view (menu) is open?
I would like to display gray color (like disabled/ transparent).
So far whatever I tried hasn't worked and not able to find straight forward solution online.
I could control rearview color but not front view.

So far I have tried changing front view color in viewWillAppear of rear view controller.

viewWillAppear in MenuController looks like:

override func viewWillAppear(_ animated: Bool) {

```<code>print("MenuController - viewWillAppear")
super.viewWillAppear(animated)
self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
self.revealViewController().view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.revealViewController().frontViewController.view.backgroundColor = UIColor.blue
self.revealViewController().rearViewController.view.backgroundColor = UIColor.gray
}
</code>```

It changes color for rear view but doesn't work for front view.
And I want grayed out disabled look not just change background color.

答:
Try and add this to your viewWillAppear method in your rearVieController class

```<code>revealViewController.frontViewController.view.backgroundColor = UIColor.blue //Set colour to what ever you want
</code>```

So it should look like this

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    revealViewController.frontViewController.view.backgroundColor = UIColor.blue
}
</code>```

Edit:

Okay I have tried to do this and it seems to work

If you create a new UIView and add it to the frontViewController then remove it when the view disappears.

```<code>var view: UIView?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //Create the view the same size as your frontViewController
    view = UIView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(revealViewController.view.frame.size.width), height: CGFloat(revealViewController.view.frame.size.height)))
    //Set the colour of the view to whatever you like
    view?.backgroundColor = UIColor.blue
    //Add the new view to the frontViewcontroller
    revealViewController.frontViewController.view.addSubview(view!)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    //Remove the view from the frontViewController
    view?.removeFromSuperview()
}
</code>```

Edit:

If you add a tap gesture to the UIView then remove the view in the tap function instead of the viewWillDisappear

```<code>var view: UIView?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //Create the view the same size as your frontViewController
    view = UIView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(revealViewController.view.frame.size.width), height: CGFloat(revealViewController.view.frame.size.height)))
    //Set the colour of the view to whatever you like
    view?.backgroundColor = UIColor.blue
    //Add a tap gesture to the UIview
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
    view?.addGestureRecognizer(tap)
    //Add the new view to the frontViewcontroller
    revealViewController.frontViewController.view.addSubview(view!)
}

func handleTap(_ sender: UITapGestureRecognizer) {
    //Remove the view from the frontViewController
    view?.removeFromSuperview()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    //Moved the remove to the tap gesture function
}
</code>```

Body:
I am using Swift 3 with SWRevealViewController to create side bar menu app.

How do I control the color of front view when rear view (menu) is open?
I would like to display gray color (like disabled/ transparent).
So far whatever I tried hasn't worked and not able to find straight forward solution online.
I could control rearview color but not front view.

So far I have tried changing front view color in viewWillAppear of rear view controller.

viewWillAppear in MenuController looks like:

override func viewWillAppear(_ animated: Bool) {

print("MenuController - viewWillAppear")
super.viewWillAppear(animated)
self.revealViewController().frontViewController.view.isUserInteractionEnabled = false
self.revealViewController().view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
self.revealViewController().frontViewController.view.backgroundColor = UIColor.blue
self.revealViewController().rearViewController.view.backgroundColor = UIColor.gray
}

It changes color for rear view but doesn't work for front view.
And I want grayed out disabled look not just change background color.

Body:
Try and add this to your viewWillAppear method in your rearVieController class

revealViewController.frontViewController.view.backgroundColor = UIColor.blue //Set colour to what ever you want

So it should look like this

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    revealViewController.frontViewController.view.backgroundColor = UIColor.blue
}

Edit:

Okay I have tried to do this and it seems to work

If you create a new UIView and add it to the frontViewController then remove it when the view disappears.

var view: UIView?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //Create the view the same size as your frontViewController
    view = UIView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(revealViewController.view.frame.size.width), height: CGFloat(revealViewController.view.frame.size.height)))
    //Set the colour of the view to whatever you like
    view?.backgroundColor = UIColor.blue
    //Add the new view to the frontViewcontroller
    revealViewController.frontViewController.view.addSubview(view!)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    //Remove the view from the frontViewController
    view?.removeFromSuperview()
}

Edit:

If you add a tap gesture to the UIView then remove the view in the tap function instead of the viewWillDisappear

var view: UIView?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //Create the view the same size as your frontViewController
    view = UIView(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(revealViewController.view.frame.size.width), height: CGFloat(revealViewController.view.frame.size.height)))
    //Set the colour of the view to whatever you like
    view?.backgroundColor = UIColor.blue
    //Add a tap gesture to the UIview
    let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
    view?.addGestureRecognizer(tap)
    //Add the new view to the frontViewcontroller
    revealViewController.frontViewController.view.addSubview(view!)
}

func handleTap(_ sender: UITapGestureRecognizer) {
    //Remove the view from the frontViewController
    view?.removeFromSuperview()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    //Moved the remove to the tap gesture function
}


问:
Bind dropdown using jQuery in ruby on rails.syntax error, unexpected tIDENTIFIER, expecting ':' render :text => [@storeitem.unit_pr... ^
I have two controller Indent and InventoryStoreItem relation is 'indent-'has_many :inventory_store_items' and inventory_store_item-'belongs_to :indent'.when i select drop down as store_item_id(i.e is item_name) from indent-form it will fetch store item attributes i.e is unit_price,quantity,batch_no from store item. I tried using  when user select drop down option from select box. than on change event will fire and through ajax.but the js did'nt works.This is my code.

indent_controller

```<code>class IndentsController < ApplicationController
def index_indent
 @store_items = InventoryStoreItem.find(params[:id])
 @indents = Indent.all
 @stores = InventoryStore.all
end

def load_item_data
 @storeitem = InventoryStoreItem.find_by_id(params[:inventory_store_item_id]).present? InventoryStoreItem.find(params[:inventory_store_item_id]): InventoryStoreItem.unscoped.find_by_id(params[:inventory_store_item_id])
end
</code>```

indent.js.coffee

```<code> #Load Items data when an item is selected from dropdown list
'$('#select_inventory_store_item_id').on('change',function(){ var inventory_store_item_id = $('#select_inventory_store_item_id').val() $.ajax({ url: '/indents/load_item_data', type: 'GET', data: {'id' : inventory_store_item_id}, dataType: 'json' }).success(function(data) })'
</code>```

new_indent

```<code><%= form_for @indent, url:{controller: 'indents',action:'create_indent'} do |c|%>
 <div class="form-group">
  <div class="col-md-3"><b>Indent No:</b></div>
   <%=c.text_field :indent_no, placeholder: "Indent No", class: "form-control",style:"width:250px"%>
 </div>

 <div class="form-group">
  <div class="col-md-3"><b>Expected Date:</b></div>
   <%= c.date_field :expected_date, :value => Time.now.strftime('%Y-%m-%d'),class: "datepicker form-control",style:"width:250px" %>
 </div>

 <div class="form-group">
  <div class="col-md-3"><b>Description</b></div>
   <%=c.text_field :description, class: "form-control",style: 'width:350px;height:100px'%>
 </div>

 <h3>Indent Items</h3>
 <div class="form-group">
  <div class="col-md-3"><b>Required</b></div>
   <%=c.text_field :required, placeholder: "Required", class: "form-control",style:"width:250px"%>
 </div>

 <div class="form-group">
  <div class="col-md-3"><b>Pending</b></div>
   <%=c.text_field :pending, placeholder: "Pending", class: "form-control",style:"width:250px"%>
  </div>

 <div class="form-group">
  <div class="col-md-3"> <b>Store Item:</b></div>
   <td class="col-3"> <%= c.select :inventory_store_item_id,InventoryStoreItem.all.collect{|b| [b.item_name,b.id]},{prompt:"select Item"}%></td>
 </div>
 <div class="form-group">
  <div class="col-md-3"><b>Unit_price</b></div>
   <%=text_field_tag :unit_price%>
 </div>

 <div class="form-group">
  <div class="col-md-3"><b>Quantity</b></div>
   <%=text_field_tag :quantity%>
 </div>

 <div class="form-group">
  <div class="col-md-3"><b>Batch No</b></div>
   <%=text_field_tag :batch_no%>
 </div>

 <div class="col-sm-4 col-sm-offset-4">
  <div class="form-actions">
   <%= c.submit 'Save', class: "btn btn-primary"%>
 </div>
</code>```

答:
data: {id: inventory_store_item_id}
It should be data: {inventory_store_item_id: inventory_store_item_id}.

Your load_item_data action is still wrong. The syntax is condition ? true : false.

@storeitem = InventoryStoreItem.find_by_id(params[:inventory_store_item_id]).present? ? InventoryStoreItem.find(params[:inventory_store_item_id]) : InventoryStoreItem.unscoped.find_by_id(params[:inventory_store_item_id])

Body:
I have two controller Indent and InventoryStoreItem relation is 'indent-'has_many :inventory_store_items' and inventory_store_item-'belongs_to :indent'.when i select drop down as store_item_id(i.e is item_name) from indent-form it will fetch store item attributes i.e is unit_price,quantity,batch_no from store item. I tried using  when user select drop down option from select box. than on change event will fire and through ajax.but the js did'nt works.This is my code.

indent_controller

class IndentsController < ApplicationController
def index_indent
 @store_items = InventoryStoreItem.find(params[:id])
 @indents = Indent.all
 @stores = InventoryStore.all
end

def load_item_data
 @storeitem = InventoryStoreItem.find_by_id(params[:inventory_store_item_id]).present? InventoryStoreItem.find(params[:inventory_store_item_id]): InventoryStoreItem.unscoped.find_by_id(params[:inventory_store_item_id])
end

indent.js.coffee

 #Load Items data when an item is selected from dropdown list
'$('#select_inventory_store_item_id').on('change',function(){ var inventory_store_item_id = $('#select_inventory_store_item_id').val() $.ajax({ url: '/indents/load_item_data', type: 'GET', data: {'id' : inventory_store_item_id}, dataType: 'json' }).success(function(data) })'

new_indent

<%= form_for @indent, url:{controller: 'indents',action:'create_indent'} do |c|%>

Indent No:

   <%=c.text_field :indent_no, placeholder: "Indent No", class: "form-control",style:"width:250px"%>

Expected Date:

   <%= c.date_field :expected_date, :value => Time.now.strftime('%Y-%m-%d'),class: "datepicker form-control",style:"width:250px" %>

Description

   <%=c.text_field :description, class: "form-control",style: 'width:350px;height:100px'%>

Indent Items

Required

   <%=c.text_field :required, placeholder: "Required", class: "form-control",style:"width:250px"%>

Pending

   <%=c.text_field :pending, placeholder: "Pending", class: "form-control",style:"width:250px"%>

 Store Item:

    <%= c.select :inventory_store_item_id,InventoryStoreItem.all.collect{|b| [b.item_name,b.id]},{prompt:"select Item"}%>

Unit_price

   <%=text_field_tag :unit_price%>

Quantity

   <%=text_field_tag :quantity%>

Batch No

   <%=text_field_tag :batch_no%>

   <%= c.submit 'Save', class: "btn btn-primary"%>


问:
How to use pandas.DataFrame.mask for NaN
I want to ignore NaN values in my selected dataframe columns when I want to normalize with sklearn.preprocessing.normalize. Column example:

```<code>0     12.0
1     12.0
2      3.0
3      NaN
4      3.0
5      3.0
6      NaN
7      NaN
8      3.0
9      3.0
10     3.0
11     4.0
12    10.0
</code>```

答:
You can make use of function dropna(). It will return the same dataframe with rows containing NaN deleted.

```<code>>>> a.dropna()
     0  12.0
0    1    12
1    2     3
3    4     3
4    5     3
7    8     3
8    9     3
9   10     3
10  11     4
11  12    10
</code>```

Body:
I want to ignore NaN values in my selected dataframe columns when I want to normalize with sklearn.preprocessing.normalize. Column example:

0     12.0
1     12.0
2      3.0
3      NaN
4      3.0
5      3.0
6      NaN
7      NaN
8      3.0
9      3.0
10     3.0
11     4.0
12    10.0

Body:
You can make use of function dropna(). It will return the same dataframe with rows containing NaN deleted.

>>> a.dropna()
     0  12.0
0    1    12
1    2     3
3    4     3
4    5     3
7    8     3
8    9     3
9   10     3
10  11     4
11  12    10


问:
Scrolling while message box is running
I have the following macro to show a message box to the user:

```<code>Sub Messageboxtest()
Test = MsgBox("Do you want to continue", vbYesNo)
If Answer = vbYes Then
Sheets(1).Range("A2").Value = 1
Else
End If
End Sub
</code>```

The macro itself works perfectly. However, once the message box is shown on the excel screen the user cannot scroll down in the Excel File anymore.

For an input box I know there is the function Application.InputBox but is there also something like Application.MessageBox?

答:
There's API alternative! Declare in a top of module this function:

```<code>#If VBA7 Then
    Public Declare PtrSafe Function ModelessMsgBox Lib "User32" Alias "MessageBoxA" (Optional ByVal hWnd As Long, _
            Optional ByVal prompt As String, _
            Optional ByVal title As String, _
            Optional ByVal buttons As Long) As Long
#Else
    Public Declare Function ModelessMsgBox Lib "User32" Alias "MessageBoxA" (Optional ByVal hWnd As Long, _
            Optional ByVal prompt As String, _
            Optional ByVal title As String, _
            Optional ByVal buttons As Long) As Long
#End If
</code>```

And use it like this:

```<code>Call ModelessMsgBox(prompt:="MsgBox!!!!", buttons:=vbYesNo)
</code>```

However, this MsgBox stops code execution (when modeless forms doesn't, dooming you to use another garbage set of global/static variables and/or to supress events just to control execution flow), so it can be used like this:

```<code>If ModelessMsgBox(prompt:="MsgBox!!!!", buttons:=vbYesNo) = vbYes Then
    'do smth
Else
    'do smth else
End If
</code>```

More here

Title: Scrolling while message box is running

Body:
I have the following macro to show a message box to the user:

Sub Messageboxtest()
Test = MsgBox("Do you want to continue", vbYesNo)
If Answer = vbYes Then
Sheets(1).Range("A2").Value = 1
Else
End If
End Sub

The macro itself works perfectly. However, once the message box is shown on the excel screen the user cannot scroll down in the Excel File anymore.

For an input box I know there is the function Application.InputBox but is there also something like Application.MessageBox?

Body:
There's API alternative! Declare in a top of module this function:

#If VBA7 Then
    Public Declare PtrSafe Function ModelessMsgBox Lib "User32" Alias "MessageBoxA" (Optional ByVal hWnd As Long, _
            Optional ByVal prompt As String, _
            Optional ByVal title As String, _
            Optional ByVal buttons As Long) As Long
#Else
    Public Declare Function ModelessMsgBox Lib "User32" Alias "MessageBoxA" (Optional ByVal hWnd As Long, _
            Optional ByVal prompt As String, _
            Optional ByVal title As String, _
            Optional ByVal buttons As Long) As Long
#End If

And use it like this:

Call ModelessMsgBox(prompt:="MsgBox!!!!", buttons:=vbYesNo)

However, this MsgBox stops code execution (when modeless forms doesn't, dooming you to use another garbage set of global/static variables and/or to supress events just to control execution flow), so it can be used like this:

If ModelessMsgBox(prompt:="MsgBox!!!!", buttons:=vbYesNo) = vbYes Then
    'do smth
Else
    'do smth else
End If

More here


问:
I don't understand why is this step necessary to count the number of chars in text document
```<code>lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

```<code>no_of_chars = lines.length
</code>```

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

答:
When you do this

```<code>lines = File.readlines("new text document.txt")
</code>```

you have an array of strings, i.e.:

```<code>lines #=> [
  "The surgeon lead over ...\n", # <- There's a newline at the end of each string
  "The medical gentleman ...\n",
]
</code>```

There are as many entries on the array as lines on your text file. That's why you count the number of lines by doing:

```<code>lines_count =lines.size
</code>```

When you call lines.join you are essentially concatenating all the strings together one after another

```<code>text = lines.join
text # => "The surgeon ... dress the infant"
</code>```

And to calculate the number of characters of string you just call length on it.

The reason they look similar to you on the console is because when you print them they get represented in an identical way. To highlight the difference you may call inspect on each of them:

```<code>puts lines.inspect
puts text.inspect
</code>```

Body:
lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

no_of_chars = lines.length

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

Body:
When you do this

lines = File.readlines("new text document.txt")

you have an array of strings, i.e.:

lines #=> [
  "The surgeon lead over ...\n", # <- There's a newline at the end of each string
  "The medical gentleman ...\n",
]

There are as many entries on the array as lines on your text file. That's why you count the number of lines by doing:

lines_count =lines.size

When you call lines.join you are essentially concatenating all the strings together one after another

text = lines.join
text # => "The surgeon ... dress the infant"

And to calculate the number of characters of string you just call length on it.

The reason they look similar to you on the console is because when you print them they get represented in an identical way. To highlight the difference you may call inspect on each of them:

puts lines.inspect
puts text.inspect


问:
I need help to connect WebSocket SignalR
i have a problem to connect my app.js on my hubs/socket.js

when made my js and put the conecction

var stream = $.connection.sockets;

show my this error

app.js:2 Uncaught TypeError: Cannot read property 'sockets' of undefined

i coppy a example from other proyect and i don't know how does it work

i made the proyect in asp.net mvc in visual studio 2015

答:
What is the order of js references you have made?
Also, have you added reference to the signalr jQuery library and signalr/hubs?</p>


问:
keyboard search button enter
i have a employees form that contain button i i start my project when i want to search i have to click by mouse arrow on search can i choose another option by clicking enter button for search for more details for my project i'm using visual studio 2017 c# forms if any detail is missing please just notice

答:
Wrap the part you want to submit with a Panel. Then assign a DefaultButton to that Panel. Now when a user presses enter in a TextBox within that panel, the assigned button will be pressed.

```<code><asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
          ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"
          ValidationGroup="myForm"></asp:RequiredFieldValidator>

    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myForm" />

</asp:Panel>
</code>```

Title: keyboard search button enter

Body:
Wrap the part you want to submit with a Panel. Then assign a DefaultButton to that Panel. Now when a user presses enter in a TextBox within that panel, the assigned button will be pressed.

<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">

    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
          ControlToValidate="TextBox1" ErrorMessage="RequiredFieldValidator"
          ValidationGroup="myForm"></asp:RequiredFieldValidator>

    <asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myForm" />

</asp:Panel>


问:
Is it possible to supply Tomcat6's context.xml file via the Maven Cargo plugin?
I'd like to keep Tomcat's context.xml file out of my WAR file's META-INF directory if possible.  Can this be done with Maven's cargo plugin?  I can't seem to find the correct configuration.</p>

答:
I haven't found a way to do this yet, but I have come up with a work around that works in my project.  I currently have a project with essentially 3 submodules:

```<code>    dependencies
    webapp
    smoketest
</code>```

When I'm building the "webapp" project, I execute the following plugin declaration:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <executions>
        <execution>
        <id>create-war-smoketest</id>
        <phase>verify</phase>
        <goals>
            <goal>war</goal>
        </goals>
        <configuration>
            <webappDirectory>${project.build.directory}/exploded</webappDirectory>
            <primaryArtifact>false</primaryArtifact>
            <classifier>smoketest</classifier>
            <webResources>
            <resource>
                <filtering>true</filtering>
                <directory>src/test/resources/smoketest</directory>
                <targetPath>META-INF</targetPath>
                <includes>
                    <include>context.xml</include>
                </includes>
            </resource>
            </webResources>
        </configuration>
        </execution>
    </executions>
</plugin>
</code>```

And then when I'm running my Cargo/WebTest suite in the SmokeTest project, I specify the smoketest WAR file as a dependency and in my Cargo configuration set my deployrables thusly:

```<code><deployables>
    <deployable>
        <groupId>${pom.groupId}</groupId>
        <artifactId>webapp</artifactId>
        <type>war</type>
        <properties>
            <context>smoketest</context>
        </properties>
    </deployable>
</deployables>
</code>```

With the dependency looking something like:

```<code><dependencies>
    <dependency>
        <groupId>${pom.groupId}</groupId>
        <artifactId>webapp</artifactId>
        <version>${pom.version}</version>
        <classifier>smoketest</classifier>
        <type>war</type>
        <scope>system</scope>
        <!-- trick the dependency plugin to never look for it in the repo -->
        <systemPath>${basedir}/../webapp/target/webapp-${pom.version}-smoketest.war</systemPath>
    </dependency>
</dependencies>
</code>```

It's extremely dirty, but it at least works... for now.  One quick note: my comment about forcing it to never look for a version in the repo is possibly incorrect at this point; I think this trick may have been broken by a change to the dependency plugin at some point.

Body:
I haven't found a way to do this yet, but I have come up with a work around that works in my project.  I currently have a project with essentially 3 submodules:

    dependencies
    webapp
    smoketest

When I'm building the "webapp" project, I execute the following plugin declaration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <executions>
        <execution>
        <id>create-war-smoketest</id>
        <phase>verify</phase>
        <goals>
            <goal>war</goal>
        </goals>
        <configuration>
            <webappDirectory>${project.build.directory}/exploded</webappDirectory>
            <primaryArtifact>false</primaryArtifact>
            <classifier>smoketest</classifier>
            <webResources>
            <resource>
                <filtering>true</filtering>
                <directory>src/test/resources/smoketest</directory>
                <targetPath>META-INF</targetPath>
                <includes>
                    <include>context.xml</include>
                </includes>
            </resource>
            </webResources>
        </configuration>
        </execution>
    </executions>
</plugin>

And then when I'm running my Cargo/WebTest suite in the SmokeTest project, I specify the smoketest WAR file as a dependency and in my Cargo configuration set my deployrables thusly:

<deployables>
    <deployable>
        <groupId>${pom.groupId}</groupId>
        <artifactId>webapp</artifactId>
        <type>war</type>
        <properties>
            <context>smoketest</context>
        </properties>
    </deployable>
</deployables>

With the dependency looking something like:

<dependencies>
    <dependency>
        <groupId>${pom.groupId}</groupId>
        <artifactId>webapp</artifactId>
        <version>${pom.version}</version>
        <classifier>smoketest</classifier>
        <type>war</type>
        <scope>system</scope>
        <!-- trick the dependency plugin to never look for it in the repo -->
        <systemPath>${basedir}/../webapp/target/webapp-${pom.version}-smoketest.war</systemPath>
    </dependency>
</dependencies>

It's extremely dirty, but it at least works... for now.  One quick note: my comment about forcing it to never look for a version in the repo is possibly incorrect at this point; I think this trick may have been broken by a change to the dependency plugin at some point.


问:
Char Array to Lambda Expression
I am now learning lambda expression used in Java.
In this case, I have a problem in changing char[] array to lambda expression.
So, I would like to ask some help.
My sample code is below.

```<code>    Map<String, String> tempMap = new HashMap<String, String>();
    tempMap.put("a", "A");
    tempMap.put("b", "B");
    tempMap.put("c", "C");
    tempMap.put("d", "D");
    tempMap.put("e", "E");
    String tempStr = "abcdef";
    StringBuilder tempBuilder = new StringBuilder();
    char[] tempArray = tempStr.toCharArray();
    for(char c : tempArray) {
    tempBuilder.append(tempMap.getOrDefault(String.ValueOf(c),
    String.ValueOf(c));
    }
</code>```

Result should be "ABCDEf". Thanks.

答:
An alternative to 4castle’s answer is

```<code>String output = Pattern.compile("").splitAsStream(tempStr)
                       .map(s -> tempMap.getOrDefault(s, s))
                       .collect(Collectors.joining());
</code>```

This doesn’t handle characters outside the BMP, but as long as you’re note using them as keys in the Map, the surrogate pairs will be correctly assembled to their original form in the result string, like in you original char[] approach.

If you want to support characters outside the BMP, you can use

```<code>String output = Pattern.compile("(?!\\p{Cs})").splitAsStream(tempStr)
                       .map(s -> tempMap.getOrDefault(s, s))
                       .collect(Collectors.joining());
</code>```

Title: Char Array to Lambda Expression

Body:
I am now learning lambda expression used in Java.
In this case, I have a problem in changing char[] array to lambda expression.
So, I would like to ask some help.
My sample code is below.

    Map<String, String> tempMap = new HashMap<String, String>();
    tempMap.put("a", "A");
    tempMap.put("b", "B");
    tempMap.put("c", "C");
    tempMap.put("d", "D");
    tempMap.put("e", "E");
    String tempStr = "abcdef";
    StringBuilder tempBuilder = new StringBuilder();
    char[] tempArray = tempStr.toCharArray();
    for(char c : tempArray) {
    tempBuilder.append(tempMap.getOrDefault(String.ValueOf(c),
    String.ValueOf(c));
    }

Result should be "ABCDEf". Thanks.

Body:
An alternative to 4castle’s answer is

String output = Pattern.compile("").splitAsStream(tempStr)
                       .map(s -> tempMap.getOrDefault(s, s))
                       .collect(Collectors.joining());

This doesn’t handle characters outside the BMP, but as long as you’re note using them as keys in the Map, the surrogate pairs will be correctly assembled to their original form in the result string, like in you original char[] approach.

If you want to support characters outside the BMP, you can use

String output = Pattern.compile("(?!\\p{Cs})").splitAsStream(tempStr)
                       .map(s -> tempMap.getOrDefault(s, s))
                       .collect(Collectors.joining());