答:
Try this method, this will help you:</p>

```<code>public static boolean isNetworkConnected(Context context)
{
    ConnectivityManager connectivityManager = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null)
    {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected())
        {
            return true;
        }
    }
    return false;
}
</code>```

Title: Android Internet connectivity check better method

Body:
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

Body:
Try this method, this will help you:

public static boolean isNetworkConnected(Context context)
{
    ConnectivityManager connectivityManager = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null)
    {
        NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected())
        {
            return true;
        }
    }
    return false;
}


来源: stackexchange

问:
How to set more than one limit on for loop : javascript
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

```<code>for(let a=0;a<usss.length || a<3;a++)
</code>```

Simple

```<code>var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}
</code>```

problem

```<code>var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}
</code>```

The way around,

```<code>var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}
</code>```

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

答:
There will be no way without using an if somewhere as you have to check the length of the value.

var users = ['s','g','h','i'];

// define the length value outside
var length = users.length >= 3 ? 3 : users.length;

for(let a=0; a < length; a++){
   console.log(users[a]);
}

var users2 = ['s','g'];
for(let a=0; a < length; a++){
   console.log(users[a]);
}

// you can define it inside the for loop but it's not so nice for reading
for(let a=0; a < (users.length >= 3 ? 3 : users.length); a++){
   console.log(users[a]);
}```
</div>
</div>
</p>

<p>Maybe the nicest would be to create a function and pass the <code>3</code> as a maxLength parameter</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var logMax = function(users, maxLength, info) {
  let length = users.length >= maxLength ? maxLength : users.length;
  for(let a=0; a < length; a++){
    console.log(info, ' => ' + users[a]);
  }
}

var users = ['s','g','h','i'];
logMax(users, 3, 'first');

logMax(['s','g'], 3, 'second');</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

for(let a=0;a<usss.length || a<3;a++)

Simple

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around,

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

Body:
There will be no way without using an if somewhere as you have to check the length of the value.

var users = ['s','g','h','i'];

// define the length value outside
var length = users.length >= 3 ? 3 : users.length;

for(let a=0; a < length; a++){
   console.log(users[a]);
}

var users2 = ['s','g'];
for(let a=0; a < length; a++){
   console.log(users[a]);
}

// you can define it inside the for loop but it's not so nice for reading
for(let a=0; a < (users.length >= 3 ? 3 : users.length); a++){
   console.log(users[a]);
}

Maybe the nicest would be to create a function and pass the 3 as a maxLength parameter

var logMax = function(users, maxLength, info) {
  let length = users.length >= maxLength ? maxLength : users.length;
  for(let a=0; a < length; a++){
    console.log(info, ' => ' + users[a]);
  }
}

var users = ['s','g','h','i'];
logMax(users, 3, 'first');

logMax(['s','g'], 3, 'second');


问:
How to make shell script executable after decompress without chmod
I am studying linux, and I have to make all shell scripts executable by this command:

```<code>find ./ -name "*.sh" -exec chmod u+x {} \;
</code>```

But when I download Logstash.tar.gz and extract it to /opt, all shell scripts were executable, no chmod needed. And /opt is not in $PATH.

```<code>echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin
</code>```

How do I build an app like logstash works?

===updated test steps for verification===

```<code>mkdir testtar && cd testtar
## create a executable script
echo test_with_x >> test_with_x.sh
chmod u+x test_with_x.sh
## create a not executable script
echo test_without_x >> test_without_x.sh
cd ..
## compress with gzip
tar -zcvf testtar.tar.gz ./testtar

mkdir testextract
mv testtar.tar.gz ./testextract
cd ./testextract
tar -zxvf testtar.tar.gz
## decompressed and see a executable and not executable script
</code>```

答:
Logstash tar bundle might have been created with executable permissions on all scripts. It should be the reason why it works fine after extracting without using chmod u+x command. If you also create a tar bundle with executable scripts, you should also get executable scripts after decompressing without using chmod u+x.

If you want your shell scripts to be executed without using chmod u+x, provide your shell script as an argument to your shell interpreter.

For e.g,

```<code>bash MyScript.sh
sh MyScript.sh
ksh MyScript.sh
</code>```

Body:
I am studying linux, and I have to make all shell scripts executable by this command:

find ./ -name "*.sh" -exec chmod u+x {} \;

But when I download Logstash.tar.gz and extract it to /opt, all shell scripts were executable, no chmod needed. And /opt is not in $PATH.

echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/usr/lib/jvm/java-8-oracle/bin:/usr/lib/jvm/java-8-oracle/db/bin:/usr/lib/jvm/java-8-oracle/jre/bin

How do I build an app like logstash works?

===updated test steps for verification===

mkdir testtar && cd testtar
## create a executable script
echo test_with_x >> test_with_x.sh
chmod u+x test_with_x.sh
## create a not executable script
echo test_without_x >> test_without_x.sh
cd ..
## compress with gzip
tar -zcvf testtar.tar.gz ./testtar

mkdir testextract
mv testtar.tar.gz ./testextract
cd ./testextract
tar -zxvf testtar.tar.gz
## decompressed and see a executable and not executable script

Body:
Logstash tar bundle might have been created with executable permissions on all scripts. It should be the reason why it works fine after extracting without using chmod u+x command. If you also create a tar bundle with executable scripts, you should also get executable scripts after decompressing without using chmod u+x.

If you want your shell scripts to be executed without using chmod u+x, provide your shell script as an argument to your shell interpreter.

For e.g,

bash MyScript.sh
sh MyScript.sh
ksh MyScript.sh


问:
How do I stop after_create callback that interacts with an external API from being executed when running rspec tests?
I have a Rails model with an after_create callback, that has code which interacts with an external API. That code is getting executed and content on another app is being created when I run rspec tests.

I want to do something such as:

```<code>after_create :external_api_code, unless: testing?

def testing?
  #what goes here to recognize that the object is being created in a test?
end
</code>```

答:
To check whether or not code is running in the test environment:

```<code>Rails.env.test?
</code>```

To avoid running external API code in RSpec, put this in your configuration block:

```<code>RSpec.configure do |config|
  config.before(:each) do
    allow_any_instance_of(Model).to receive(:external_api_code).and_return(return_value)
  end
end
</code>```

To actually run the code in the test that needs it run:

```<code>allow_any_instance_of(Model).to receive(:external_api_code).and_call_original
</code>```

Body:
I have a Rails model with an after_create callback, that has code which interacts with an external API. That code is getting executed and content on another app is being created when I run rspec tests.

I want to do something such as:

after_create :external_api_code, unless: testing?

def testing?
  #what goes here to recognize that the object is being created in a test?
end

Body:
To check whether or not code is running in the test environment:

Rails.env.test?

To avoid running external API code in RSpec, put this in your configuration block:

RSpec.configure do |config|
  config.before(:each) do
    allow_any_instance_of(Model).to receive(:external_api_code).and_return(return_value)
  end
end

To actually run the code in the test that needs it run:

allow_any_instance_of(Model).to receive(:external_api_code).and_call_original


问:
Quickbooks SDK Create Invoice will not add second line to invoice PHP
I am using sample code and testing in the sandbox to get a better understanding of CreateInvoice. My code writes the second line into line one on the invoice.
Also where can I find better "how to" documentation?  What does $IPPId->value = "4"; represent?  When I give the Item an id the description and unit price does not show up on the invoice, However the item name does.  </p>

```<code>    // Create a new Invoice
$invoice = new IPPInvoice();
//$invoice->DocNumber="1234"; //You assign the Invoice Number
$invoice->AutoDocNumber="1"; //Invoice number generated by QB

//Assign Customer to the invoice
$customerRef = new IPPReferenceType();
$customerRef->value = "3"; //CustomerID
$invoice->CustomerRef = $customerRef;

//New Invoice Line
$IPPLine = new IPPLine();
    $IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
    $IPPId->value = "4";
    $IPPLine->Id = $IPPId;

    $IPPLine->LineNum = "1";
    $IPPLine->Description = "DP2OrderID - Sitting Reference - CustomerRef Goes Here"; //Invoice Title
    $IPPLine->Amount = 25.0; //Price - Order Sum

    $enum = new IPPLineDetailTypeEnum();
    $enum->value = "DescriptionOnly";
    $IPPLine->DetailType = $enum;

$invoice->Line = $IPPLine; //Add line to invoice

//New Invoice Line
$IPPLine = new IPPLine();
    $IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
    $IPPId->value = "4";
    $IPPLine->Id = $IPPId;

    $IPPLine->LineNum = "2";
    $IPPLine->Description = "Line two"; //Invoice Title
    $IPPLine->Amount = 25.0; //Price - Order Sum

    $enum = new IPPLineDetailTypeEnum();
    $enum->value = "SalesItemLineDetail";
    $IPPLine->DetailType = $enum;

    $SalesItemLineDetail = new IPPSalesItemLineDetail();
    $SalesItemLineDetail->ItemRef = "21";
    $SalesItemLineDetail->Qty= 4;
    $IPPLine->SalesItemLineDetail = $SalesItemLineDetail;
$invoice->Line = $IPPLine; //Add line to invoice

//Add Invoice to quickbooks
$resultingInvoiceObj = $dataService->Add($invoice);
</code>```

答:
You need to add IPPLine object in one temporary array and then reference that temp array to Invoice. Please modify your code as below and it should be worked.</p>

```<code>$temparr = []; //create one new temp array

