问:
Converting text box value to int
I have been trying to apply solutions I found on both Google and Stackoverflow, but they don't seem to be working.

What exactly is going wrong here? The checkbox is insignificant here and I can take it out, but it makes no difference.

```<code><div class="form-group">
    <label for="tbid" class="col-lg-3 control-label">Results per page </label>
        <div class="col-lg-3">
            <input type="checkbox" class="checkbox" display="inline-block" name="checkbox_results" onclick="checkbox_results_click();">
            <input type="text" id="results" class="form-control" name="results" placeholder="results">
        </div>
</div>
</code>```

Then in the js portion, I am trying to convert results into an int.

```<code><script type="text/javascript">
    int results = null;
    var x=document.getElementById("results").value;

    results = parseInt(x);
    if(results==null)
        results=10;

    var pager = new Pager(results);

</script>
</code>```

EDIT: I should also add that if I just put a int parameter when calling pager, like 25, for example, it actually works. So something is going wrong with results.

答:
Use parseFloat it will work like this

```

Title: Converting text box value to int

Body:
I have been trying to apply solutions I found on both Google and Stackoverflow, but they don't seem to be working.

What exactly is going wrong here? The checkbox is insignificant here and I can take it out, but it makes no difference.

    Results per page

            <input type="checkbox" class="checkbox" display="inline-block" name="checkbox_results" onclick="checkbox_results_click();">
            <input type="text" id="results" class="form-control" name="results" placeholder="results">

Then in the js portion, I am trying to convert results into an int.

EDIT: I should also add that if I just put a int parameter when calling pager, like 25, for example, it actually works. So something is going wrong with results.

Body:
Use parseFloat it will work like this

<script type="text/javascript">
    int results = null;
    var x=document.getElementById("results").value;

    results = parseFloat(x);
    if(results==null)
        results=10;

    var pager = new Pager(results);

</script>


来源: stackexchange

问:
Clear contents of two sheets from the macro file
```<code>Sub Button_Click()

    With Thiswoorkbook.sheets("abc")
      .Rows("2:"&.Rows.count).ClearContents
    End with

    with Thiswoorkbook.sheets("xyz")
      .Rows("1:"&.Rows.count).ClearContents
    End with

end sub
</code>```

<p>i am using the above mentioned codes but i need to click twice clear the contents is there any way to fix the code to do it in single click  </p>

答: Based on the information that you have provided, it seems that you may have assigned the macro to a shape, then you have to double click the shape to get it to run. An ActiveX control button will run with a single click. See how to put an ActiveX control button into your spreadsheet at the linked documentation for Microsoft Office. https://support.office.com/en-us/article/Assign-a-macro-to-a-Form-or-a-Control-button-d58edd7d-cb04-4964-bead-9c72c843a283</p>

ContentLicense: CC BY-SA 3.0

Body:
Sub Button_Click()

    With Thiswoorkbook.sheets("abc")
      .Rows("2:"&.Rows.count).ClearContents
    End with

    with Thiswoorkbook.sheets("xyz")
      .Rows("1:"&.Rows.count).ClearContents
    End with

end sub

i am using the above mentioned codes but i need to click twice clear the contents is there any way to fix the code to do it in single click


问:
Given an array of integers, find the second largest and second smallest within the array
I am trying to come up with a function that will take an array of integers and output the 2nd highest number and the 2nd smallest number. The function will take into account floats, duplicates, and negative numbers. </p>

<p>Two functions pass all the tests below except for test2. </p>

```<code>var test1 = [7, 7, 12, 98, 106]
  answer1 = {2nd Min: 12, 2nd Max: 98}

var test2 = [5, 23, -112, 6, 70, 70, -112]
  answer2 = {2nd Min: 5, 2nd Max: 23}

var test3 = [-22, 22]
  answer3 = {2nd Min: 22, 2nd Max: -22}

var test4 = [10, 89, 3]
   answer = {2nd Min: 10, 2nd Max: 10}

var test5 = [10.4, -12.09, .75, 22]
  answer3 = {2nd Min: 0.75, 2nd Max: 10.4}

 /*/          \ \
 ---SOLUTION 1---
 \ \          /*/
function secondGreatLow1(arr) {
  //make copy of array because it will be spliced in the following functions
  var arrCopy = arr.slice();
  //push returned values of each function into this the answer array
  var answer = []
  answer.push(secondMin(arrCopy));
  answer.push(secondMax(arrCopy));
  return answer;
};

//helper function 1
var secondMin = function (arr){
  var arrCopy = arr.slice();
  //check length of array
  if (arr.length == 2) {
    return arr[1];
  } else {
    var min = Math.min.apply(null, arrCopy);
    arrCopy.splice(arrCopy.indexOf(min), 1);
    //check for duplicates
    for (var i = 0; i < arrCopy.length; i++) {
      if (arrCopy.indexOf(min) === -1) {
        //.apply is used for arrays
        return Math.min.apply(null, arrCopy);
      } else {
        arrCopy.splice(arrCopy.indexOf(min), 1);
        return Math.min.apply(null, arrCopy);
      }
    };
  }
};

//helper function 2
var secondMax = function (arr){
  var arrCopy = arr.slice();
  if (arr.length == 2) {
    return arr[0];
  } else {
    var max = Math.max.apply(null, arrCopy);
    arrCopy.splice(arrCopy.indexOf(max), 1);
    //check for duplicates
    for (var i = 0; i < arrCopy.length; i++) {
      if (arrCopy.indexOf(max) === -1) {
        return Math.max.apply(null, arrCopy);
      } else {
        arrCopy.splice(arrCopy.indexOf(max), 1);
        return Math.min.apply(null, arrCopy);
      }
    };
  }
};

 /*/          \ \
 ---SOLUTION 2---
 \ \         /*/
function secondGreatLow2 (numbers) {
  var arr = withoutDuplicates(numbers);
  arr.sort(function(a,b) { return a-b; });
  return arr[1] + ' ' + arr[arr.length-2];
};

// helpers
var withoutDuplicates = function(arr) {
  var out = [];
  for(var i=0; i<arr.length; i++) {
    if(i === 0 || arr[i] !== arr[i-1]) {
      out.push(arr[i]);
    }
  }
  return out;
};
</code>```

答:
This is an easy and simple method for a second highest number but the problem is we could not get a number if there have duplicate exists in the array.</p>

```<code> function getSecondLargest(nums) {

if(nums.length<2){
    return nums;
}
var first=0;
var second=0;
for(var i=0; i<nums.length;i++)
    {
        if(nums[i]>first)
            {
                second = first;
                first = nums[i]
            }
        else(nums[i]>second && nums[i]!=first)
        {
            second = nums[i];
        }

    }
return second;
}
</code>```

Body:
I am trying to come up with a function that will take an array of integers and output the 2nd highest number and the 2nd smallest number. The function will take into account floats, duplicates, and negative numbers.

Two functions pass all the tests below except for test2.

var test1 = [7, 7, 12, 98, 106]
  answer1 = {2nd Min: 12, 2nd Max: 98}

var test2 = [5, 23, -112, 6, 70, 70, -112]
  answer2 = {2nd Min: 5, 2nd Max: 23}

var test3 = [-22, 22]
  answer3 = {2nd Min: 22, 2nd Max: -22}

var test4 = [10, 89, 3]
   answer = {2nd Min: 10, 2nd Max: 10}

var test5 = [10.4, -12.09, .75, 22]
  answer3 = {2nd Min: 0.75, 2nd Max: 10.4}

 /*/          \ \
 ---SOLUTION 1---
 \ \          /*/
function secondGreatLow1(arr) {
  //make copy of array because it will be spliced in the following functions
  var arrCopy = arr.slice();
  //push returned values of each function into this the answer array
  var answer = []
  answer.push(secondMin(arrCopy));
  answer.push(secondMax(arrCopy));
  return answer;
};

//helper function 1
var secondMin = function (arr){
  var arrCopy = arr.slice();
  //check length of array
  if (arr.length == 2) {
    return arr[1];
  } else {
    var min = Math.min.apply(null, arrCopy);
    arrCopy.splice(arrCopy.indexOf(min), 1);
    //check for duplicates
    for (var i = 0; i < arrCopy.length; i++) {
      if (arrCopy.indexOf(min) === -1) {
        //.apply is used for arrays
        return Math.min.apply(null, arrCopy);
      } else {
        arrCopy.splice(arrCopy.indexOf(min), 1);
        return Math.min.apply(null, arrCopy);
      }
    };
  }
};

//helper function 2
var secondMax = function (arr){
  var arrCopy = arr.slice();
  if (arr.length == 2) {
    return arr[0];
  } else {
    var max = Math.max.apply(null, arrCopy);
    arrCopy.splice(arrCopy.indexOf(max), 1);
    //check for duplicates
    for (var i = 0; i < arrCopy.length; i++) {
      if (arrCopy.indexOf(max) === -1) {
        return Math.max.apply(null, arrCopy);
      } else {
        arrCopy.splice(arrCopy.indexOf(max), 1);
        return Math.min.apply(null, arrCopy);
      }
    };
  }
};

 /*/          \ \
 ---SOLUTION 2---
 \ \         /*/
function secondGreatLow2 (numbers) {
  var arr = withoutDuplicates(numbers);
  arr.sort(function(a,b) { return a-b; });
  return arr[1] + ' ' + arr[arr.length-2];
};

// helpers
var withoutDuplicates = function(arr) {
  var out = [];
  for(var i=0; i<arr.length; i++) {
    if(i === 0 || arr[i] !== arr[i-1]) {
      out.push(arr[i]);
    }
  }
  return out;
};

Body:
This is an easy and simple method for a second highest number but the problem is we could not get a number if there have duplicate exists in the array.

 function getSecondLargest(nums) {

if(nums.length<2){
    return nums;
}
var first=0;
var second=0;
for(var i=0; i<nums.length;i++)
    {
        if(nums[i]>first)
            {
                second = first;
                first = nums[i]
            }
        else(nums[i]>second && nums[i]!=first)
        {
            second = nums[i];
        }

    }
return second;
}


问:
How do I create a Google Oauth2 client_id that doesn't just return "Forbidden"?
I'm trying to use p2/OAuth2 to access my documents on Google Drive.

I downloaded the sample Mac app and ran it, and it shows a Google "OAuth consent screen", and I click the "Allow" button, and it all works.  So I think the sample code is good.

Then I logged into the Google APIs console, and:

enabled all the APIs that seemed like they might be relevant to this test (getting my name and user info): "Google Drive API", "Contacts API", "People API", "Google IAM API", etc.

created a "project" for my application

created a new "OAuth client ID" (credentials) for my app

I pasted my client_id into the OAuth2App sample, in place of the demo client_id/client_secret, and it fails.  It shows the "OAuth consent screen" in a sheet, with the name of my application, but when I click "Allow", it just says "Forbidden".

Things I've tried that didn't help:

I've found this page which says creating a client ID of type "Other" in Google doesn't work, and I need to choose iOS.  I've tried both "Other" and "iOS" types, and both give me "Forbidden".

With type "Other", it gives me a client_secret, as well.  I don't want or need that, because this is a local app, but I found this question which suggests it doesn't matter to Google.  I tried every way:

With the correct client_secret, I get "Forbidden".

With an incorrect client_secret, I get "Unauthorized".

With no client_secret, I get "client_secret is missing".

So I know it's checking that for type="Other", and doesn't seem to care that it's absent for type="iOS".  In any event, since it's a different error when that's wrong/missing, that doesn't seem to be my problem here.

I turned on oauth.verbose to see if there's anything useful, but the logs are identical to the successful case (stock IDs), except for the values of some of the IDs/tokens.

How did p2/OAuth2 create a client_id for Google that works?  Why is mine only returning "Forbidden"?

答:
If it is your Local app, You'll need to select the installed option while selecting the type, and use Web Athorization Broker

this link might be helpful, its unsolved but has solution for the point you are stuck.

1.) ClientID and ClientSecret both are necessary while using installed application.

--> Also check your network rights if it is allowing the Drive api, that can also give Forbidden Error


问:
Substring assignment
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

```<code><head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

<script type="text/javascript">

var text= test.length;

for (i=0;i< test.length;i++)

function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}

    </script>

</head>

<body>
<h1>Assignment 14</h1>
    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

</body>
</code>```

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

答:
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:

substring(0,i)

Title: Substring assignment

Body:
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

Assignment 14

    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.


问:
Unable to access Kafka Docker container from outside through java basic app without updating /etc/hosts file
Set up:
1.Docker Kafka Container which is having Kafka running.
2.Java basic application which produce and consume Kafka messages from outside the Kafka container.

From outside the container I am trying to send Kafka messages using java script and consume those messages with consumer written in java script.
This is working if I am updating etc/hosts file with Kafka container IP address and hostname details.
Please suggest solution to prevent updating etc/hosts file details.
Requirement: With ought updating etc/hosts file how can we access the Kafka container from outside.

答:
Got answer for my issue.
Need to provide "Listener" value to "0.0.0.0:9092" in Kafka "server.properties" file.
Updated Docker file for kafka so that when container is up for Kafka it should have below value for Listener in Kafka container.

Kafka Container>config>Server.properties>Listener=0.0.0.0:9092.

Once this is done just start the Kafka container with port forwarding for Zookeeper and Kafka ports with localhost. And then you are able to send the Kafka messages from local to Kafka container and also able to consume those messages from outside the Kafka container.


问:
Map json Object with randomise array creation
I have JSON object and array

```<code>sampleJson={"id":1,"option1":"","option2":"","option3":""}
sampleArray=["car","","Animals"]
</code>```

i want to add sampleArray to sampleJson in following format

```<code>sampleJson={"id":1,"option1"="car","option2":"Animals","option3":""}
</code>```

sample array will be randomise like ["","car",""] Or ["","animal","Car"]?

答:
```<code>var sampleJson={"id":1,"option1":"","option2":"","option3":""}
var sampleArray=["car","","Animals"];
var count = 1;
sampleArray.forEach(function(ele){
    if(ele.length){
        sampleJson['option' + count] = ele;
        count++;
    }
})
console.log(sampleJson);//{id: 1, option1: "car", option2: "Animals", option3: ""}
</code>```

Body:
I have JSON object and array

sampleJson={"id":1,"option1":"","option2":"","option3":""}
sampleArray=["car","","Animals"]

i want to add sampleArray to sampleJson in following format

sampleJson={"id":1,"option1"="car","option2":"Animals","option3":""}

sample array will be randomise like ["","car",""] Or ["","animal","Car"]?


问:
Understanding ExtJS model associations
I am trying to understand how ExtJS associations work. I have not found an understandable tutorial on this issue that covers my main two use cases and especially how ExtJS differentiates between the two:

Association between two models through an "Id" reference.

Association between two models through a Parent-Child relationship.

I have laid the ground in this fiddle, can someone help me to fill in the gaps?

答:
```<code> **fields: [
        {name: 'AA', mapping: 'qq'},
        {name: 'SS', mapping: 'pp'},
    ]**

The **name** you write the name given in gui part
eg:
{
xtype:'mytext',
label:'',
**name:'AA',**
editable:true
}

when you receive responses like this and in xml so the data is mapped like this:
*<wer>
<qq>data</qq>
<>data</>
</wer>*

so, we map the response data to name in gui.....
</code>```

Title: Understanding ExtJS model associations


问:
How to set input shape of a GRU/LSTM
I am trying to train my model to predict the next number in an integer sequence. The integer sequence that I created was generated in random.
My X_train = [[1,2,3,4,5,6], [45,45,46,47,48,49], [203,204,205,206,207,208]...]
and Y_train = [[7,8,9], [50,51,52], [209,210,211]]
The shape of X_train = (10000,6,511) and Y_train = (10000,3,511)
How should I set my input shape for my GRU/LSTM model?

```<code>def define_models(n_input = 6, n_output = 3):
    # define training encoder
    sequence = Input(shape=(n_input,), dtype="int32")
    embedded = Embedding(13, 300, mask_zero=True)(sequence)
    gru1 = GRU(1000, return_sequences=True)(embedded)
    after_dp = Dropout(0.5)(gru1)
    gru2 = GRU(1000, return_sequences=True)(after_dp)
    after_dp = Dropout(0.5)(gru2)
    output = TimeDistributed(Dense(13, activation="softmax"))(after_dp)

    model = Model(input=sequence, output=output)

    return model