$invoice = new IPPInvoice();
//$invoice->DocNumber="1234"; //You assign the Invoice Number
$invoice->AutoDocNumber="1"; //Invoice number generated by QB

//Assign Customer to the invoice
$customerRef = new IPPReferenceType();
$customerRef->value = "3"; //CustomerID
$invoice->CustomerRef = $customerRef;

//New Invoice Line
$IPPLine = new IPPLine();
$IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
$IPPId->value = "4";
$IPPLine->Id = $IPPId;

$IPPLine->LineNum = "1";
$IPPLine->Description = "DP2OrderID - Sitting Reference - CustomerRef Goes Here"; //Invoice Title
$IPPLine->Amount = 25.0; //Price - Order Sum

$enum = new IPPLineDetailTypeEnum();
$enum->value = "DescriptionOnly";
$IPPLine->DetailType = $enum;

array_push($temparr,$IPPLine); //add line object in temp array

//New Invoice Line
$IPPLine = new IPPLine();
$IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
$IPPId->value = "4";
$IPPLine->Id = $IPPId;

$IPPLine->LineNum = "2";
$IPPLine->Description = "Line two"; //Invoice Title
$IPPLine->Amount = 25.0; //Price - Order Sum

$enum = new IPPLineDetailTypeEnum();
$enum->value = "SalesItemLineDetail";
$IPPLine->DetailType = $enum;

$SalesItemLineDetail = new IPPSalesItemLineDetail();
$SalesItemLineDetail->ItemRef = "21";
$SalesItemLineDetail->Qty= 4;
$IPPLine->SalesItemLineDetail = $SalesItemLineDetail;

array_push($temparr,$IPPLine); //add line object in temp array

$invoice->Line = $temparr; //Add line to invoice

//Add Invoice to quickbooks
$resultingInvoiceObj = $dataService->Add($invoice);
</code>```

Body:
I am using sample code and testing in the sandbox to get a better understanding of CreateInvoice. My code writes the second line into line one on the invoice.
Also where can I find better "how to" documentation?  What does $IPPId->value = "4"; represent?  When I give the Item an id the description and unit price does not show up on the invoice, However the item name does.

    // Create a new Invoice
$invoice = new IPPInvoice();
//$invoice->DocNumber="1234"; //You assign the Invoice Number
$invoice->AutoDocNumber="1"; //Invoice number generated by QB

//Assign Customer to the invoice
$customerRef = new IPPReferenceType();
$customerRef->value = "3"; //CustomerID
$invoice->CustomerRef = $customerRef;

//New Invoice Line
$IPPLine = new IPPLine();
    $IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
    $IPPId->value = "4";
    $IPPLine->Id = $IPPId;

    $IPPLine->LineNum = "1";
    $IPPLine->Description = "DP2OrderID - Sitting Reference - CustomerRef Goes Here"; //Invoice Title
    $IPPLine->Amount = 25.0; //Price - Order Sum

    $enum = new IPPLineDetailTypeEnum();
    $enum->value = "DescriptionOnly";
    $IPPLine->DetailType = $enum;

$invoice->Line = $IPPLine; //Add line to invoice

//New Invoice Line
$IPPLine = new IPPLine();
    $IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
    $IPPId->value = "4";
    $IPPLine->Id = $IPPId;

    $IPPLine->LineNum = "2";
    $IPPLine->Description = "Line two"; //Invoice Title
    $IPPLine->Amount = 25.0; //Price - Order Sum

    $enum = new IPPLineDetailTypeEnum();
    $enum->value = "SalesItemLineDetail";
    $IPPLine->DetailType = $enum;

    $SalesItemLineDetail = new IPPSalesItemLineDetail();
    $SalesItemLineDetail->ItemRef = "21";
    $SalesItemLineDetail->Qty= 4;
    $IPPLine->SalesItemLineDetail = $SalesItemLineDetail;
$invoice->Line = $IPPLine; //Add line to invoice

//Add Invoice to quickbooks
$resultingInvoiceObj = $dataService->Add($invoice);

Body:
You need to add IPPLine object in one temporary array and then reference that temp array to Invoice. Please modify your code as below and it should be worked.

$temparr = []; //create one new temp array

$invoice = new IPPInvoice();
//$invoice->DocNumber="1234"; //You assign the Invoice Number
$invoice->AutoDocNumber="1"; //Invoice number generated by QB

//Assign Customer to the invoice
$customerRef = new IPPReferenceType();
$customerRef->value = "3"; //CustomerID
$invoice->CustomerRef = $customerRef;

//New Invoice Line
$IPPLine = new IPPLine();
$IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
$IPPId->value = "4";
$IPPLine->Id = $IPPId;

$IPPLine->LineNum = "1";
$IPPLine->Description = "DP2OrderID - Sitting Reference - CustomerRef Goes Here"; //Invoice Title
$IPPLine->Amount = 25.0; //Price - Order Sum

$enum = new IPPLineDetailTypeEnum();
$enum->value = "DescriptionOnly";
$IPPLine->DetailType = $enum;

array_push($temparr,$IPPLine); //add line object in temp array

//New Invoice Line
$IPPLine = new IPPLine();
$IPPId = new IPPReferenceType(); //Reference type of all IDs that are taken as input or output
$IPPId->value = "4";
$IPPLine->Id = $IPPId;

$IPPLine->LineNum = "2";
$IPPLine->Description = "Line two"; //Invoice Title
$IPPLine->Amount = 25.0; //Price - Order Sum

$enum = new IPPLineDetailTypeEnum();
$enum->value = "SalesItemLineDetail";
$IPPLine->DetailType = $enum;

$SalesItemLineDetail = new IPPSalesItemLineDetail();
$SalesItemLineDetail->ItemRef = "21";
$SalesItemLineDetail->Qty= 4;
$IPPLine->SalesItemLineDetail = $SalesItemLineDetail;

array_push($temparr,$IPPLine); //add line object in temp array

$invoice->Line = $temparr; //Add line to invoice

//Add Invoice to quickbooks
$resultingInvoiceObj = $dataService->Add($invoice);


问:
angular-xeditable onsave event
I am using angular package angular-xeditable the problem is I want to call its event onaftersave after i edit the label here is my html:

```<code><h4 >{{ title.key || 'empty' }}
  <span   onaftersave="save()"  editable-text="title.key ">
  <i class="fa fa-pencil-square-o" "></i></span>
</h4>
</code>```

the event onaftersave is called even if i click on the edit button and also while typing in the field

what I want is to call the event only when I click the button

答:
Try to use this code this will helps to prevent function call.</p>

```<code><span>
<a onaftersave="save();" data-ng-model="title.key" e-placeholder="Your text" editable-text="title.key">
<span>{{title.key || 'empty'}}</span>
</a>
</span>
</code>```

Title: angular-xeditable onsave event

Body:
I am using angular package angular-xeditable the problem is I want to call its event onaftersave after i edit the label here is my html:

{{ title.key || 'empty' }}

the event onaftersave is called even if i click on the edit button and also while typing in the field

what I want is to call the event only when I click the button

Body:
Try to use this code this will helps to prevent function call.

<span>
<a onaftersave="save();" data-ng-model="title.key" e-placeholder="Your text" editable-text="title.key">
<span>{{title.key || 'empty'}}</span>
</a>
</span>


问:
Executing PHP via command line
I want to be able to execute PHP via command line with a $_GET variable.  I understand I can do this with exec, but I'd like to understand more of the security risk and what things I should look out for.  The parameter I want to pass is a MySQL auto_incremented ID returned from MySQL, so I'm not concerned with user input.  But by merely allowing this to happen what things should be considered in regards to security?

The script will accept an order ID and send the customer an email invoice.  This allows me to perform this function from multiple sections of the site only maintaining the code in 1 location.

答:
Why can't you use argv/argc?</p>

```<code>$id = isset($argv[1]) ? (int)$argv[1] : (int)$_REQUEST['id'];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Executing PHP via command line

Body:
Why can't you use argv/argc?

$id = isset($argv[1]) ? (int)$argv[1] : (int)$_REQUEST['id'];


问:
Find the kth smallest element in an unsorted array of non-negative integers
Not allowed to modify the array ( The array is read only ).
Using constant extra space is allowed.

ex:
A : [2 1 4 3 2]
k : 3

answer : 2

I did it below way. The answer is correct but need to be more memory efficient.

```<code>void insert_sorted(vector<int> &B, int a,int k)
{
    for(int i=0;i<k;i++)
    {
        if(B[i]>=a)
        {
            for(int j=k-1;j>i;j--)
                B[j]=B[j-1];
            B[i]=a;
            return;
        }
    }
}

int Solution::kthsmallest(const vector<int> &A, int k) {

    vector <int> B;
    for(int i=0;i<k;i++)
    {
        B.push_back(INT_MAX);
    }
    int l=A.size();

    for(int i=0;i<l;i++)
    {
        if(B[k-1]>=A[i])
            insert_sorted(B,A[i],k);
    }

    return B[k-1];
}
</code>```

答:
If only constant extra space is allowed, we can use a simple O(n*k) algorithm.

```<code>int kth_smallest(const vector<int>& v, int k) {
    int curmin = -1;
    int order = -1;
    while (order < k) { // while kth element wasn't reached
        curmin = *min_element(v.begin(), v.end(), [curmin](int a, int b) {
            if (a <= curmin) return false;
            if (b <= curmin) return true;
            return a < b;
        }); // find minimal number among not counted yet

        order += count(v.begin(), v.end(), curmin); // count all 'minimal' numbers
    }
    return curmin;
}
</code>```