</code>```

i am getting the error :

```<code>ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with shape (10000, 6, 511)
</code>```

How should I fix it for my dataset?

答:
You are only giving one dimension as the input_shape, while you are giving a 3d array as input.For a n-d input array, the input_shape should be last n-1 dimension values. Hence the input shape should be
 (X_train.shape[1],X_train.shape[2]).

Replace this line

```<code> sequence = Input(shape=(n_input,), dtype="int32")
</code>```

with this

```<code> sequence = Input(shape=(X_train.shape[1],X_train.shape[2]), dtype="int32")
</code>```

Title: How to set input shape of a GRU/LSTM

Body:
I am trying to train my model to predict the next number in an integer sequence. The integer sequence that I created was generated in random.
My X_train = [[1,2,3,4,5,6], [45,45,46,47,48,49], [203,204,205,206,207,208]...]
and Y_train = [[7,8,9], [50,51,52], [209,210,211]]
The shape of X_train = (10000,6,511) and Y_train = (10000,3,511)
How should I set my input shape for my GRU/LSTM model?

def define_models(n_input = 6, n_output = 3):
    # define training encoder
    sequence = Input(shape=(n_input,), dtype="int32")
    embedded = Embedding(13, 300, mask_zero=True)(sequence)
    gru1 = GRU(1000, return_sequences=True)(embedded)
    after_dp = Dropout(0.5)(gru1)
    gru2 = GRU(1000, return_sequences=True)(after_dp)
    after_dp = Dropout(0.5)(gru2)
    output = TimeDistributed(Dense(13, activation="softmax"))(after_dp)

    model = Model(input=sequence, output=output)

    return model

i am getting the error :

ValueError: Error when checking input: expected input_1 to have 2 dimensions, but got array with shape (10000, 6, 511)

How should I fix it for my dataset?

Body:
You are only giving one dimension as the input_shape, while you are giving a 3d array as input.For a n-d input array, the input_shape should be last n-1 dimension values. Hence the input shape should be
 (X_train.shape[1],X_train.shape[2]).

Replace this line

 sequence = Input(shape=(n_input,), dtype="int32")

with this

 sequence = Input(shape=(X_train.shape[1],X_train.shape[2]), dtype="int32")


问:
Javascript setting innerHTML null issue
When i run an ajax query, i get back an array of results. I want to create a new element and set its inner html to the results. The results are working fine, im getting them no problem. They contain the correct data. I can create the element with an id based on the result fine as well i just get:

Uncaught TypeError: Cannot set property 'innerHTML' of null

on this line:

```<code>document.getElementById(result[i]).innerHTML = result[i];
</code>```

Do you know what is the issue?

Javascript:

```<code>function SearchReviews() {
    $(document).ready(function() {

        searchData = "searchData=" + $("#searchReviews").val() + "&action=" + "searchReviews";
        urlPath = "../index.php";

        if ($.trim($("#searchReviews").val()).length > 0) { // client is typing
            // Send the search data to database
            $.ajax({
                type: "POST",
                url: urlPath,
                data: searchData,
                dataType: 'JSON',
                success: function (result) {
                    console.log(result[0]);
                    console.log(result.length);

                    $("#searchText").empty(); // we want to refresh the results

                    for (i = 0; i < result.length; i++) {
                        var html = '<p id=' + result[i] + '></p><hr>';
                        $("#searchText").append(html);
                        document.getElementById(result[i]).innerHTML = result[i];
                    }
                },
                error: function(xhr, status, error) {
                    alert("Error" + xhr.responseText);
                }
            })
        } else {
            $("#searchText").empty();
        }
    })
}
</code>```

HTML

```<code>            <div class="col-sm-5">
                <p class="text-center">Reviews</p> <hr>
                <div class="input-group">
                <input type="text" class="form-control" id="searchReviews" placeholder="Search reviews" onkeydown="SearchReviews();">
                </div>
                <p class="text-center" id="searchText"></p>
            </div>
</code>```

答:
You can not use your result as selector attribute ID. ID should be unique and no space for one ID.

You can try this

```<code>for (i = 0; i < result.length; i++) {
    var html = '<p id="result' + i + '">'+ result[i] +'</p><hr>';
    $("#searchText").append(html);
}
</code>```

Hope this works!

Title: Javascript setting innerHTML null issue

Body:
When i run an ajax query, i get back an array of results. I want to create a new element and set its inner html to the results. The results are working fine, im getting them no problem. They contain the correct data. I can create the element with an id based on the result fine as well i just get:

Uncaught TypeError: Cannot set property 'innerHTML' of null

on this line:

document.getElementById(result[i]).innerHTML = result[i];

Do you know what is the issue?

Javascript:

function SearchReviews() {
    $(document).ready(function() {

        searchData = "searchData=" + $("#searchReviews").val() + "&action=" + "searchReviews";
        urlPath = "../index.php";

        if ($.trim($("#searchReviews").val()).length > 0) { // client is typing
            // Send the search data to database
            $.ajax({
                type: "POST",
                url: urlPath,
                data: searchData,
                dataType: 'JSON',
                success: function (result) {
                    console.log(result[0]);
                    console.log(result.length);

                    $("#searchText").empty(); // we want to refresh the results

                    for (i = 0; i < result.length; i++) {
                        var html = '

';
                        $("#searchText").append(html);
                        document.getElementById(result[i]).innerHTML = result[i];
                    }
                },
                error: function(xhr, status, error) {
                    alert("Error" + xhr.responseText);
                }
            })
        } else {
            $("#searchText").empty();
        }
    })
}

HTML

Reviews

                <input type="text" class="form-control" id="searchReviews" placeholder="Search reviews" onkeydown="SearchReviews();">

Body:
You can not use your result as selector attribute ID. ID should be unique and no space for one ID.

You can try this

for (i = 0; i < result.length; i++) {
    var html = '<p id="result' + i + '">'+ result[i] +'</p><hr>';
    $("#searchText").append(html);
}

Hope this works!


问:
Scapy Installation error in CentOS release 6.9 server?
I am trying to install scapy in server. But I am getting error.
1) I installed pip, python 2.66 was already installed.
2) Then i ran command pip installed scapy

Then in the terminal when i type scapy, i get:

```<code>[root@virgina02 alamin]# scapy
INFO: Can't import matplotlib. Won't be able to plot.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
INFO: No IPv6 support in kernel
WARNING: No route found for IPv6 destination :: (no default route?)
INFO: Can't import python Crypto lib. Won't be able to decrypt WEP.
INFO: Can't import python Crypto lib. Disabled certificate manipulation tools
INFO: Can't import python ecdsa lib. Disabled certificate manipulation tools
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Welcome to Scapy (2.3.3)
>>
</code>```

now I can still use scapy to send tcp packets but I am getting checksum error. So I was wondering if that checksum error was related to the above error?

答:
This warning did not cause the checksum error. The checksum error was my mistake.
I also found why I got this error.

This error/warnings ware due to python2.6.
Scapy higher version of 2 requires python >= 2.7

Body:
I am trying to install scapy in server. But I am getting error.
1) I installed pip, python 2.66 was already installed.
2) Then i ran command pip installed scapy

Then in the terminal when i type scapy, i get:

[root@virgina02 alamin]# scapy
INFO: Can't import matplotlib. Won't be able to plot.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
INFO: No IPv6 support in kernel
WARNING: No route found for IPv6 destination :: (no default route?)
INFO: Can't import python Crypto lib. Won't be able to decrypt WEP.
INFO: Can't import python Crypto lib. Disabled certificate manipulation tools
INFO: Can't import python ecdsa lib. Disabled certificate manipulation tools
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a Python object' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Exception RuntimeError: 'maximum recursion depth exceeded in __subclasscheck__' in <type 'exceptions.AttributeError'> ignored
Welcome to Scapy (2.3.3)
>>

now I can still use scapy to send tcp packets but I am getting checksum error. So I was wondering if that checksum error was related to the above error?


问:
Meteor.users.findOne works for console.log but not for publishing?
Im publishing my current user this this: </p>

```<code>Meteor.publish('currentUser', function() {
  return Meteor.users.find(
    { _id: this.userId },
    { fields: { groups: 1, name: 1 } },
  );
});
</code>```

<p>Its working but I belive that findOne is more efficient. The following console.log works but returning Meteor.users.findOne doens't work: </p>

```<code>Meteor.publish('currentUser', function() {
  const test = Meteor.users.findOne(
    {},
    { fields: { groups: 1, events: 1, name: 1 } },
  );
  console.log(test); // this works

  // This doesn't work
  return Meteor.users.findOne(
    {},
    { fields: { groups: 1, events: 1, name: 1 } },
  );
});
</code>```

答:
The Meteor docs states that the publication should be either of 2 things:

A cursor

An array of cursors (of different collections)

Publish functions can return a Collection.Cursor, in which case Meteor
  will publish that cursor’s documents to each subscribed client. You
  can also return an array of Collection.Cursors, in which case Meteor
  will publish all of the cursors.

findOne returns a document. So I suppose it won't work.

Body:
Im publishing my current user this this:

Meteor.publish('currentUser', function() {
  return Meteor.users.find(
    { _id: this.userId },
    { fields: { groups: 1, name: 1 } },
  );
});

Its working but I belive that findOne is more efficient. The following console.log works but returning Meteor.users.findOne doens't work:

Meteor.publish('currentUser', function() {
  const test = Meteor.users.findOne(
    {},
    { fields: { groups: 1, events: 1, name: 1 } },
  );
  console.log(test); // this works

  // This doesn't work
  return Meteor.users.findOne(
    {},
    { fields: { groups: 1, events: 1, name: 1 } },
  );
});


问:
Cropping image by setting height dynamically
Guess a picture of man. (Head at top & legs at bottom) :P

I am setting height dynamically using layoutparam.

When I set height for instance 300,

It sets height from HEAD to 300 units toward legs of image.

What I want is to set height from LEGs to top 300 units.

```<code>imageView.setHeight()
</code>```

答:
Use this method in your java class:

```<code>private void scaleImage(ImageView view) throws NoSuchElementException {
    // Get bitmap from the the ImageView.
    Bitmap bitmap = null;

    try {
        Drawable drawing = view.getDrawable();
        bitmap = ((BitmapDrawable) drawing).getBitmap();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("No drawable on given view");
    } catch (ClassCastException e) {
        // Check bitmap is Ion drawable
//          bitmap = Ion.with(view).getBitmap();
    }

    // Get current dimensions AND the desired bounding box
    int width = 0;

    try {
        width = bitmap.getWidth();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("Can't find bitmap on given view/drawable");
    }

    int height = bitmap.getHeight();
    int bounding = dpToPx(150);// set height
    Logger.i("Test", "original width = " + Integer.toString(width));
    Logger.i("Test", "original height = " + Integer.toString(height));
    Logger.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Logger.i("Test", "xScale = " + Float.toString(xScale));
    Logger.i("Test", "yScale = " + Float.toString(yScale));
    Logger.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Logger.i("Test", "scaled width = " + Integer.toString(width));
    Logger.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Logger.i("Test", "done");
    }

    private int dpToPx(int dp) {
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
    }
</code>```

Now, how to call this methord :

```<code>        Bitmap bitmap;

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                imageView.setImageBitmap(bitmap);
                scaleImage(imageView);// call your imageview
            } catch (IOException e) {
                e.printStackTrace();
            }
</code>```

Body:
Guess a picture of man. (Head at top & legs at bottom) :P

I am setting height dynamically using layoutparam.

When I set height for instance 300,

It sets height from HEAD to 300 units toward legs of image.

What I want is to set height from LEGs to top 300 units.

imageView.setHeight()

Body:
Use this method in your java class:

private void scaleImage(ImageView view) throws NoSuchElementException {
    // Get bitmap from the the ImageView.
    Bitmap bitmap = null;

    try {
        Drawable drawing = view.getDrawable();
        bitmap = ((BitmapDrawable) drawing).getBitmap();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("No drawable on given view");
    } catch (ClassCastException e) {
        // Check bitmap is Ion drawable
//          bitmap = Ion.with(view).getBitmap();
    }

    // Get current dimensions AND the desired bounding box
    int width = 0;

    try {
        width = bitmap.getWidth();
    } catch (NullPointerException e) {
        throw new NoSuchElementException("Can't find bitmap on given view/drawable");
    }

    int height = bitmap.getHeight();
    int bounding = dpToPx(150);// set height
    Logger.i("Test", "original width = " + Integer.toString(width));
    Logger.i("Test", "original height = " + Integer.toString(height));
    Logger.i("Test", "bounding = " + Integer.toString(bounding));

    // Determine how much to scale: the dimension requiring less scaling is
    // closer to the its side. This way the image always stays inside your
    // bounding box AND either x/y axis touches it.
    float xScale = ((float) bounding) / width;
    float yScale = ((float) bounding) / height;
    float scale = (xScale <= yScale) ? xScale : yScale;
    Logger.i("Test", "xScale = " + Float.toString(xScale));
    Logger.i("Test", "yScale = " + Float.toString(yScale));
    Logger.i("Test", "scale = " + Float.toString(scale));

    // Create a matrix for the scaling and add the scaling data
    Matrix matrix = new Matrix();
    matrix.postScale(scale, scale);

    // Create a new bitmap and convert it to a format understood by the ImageView
    Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    width = scaledBitmap.getWidth(); // re-use
    height = scaledBitmap.getHeight(); // re-use
    BitmapDrawable result = new BitmapDrawable(scaledBitmap);
    Logger.i("Test", "scaled width = " + Integer.toString(width));
    Logger.i("Test", "scaled height = " + Integer.toString(height));

    // Apply the scaled bitmap
    view.setImageDrawable(result);

    // Now change ImageView's dimensions to match the scaled image
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
    params.width = width;
    params.height = height;
    view.setLayoutParams(params);

    Logger.i("Test", "done");
    }

    private int dpToPx(int dp) {
    float density = getApplicationContext().getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
    }

Now, how to call this methord :

        Bitmap bitmap;

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                imageView.setImageBitmap(bitmap);
                scaleImage(imageView);// call your imageview
            } catch (IOException e) {
                e.printStackTrace();
            }


问:
How to refresh listView after database operation
How do I update the data of my ListView after doing operations on it? In the onClick of the custom adapter? In the MainActivity OnResume? I saw a lot of posts on that, but every time they just gave a line of code but not where to put it.

My custom Adapter:

```<code>    class CustomAdapter extends ArrayAdapter {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Contact> arrayList; //Lui transmettre le tableau adapter
    private ContactDatabase db;

    public CustomAdapter(Context context, ArrayList<Contact> arrayList){
        super(context, R.layout.contact_list, arrayList);
        db = new ContactDatabase(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.arrayList = arrayList;
    }

    private class ViewHolder{
        TextView txtName, txtPhone;
        ImageView tete, dial;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.contact_list, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.txtName = convertView.findViewById(R.id.clName);
            viewHolder.txtPhone = convertView.findViewById(R.id.clNumber);
            viewHolder.tete = convertView.findViewById(R.id.cl_icone);
            viewHolder.dial = convertView.findViewById(R.id.cl_dial);

            //Definition du tag
            convertView.setTag(viewHolder);

        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //Definition des changements
        final Contact contact = arrayList.get(position);
        //viewHolder.txtName.setText(db.dbToString(position + 1));
        viewHolder.txtName.setText(Integer.toString(contact.getId()));
        viewHolder.txtPhone.setText(contact.getPhone());
        viewHolder.tete.setImageResource(contact.getImage());

        //Change color
//        int backgroundColor = ContextCompat.getColor(context, contact.getColor());
//        viewHolder.txtPhone.setTextColor(backgroundColor);

        //OnClick sur l'icone telephone
        viewHolder.dial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("tel:" + contact.getPhone()));
                //context.startActivity(intent);
                db.delete(contact.getId());
            }
        });

//        //OnClick sur l'icone image
        viewHolder.tete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, AddContactActivity.class); //On creer l'intent de donnee
//                intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
//                intent.putExtra("index", position); //On place les donnes enregistrer dans l'intent quon fera passe
//                ((Activity) context).startActivityForResult(intent, 100);

            }
        });

        return convertView;
    }

}

My Main Activity:

public class MainActivity extends AppCompatActivity{

    private ListView listView;
    private FloatingActionButton btnAdd;
    private ArrayList<Contact> contacts;
    ContactDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Definition des ID
        btnAdd = findViewById(R.id.btn_add);
        listView = findViewById(R.id.list_view); //Recheche du listView
        listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