online version to play with: http://ideone.com/KNMYxA

Body:
Not allowed to modify the array ( The array is read only ).
Using constant extra space is allowed.

ex:
A : [2 1 4 3 2]
k : 3

answer : 2

I did it below way. The answer is correct but need to be more memory efficient.

void insert_sorted(vector<int> &B, int a,int k)
{
    for(int i=0;i<k;i++)
    {
        if(B[i]>=a)
        {
            for(int j=k-1;j>i;j--)
                B[j]=B[j-1];
            B[i]=a;
            return;
        }
    }
}

int Solution::kthsmallest(const vector<int> &A, int k) {

    vector <int> B;
    for(int i=0;i<k;i++)
    {
        B.push_back(INT_MAX);
    }
    int l=A.size();

    for(int i=0;i<l;i++)
    {
        if(B[k-1]>=A[i])
            insert_sorted(B,A[i],k);
    }

    return B[k-1];
}

Body:
If only constant extra space is allowed, we can use a simple O(n*k) algorithm.

int kth_smallest(const vector<int>& v, int k) {
    int curmin = -1;
    int order = -1;
    while (order < k) { // while kth element wasn't reached
        curmin = *min_element(v.begin(), v.end(), [curmin](int a, int b) {
            if (a <= curmin) return false;
            if (b <= curmin) return true;
            return a < b;
        }); // find minimal number among not counted yet

        order += count(v.begin(), v.end(), curmin); // count all 'minimal' numbers
    }
    return curmin;
}

online version to play with: http://ideone.com/KNMYxA


问:
How to prevent an image size from changing when I resize the browser
How can i prevent an image from resizing when i try to change the browser's size? Here's an example of what I am talking about. Try to resize your browser and you'll see the image not changing. It seems simple but I've tried everything I know without success.

Thanks

答:
Try This

CSS

```<code>.hero img
{
width:500px; !important /* desired pixel value */
}
</code>```

hope this helps..

Body:
Try This

CSS

.hero img
{
width:500px; !important /* desired pixel value */
}

hope this helps..


问:
evaluating else if after an if condition is true
Consider this snippet:

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}
</code>```

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

答:
The second condition isn't being checked because an else statement will only be evaluated when the preceding conditions are evaluated to be false. There are several ways to fix this, some of which are shown in other answers. One such way is to use a single if statement, which combines both conditions:

```<code>if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
    textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
}
</code>```

Body:
Consider this snippet:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.MaxLength > 0)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
    else if (textBox1.MaxLength < 32768)
    {
        textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
    }
}

Why is it not evaluating the second condition (the lesser than condition)? It's also true, isn't it?

If I have to make the second one to work in the same condition, what minor change must be made?

Body:
The second condition isn't being checked because an else statement will only be evaluated when the preceding conditions are evaluated to be false. There are several ways to fix this, some of which are shown in other answers. One such way is to use a single if statement, which combines both conditions:

if (textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
    textBox2.Text = Convert.ToBoolean(Math.Sqrt(textBox1.MaxLength)).ToString();
}


问:
Detect if a user prints something via javascript
I've got a problem with detecting a print event in javascript.
For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?

I've already tried using onafterprint but maybe I didn't do this correctly or I'dont know.

it was something like this inside my main js file.

```<code>window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');
};
</code>```

I took that from here: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

答:
Do you realize that you code do nothing ?
This one will help you.

```<code>(function() {
    var beforePrint = function() {
        console.log('Functionality to run before printing.');
    };
    var afterPrint = function() {
        console.log('Functionality to run after printing');
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());
</code>```

run it in your dev console on any open page, then hit ctrl-P and you should see message.

Body:
I've got a problem with detecting a print event in javascript.
For example, a user wats to print document and presses print in a web-page, then another window appers, e.g. to print from Adobe Reader, then appears another window of Adobe Reader where you can set properties, choose pages to print and what not...and there is the print button in this window. Can I actually detect when the user presses this print button inside this Adobe Reader window in browser using javascript?

I've already tried using onafterprint but maybe I didn't do this correctly or I'dont know.

it was something like this inside my main js file.

window.onbeforeprint = function() {
    console.log('This will be called before the user prints.');
};
window.onafterprint = function() {
    console.log('This will be called after the user prints');
};

I took that from here: https://www.tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/

Body:
Do you realize that you code do nothing ?
This one will help you.

(function() {
    var beforePrint = function() {
        console.log('Functionality to run before printing.');
    };
    var afterPrint = function() {
        console.log('Functionality to run after printing');
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

run it in your dev console on any open page, then hit ctrl-P and you should see message.


问:
How to get the list of sub folder in a SharePoint Document library updated atleast before 30 days
I want to get all the Title of the sub-folder which are modified at least before 30 days in a SharePoint Document library  </p>

答: Use caml query to get all the sub folders. Where Modified date less than your date and greater than your date. ViewAttributes recursiveall.</p>


问:
proper way of doing auto complete dropdown in angular 2
hello friends I am new in angular 2 I find the way to auto complete dropdown I tried the ng2-select but it did not work for me. is there is another npm that work with angular 2. as the functionality is we also set the selected value for the dropdown as well? if you know any npm that provide autocomplete as well as set the initial value as well then suggest me thank u.</p>

答: I am using ngui-angular2-auto-complete npm. It's working in my project. You can use. here the link


问:
how to return IEnumerable List values to View page in mvc
Getting data in a list format using IEnumerable,How to return to View page from controller.

model.Name = UserPermissions.Name; is this correct format?

List containing name,Id,Amount,Currency for each plan.

model.Name = UserPermissions.Name;  getting error here.from list pass all data to view dynamically in DIV.How to pass data and display in view.help me guys

```<code>   public ActionResult Plans(Plan model)
{
    var planServicenew = new StripePlanService(apiKey);
            IEnumerable<StripePlan> responsenew = planServicenew.List();
            foreach (var UserPermissions in responsenew)
            {
                model.Name = UserPermissions.Name;
            }
    return View(model);
}
</code>```

view page

```<code>@model IEnumerable<ABACUS.Models.Plan>
@foreach (var item in Model)
{
        <div class="plan">
            <h3 class="plan-title">@Html.DisplayFor(modelItem => item.Name)</h3>
            <p class="plan-price">@Html.DisplayFor(modelItem => item.Currency)@Html.DisplayFor(modelItem => item.Amount) <span class="plan-unit">per month</span></p>
            <ul class="plan-features">
                <li class="plan-feature">@Html.DisplayFor(modelItem => item.Trial)-days <span class="plan-feature-name">Trial</span></li>

            </ul>
            <a href="#" class="plan-button">Choose Plan</a>
        </div>
}
</code>```

答:
Considering you have "Plan" model and you want to pass the list of Plans to your view,

try below way to resolve your issue -

```<code>var planServicenew = new StripePlanService(apiKey);
        IEnumerable<StripePlan> responsenew = planServicenew.List();

        var plans = (from r in responsenew
                    select new Plan
                    {
                        Name = r.Name,
                        Currency = r.Currency,
                        Amount = r.Amount,
                        Trial = r.Trial
                    }).ToList() as List<Plan>;
         return View(plans);
</code>```

Body:
Getting data in a list format using IEnumerable,How to return to View page from controller.

model.Name = UserPermissions.Name; is this correct format?

List containing name,Id,Amount,Currency for each plan.

model.Name = UserPermissions.Name;  getting error here.from list pass all data to view dynamically in DIV.How to pass data and display in view.help me guys

   public ActionResult Plans(Plan model)
{
    var planServicenew = new StripePlanService(apiKey);
            IEnumerable<StripePlan> responsenew = planServicenew.List();
            foreach (var UserPermissions in responsenew)
            {
                model.Name = UserPermissions.Name;
            }
    return View(model);
}

view page

@model IEnumerable<ABACUS.Models.Plan>
@foreach (var item in Model)
{

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.Currency)@Html.DisplayFor(modelItem => item.Amount) per month

@Html.DisplayFor(modelItem => item.Trial)-days Trial

            Choose Plan

}

Body:
Considering you have "Plan" model and you want to pass the list of Plans to your view,

try below way to resolve your issue -

var planServicenew = new StripePlanService(apiKey);
        IEnumerable<StripePlan> responsenew = planServicenew.List();

        var plans = (from r in responsenew
                    select new Plan
                    {
                        Name = r.Name,
                        Currency = r.Currency,
                        Amount = r.Amount,
                        Trial = r.Trial
                    }).ToList() as List<Plan>;
         return View(plans);


问:
Null Pointer Exception : android.widget.Button
in my problem, I have a widget button. if the button I'm click it will go to the next activity, but after I clicked my Application has Stopped. The indicated was about

NullPointerException : Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Below My Code

```<code>ArrayList<HashMap<String, String>> menuList;
String searchkey;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_listing);
    Bundle extras = getIntent().getExtras();
    searchkey = extras.getString("txtsearch").toString();
    //rename actionbar title to search keyword
    setTitle("Hasil Pencarian " + searchkey);
    //URL with search key
    menuList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    BtnDetail = (Button) findViewById(R.id.btnDetail);
    BtnDetail.setOnClickListener(this);
    new GetMenu().execute();
}
public void onClick (View v){
    if (v.getId()==R.id.btnDetail)
    {
        Intent maps = new Intent(this,MapsActivity.class);
        startActivity(maps);
    }
}

private class GetMenu extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(Listing.this);
        pDialog.setMessage("Loading,, Please Wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected Void doInBackground(Void... arg0){
        HttpHandler sh = new HttpHandler();
        String url_search = "http://10.0.2.2/search/search.php?txtsearch="+searchkey;
        Log.e(TAG,url_search);
        //Making request to url and getting response

        String jsonStr = sh.makeServiceCall(url_search);
        Log.e(TAG,"Response from URL :" +jsonStr);

        if (jsonStr != null){
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                // Getting JSON Array node name
                JSONArray contacts = jsonObj.getJSONArray("data");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);
                    String id = c.getString("menu_kuliner.kd_kuliner");
                    String menu = c.getString("menu_kuliner.menu");
                    String harga = c.getString("menu_kuliner.harga");
                    String kuliner = c.getString("nama_kuliner.nm_kuliner");
                    String alamat = c.getString("nama_kuliner.alamat");
                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();
                    // adding each child node to HashMap key => value
                    contact.put("menu_kuliner.kd_kuliner", id);
                    contact.put("menu_kuliner.menu", menu);
                    contact.put("menu_kuliner.harga", harga);
                    contact.put("nama_kuliner.nm_kuliner", kuliner);
                    contact.put("nama_kuliner.alamat", alamat);
                    // adding contact to contact list
                    menuList.add(contact);
            }
            //if JSON format error
        } catch (final JSONException e){
                Log.e(TAG,"JSON Parsing Error :" +e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "JSON Parsing Error :" +e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
    } else {
            Log.e(TAG, "Couldnt get JSON From Server !");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldnt get JSON From Server ! Check Logcat for possible Error",
                            Toast.LENGTH_LONG).show();
                }
            });
        }
        return null;
}

@Override
    protected void onPostExecute (Void result) {
    super.onPostExecute(result);

    if (pDialog.isShowing())
        pDialog.dismiss();

    ListAdapter adapter = new SimpleAdapter(
            Listing.this, menuList, R.layout.list_item,
            new String[]{"menu_kuliner.kd_kuliner", "menu_kuliner.menu", "menu_kuliner.harga", "nama_kuliner.nm_kuliner", "nama_kuliner.alamat"}, //<= ARRAY LIST
            new int[]{R.id.id, R.id.menu, R.id.harga, R.id.kuliner, R.id.alamat});
    lv.setAdapter(adapter);
    }
}
</code>```

}

This is my Activity_listing.xml

```<code>android:id="@+id/activity_listing"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Listing" >

    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</code>```

This is my list_item.xml

```<code><TextView android:id="@+id/menu"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize=" 17dip"
    android:textStyle="bold" />

<TextView android:id="@+id/harga"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />

<TextView android:id="@+id/kuliner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />

<TextView android:id="@+id/alamat"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />
<Button
    android:id="@+id/btnDetail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

androidManifest

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBrGERGDjAf2XKeS9Q_MGd24hOX_PUTKpQ" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Listing">

    </activity>
    <activity android:name=".MapsActivity">

    </activity>
</application>
</code>```

EDIT

```<code>ArrayList<HashMap<String, String>> menuList;
String searchkey;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_listing);
    Bundle extras = getIntent().getExtras();
    searchkey = extras.getString("txtsearch").toString();
    //rename actionbar title to search keyword
    setTitle("Hasil Pencarian " + searchkey);
    //URL with search key
    menuList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
            if( view.getId()== R.id.btnDetail)
            {
                Intent maps = new Intent(Listing.this,MapsActivity.class);
                startActivity(maps);
            }
        }
    });
</code>```

答:
You can use list item click listener for handling click events for listview

```<code>lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if( view.getId() == R.id.btnDetail ) {
               Intent maps = new Intent(MainActivity.this, MapsActivity.class);
               startActivity(maps);
            }
        }
    });
</code>```

If you want the click listener to be handled via button click use above code , or you can remove the if condition for checking the button id and directly call the maps activity from the event handler. .

Body:
in my problem, I have a widget button. if the button I'm click it will go to the next activity, but after I clicked my Application has Stopped. The indicated was about

NullPointerException : Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Below My Code

ArrayList<HashMap<String, String>> menuList;
String searchkey;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_listing);
    Bundle extras = getIntent().getExtras();
    searchkey = extras.getString("txtsearch").toString();
    //rename actionbar title to search keyword
    setTitle("Hasil Pencarian " + searchkey);
    //URL with search key
    menuList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    BtnDetail = (Button) findViewById(R.id.btnDetail);
    BtnDetail.setOnClickListener(this);
    new GetMenu().execute();
}
public void onClick (View v){
    if (v.getId()==R.id.btnDetail)
    {
        Intent maps = new Intent(this,MapsActivity.class);
        startActivity(maps);
    }
}

private class GetMenu extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pDialog = new ProgressDialog(Listing.this);
        pDialog.setMessage("Loading,, Please Wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected Void doInBackground(Void... arg0){
        HttpHandler sh = new HttpHandler();
        String url_search = "http://10.0.2.2/search/search.php?txtsearch="+searchkey;
        Log.e(TAG,url_search);
        //Making request to url and getting response

        String jsonStr = sh.makeServiceCall(url_search);
        Log.e(TAG,"Response from URL :" +jsonStr);

        if (jsonStr != null){
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                // Getting JSON Array node name
                JSONArray contacts = jsonObj.getJSONArray("data");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);
                    String id = c.getString("menu_kuliner.kd_kuliner");
                    String menu = c.getString("menu_kuliner.menu");
                    String harga = c.getString("menu_kuliner.harga");
                    String kuliner = c.getString("nama_kuliner.nm_kuliner");
                    String alamat = c.getString("nama_kuliner.alamat");
                    // tmp hash map for single contact
                    HashMap<String, String> contact = new HashMap<>();
                    // adding each child node to HashMap key => value
                    contact.put("menu_kuliner.kd_kuliner", id);
                    contact.put("menu_kuliner.menu", menu);
                    contact.put("menu_kuliner.harga", harga);
                    contact.put("nama_kuliner.nm_kuliner", kuliner);
                    contact.put("nama_kuliner.alamat", alamat);
                    // adding contact to contact list
                    menuList.add(contact);
            }
            //if JSON format error
        } catch (final JSONException e){
                Log.e(TAG,"JSON Parsing Error :" +e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "JSON Parsing Error :" +e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
    } else {
            Log.e(TAG, "Couldnt get JSON From Server !");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldnt get JSON From Server ! Check Logcat for possible Error",
                            Toast.LENGTH_LONG).show();
                }
            });
        }
        return null;
}

@Override
    protected void onPostExecute (Void result) {
    super.onPostExecute(result);

    if (pDialog.isShowing())
        pDialog.dismiss();

    ListAdapter adapter = new SimpleAdapter(
            Listing.this, menuList, R.layout.list_item,
            new String[]{"menu_kuliner.kd_kuliner", "menu_kuliner.menu", "menu_kuliner.harga", "nama_kuliner.nm_kuliner", "nama_kuliner.alamat"}, //<= ARRAY LIST
            new int[]{R.id.id, R.id.menu, R.id.harga, R.id.kuliner, R.id.alamat});
    lv.setAdapter(adapter);
    }
}

}

This is my Activity_listing.xml

android:id="@+id/activity_listing"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Listing" >

    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

This is my list_item.xml

<TextView android:id="@+id/menu"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize=" 17dip"
    android:textStyle="bold" />

<TextView android:id="@+id/harga"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />

<TextView android:id="@+id/kuliner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />

<TextView android:id="@+id/alamat"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="14dip" />
<Button
    android:id="@+id/btnDetail"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

androidManifest

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBrGERGDjAf2XKeS9Q_MGd24hOX_PUTKpQ" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Listing">

    </activity>
    <activity android:name=".MapsActivity">

    </activity>
</application>

EDIT

ArrayList<HashMap<String, String>> menuList;
String searchkey;

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    setContentView(R.layout.activity_listing);
    Bundle extras = getIntent().getExtras();
    searchkey = extras.getString("txtsearch").toString();
    //rename actionbar title to search keyword
    setTitle("Hasil Pencarian " + searchkey);
    //URL with search key
    menuList = new ArrayList<>();
    lv = (ListView) findViewById(R.id.list);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView <?> parent, View view, int position, long id) {
            if( view.getId()== R.id.btnDetail)
            {
                Intent maps = new Intent(Listing.this,MapsActivity.class);
                startActivity(maps);
            }
        }
    });

Body:
You can use list item click listener for handling click events for listview

lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if( view.getId() == R.id.btnDetail ) {
               Intent maps = new Intent(MainActivity.this, MapsActivity.class);
               startActivity(maps);
            }
        }
    });

If you want the click listener to be handled via button click use above code , or you can remove the if condition for checking the button id and directly call the maps activity from the event handler. .


问:
Create/Edit MS Word & Word Perfect docs in Django?
Is it possible to create and/or edit MS Word and Word Perfect documents with django? I'd like to be able to allow the user to fill out a form and have the form fields inserted into an MS Word/Word Perfect document. Or, the form fields are used to create a new MS Word/Word Perfect document. The user can then send that document via email to others who may not have access to the django web-app.

I have a client who needs this functionality and I'd like to keep it all within the web-app.

Any ideas?

Thanks!

答:
For MS Word, you could use docx-mailmerge. Run the following commands to install lxml(dependecy required by docx-mailmerge) and docx-mailmerge

```<code>conda install lxml
pip install docx-mailmerge
</code>```

In order for docx-mailmerge to work correctly, you need to create a standard Word document and define the appropriate merge fields. The examples below are for Word 2010. Other versions of Word should be similar. It actually took me a while to figure out this process but once you do it a couple of times, it is pretty simple.

Start Word and create the basic document structure. Then place the cursor in the location where the merged data should be inserted and choose Insert -> Quick Parts -> Field..:
Word Quick Parts

From the Field dialog box, select the “MergeField” option from the Field Names list. In the Field Name, enter the name you want for the field. In this case, we are using Business Name.
Word Add Field

Once you click ok, you should see something like this: <> in the Word document. You can go ahead and create the document with all the needed fields.

```<code>    from __future__ import print_function
    from mailmerge import MailMerge
    from datetime import date

    template = "Practical-Business-Python.docx"
    document = MailMerge(template)

    document.merge(
    status='Gold',
    city='Springfield',
    phone_number='800-555-5555',
    Business='Cool Shoes',
    zip='55555',
    purchases='$500,000',
    shipping_limit='$500',
    state='MO',
    address='1234 Main Street',
    date='{:%d-%b-%Y}'.format(date.today()),
    discount='5%',
    recipient='Mr. Jones')

    document.write('test-output.docx')