        //Listener pour le button ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //Creation de ladapter
        db = new ContactDatabase(this);
        contacts = db.getData();
        CustomAdapter adapter = new CustomAdapter(this, contacts);
        listView.setAdapter(adapter);
    }

}
</code>```

Can you give me the code to put and where to put it exactly, so that after each operation my listView refresh automatically

答:
use

```<code>CustomAdapter adapter = new CustomAdapter ():
adapter.notifyDataSetChanged();
</code>```

where ever you are adding or deleting in listview

Body:
How do I update the data of my ListView after doing operations on it? In the onClick of the custom adapter? In the MainActivity OnResume? I saw a lot of posts on that, but every time they just gave a line of code but not where to put it.

My custom Adapter:

    class CustomAdapter extends ArrayAdapter {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Contact> arrayList; //Lui transmettre le tableau adapter
    private ContactDatabase db;

    public CustomAdapter(Context context, ArrayList<Contact> arrayList){
        super(context, R.layout.contact_list, arrayList);
        db = new ContactDatabase(context);
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.arrayList = arrayList;
    }

    private class ViewHolder{
        TextView txtName, txtPhone;
        ImageView tete, dial;
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder viewHolder;

        if(convertView == null){
            //Reglage general
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.contact_list, parent, false); //Layout du design

            //Recuperation des ID
            viewHolder.txtName = convertView.findViewById(R.id.clName);
            viewHolder.txtPhone = convertView.findViewById(R.id.clNumber);
            viewHolder.tete = convertView.findViewById(R.id.cl_icone);
            viewHolder.dial = convertView.findViewById(R.id.cl_dial);

            //Definition du tag
            convertView.setTag(viewHolder);

        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //Definition des changements
        final Contact contact = arrayList.get(position);
        //viewHolder.txtName.setText(db.dbToString(position + 1));
        viewHolder.txtName.setText(Integer.toString(contact.getId()));
        viewHolder.txtPhone.setText(contact.getPhone());
        viewHolder.tete.setImageResource(contact.getImage());

        //Change color
//        int backgroundColor = ContextCompat.getColor(context, contact.getColor());
//        viewHolder.txtPhone.setTextColor(backgroundColor);

        //OnClick sur l'icone telephone
        viewHolder.dial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse("tel:" + contact.getPhone()));
                //context.startActivity(intent);
                db.delete(contact.getId());
            }
        });

//        //OnClick sur l'icone image
        viewHolder.tete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, AddContactActivity.class); //On creer l'intent de donnee
//                intent.putExtra("BUNDLE", args); //On place les donnes enregistrer dans l'intent quon fera passe
//                intent.putExtra("index", position); //On place les donnes enregistrer dans l'intent quon fera passe
//                ((Activity) context).startActivityForResult(intent, 100);

            }
        });

        return convertView;
    }

}

My Main Activity:

public class MainActivity extends AppCompatActivity{

    private ListView listView;
    private FloatingActionButton btnAdd;
    private ArrayList<Contact> contacts;
    ContactDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Definition des ID
        btnAdd = findViewById(R.id.btn_add);
        listView = findViewById(R.id.list_view); //Recheche du listView
        listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

        //Listener pour le button ADD
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        //Creation de ladapter
        db = new ContactDatabase(this);
        contacts = db.getData();
        CustomAdapter adapter = new CustomAdapter(this, contacts);
        listView.setAdapter(adapter);
    }

}

Can you give me the code to put and where to put it exactly, so that after each operation my listView refresh automatically

Body:
use

CustomAdapter adapter = new CustomAdapter ():
adapter.notifyDataSetChanged();

where ever you are adding or deleting in listview


问:
DataGrid for Android
Hello i want to build an Android application to handle my budget. I have build an budget-app before but that was in WPF and with C#. In WPF there is something called DataGrid that looks something like this

https://www.codeproject.com/KB/WPF/WPFDataGridExamples/datasetgrid.png
(I am not allowed to post images)

And i was wondering if there was something like this in Android, that could display a table of information to the user.

Thank you.

答:
You could use Grid View.

GridView is a ViewGroup that displays items in a two-dimensional,
  scrollable grid. The grid items are automatically inserted to the
  layout using a ListAdapter.

Title: DataGrid for Android


问:
Throttle and queue up API requests due to per second cap
I'm use mikeal/request to make API calls. One of the API's I use most frequently (the Shopify API). Recently put out a new call limit, I'm seeing errors like:

```<code>Exceeded 6.0 calls per second for api client. Slow your requests or contact support for higher limits.
</code>```

I've already gotten an upgrade, but regardless of how much bandwidth I get I have to account for this. A large majority of the requests to the Shopify API are within async.map() functions, which loop asynchronous requests, and gather the bodies.

I'm looking for any help, perhaps a library that already exists, that would wrap around the request module and actually block, sleep, throttle, allocate, manage, the many simultaneous requests that are firing off asynchronously and limit them to say 6 requests at a time. I have no problem with working on such a project if it doesn't exist. I just don't know how to handle this kind of situation, and I'm hoping for some kind of standard.

I made a ticket with mikeal/request.

答:
In async module, this requested feature is closed as "wont fix"

Reason given in 2016 is "managing that kind of construct properly is
a hard problem."   See right side of here:
https://github.com/caolan/async/issues/1314

Reason given in 2013 is "wouldn't scale to multiple processes"   See:
https://github.com/caolan/async/issues/37#issuecomment-14336237

There is a solution using leakybucket or token bucket model, it is implemented "limiter" npm module as RateLimiter.

RateLimiter, see example here: https://github.com/caolan/async/issues/1314#issuecomment-263715550

Another way is using PromiseThrottle, I used this, working example is below:

```<code>var PromiseThrottle = require('promise-throttle');
let RATE_PER_SECOND = 5; // 5 = 5 per second, 0.5 = 1 per every 2 seconds

var pto = new PromiseThrottle({
    requestsPerSecond: RATE_PER_SECOND, // up to 1 request per second
    promiseImplementation: Promise  // the Promise library you are using
});

let timeStart = Date.now();
var myPromiseFunction = function (arg) {
    return new Promise(function (resolve, reject) {
        console.log("myPromiseFunction: " + arg + ", " + (Date.now() - timeStart) / 1000);
        let response = arg;
        return resolve(response);
    });
};

let NUMBER_OF_REQUESTS = 15;
let promiseArray = [];
for (let i = 1; i <= NUMBER_OF_REQUESTS; i++) {
    promiseArray.push(
            pto
            .add(myPromiseFunction.bind(this, i)) // passing am argument using bind()
            );
}

Promise
        .all(promiseArray)
        .then(function (allResponsesArray) { // [1 .. 100]
            console.log("All results: " + allResponsesArray);
        });
</code>```

Output:

```<code>myPromiseFunction: 1, 0.031
myPromiseFunction: 2, 0.201
myPromiseFunction: 3, 0.401
myPromiseFunction: 4, 0.602
myPromiseFunction: 5, 0.803
myPromiseFunction: 6, 1.003
myPromiseFunction: 7, 1.204
myPromiseFunction: 8, 1.404
myPromiseFunction: 9, 1.605
myPromiseFunction: 10, 1.806
myPromiseFunction: 11, 2.007
myPromiseFunction: 12, 2.208
myPromiseFunction: 13, 2.409
myPromiseFunction: 14, 2.61
myPromiseFunction: 15, 2.811
All results: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
</code>```

We can clearly see the rate from output, i.e. 5 calls for every second.

ContentLicense: CC BY-SA 4.0

Body:
I'm use mikeal/request to make API calls. One of the API's I use most frequently (the Shopify API). Recently put out a new call limit, I'm seeing errors like:

Exceeded 6.0 calls per second for api client. Slow your requests or contact support for higher limits.

I've already gotten an upgrade, but regardless of how much bandwidth I get I have to account for this. A large majority of the requests to the Shopify API are within async.map() functions, which loop asynchronous requests, and gather the bodies.

I'm looking for any help, perhaps a library that already exists, that would wrap around the request module and actually block, sleep, throttle, allocate, manage, the many simultaneous requests that are firing off asynchronously and limit them to say 6 requests at a time. I have no problem with working on such a project if it doesn't exist. I just don't know how to handle this kind of situation, and I'm hoping for some kind of standard.

I made a ticket with mikeal/request.

Body:
In async module, this requested feature is closed as "wont fix"

Reason given in 2016 is "managing that kind of construct properly is
a hard problem."   See right side of here:
https://github.com/caolan/async/issues/1314

Reason given in 2013 is "wouldn't scale to multiple processes"   See:
https://github.com/caolan/async/issues/37#issuecomment-14336237

There is a solution using leakybucket or token bucket model, it is implemented "limiter" npm module as RateLimiter.

RateLimiter, see example here: https://github.com/caolan/async/issues/1314#issuecomment-263715550

Another way is using PromiseThrottle, I used this, working example is below:

var PromiseThrottle = require('promise-throttle');
let RATE_PER_SECOND = 5; // 5 = 5 per second, 0.5 = 1 per every 2 seconds

var pto = new PromiseThrottle({
    requestsPerSecond: RATE_PER_SECOND, // up to 1 request per second
    promiseImplementation: Promise  // the Promise library you are using
});

let timeStart = Date.now();
var myPromiseFunction = function (arg) {
    return new Promise(function (resolve, reject) {
        console.log("myPromiseFunction: " + arg + ", " + (Date.now() - timeStart) / 1000);
        let response = arg;
        return resolve(response);
    });
};

let NUMBER_OF_REQUESTS = 15;
let promiseArray = [];
for (let i = 1; i <= NUMBER_OF_REQUESTS; i++) {
    promiseArray.push(
            pto
            .add(myPromiseFunction.bind(this, i)) // passing am argument using bind()
            );
}

Promise
        .all(promiseArray)
        .then(function (allResponsesArray) { // [1 .. 100]
            console.log("All results: " + allResponsesArray);
        });

Output:

myPromiseFunction: 1, 0.031
myPromiseFunction: 2, 0.201
myPromiseFunction: 3, 0.401
myPromiseFunction: 4, 0.602
myPromiseFunction: 5, 0.803
myPromiseFunction: 6, 1.003
myPromiseFunction: 7, 1.204
myPromiseFunction: 8, 1.404
myPromiseFunction: 9, 1.605
myPromiseFunction: 10, 1.806
myPromiseFunction: 11, 2.007
myPromiseFunction: 12, 2.208
myPromiseFunction: 13, 2.409
myPromiseFunction: 14, 2.61
myPromiseFunction: 15, 2.811
All results: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

We can clearly see the rate from output, i.e. 5 calls for every second.


问:
Read my own dataset for NLTK Part of Speech tagging using PerceptronTagger
I'm new to NLTK and still pretty new to python. I want to use my own dataset to train and test NLTK's Perceptron tagger. The training and testing data has the following format (it's just saved in a txt file):

```<code>Pierre  NNP
Vinken  NNP
,       ,
61      CD
years   NNS
old     JJ
,       ,
will    MD
join    VB
the     DT
board   NN
as      IN
a       DT
nonexecutive    JJ
director        NN
Nov.    NNP
29      CD
.       .
</code>```

I want to call these functions on the data:

```<code>perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False)
perceptron_tagger.train(train_data)
accuracy = perceptron_tagger.evaluate(test_data)
</code>```

I've tried a few things but I just can't figure out what format the data is expected to be in. Any help would be appreciated! Thanks

答:
The input for train() and evaluate() functions of the PerceptronTagger  requires a list of list of tuples, where each inner list is a list each tuple is a pair of string.

Given train.txt and test.txt:

```<code>$ cat train.txt
This foo
is  foo
a   foo
sentence    bar
.   .