</code>```

More at http://pbpython.com/python-word-template.html

Body:
For MS Word, you could use docx-mailmerge. Run the following commands to install lxml(dependecy required by docx-mailmerge) and docx-mailmerge

conda install lxml
pip install docx-mailmerge

In order for docx-mailmerge to work correctly, you need to create a standard Word document and define the appropriate merge fields. The examples below are for Word 2010. Other versions of Word should be similar. It actually took me a while to figure out this process but once you do it a couple of times, it is pretty simple.

Start Word and create the basic document structure. Then place the cursor in the location where the merged data should be inserted and choose Insert -> Quick Parts -> Field..:
Word Quick Parts

From the Field dialog box, select the “MergeField” option from the Field Names list. In the Field Name, enter the name you want for the field. In this case, we are using Business Name.
Word Add Field

Once you click ok, you should see something like this: <> in the Word document. You can go ahead and create the document with all the needed fields.

    from __future__ import print_function
    from mailmerge import MailMerge
    from datetime import date

    template = "Practical-Business-Python.docx"
    document = MailMerge(template)

    document.merge(
    status='Gold',
    city='Springfield',
    phone_number='800-555-5555',
    Business='Cool Shoes',
    zip='55555',
    purchases='$500,000',
    shipping_limit='$500',
    state='MO',
    address='1234 Main Street',
    date='{:%d-%b-%Y}'.format(date.today()),
    discount='5%',
    recipient='Mr. Jones')

    document.write('test-output.docx')

More at http://pbpython.com/python-word-template.html


问:
How to select the same column from multiple table with almost same name in SQL?
I'd like to select a 2 column from lot of table.

Exemple

```<code>Table_2017-01
id   name   value

Table_2017-02
id   name   value

Table_2017-03
id   name   value
</code>```

etc...

My Query would be

```<code>SELECT name, value
FROM Table_2017-01, Table_2017-02, Table_2017-03
</code>```

But I'd like to know if something it's possible like

```<code>SELECT name, value FROM LIKE Table_%
</code>```

I know this last query is not possible and it could be easier for me if a query exist for this problem as I can have a lot of table with just a part of the name different.

答:
To select mutiple columns with the same name you have to the table as prefix like:

```<code>SELECT `Table_2017-01.name`, `Table_2017-02.name`, `Table_2017-03.name` FROM Table_2017-01,`Table_2017-02, Table_2017-03
</code>```

If you want them in one Column, use Union.

```<code>(SELECT `Table_2017-01.name` from Table_2017-01)
Union
(SELECT `Table_2017-02.name` from Table_2017-02)
</code>```

Body:
I'd like to select a 2 column from lot of table.

Exemple

Table_2017-01
id   name   value

Table_2017-02
id   name   value

Table_2017-03
id   name   value

etc...

My Query would be

SELECT name, value
FROM Table_2017-01, Table_2017-02, Table_2017-03

But I'd like to know if something it's possible like

SELECT name, value FROM LIKE Table_%

I know this last query is not possible and it could be easier for me if a query exist for this problem as I can have a lot of table with just a part of the name different.

Body:
To select mutiple columns with the same name you have to the table as prefix like:

SELECT `Table_2017-01.name`, `Table_2017-02.name`, `Table_2017-03.name` FROM Table_2017-01,`Table_2017-02, Table_2017-03

If you want them in one Column, use Union.

(SELECT `Table_2017-01.name` from Table_2017-01)
Union
(SELECT `Table_2017-02.name` from Table_2017-02)


问:
Key Events in TabActivities?
I have a TabActivity and want to catch and handle presses of HOME and BACK. Where do I need to catch these events?

In my subclass of TabActivity I implement the following:

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        // Code handling
    }

    return super.onKeyDown(keyCode, event);
}
</code>```

Didn't work.

So I placed a breakpoint on the switch statement line. But this function never gets called, whether I press volume up/down, menu, home, or back. Where do I need to catch these KeyEvents?

答:
I had the same issue and found overriding dispatchKeyEvent worked.

An example of which can be found here for back button press:

http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

Title: Key Events in TabActivities?

Body:
I have a TabActivity and want to catch and handle presses of HOME and BACK. Where do I need to catch these events?

In my subclass of TabActivity I implement the following:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        // Code handling
    }

    return super.onKeyDown(keyCode, event);
}

Didn't work.

So I placed a breakpoint on the switch statement line. But this function never gets called, whether I press volume up/down, menu, home, or back. Where do I need to catch these KeyEvents?


问:
CSS code use to make sure that only 2 line sentence to display is not working for IE
I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."

```<code>   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
</code>```

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

答:
Have you try all these?</p>

```<code>display: -moz-box;
display: -webkit-box;
display: box;
display: -ms-flexbox;
</code>```

Body:
I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."

   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

Body:
Have you try all these?

display: -moz-box;
display: -webkit-box;
display: box;
display: -ms-flexbox;


问:
How to uninstall python jupyter correctly?
I have jupyter installed with python3.5 on my Mac OSX, but I want the python2.7 version.  So, I basically need to uninstall the 3.5 version, and reinstall the 2.7 version.

But for some reason I can't uninstall the 3.5 version.  I tried sudo python3 -m pip uninstall jupyter, and you can see the results below:

```<code>✔  ~/current/directory
20:08 $ which jupyter
/Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter
✔  ~/current/directory
20:08 $ sudo python3 -m pip uninstall jupyter
The directory '/Users/<username>/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Cannot uninstall requirement jupyter, not installed
The directory '/Users/<username>/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
✘-1  ~/current/directory
20:09 $ which jupyter
/Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter
</code>```

...as you can see above, the which jupyter command still returns a valid path, AND not only that.  I'm still able to launch jupyter notebook from the command line, and it opens a notebook.

How do I correctly get rid of my existing version of jupyter ? OR, if someone knows how to ADD a python2 kernel to my existing jupyter, that would be fine too.  Is that possible?

All I can think of is to manually kill the files and subfolders inside of /Library/Frameworks/Python.framework/Versions/3.5/bin/, but this seems unnecessarily brutal?

答:
The answer over here solved my problem: https://stackoverflow.com/a/42277762/8057434

I'll just summarize what to do.
Run

conda uninstall notebook nbconvert nbformat ipykernel ipywidgets qtconsole traitlets tornado jupyter_* ipython_genutils jinja2 -y

in your terminal.

You can use pip uninstall instead of conda uninstall if you aren't using anaconda.

Body:
I have jupyter installed with python3.5 on my Mac OSX, but I want the python2.7 version.  So, I basically need to uninstall the 3.5 version, and reinstall the 2.7 version.

But for some reason I can't uninstall the 3.5 version.  I tried sudo python3 -m pip uninstall jupyter, and you can see the results below:

✔  ~/current/directory
20:08 $ which jupyter
/Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter
✔  ~/current/directory
20:08 $ sudo python3 -m pip uninstall jupyter
The directory '/Users/<username>/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Cannot uninstall requirement jupyter, not installed
The directory '/Users/<username>/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
You are using pip version 8.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
✘-1  ~/current/directory
20:09 $ which jupyter
/Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter

...as you can see above, the which jupyter command still returns a valid path, AND not only that.  I'm still able to launch jupyter notebook from the command line, and it opens a notebook.

How do I correctly get rid of my existing version of jupyter ? OR, if someone knows how to ADD a python2 kernel to my existing jupyter, that would be fine too.  Is that possible?

All I can think of is to manually kill the files and subfolders inside of /Library/Frameworks/Python.framework/Versions/3.5/bin/, but this seems unnecessarily brutal?

ContentLicense: CC BY-SA 4.0


问:
Can we edit and update tableau data using JavaScript API
I want to know can we edit data and update data using Tableau JavaScript API. I tried but didn’t get any function to do this work, for now I  can only change view ,download data, filter data, customized  view. If edit data can be done using JavaScript API ,please share any tutorial on this.</p>

答:
```<code>try like this:-

<title>getData() Basic Example</title>
        <script type="text/javascript" src="https://public.tableau.com/javascripts/api/tableau-2.min.js"></script>
        <script type="text/javascript">
            var viz, sheet, table;

            function initViz() {
        var containerDiv = document.getElementById("vizContainer"),
                    url = "http://public.tableau.com/views/RegionalSampleWorkbook/Storms",
                    options = {
                        hideTabs: true,
                        hideToolbar: true,
                        onFirstInteractive: function () {
                            document.getElementById('getData').disabled = false; // Enable our button
                        }
                    };
                viz = new tableau.Viz(containerDiv, url, options);
            }

<body onload="initViz();">
        <div class="page-header">
            <h1>getData() Basic Example</h1>
            <p>Click the "Get Data" button to get underlying data for the viz.</p>
            <button id="getData" onclick="getUnderlyingData()" class="btn" disabled>Get Data</button>
        </div>
        <div id="vizContainer" style="width:600px; height:600px;"></div>
        <div id="dataTarget"></div>
    </body>
</code>```


答:
else if is only checked if the first condition isn't satisfied.

If you want both of them to be true, you should do

```<code>if(textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
   // do stuff here
}
</code>```

Title: evaluating else if after an if condition is true

Body:
else if is only checked if the first condition isn't satisfied.

If you want both of them to be true, you should do

if(textBox1.MaxLength > 0 && textBox1.MaxLength < 32768)
{
   // do stuff here
}


问:
How to set more than one limit on for loop : javascript
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

```<code>for(let a=0;a<usss.length || a<3;a++)
</code>```

Simple

```<code>var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}
</code>```

problem

```<code>var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}
</code>```

The way around,

```<code>var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}
</code>```

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.

答:
This seems to work :

var users = ['s','g','h','i'];

var users2 = ['s','g'];

for(let a=0;(a<3 && a<users.length) ;a++){
   console.log(users[a]);
}

for(let a=0;(a<3 && a<users2.length);a++){
  console.log(users2[a]);
}```

Body:
I am working with javascript arrays, here i am using for loop to get the top three results.(no .length limit)

Attempting to have something like

for(let a=0;a<usss.length || a<3;a++)

Simple

var users = ['s','g','h','i'];
for(let a=0;a<3;a++){//dont want to use a < users.length
   console.log(users[a]);
}

problem

var users2 = ['s','g'];
for(let a=0;a<3;a++){
  console.log(users2[a]);
}

The way around,

var users2 = ['s','g'];
for(let a=0;a<users2.length;a++){
 if(a<3){
  console.log(users2[a]);
 }
}

Real Question

How can i avoid using extra if() condition in my last stated code?

I am sorry if its very basic question, i just stuck on it.
Any help or information will be appreciated. Thanks for your time.


问:
How will Push Sync work with S3
I am currently developing the android app in which there are two users, consider Employer and Employee. In app, there is functionality where Employer will upload any file from app and it will store in AWS S3 bucket. Now I want, whenever employer upload any file, all the employees' app will be notified and the file will be downloaded in device.

Please help, How will I achieve through Push Sync OR any other way to do it?

Thanks in advance!

答: Try with AWS SNS (Simple Notification Service). Once you configure with your S3 bucket, if any updates to your s3 bucket it will gets automatically trigger. From there call any of your service / API / Lambda function to send notifications. </p>

Title: How will Push Sync work with S3


问:
What is difference between foreign key and reference key?
I am very confused about those two terms. Are they the same or different?

Some books and people say they are the same and others say they are different.

I tried but couldn't find a conclusive answer.

答:
A foreign key must refer to a primary key.
When using REFERENCES constraint simply, then it isn't necessary that the referenced key be a primary key.


问:
Drop multiple columns from DataFrame recursively in SPARK <= version 1.6.0
I want to drop multiple cols from the data frame in one go. Don't want to write .drop("col1").drop("col2").

Note: I am using spark-1.6.0

答:
This functionality is available in the current spark version (2.0 onwards) and for earlier version we can make use of the below code.

1.

```<code>    implicit class DataFrameOperation(df: DataFrame) {
            def dropCols(cols: String*): DataFrame = {
               @tailrec def deleteCol(df: DataFrame, cols: Seq[String]): DataFrame =
               if(cols.size == 0) df else deleteCol(df.drop(cols.head), cols.tail)
        deleteCol(df, cols)
}
}
</code>```

To call the method

```<code>val finalDF = dataFrame.dropCols("col1","col2","col3")
</code>```

Body:
This functionality is available in the current spark version (2.0 onwards) and for earlier version we can make use of the below code.

1.

    implicit class DataFrameOperation(df: DataFrame) {
            def dropCols(cols: String*): DataFrame = {
               @tailrec def deleteCol(df: DataFrame, cols: Seq[String]): DataFrame =
               if(cols.size == 0) df else deleteCol(df.drop(cols.head), cols.tail)
        deleteCol(df, cols)
}
}

To call the method

val finalDF = dataFrame.dropCols("col1","col2","col3")


问:
Spark Kafka Integration using receiver with WAL
I was reading below blog in Databricks

https://databricks.com/blog/2015/03/30/improvements-to-kafka-integration-of-spark-streaming.html

While explaining the process how spark kafka integration works using receiver with WAl , it says

1.The Kafka data is continuously received by Kafka Receivers running in the Spark workers/executors. This used the high-level consumer API
  of Kafka.

2.The received data is stored in Spark’s worker/executor memory as well as to the WAL (replicated on HDFS). The Kafka Receiver updated
  Kafka’s offsets to Zookeeper only after the data has been persisted to
  the log.

Now my doubt is how a high level consumer can update offset in zookeeper , as high level consumer does not handle offset, it is handled by zookeeper. So once we read a message from kafka using zookeeper then zookeeper automatically update the offset.

答:
So when a consumer retrieves data from a particular topic in kafka it is the responsibility of the consumer to update the offsets in zookeeper. So when you use a custom kafka consumer it has an inbuild kafka API( org.apache.kafka.clients.consumer.* does that )that will update the offsets once you receive the data from that particular topic.

In case of that receiver based approach in spark it uses Kafka's high level API to update the offsets in zookeeper.


问:
Counting number of words in Python file
I'm trying to count the number of instances several words appear in a file.

Here is my code:

```<code>#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))
</code>```

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

答:
The main problem is that file.read() consumes the file. Thus the second time you search you end up searching an empty file. The simplest solution is to read the file once (if it is not too large) and then just search the previously read text:

```<code>#!/usr/bin/env python

with  open('my_output', 'r') as file:
    text =  file.read()

word1 = 'wordA'
print('wordA', text.split().count(word1))
word2 = 'wordB'
print('wordB', text.split().count(word2))
word3 = 'wordC'
print('wordC', text.split().count(word3))
</code>```

To improve performance it is also possible to split only once:

```<code>#!/usr/bin/env python

with  open('my_output', 'r') as file:
    split_text =  file.read().split()

word1 = 'wordA'
print('wordA', split_text.count(word1))
word2 = 'wordB'
print('wordB', split_text.count(word2))
word3 = 'wordC'
print('wordC', split_text.count(word3))
</code>```

Using with will also ensure that the file closes correctly after being read.

Title: Counting number of words in Python file

Body:
I'm trying to count the number of instances several words appear in a file.

Here is my code:

#!/usr/bin/env python

file = open('my_output', 'r')

word1 = 'wordA'
print('wordA', file.read().split().count(word1))
word2 = 'wordB'
print('wordB', file.read().split().count(word2))
word3 = 'wordC'
print('wordC', file.read().split().count(word3))

The issue in the code is that it only counts the number of instances of word1. How can this code be fixed to count word2 and word3?

Thanks!

Body:
The main problem is that file.read() consumes the file. Thus the second time you search you end up searching an empty file. The simplest solution is to read the file once (if it is not too large) and then just search the previously read text:

#!/usr/bin/env python

with  open('my_output', 'r') as file:
    text =  file.read()

word1 = 'wordA'
print('wordA', text.split().count(word1))
word2 = 'wordB'
print('wordB', text.split().count(word2))
word3 = 'wordC'
print('wordC', text.split().count(word3))

To improve performance it is also possible to split only once:

#!/usr/bin/env python

with  open('my_output', 'r') as file:
    split_text =  file.read().split()

word1 = 'wordA'
print('wordA', split_text.count(word1))
word2 = 'wordB'
print('wordB', split_text.count(word2))
word3 = 'wordC'
print('wordC', split_text.count(word3))

Using with will also ensure that the file closes correctly after being read.


问:
How to install the scm perforce provider for SonarQube 5.3?
I want to use perforce as SonarQube 5.3 scm provider, but it failed with this error message:

```<code>ERROR: SCM provider was set to "perforce" but no SCM provider found for this key.
Supported SCM providers are svn,git
</code>```

I want to install perforce plugin in SonarQube update center, but it said:

```<code>Error while downloading plugin 'scmperforce' with version '1.4'.
No compatible plugin found.
</code>```

And I can't find any available scm perforce plugins on the SonarQube website.

How to use perforce with SonarQube 5.3?

答:
The current version of SonarQube is 6.4 and the current LTS is 5.6.6. Plugin versions only compatible with versions lower than those have been purged from the Update Center.

There is, however, a version of the Perforce plugin that's compatible with 5.6.6.

Body:
I want to use perforce as SonarQube 5.3 scm provider, but it failed with this error message:

ERROR: SCM provider was set to "perforce" but no SCM provider found for this key.
Supported SCM providers are svn,git

I want to install perforce plugin in SonarQube update center, but it said:

Error while downloading plugin 'scmperforce' with version '1.4'.
No compatible plugin found.

And I can't find any available scm perforce plugins on the SonarQube website.

How to use perforce with SonarQube 5.3?


问:
How do I tweak CSS on the Django 1.2.3 admin media?
I would like to make CSS-only adjustments to the admin interface (on an RHEL box I don't have sysadmin privileges to). To that end, I would like a local version of /media/ to tweak.

http://docs.djangoproject.com/en/dev/howto/static-files/ (but not http://docs.djangoproject.com/en/1.2/howto/static-files/) suggests running a manage.py collectstatic or manage.py findstatic, and my Django 1.2.3 manage.py does not recognize those commands. Adding 'django.contrib.staticfiles' to my INSTALLED_APPS also broke things (not found).

I would like to customize the CSS, and the way I envision doing that is by getting a private copy of the media for Django's admin and changing from there. What are my best options for a Django 1.2.3 installation?

答:
I found a way to do it:

1: Download a fresh copy of Django and unpack it. Under the Django-x.x.x directory was a media directory.

2: Tar/transfer/untar the media directory on my target machine.

3: Change the CSS as needed.

4: When calling python manage.py runserver, add a flag of --adminmedia=./media .


问:
Error: com.google.common.cache.CacheBuilder.from(Lcom/google/common/cache/CacheBuilderSpec;)Lcom/google/common/cache/CacheBuilder;
A strange run time error when working with JPMML library (with guava).

I used the jpmml related dependencies in my pom.xml like below

```<code>    <dependency>
        <groupId>org.jpmml</groupId>
        <artifactId>pmml-evaluator</artifactId>
        <version>1.3.6</version>
        </exclusions>
    </dependency>