That    foo
is  foo
another foo
sentence    bar
in  foo
conll   bar
format  bar
.   .

$ cat test.txt
What    foo
is  foo
this    foo
sentence    bar
?   ?

How foo
about   foo
that    foo
sentence    bar
?   ?
</code>```

Read the files in CoNLL format into list of tuples.

```<code># Using https://github.com/alvations/lazyme
>>> from lazyme import per_section
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))]

# Or otherwise

>>> def per_section(it, is_delimiter=lambda x: x.isspace()):
...     """
...     From http://stackoverflow.com/a/25226944/610569
...     """
...     ret = []
...     for line in it:
...         if is_delimiter(line):
...             if ret:
...                 yield ret  # OR  ''.join(ret)
...                 ret = []
...         else:
...             ret.append(line.rstrip())  # OR  ret.append(line)
...     if ret:
...         yield ret
...
>>>
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))]
>>> tagged_test_sentences
[[('What', 'foo'), ('is', 'foo'), ('this', 'foo'), ('sentence', 'bar'), ('?', '?')], [('How', 'foo'), ('about', 'foo'), ('that', 'foo'), ('sentence', 'bar'), ('?', '?')]]
</code>```

Now you can train/evaluate the tagger:

```<code>>>> from lazyme import per_section
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))]
>>> from nltk.tag.perceptron import PerceptronTagger
>>> pct = PerceptronTagger(load=False)
>>> pct.train(tagged_train_sentences)
>>> pct.tag('Where do I find a foo bar sentence ?'.split())
[('Where', 'foo'), ('do', 'foo'), ('I', '.'), ('find', 'foo'), ('a', 'foo'), ('foo', 'bar'), ('bar', 'foo'), ('sentence', 'bar'), ('?', '.')]
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))]
>>> pct.evaluate(tagged_test_sentences)
0.8
</code>```

Body:
I'm new to NLTK and still pretty new to python. I want to use my own dataset to train and test NLTK's Perceptron tagger. The training and testing data has the following format (it's just saved in a txt file):

Pierre  NNP
Vinken  NNP
,       ,
61      CD
years   NNS
old     JJ
,       ,
will    MD
join    VB
the     DT
board   NN
as      IN
a       DT
nonexecutive    JJ
director        NN
Nov.    NNP
29      CD
.       .

I want to call these functions on the data:

perceptron_tagger = nltk.tag.perceptron.PerceptronTagger(load=False)
perceptron_tagger.train(train_data)
accuracy = perceptron_tagger.evaluate(test_data)

I've tried a few things but I just can't figure out what format the data is expected to be in. Any help would be appreciated! Thanks

Body:
The input for train() and evaluate() functions of the PerceptronTagger  requires a list of list of tuples, where each inner list is a list each tuple is a pair of string.

Given train.txt and test.txt:

$ cat train.txt
This foo
is  foo
a   foo
sentence    bar
.   .

That    foo
is  foo
another foo
sentence    bar
in  foo
conll   bar
format  bar
.   .

$ cat test.txt
What    foo
is  foo
this    foo
sentence    bar
?   ?

How foo
about   foo
that    foo
sentence    bar
?   ?

Read the files in CoNLL format into list of tuples.

# Using https://github.com/alvations/lazyme
>>> from lazyme import per_section
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))]

# Or otherwise

>>> def per_section(it, is_delimiter=lambda x: x.isspace()):
...     """
...     From http://stackoverflow.com/a/25226944/610569
...     """
...     ret = []
...     for line in it:
...         if is_delimiter(line):
...             if ret:
...                 yield ret  # OR  ''.join(ret)
...                 ret = []
...         else:
...             ret.append(line.rstrip())  # OR  ret.append(line)
...     if ret:
...         yield ret
...
>>>
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))]
>>> tagged_test_sentences
[[('What', 'foo'), ('is', 'foo'), ('this', 'foo'), ('sentence', 'bar'), ('?', '?')], [('How', 'foo'), ('about', 'foo'), ('that', 'foo'), ('sentence', 'bar'), ('?', '?')]]

Now you can train/evaluate the tagger:

>>> from lazyme import per_section
>>> tagged_train_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('train.txt'))]
>>> from nltk.tag.perceptron import PerceptronTagger
>>> pct = PerceptronTagger(load=False)
>>> pct.train(tagged_train_sentences)
>>> pct.tag('Where do I find a foo bar sentence ?'.split())
[('Where', 'foo'), ('do', 'foo'), ('I', '.'), ('find', 'foo'), ('a', 'foo'), ('foo', 'bar'), ('bar', 'foo'), ('sentence', 'bar'), ('?', '.')]
>>> tagged_test_sentences = [[tuple(token.split('\t')) for token in sent] for sent in per_section(open('test.txt'))]
>>> pct.evaluate(tagged_test_sentences)
0.8


问:
Dyntable sort does not work at all from Ajax
I am using dyna table with Ajax. Sorting, searching, pagination nothing is working. I only get a list in my table but on clicking the column header nothing happens.

Please help.This is my code.

My html file is

```<code><table style="width:100%" id="my-final-table" class="tablesorter" >
    <thead>
        <tr bgcolor="#239B56">
          <th><font style="color:#fff">Rollno</font></th>
          <th><font style="color:#fff">Name</font></th>
          <th><font style="color:#fff">Marks</font></th>
          <th><font style="color:#fff">Percentage</font></th>
      </tr>
  </thead>
  <tbody>

  </tbody>
</table>
</code>```

My Ajax code is

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/jquery.dynatable.js"></script>
<style src="/jquery.dynatable.css"></style>

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#my-final-table').dynatable({

          dataset: {
            ajax: true,
            ajaxOnLoad: true,
            ajaxUrl: '/result_analysis_subject_json.json',
            records: []
        }
    });

    });

</script>
</code>```

And my JSON file is

```<code>{"records":[{"rollno":"1","name":"Aditya Kumar Sharma","marks":"12.00","percentage":40},{"rollno":"2","name":"Aksh Kathuria","marks":"19.00","percentage":63},{"rollno":"3","name":"Anant ","marks":"14.00","percentage":47},{"rollno":"4","name":"Arnav Arora","marks":"28.00","percentage":93},{"rollno":"5","name":"Ayush Sai Raina","marks":"26.00","percentage":87},{"rollno":"6","name":"Ayush Rawat","marks":"21.00","percentage":70},{"rollno":"7","name":"Bhagya Dua","marks":"11.00","percentage":37},{"rollno":"8","name":"Bhvesh Gautam","marks":"26.00","percentage":87},{"rollno":"9","name":"Chaitanya Dubey","marks":"18.00","percentage":60},{"rollno":"10","name":"Chanchal","marks":"5.00","percentage":17},{"rollno":"11","name":"Deeksha","marks":"28.00","percentage":93},{"rollno":"12","name":"Dimple Bhatia","marks":"26.00","percentage":87},{"rollno":"13","name":"Ekta Yadav","marks":"27.00","percentage":90},{"rollno":"14","name":"Eshan Sharma","marks":"24.00","percentage":80},{"rollno":"15","name":"Harman Arora","marks":"13.00","percentage":43},{"rollno":"16","name":"Himanya ","marks":"18.00","percentage":60},{"rollno":"17","name":"Hiya Bhatia","marks":"29.00","percentage":97},{"rollno":"18","name":"Ishmeet Kaur","marks":"13.00","percentage":43},{"rollno":"19","name":"Jivitesh Gwadi","marks":"20.00","percentage":67},{"rollno":"20","name":"Jiya Hussain","marks":"7.00","percentage":23},{"rollno":"21","name":"Krish Kohli","marks":"13.00","percentage":43},{"rollno":"22","name":"Krishna Sharma","marks":"22.00","percentage":73},{"rollno":"23","name":"Lisha Kapoor","marks":"27.00","percentage":90},{"rollno":"24","name":"Mannant Sehgal","marks":"20.00","percentage":67},{"rollno":"25","name":"Mayank Mehta","marks":"19.00","percentage":63},{"rollno":"26","name":"Mehak Singh","marks":"26.00","percentage":87},{"rollno":"27","name":"Nandini Bhargava","marks":"29.00","percentage":97},{"rollno":"28","name":"Parth Talwar","marks":"27.00","percentage":90},{"rollno":"29","name":"Pawni Yadav","marks":"27.00","percentage":90},{"rollno":"30","name":"Prachi Dahiya","marks":"21.00","percentage":70},{"rollno":"31","name":"Prachi Sharma","marks":"18.00","percentage":60},{"rollno":"32","name":"Rashi Bainsla","marks":"19.00","percentage":63},{"rollno":"33","name":"Ravinder Singh","marks":"5.00","percentage":17},{"rollno":"34","name":"Riya Sethi","marks":"14.00","percentage":47},{"rollno":"35","name":"Sahib Kharbanda","marks":"24.00","percentage":80},{"rollno":"36","name":"Sajal Kukreja","marks":"23.00","percentage":77},{"rollno":"37","name":"Shrishty Singh","marks":"26.00","percentage":87},{"rollno":"38","name":"Tanisha Kaur","marks":"26.00","percentage":87},{"rollno":"39","name":"Toshiv Mudgal","marks":"16.00","percentage":53},{"rollno":"40","name":"Yash Anand","marks":"23.00","percentage":77}],"queryRecordCount":40,"totalRecordCount":40}
</code>```

答:
in the ajax call

records: function myFunction(rec){}

perform your js library code in myFunction on rec

Body:
I am using dyna table with Ajax. Sorting, searching, pagination nothing is working. I only get a list in my table but on clicking the column header nothing happens.

Please help.This is my code.

My html file is

          Rollno
          Name
          Marks
          Percentage

My Ajax code is

And my JSON file is

{"records":[{"rollno":"1","name":"Aditya Kumar Sharma","marks":"12.00","percentage":40},{"rollno":"2","name":"Aksh Kathuria","marks":"19.00","percentage":63},{"rollno":"3","name":"Anant ","marks":"14.00","percentage":47},{"rollno":"4","name":"Arnav Arora","marks":"28.00","percentage":93},{"rollno":"5","name":"Ayush Sai Raina","marks":"26.00","percentage":87},{"rollno":"6","name":"Ayush Rawat","marks":"21.00","percentage":70},{"rollno":"7","name":"Bhagya Dua","marks":"11.00","percentage":37},{"rollno":"8","name":"Bhvesh Gautam","marks":"26.00","percentage":87},{"rollno":"9","name":"Chaitanya Dubey","marks":"18.00","percentage":60},{"rollno":"10","name":"Chanchal","marks":"5.00","percentage":17},{"rollno":"11","name":"Deeksha","marks":"28.00","percentage":93},{"rollno":"12","name":"Dimple Bhatia","marks":"26.00","percentage":87},{"rollno":"13","name":"Ekta Yadav","marks":"27.00","percentage":90},{"rollno":"14","name":"Eshan Sharma","marks":"24.00","percentage":80},{"rollno":"15","name":"Harman Arora","marks":"13.00","percentage":43},{"rollno":"16","name":"Himanya ","marks":"18.00","percentage":60},{"rollno":"17","name":"Hiya Bhatia","marks":"29.00","percentage":97},{"rollno":"18","name":"Ishmeet Kaur","marks":"13.00","percentage":43},{"rollno":"19","name":"Jivitesh Gwadi","marks":"20.00","percentage":67},{"rollno":"20","name":"Jiya Hussain","marks":"7.00","percentage":23},{"rollno":"21","name":"Krish Kohli","marks":"13.00","percentage":43},{"rollno":"22","name":"Krishna Sharma","marks":"22.00","percentage":73},{"rollno":"23","name":"Lisha Kapoor","marks":"27.00","percentage":90},{"rollno":"24","name":"Mannant Sehgal","marks":"20.00","percentage":67},{"rollno":"25","name":"Mayank Mehta","marks":"19.00","percentage":63},{"rollno":"26","name":"Mehak Singh","marks":"26.00","percentage":87},{"rollno":"27","name":"Nandini Bhargava","marks":"29.00","percentage":97},{"rollno":"28","name":"Parth Talwar","marks":"27.00","percentage":90},{"rollno":"29","name":"Pawni Yadav","marks":"27.00","percentage":90},{"rollno":"30","name":"Prachi Dahiya","marks":"21.00","percentage":70},{"rollno":"31","name":"Prachi Sharma","marks":"18.00","percentage":60},{"rollno":"32","name":"Rashi Bainsla","marks":"19.00","percentage":63},{"rollno":"33","name":"Ravinder Singh","marks":"5.00","percentage":17},{"rollno":"34","name":"Riya Sethi","marks":"14.00","percentage":47},{"rollno":"35","name":"Sahib Kharbanda","marks":"24.00","percentage":80},{"rollno":"36","name":"Sajal Kukreja","marks":"23.00","percentage":77},{"rollno":"37","name":"Shrishty Singh","marks":"26.00","percentage":87},{"rollno":"38","name":"Tanisha Kaur","marks":"26.00","percentage":87},{"rollno":"39","name":"Toshiv Mudgal","marks":"16.00","percentage":53},{"rollno":"40","name":"Yash Anand","marks":"23.00","percentage":77}],"queryRecordCount":40,"totalRecordCount":40}


问:
How to vlookup value and get value to the right
How do I vlookup for a value and get value to the right?

Dataframe one:

```<code>   AD1   AF   GG
0  DDA   4    2
1  AA    1    2
</code>```

Dataframe two:

```<code>    AD   FA  HH
0   DDA  3   4
1   DD   3   4
</code>```

Desired (dataframe 3):

```<code>    AD   FA
0   DDA  3
1   DD  NaN
</code>```

For:

```<code>df3 = pd.DataFrame(columns=['AD', 'FA'])
WE = df3.merge(df1, on='AD1', how='left')
df1['FA']=WE
#WE = df2.AD=np.where(df2.AD.isin(df1.AD1),df2.AD,np.nan)
</code>```

I get KeyError: 'AD'

答:
It seems you need:

```<code>df3 = df2[['AD', 'FA']].copy()
df3.FA=np.where(df2.AD.isin(df1.AD1),df3.FA,np.nan)
print (df3)
    AD   FA
0  DDA  3.0
1   DD  NaN
</code>```

EDIT:

```<code>print (df1)
       EW       WE      DA     dd  AA
0  cheese     fdwa  waddcv   21.0 NaN
1  cheese  dwadwad    dwad  231.0 NaN
2  cheese      dwa  waddcv    3.0 NaN

print (df2)
       AD   FA     BA  DA    daw
0  cheese  1.0  300.0   T      T
1  dwadaw  3.0  400.0  21  31232
</code>```

```<code>#remove duplicates in EW and merge by different columns
df3 = df2.merge(df1.drop_duplicates('EW')[['EW']], left_on='AD', right_on='EW', how='left')
df3.FA=np.where(df2.AD.isin(df1.EW),df3.FA,np.nan)
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0
1  dwadaw  NaN
</code>```

EDIT1:

```<code>df3 = df2[df2.AD.isin(df1.EW)]
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0
</code>```

Detail:

```<code>print (df2.AD.isin(df1.EW))
0     True
1    False
Name: AD, dtype: bool
</code>```

Body:
How do I vlookup for a value and get value to the right?

Dataframe one:

   AD1   AF   GG
0  DDA   4    2
1  AA    1    2

Dataframe two:

    AD   FA  HH
0   DDA  3   4
1   DD   3   4

Desired (dataframe 3):

    AD   FA
0   DDA  3
1   DD  NaN

For:

df3 = pd.DataFrame(columns=['AD', 'FA'])
WE = df3.merge(df1, on='AD1', how='left')
df1['FA']=WE
#WE = df2.AD=np.where(df2.AD.isin(df1.AD1),df2.AD,np.nan)

I get KeyError: 'AD'

Body:
It seems you need:

df3 = df2[['AD', 'FA']].copy()
df3.FA=np.where(df2.AD.isin(df1.AD1),df3.FA,np.nan)
print (df3)
    AD   FA
0  DDA  3.0
1   DD  NaN

EDIT:

print (df1)
       EW       WE      DA     dd  AA
0  cheese     fdwa  waddcv   21.0 NaN
1  cheese  dwadwad    dwad  231.0 NaN
2  cheese      dwa  waddcv    3.0 NaN

print (df2)
       AD   FA     BA  DA    daw
0  cheese  1.0  300.0   T      T
1  dwadaw  3.0  400.0  21  31232