</code>```

It started throwing the exception. Then i tried like below.

```<code>    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>
    <dependency>
        <groupId>org.jpmml</groupId>
        <artifactId>pmml-evaluator</artifactId>
        <version>1.3.6</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

I tried with 11.x/12.x/15.x/18.x/19.x/20.x versions of guava But still i am facing the same exception. I have gone through google and people have used guava-19.0 version and it worked for them, But i am not able to achieve this. Can someone please tell me am i missing something.

Please find the full stack trace below.

```<code>java.lang.NoSuchMethodError: com.google.common.cache.CacheBuilder.from(Lcom/google/common/cache/CacheBuilderSpec;)Lcom/google/common/cache/CacheBuilder;
    at org.jpmml.evaluator.CacheUtil.newCacheBuilder(CacheUtil.java:97)
    at org.jpmml.evaluator.CacheUtil.buildLoadingCache(CacheUtil.java:90)
    at org.jpmml.evaluator.ModelEvaluator.<clinit>(ModelEvaluator.java:660)
    at org.jpmml.evaluator.ModelEvaluatorFactory.newModelEvaluator(ModelEvaluatorFactory.java:80)
    at org.jpmml.evaluator.ModelEvaluatorFactory.newModelEvaluator(ModelEvaluatorFactory.java:66)
.....
.....
</code>```

答: Looks like you have correct version in maven pom, but during runtime it is picking old version, make sure it picks the correct version at run time. Check your class path on the data nodes.</p>

Body:
A strange run time error when working with JPMML library (with guava).

I used the jpmml related dependencies in my pom.xml like below

    <dependency>
        <groupId>org.jpmml</groupId>
        <artifactId>pmml-evaluator</artifactId>
        <version>1.3.6</version>
        </exclusions>
    </dependency>

It started throwing the exception. Then i tried like below.

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>
    <dependency>
        <groupId>org.jpmml</groupId>
        <artifactId>pmml-evaluator</artifactId>
        <version>1.3.6</version>
        <exclusions>
            <exclusion>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

I tried with 11.x/12.x/15.x/18.x/19.x/20.x versions of guava But still i am facing the same exception. I have gone through google and people have used guava-19.0 version and it worked for them, But i am not able to achieve this. Can someone please tell me am i missing something.

Please find the full stack trace below.

java.lang.NoSuchMethodError: com.google.common.cache.CacheBuilder.from(Lcom/google/common/cache/CacheBuilderSpec;)Lcom/google/common/cache/CacheBuilder;
    at org.jpmml.evaluator.CacheUtil.newCacheBuilder(CacheUtil.java:97)
    at org.jpmml.evaluator.CacheUtil.buildLoadingCache(CacheUtil.java:90)
    at org.jpmml.evaluator.ModelEvaluator.<clinit>(ModelEvaluator.java:660)
    at org.jpmml.evaluator.ModelEvaluatorFactory.newModelEvaluator(ModelEvaluatorFactory.java:80)
    at org.jpmml.evaluator.ModelEvaluatorFactory.newModelEvaluator(ModelEvaluatorFactory.java:66)
.....
.....


问:
Sorting column not working on gridview
probably this is easy but I am facing troubles to make sort works for a column of a gridview. The idea is to click at column:

```<code><asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory" SortExpression="availInventory" />
</code>```

So explaining how the gridview is sourced the following columns values are obtain through a sql query consult and they are binded to the gridview: Family, Recipe, Top Part Number, Generic Part Number, Child#1 Part Number, Factor Child1, Child#2 Part Number, Factor Child2, Child#3 Part Number, Factor Child3.
The values for columns Attrition, Inventory Child1, Inventory Child2, Inventory Child3 and Available Inventory are calculated at RowDataBound method of the gridview.
The gridview is loaded at page after selection of some dropdownlists.

Gridview

```<code>        <asp:GridView ID="recipegrid" runat="server" Width="1200px" Height="152px" AutoGenerateColumns="false" AllowSorting="true" OnSorting="recipegrid_Sorting" CssClass="generalgrid" AllowPaging="true" OnPageIndexChanging="OnPaging" PageSize="50" OnRowDataBound="recipegrid_RowDataBound" OnSelectedIndexChanged="recipegrid_SelectedIndexChanged" HeaderStyle-CssClass="gridHeader" RowStyle-CssClass="gridRows" PagerStyle-CssClass="paginationRow" OnDataBound="recipegrid_DataBound">
        <Columns>
    <asp:BoundField ItemStyle-Width="150px" DataField="Family" HeaderText="Family" />
    <asp:BoundField ItemStyle-Width="150px" DataField="RecipePN" HeaderText="Recipe" />
    <asp:BoundField ItemStyle-Width="150px" DataField="TopPN" HeaderText="Top Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="GenericPN" HeaderText="Generic Part Number" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Attrition" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child1PN" HeaderText="Child#1 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild1" HeaderText="Factor Child1" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child1" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child2PN" HeaderText="Child#2 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild2" HeaderText="Factor Child2" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child2" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child3PN" HeaderText="Child#3 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild3" HeaderText="Factor Child3" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child3" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory" SortExpression="availInventory" />

    <asp:TemplateField HeaderText="Status" Visible="false" ItemStyle-Width="150px">
            <ItemTemplate>
                <asp:Label ID="lblStatus" runat="server"></asp:Label>
            </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Select Data" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:RadioButton ID="recipeselector"  runat="server" AutoPostBack="true"  OnCheckedChanged="rbtnSelect_CheckedChanged" />
                   <!-- <asp:HiddenField ID="HiddenField1" runat="server"  /> -->
                </ItemTemplate>
    </asp:TemplateField>

        </Columns>
        <EmptyDataTemplate><label class="labelemptygriddata"> No data loaded from DB!</label> </EmptyDataTemplate>
    </asp:GridView>
</code>```

sortDirection Method

```<code>        private string sortDirectionMethod (SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;

        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }
</code>```

Sorting method

```<code>        protected void recipegrid_Sorting(object sender, GridViewSortEventArgs e)
    {

        //DataTable dt = recipegrid.DataSource as DataTable;
        DataTable dt = new DataTable();

        //Session["grid"] = recipegrid.DataSource;

        dt = (DataTable)Session["grid"];

        if (dt != null)
        {
            DataView dv = new DataView(dt);
            dv.Sort = e.SortExpression + " " + sortDirectionMethod(e.SortDirection);

            recipegrid.DataSource = dv;
            recipegrid.DataBind();
        }

    }
</code>```

So the issue is the sorting is not working as I get the following error:

An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code
Additional information: Cannot find column availInventory.

Any help or guidance will be much appreciated.
Thanks

EDIT
adding code of fetching/storing values of gridview to datatable, which is contained inside RowDataBound Method. The method is too large so I am only posting where I form the datatable and define the session variable:

```<code>            //copy info from gridview to session
        //need to add each column name and type
        DataTable dt = new DataTable();
        DataRow dr;
        //Boolean noCheck = false;

        //column Family
        dt.Columns.Add("Family", typeof(string));
        //column Recipe
        dt.Columns.Add("Recipe", typeof(string));
        //column Top Part Number
        dt.Columns.Add("Top Part Number", typeof(string));
        //column Generic Part Number
        dt.Columns.Add("Generic Part Number", typeof(string));
        //column Attrition
        dt.Columns.Add("Attrition", typeof(string));

        //column child#1 Part Number
        dt.Columns.Add("Child#1 Part Number", typeof(string));
        //column Factor Child1
        dt.Columns.Add("Factor Child1", typeof(string));
        //column Inventory Child1
        dt.Columns.Add("Inventory Child1", typeof(string));

        //column Child#2 Part Number
        dt.Columns.Add("Child#2 Part Number", typeof(string));
        //column Factor Child2
        dt.Columns.Add("Factor Child2", typeof(string));
        //column Inventory Child2
        dt.Columns.Add("Inventory Child2", typeof(string));

        //column Child#3 Part Number
        dt.Columns.Add("Child#3 Part Number", typeof(string));
        //column Factor Child3
        dt.Columns.Add("Factor Child3", typeof(string));
        //column Inventory Child3
        dt.Columns.Add("Inventory Child3", typeof(string));

        //column Available Inventory
        dt.Columns.Add("Available Inventory", typeof(Int32));

        //column select data
        dt.Columns.Add("Select Data", typeof(string));

        foreach (GridViewRow row in recipegrid.Rows)
        {
            System.Web.UI.WebControls.RadioButton selectData = (System.Web.UI.WebControls.RadioButton)row.FindControl("recipeselector");
            dr = dt.NewRow();

            //family
            dr[0] = row.Cells[0].Text;
            //recipe
            dr[1] = row.Cells[1].Text;
            //top partnumber
            dr[2] = row.Cells[2].Text;
            //generic partnumber
            dr[3] = row.Cells[3].Text;
            //attrition
            dr[4] = row.Cells[4].Text;

            //child#1 partnumber
            dr[5] = row.Cells[5].Text;
            //factor child1
            dr[6] = row.Cells[6].Text;
            //inventory child1
            dr[7] = row.Cells[7].Text;

            //child#2 partnumber
            dr[8] = row.Cells[8].Text;
            //factor child2
            dr[9] = row.Cells[9].Text;
            //inventory child2
            dr[10] = row.Cells[10].Text;

            //child#3 partnumber
            dr[11] = row.Cells[11].Text;
            //factor child3
            dr[12] = row.Cells[12].Text;
            //inventory child3
            dr[13] = row.Cells[13].Text;

            //available inventory
            dr[14] = Convert.ToInt32(row.Cells[14].Text);

            //select data
            dr[15] = selectData.Checked = false;

            dt.Rows.Add(dr);
        }
        Session["grid"] = dt;
</code>```

答:
The error is: Cannot find column availInventory.

Your bound field is

```<code><asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory"
    SortExpression="availInventory" />
</code>```

Try changing the SortExpression to Available Inventory, to match

dt.Columns.Add("Available Inventory", typeof(Int32));.

Title: Sorting column not working on gridview

Body:
probably this is easy but I am facing troubles to make sort works for a column of a gridview. The idea is to click at column:

<asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory" SortExpression="availInventory" />

So explaining how the gridview is sourced the following columns values are obtain through a sql query consult and they are binded to the gridview: Family, Recipe, Top Part Number, Generic Part Number, Child#1 Part Number, Factor Child1, Child#2 Part Number, Factor Child2, Child#3 Part Number, Factor Child3.
The values for columns Attrition, Inventory Child1, Inventory Child2, Inventory Child3 and Available Inventory are calculated at RowDataBound method of the gridview.
The gridview is loaded at page after selection of some dropdownlists.

Gridview

        <asp:GridView ID="recipegrid" runat="server" Width="1200px" Height="152px" AutoGenerateColumns="false" AllowSorting="true" OnSorting="recipegrid_Sorting" CssClass="generalgrid" AllowPaging="true" OnPageIndexChanging="OnPaging" PageSize="50" OnRowDataBound="recipegrid_RowDataBound" OnSelectedIndexChanged="recipegrid_SelectedIndexChanged" HeaderStyle-CssClass="gridHeader" RowStyle-CssClass="gridRows" PagerStyle-CssClass="paginationRow" OnDataBound="recipegrid_DataBound">
        <Columns>
    <asp:BoundField ItemStyle-Width="150px" DataField="Family" HeaderText="Family" />
    <asp:BoundField ItemStyle-Width="150px" DataField="RecipePN" HeaderText="Recipe" />
    <asp:BoundField ItemStyle-Width="150px" DataField="TopPN" HeaderText="Top Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="GenericPN" HeaderText="Generic Part Number" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Attrition" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child1PN" HeaderText="Child#1 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild1" HeaderText="Factor Child1" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child1" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child2PN" HeaderText="Child#2 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild2" HeaderText="Factor Child2" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child2" />
    <asp:BoundField ItemStyle-Width="150px" DataField="Child3PN" HeaderText="Child#3 Part Number" />
    <asp:BoundField ItemStyle-Width="150px" DataField="FactorChild3" HeaderText="Factor Child3" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Inventory Child3" />
    <asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory" SortExpression="availInventory" />

    <asp:TemplateField HeaderText="Status" Visible="false" ItemStyle-Width="150px">
            <ItemTemplate>
                <asp:Label ID="lblStatus" runat="server"></asp:Label>
            </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Select Data" ItemStyle-Width="150px" >
                <ItemTemplate>
                    <asp:RadioButton ID="recipeselector"  runat="server" AutoPostBack="true"  OnCheckedChanged="rbtnSelect_CheckedChanged" />

                </ItemTemplate>
    </asp:TemplateField>

        </Columns>
        <EmptyDataTemplate> No data loaded from DB! </EmptyDataTemplate>
    </asp:GridView>

sortDirection Method

        private string sortDirectionMethod (SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;

        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }

Sorting method

        protected void recipegrid_Sorting(object sender, GridViewSortEventArgs e)
    {

        //DataTable dt = recipegrid.DataSource as DataTable;
        DataTable dt = new DataTable();

        //Session["grid"] = recipegrid.DataSource;

        dt = (DataTable)Session["grid"];

        if (dt != null)
        {
            DataView dv = new DataView(dt);
            dv.Sort = e.SortExpression + " " + sortDirectionMethod(e.SortDirection);

            recipegrid.DataSource = dv;
            recipegrid.DataBind();
        }

    }

So the issue is the sorting is not working as I get the following error:

An exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll but was not handled in user code
Additional information: Cannot find column availInventory.

Any help or guidance will be much appreciated.
Thanks

EDIT
adding code of fetching/storing values of gridview to datatable, which is contained inside RowDataBound Method. The method is too large so I am only posting where I form the datatable and define the session variable:

            //copy info from gridview to session
        //need to add each column name and type
        DataTable dt = new DataTable();
        DataRow dr;
        //Boolean noCheck = false;

        //column Family
        dt.Columns.Add("Family", typeof(string));
        //column Recipe
        dt.Columns.Add("Recipe", typeof(string));
        //column Top Part Number
        dt.Columns.Add("Top Part Number", typeof(string));
        //column Generic Part Number
        dt.Columns.Add("Generic Part Number", typeof(string));
        //column Attrition
        dt.Columns.Add("Attrition", typeof(string));

        //column child#1 Part Number
        dt.Columns.Add("Child#1 Part Number", typeof(string));
        //column Factor Child1
        dt.Columns.Add("Factor Child1", typeof(string));
        //column Inventory Child1
        dt.Columns.Add("Inventory Child1", typeof(string));

        //column Child#2 Part Number
        dt.Columns.Add("Child#2 Part Number", typeof(string));
        //column Factor Child2
        dt.Columns.Add("Factor Child2", typeof(string));
        //column Inventory Child2
        dt.Columns.Add("Inventory Child2", typeof(string));

        //column Child#3 Part Number
        dt.Columns.Add("Child#3 Part Number", typeof(string));
        //column Factor Child3
        dt.Columns.Add("Factor Child3", typeof(string));
        //column Inventory Child3
        dt.Columns.Add("Inventory Child3", typeof(string));

        //column Available Inventory
        dt.Columns.Add("Available Inventory", typeof(Int32));

        //column select data
        dt.Columns.Add("Select Data", typeof(string));

        foreach (GridViewRow row in recipegrid.Rows)
        {
            System.Web.UI.WebControls.RadioButton selectData = (System.Web.UI.WebControls.RadioButton)row.FindControl("recipeselector");
            dr = dt.NewRow();

            //family
            dr[0] = row.Cells[0].Text;
            //recipe
            dr[1] = row.Cells[1].Text;
            //top partnumber
            dr[2] = row.Cells[2].Text;
            //generic partnumber
            dr[3] = row.Cells[3].Text;
            //attrition
            dr[4] = row.Cells[4].Text;

            //child#1 partnumber
            dr[5] = row.Cells[5].Text;
            //factor child1
            dr[6] = row.Cells[6].Text;
            //inventory child1
            dr[7] = row.Cells[7].Text;

            //child#2 partnumber
            dr[8] = row.Cells[8].Text;
            //factor child2
            dr[9] = row.Cells[9].Text;
            //inventory child2
            dr[10] = row.Cells[10].Text;

            //child#3 partnumber
            dr[11] = row.Cells[11].Text;
            //factor child3
            dr[12] = row.Cells[12].Text;
            //inventory child3
            dr[13] = row.Cells[13].Text;

            //available inventory
            dr[14] = Convert.ToInt32(row.Cells[14].Text);

            //select data
            dr[15] = selectData.Checked = false;

            dt.Rows.Add(dr);
        }
        Session["grid"] = dt;

Body:
The error is: Cannot find column availInventory.

Your bound field is

<asp:BoundField ItemStyle-Width="150px"  HeaderText="Available Inventory"
    SortExpression="availInventory" />

Try changing the SortExpression to Available Inventory, to match

dt.Columns.Add("Available Inventory", typeof(Int32));.