#remove duplicates in EW and merge by different columns
df3 = df2.merge(df1.drop_duplicates('EW')[['EW']], left_on='AD', right_on='EW', how='left')
df3.FA=np.where(df2.AD.isin(df1.EW),df3.FA,np.nan)
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0
1  dwadaw  NaN

EDIT1:

df3 = df2[df2.AD.isin(df1.EW)]
df3 = df3[['AD','FA']]
print (df3)
       AD   FA
0  cheese  1.0

Detail:

print (df2.AD.isin(df1.EW))
0     True
1    False
Name: AD, dtype: bool


问:
How to dynamically hide some options from a drop-down list using jQuery

I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">
            <div id="state1">
               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>
            </div>
            <div id="state2">
               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>
            </div>
        </select>
  <input name="submit" type="submit" value="Submit" />
</form></code>```

答:
You should make a link between states and cities for example with data-state:

```<code><option value="0" data-state="state1">City1a</option>
</code>```

$("#state").change(function() {
  var selected_state = $(this).val();
$('#city').removeAttr('disabled').children('option').hide();
  $('#city option[data-state="' + selected_state + '"]').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">

  <label>State:</label>
  <select name="state" id="state">
 <option>-- choose state--</option>
<option value="state1">State1</option>
<option value="state2">State2</option>
</select>

  <label>City:</label>
  <select name="city" id="city" disabled>
 <option>-- choose city --</option>
<option value="0" data-state="state1">City1a</option>
<option value="1" data-state="state1">City1b</option>
<option value="2" data-state="state1">City1c</option>
<option value="3" data-state="state2">City2a</option>
<option value="4" data-state="state2">City2b</option>
<option value="5" data-state="state2">City2c</option>
</select>

  <input name="submit" type="submit" value="Submit" />
</form></code>```

And DO NOT wrap options with div or anything else, it's invalid.

Body:
I have two drop down list; one with states and the other with cities. I want the second list with cities to show only the cities in the selected state. Why is this not working?

$(document).ready(function($) {
  $("#state").change(function() {
    var selected_state = $("#state").val(); //get the selected state
    $("#city").children().hide(); //hide all the options
    $("#selected_state").children().show(); //only show cities in selected state
  });
});

<form method="post">
  State: <select name="state" id="state">
            <option value="state1">State1</option>
            <option value="state2">State2</option>
        </select> City:
  <select name="city" id="city">

               <option value="0">City1a</option>
               <option value="1">City1b</option>
               <option value="2">City1c</option>

               <option value="3">City2a</option>
               <option value="4">City2b</option>
               <option value="5">City2c</option>

        </select>
  <input name="submit" type="submit" value="Submit" />
</form>

Body:
You should make a link between states and cities for example with data-state:

<option value="0" data-state="state1">City1a</option>

$("#state").change(function() {
  var selected_state = $(this).val();
$('#city').removeAttr('disabled').children('option').hide();
  $('#city option[data-state="' + selected_state + '"]').show();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">

  <label>State:</label>
  <select name="state" id="state">
 <option>-- choose state--</option>
<option value="state1">State1</option>
<option value="state2">State2</option>
</select>

  <label>City:</label>
  <select name="city" id="city" disabled>
 <option>-- choose city --</option>
<option value="0" data-state="state1">City1a</option>
<option value="1" data-state="state1">City1b</option>
<option value="2" data-state="state1">City1c</option>
<option value="3" data-state="state2">City2a</option>
<option value="4" data-state="state2">City2b</option>
<option value="5" data-state="state2">City2c</option>
</select>

  <input name="submit" type="submit" value="Submit" />
</form>

And DO NOT wrap options with div or anything else, it's invalid.


问:
BLUEPRINT Google Grid Gallery rtl support
I'm u using Google Grid Gallery for one of my project using plugin tutorial.

As this project is based in multiple languages, I am unable to make the grid for rtl (arabic). The grid made by the javascript puts the li item on the left, I want it to be on right.

答:
@bimal Google-grid-gallery is using masonry and i check the use of masonry, you can do is add the line

```<code>originLeft:false,
</code>```

in your file cbpGridGallery.js like

```<code>new Masonry( grid, {
            itemSelector: 'li',
            originLeft:false,
            columnWidth: grid.querySelector( '.grid-sizer' )
        });
</code>```

ALso update your masonry js so it support orginLeft
Thanks :)

Body:
@bimal Google-grid-gallery is using masonry and i check the use of masonry, you can do is add the line

originLeft:false,

in your file cbpGridGallery.js like

new Masonry( grid, {
            itemSelector: 'li',
            originLeft:false,
            columnWidth: grid.querySelector( '.grid-sizer' )
        });

ALso update your masonry js so it support orginLeft
Thanks :)


问:
sed on a ASCII-File with no line feed
I have an ASCII-Textfile with only one (long) line in it. I want to do a normal sed on it but nothing works. vi shows me with :set list that the line ends with an $
If i add a new line manually with vi the sed command works. If i do this:

```<code>echo $(cat file) |sed 's/.*test//g'
</code>```

it does work too. Any idea why sed cant work with that?

答:
The commandf echo $(cat file) is not going to preserve white space very well.

You should be able to add a newline, while leaving the rest of the file untouched, quite easily with:

```<code>( cat inputFile ; echo ) | sed 'something or other'
</code>```

Just keep in mind that some sed implementations don't actually like very long lines. POSIX, I believe, mandated only a 8K minimum requirement. You should be okay if you're using the GNU variant, though.

Title: sed on a ASCII-File with no line feed

Body:
I have an ASCII-Textfile with only one (long) line in it. I want to do a normal sed on it but nothing works. vi shows me with :set list that the line ends with an $
If i add a new line manually with vi the sed command works. If i do this:

echo $(cat file) |sed 's/.*test//g'

it does work too. Any idea why sed cant work with that?

Body:
The commandf echo $(cat file) is not going to preserve white space very well.

You should be able to add a newline, while leaving the rest of the file untouched, quite easily with:

( cat inputFile ; echo ) | sed 'something or other'

Just keep in mind that some sed implementations don't actually like very long lines. POSIX, I believe, mandated only a 8K minimum requirement. You should be okay if you're using the GNU variant, though.


答:
change code from

```<code>private ListView listView;
private FloatingActionButton btnAdd;
private ArrayList<Contact> contacts;
ContactDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Definition des ID
    btnAdd = findViewById(R.id.btn_add);
    listView = findViewById(R.id.list_view); //Recheche du listView
    listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

    //Listener pour le button ADD
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
            startActivity(intent);
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    //Creation de ladapter
    db = new ContactDatabase(this);
    contacts = db.getData();
    CustomAdapter adapter = new CustomAdapter(this, contacts);
    listView.setAdapter(adapter);
}
</code>```

to

```<code>private ListView listView;
private FloatingActionButton btnAdd;
private ArrayList<Contact> contacts=new ArrayList<>();
ContactDatabase db;
CustomAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Definition des ID
    btnAdd = findViewById(R.id.btn_add);
    listView = findViewById(R.id.list_view); //Recheche du listView
    listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message
    adapter = new CustomAdapter(this, contacts);
    listView.setAdapter(adapter);

    //Listener pour le button ADD
    btnAdd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
        startActivity(intent);
    }
});

@Override
protected void onResume() {
   super.onResume();
   //Creation de ladapter
   contacts.clear();
   db = new ContactDatabase(this);
   contacts.addAll(db.getData());
   adapter.notifyDataSetChanged();
}
</code>```

Title: How to refresh listView after database operation

Body:
change code from

private ListView listView;
private FloatingActionButton btnAdd;
private ArrayList<Contact> contacts;
ContactDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Definition des ID
    btnAdd = findViewById(R.id.btn_add);
    listView = findViewById(R.id.list_view); //Recheche du listView
    listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message

    //Listener pour le button ADD
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
            startActivity(intent);
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    //Creation de ladapter
    db = new ContactDatabase(this);
    contacts = db.getData();
    CustomAdapter adapter = new CustomAdapter(this, contacts);
    listView.setAdapter(adapter);
}

to

private ListView listView;
private FloatingActionButton btnAdd;
private ArrayList<Contact> contacts=new ArrayList<>();
ContactDatabase db;
CustomAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Definition des ID
    btnAdd = findViewById(R.id.btn_add);
    listView = findViewById(R.id.list_view); //Recheche du listView
    listView.setEmptyView(findViewById(R.id.empty_list)); //Si listView est vide alors on affiche ce message
    adapter = new CustomAdapter(this, contacts);
    listView.setAdapter(adapter);

    //Listener pour le button ADD
    btnAdd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, AddContactActivity.class);
        startActivity(intent);
    }
});

@Override
protected void onResume() {
   super.onResume();
   //Creation de ladapter
   contacts.clear();
   db = new ContactDatabase(this);
   contacts.addAll(db.getData());
   adapter.notifyDataSetChanged();
}