问:
Using an array of pointers-to-pointers to manipulate the pointers it points to (C++)
I've been doing this as an exercise on my own to get better at C++ (messing around with a linked list I wrote). What I want to do is to reverse the list by twisting the pointers around, rather than just 'printing' the data out in reverse (which is relatively straightforward).

I have an array of pointers-to-pointers, each pointing to a node in a linked list. But this is less a question about linked-list dynamics (which I understand), and more about pointer magick.

A node looks like this,

```<code>template<class T>
struct node {
    T data;
    node *next;

    node(T value) : data(value), next(nullptr) {}
};
</code>```

And the code in question,

```<code>  node<T> **reverseArr[listLength];
  node<T> *parser = root;

  for (auto i : reverseArr) {
      i = &parser;
      parser = parser->next;
  }

  root = *(reverseArr[listLength - 1]);
  for (int ppi = listLength - 1; ppi >= 0; --ppi) {
        if (ppi == 0) {
            (*reverseArr[ppi])->next = nullptr;
            //std::cout << "ppi is zero!" << "\t";
        }
        else {
            (*reverseArr[ppi])->next = (*reverseArr[ppi - 1]);
            //std::cout << "ppi, 'tis not zero!" << "\t";
        }
  }
</code>```

My logic:

The new root is the last element of the list,

Iterate through the array in reverse,

Set the  current node's next pointer to the previous one by setting the current node's nextNode to the next node in the loop.

What's happening:

If I leave the debug print statements commented, nothing. The function's called but the linked list remains unchanged (not reversed)

If I uncomment the debug prints, the program seg-faults (which doesn't make a whole lot of sense to me but seems to indicate a flaw in my code)

I suspect there's something I'm missing that a fresh pair of eyes might catch. Am I, perhaps, mishandling the array (not accounting for the decay to a pointer or something)?

答:
You're overthinking the problem.  The correct way to reverse a single-linked list is much simpler than you think, and does not involve arrays at all.

All you need to do is walk through the list setting each node's next pointer to the head of the list, then set the head of the list to that node.  Essentially, you are unlinking each node and inserting it at the start of the list.  Once you reach the end, your list is reversed.

It just requires a bit of care, because the order that you do things is important.  Something like this should do it:

```<code>template <class T>
node<T> * reverse( node<T> * head )
{
    node<T> *current = head;
    head = NULL;

    while( current != NULL )
    {
        // store remainder of list
        node<T> *remain = current->next;

        // re-link current node at the head
        current->next = head;
        head = current;

        // continue iterating remainder of list
        current = remain;
    }

    return head;
}
</code>```

The operation has a linear time complexity.  You would invoke it by passing your list's head node as follows:

```<code>root = reverse( root );
</code>```

It should go without saying that it would be a bad idea to call this function with any node that is not the head of a list, or to pass in a list that contains cycles.

Body:
I've been doing this as an exercise on my own to get better at C++ (messing around with a linked list I wrote). What I want to do is to reverse the list by twisting the pointers around, rather than just 'printing' the data out in reverse (which is relatively straightforward).

I have an array of pointers-to-pointers, each pointing to a node in a linked list. But this is less a question about linked-list dynamics (which I understand), and more about pointer magick.

A node looks like this,

template<class T>
struct node {
    T data;
    node *next;

    node(T value) : data(value), next(nullptr) {}
};

And the code in question,

  node<T> **reverseArr[listLength];
  node<T> *parser = root;

  for (auto i : reverseArr) {
      i = &parser;
      parser = parser->next;
  }

  root = *(reverseArr[listLength - 1]);
  for (int ppi = listLength - 1; ppi >= 0; --ppi) {
        if (ppi == 0) {
            (*reverseArr[ppi])->next = nullptr;
            //std::cout << "ppi is zero!" << "\t";
        }
        else {
            (*reverseArr[ppi])->next = (*reverseArr[ppi - 1]);
            //std::cout << "ppi, 'tis not zero!" << "\t";
        }
  }

My logic:

The new root is the last element of the list,

Iterate through the array in reverse,

Set the  current node's next pointer to the previous one by setting the current node's nextNode to the next node in the loop.

What's happening:

If I leave the debug print statements commented, nothing. The function's called but the linked list remains unchanged (not reversed)

If I uncomment the debug prints, the program seg-faults (which doesn't make a whole lot of sense to me but seems to indicate a flaw in my code)

I suspect there's something I'm missing that a fresh pair of eyes might catch. Am I, perhaps, mishandling the array (not accounting for the decay to a pointer or something)?

Body:
You're overthinking the problem.  The correct way to reverse a single-linked list is much simpler than you think, and does not involve arrays at all.

All you need to do is walk through the list setting each node's next pointer to the head of the list, then set the head of the list to that node.  Essentially, you are unlinking each node and inserting it at the start of the list.  Once you reach the end, your list is reversed.

It just requires a bit of care, because the order that you do things is important.  Something like this should do it:

template <class T>
node<T> * reverse( node<T> * head )
{
    node<T> *current = head;
    head = NULL;

    while( current != NULL )
    {
        // store remainder of list
        node<T> *remain = current->next;

        // re-link current node at the head
        current->next = head;
        head = current;

        // continue iterating remainder of list
        current = remain;
    }

    return head;
}

The operation has a linear time complexity.  You would invoke it by passing your list's head node as follows:

root = reverse( root );

It should go without saying that it would be a bad idea to call this function with any node that is not the head of a list, or to pass in a list that contains cycles.


来源: stackexchange

问:
How to play and pause a Youtube video in a webpage while scrolling(using javascript or jquery)?
I mean to say that the video should not be playing when the page is loaded.
It should play when the video player comes in the focus of the window screen and it should pause when it is not visible on the screen using the scroll function.
I am not expecting to play videos on separate tabs. </p>

```<code>        <html>
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

            </head>
            <body>
                <p>
                    This is some text
                </p>

                <div style="margin-top:1000px;margin-bottom:1000px;">
                <iframe width="445" height="245" src="https://www.youtube.com/embed/LA5XtlyVILo?rel=0&enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>
               </div>

                <script type="text/javascript">
                   var videos = document.getElementsByTagName("iframe"), fraction = 0.8;

                    function checkScroll() {

                      for(var i = 0; i < videos.length; i++) {
                        var video = videos[i];

                        var x = 0,
                            y = 0,
                            w = video.width,
                            h = video.height,
                            r, //right
                            b, //bottom
                            visibleX, visibleY, visible,
                            parent;

                        parent = video;
                        while (parent && parent !== document.body) {
                          x += parent.offsetLeft;
                          y += parent.offsetTop;
                          parent = parent.offsetParent;

                        }

                        r = x + parseInt(w);
                        b = y + parseInt(h);

                        visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
                        visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));

                        visible = visibleX * visibleY / (w * h);

                        if (visible > fraction) {

                          playVideo();
                        } else if(visible < fraction) {
                          pauseVideo();

                        }

                      }

                    };

                    window.addEventListener('scroll', checkScroll, false);
                    window.addEventListener('resize', checkScroll, false);

                    //check at least once so you don't have to wait for scrolling for the video to start
                    window.addEventListener('load', checkScroll, false);

                    checkScroll();

                    function playVideo() {
                      player.playVideo();
                    }

                    function pauseVideo() {
                      player.pauseVideo();
                    }
                </script>
            </body>
        </html>
</code>```

答:
You can fire the pause event for the player by watching on the scroll event for the page as</p>

```<code>$(window).scroll(function() {
    if($(window).scrollTop() > height) { //height is the pixels by which if you scroll the player gets hidden
        player.pauseVideo();  //player is the YouTube player object you created
    }
    else
        player.playVideo(); //the player is visible.
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I mean to say that the video should not be playing when the page is loaded.
It should play when the video player comes in the focus of the window screen and it should pause when it is not visible on the screen using the scroll function.
I am not expecting to play videos on separate tabs.

                    This is some text

Body:
You can fire the pause event for the player by watching on the scroll event for the page as

$(window).scroll(function() {
    if($(window).scrollTop() > height) { //height is the pixels by which if you scroll the player gets hidden
        player.pauseVideo();  //player is the YouTube player object you created
    }
    else
        player.playVideo(); //the player is visible.
});


问:
Parsing JSON to CSV using Python: AttributeError: 'unicode' object has no attribute 'keys'
I have a nested JSON dataset containing multiple entries which look like this:

```<code>{
"coordinates": null,
"acoustic_features": {
    "instrumentalness": "0.00479",
    "liveness": "0.18",
    "speechiness": "0.0294",
    "danceability": "0.634",
    "valence": "0.342",
    "loudness": "-8.345",
    "tempo": "125.044",
    "acousticness": "0.00035",
    "energy": "0.697",
    "mode": "1",
    "key": "6"
},
"artist_id": "b2980c722a1ace7a30303718ce5491d8",
"place": null,
"geo": null,
"tweet_lang": "en",
"source": "Share.Radionomy.com",
"track_title": "8eeZ",
"track_id": "cd52b3e5b51da29e5893dba82a418a4b",
"artist_name": "Dominion",
"entities": {
    "hashtags": [{
        "text": "nowplaying",
        "indices": [0, 11]
    }, {
        "text": "goth",
        "indices": [51, 56]
    }, {
        "text": "deathrock",
        "indices": [57, 67]
    }, {
        "text": "postpunk",
        "indices": [68, 77]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "indices": [28, 50],
        "expanded_url": "cathedral13.com/blog13",
        "display_url": "cathedral13.com/blog13",
        "url": "t.co/Tatf4hEVkv"
    }]
},
"created_at": "2014-01-01 05:54:21",
"text": "#nowplaying Dominion - 8eeZ Tatf4hEVkv #goth #deathrock #postpunk",
"user": {
    "location": "middle of nowhere",
    "lang": "en",
    "time_zone": "Central Time (US & Canada)",
    "name": "Cathedral 13",
    "entities": null,
    "id": 81496937,
    "description": "I\u2019m a music junkie who is currently responsible for Cathedral 13 internet radio (goth, deathrock, post-punk)which has been online since 06/20/02."
},
"id": 418243774842929150
}
</code>```

I want to convert it into a csv file in which there are multiple columns containing the respective entries for each JSON object. The following is the Python code I have written to do it:

```<code>import json
import csv
from pprint import pprint
data = []
with open('data_subset.json') as data_file:
    for line in data_file:
        data.append(json.loads(line))

# open a file for writing
data_csv = open('Data_csv.csv', 'w')
# create the csv writer object
csvwriter = csv.writer(data_csv)

for i in range(1,10):
    count = 0
    for dat in data[i]:
        if count == 0:
             header = dat.keys()
             csvwriter.writerow(header)
             count += 1
        csvwriter.writerow(emp.values())
data_csv.close()
</code>```

On running the above code,I get the error: AttributeError: 'unicode' object has no attribute 'keys'.
What could be the problem?

答:
You can read the JSON file all in once like:

```<code>with open('a.txt') as data_file:
    data = json.load(data_file)
</code>```

Now you have the JSON as the data dictionary.

Since you want specific entries from the JSON to csv (e.g. entities is not saved to csv) you can keep a custom column header and then loop over the data to write the particular keys to the csv:

```<code># Example to save the artist_id and user id; can be extended for the actual data
header = ['artist_id', 'id']

# open a file for writing
data_csv = open('Data_csv.csv', 'wb')

# create the csv writer object
csvwriter = csv.writer(data_csv)

# write the csv header
csvwriter.writerow(header)

for entry in data:
    csvwriter.writerow([entry['artist_id'], entry['user']['id']])

data_csv.close()
</code>```

Body:
I have a nested JSON dataset containing multiple entries which look like this:

{
"coordinates": null,
"acoustic_features": {
    "instrumentalness": "0.00479",
    "liveness": "0.18",
    "speechiness": "0.0294",
    "danceability": "0.634",
    "valence": "0.342",
    "loudness": "-8.345",
    "tempo": "125.044",
    "acousticness": "0.00035",
    "energy": "0.697",
    "mode": "1",
    "key": "6"
},
"artist_id": "b2980c722a1ace7a30303718ce5491d8",
"place": null,
"geo": null,
"tweet_lang": "en",
"source": "Share.Radionomy.com",
"track_title": "8eeZ",
"track_id": "cd52b3e5b51da29e5893dba82a418a4b",
"artist_name": "Dominion",
"entities": {
    "hashtags": [{
        "text": "nowplaying",
        "indices": [0, 11]
    }, {
        "text": "goth",
        "indices": [51, 56]
    }, {
        "text": "deathrock",
        "indices": [57, 67]
    }, {
        "text": "postpunk",
        "indices": [68, 77]
    }],
    "symbols": [],
    "user_mentions": [],
    "urls": [{
        "indices": [28, 50],
        "expanded_url": "cathedral13.com/blog13",
        "display_url": "cathedral13.com/blog13",
        "url": "t.co/Tatf4hEVkv"
    }]
},
"created_at": "2014-01-01 05:54:21",
"text": "#nowplaying Dominion - 8eeZ Tatf4hEVkv #goth #deathrock #postpunk",
"user": {
    "location": "middle of nowhere",
    "lang": "en",
    "time_zone": "Central Time (US & Canada)",
    "name": "Cathedral 13",
    "entities": null,
    "id": 81496937,
    "description": "I\u2019m a music junkie who is currently responsible for Cathedral 13 internet radio (goth, deathrock, post-punk)which has been online since 06/20/02."
},
"id": 418243774842929150
}

I want to convert it into a csv file in which there are multiple columns containing the respective entries for each JSON object. The following is the Python code I have written to do it:

import json
import csv
from pprint import pprint
data = []
with open('data_subset.json') as data_file:
    for line in data_file:
        data.append(json.loads(line))

# open a file for writing
data_csv = open('Data_csv.csv', 'w')
# create the csv writer object
csvwriter = csv.writer(data_csv)

for i in range(1,10):
    count = 0
    for dat in data[i]:
        if count == 0:
             header = dat.keys()
             csvwriter.writerow(header)
             count += 1
        csvwriter.writerow(emp.values())
data_csv.close()

On running the above code,I get the error: AttributeError: 'unicode' object has no attribute 'keys'.
What could be the problem?

Body:
You can read the JSON file all in once like:

with open('a.txt') as data_file:
    data = json.load(data_file)

Now you have the JSON as the data dictionary.

Since you want specific entries from the JSON to csv (e.g. entities is not saved to csv) you can keep a custom column header and then loop over the data to write the particular keys to the csv:

# Example to save the artist_id and user id; can be extended for the actual data
header = ['artist_id', 'id']

# open a file for writing
data_csv = open('Data_csv.csv', 'wb')

# create the csv writer object
csvwriter = csv.writer(data_csv)

# write the csv header
csvwriter.writerow(header)

for entry in data:
    csvwriter.writerow([entry['artist_id'], entry['user']['id']])

data_csv.close()


问:
Complete a String containing comma and dot separated integers
Question:

Given an input String like "1,2,3..6..8,9..11", we have to convert it into "1,2,3,4,5,6,7,8,9,10,11". So basically we have to populate the ranges mentioned by dots. Below is my solution. Is there any better way to solve this ? Can we optimize this further ?

```<code>    public class FlattenAString {

    public static String flattenAString(String input) {
        StringBuilder sbr = new StringBuilder("");
        StringBuilder current = new StringBuilder("");
        StringBuilder next = new StringBuilder("");
        int i = 0;
        while (i < input.length()) {
            if (input.charAt(i) == '.') {
                i = i + 2;
                while (i != input.length() && input.charAt(i) != '.' && input.charAt(i) != ',') {
                    next.append(input.charAt(i));
                    i++;
                }
                int currentInt = Integer.parseInt(current.toString());
                int nextInt = Integer.parseInt(next.toString());
                appendFromCurrentTillPrevToNextInt(currentInt, nextInt, sbr);
                current = next;
                next = new StringBuilder("");
            } else if (input.charAt(i) == ',') {
                sbr.append(current);
                sbr.append(',');
                current = new StringBuilder("");
                i++;
            } else {
                current.append(input.charAt(i));
                i++;
            }
        }
        sbr.append(current);
        return sbr.toString();
    }

    private static void appendFromCurrentTillPrevToNextInt(int current, int val, StringBuilder sbr) {
        for (int i = current; i < val; i++) {
            sbr.append(i);
            sbr.append(',');
        }
    }
}
</code>```

答:
I would approach this by splitting your input string twice.  First, split by comma to get either single numbers or ranges with ellipsis.  For single numbers, simply add them to a list.  For ranges, do a second split on .. to obtain another list of numbers.  Then iterate over the range of each of these pairs to fill in the missing values.

Note one tricky point here is that we need to avoid double counting a number position in a range.  This is best explained by example:

```<code>3..6..8
</code>```

For this range, we first add 3, 4, 5, 6.  But for the second ellipsis, we begin at 7, and then continue until hitting 8.

```<code>String input = "1,2,3..6..8,9..11";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();

for (String part : parts) {
    if (!part.contains("..")) {
        list.add(Integer.parseInt(part));
    }
    else {
        String[] ranges = part.split("\\.\\.");
        for (int i=0; i < ranges.length-1; ++i) {
            int start = Integer.parseInt(ranges[i]) + (i == 0 ? 0 : 1);
            int end = Integer.parseInt(ranges[i+1]);
            for (int j=start; j <= end; ++j) list.add(j);
        }
    }
}

// print list of numbers
for (int i=0; i < list.size(); ++i) {
    System.out.print((i > 0 ? ", " : "") + list.get(i));
}
</code>```

Output:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
</code>```

Demo here:

Rextester

Body:
Question:

Given an input String like "1,2,3..6..8,9..11", we have to convert it into "1,2,3,4,5,6,7,8,9,10,11". So basically we have to populate the ranges mentioned by dots. Below is my solution. Is there any better way to solve this ? Can we optimize this further ?

    public class FlattenAString {

    public static String flattenAString(String input) {
        StringBuilder sbr = new StringBuilder("");
        StringBuilder current = new StringBuilder("");
        StringBuilder next = new StringBuilder("");
        int i = 0;
        while (i < input.length()) {
            if (input.charAt(i) == '.') {
                i = i + 2;
                while (i != input.length() && input.charAt(i) != '.' && input.charAt(i) != ',') {
                    next.append(input.charAt(i));
                    i++;
                }
                int currentInt = Integer.parseInt(current.toString());
                int nextInt = Integer.parseInt(next.toString());
                appendFromCurrentTillPrevToNextInt(currentInt, nextInt, sbr);
                current = next;
                next = new StringBuilder("");
            } else if (input.charAt(i) == ',') {
                sbr.append(current);
                sbr.append(',');
                current = new StringBuilder("");
                i++;
            } else {
                current.append(input.charAt(i));
                i++;
            }
        }
        sbr.append(current);
        return sbr.toString();
    }

    private static void appendFromCurrentTillPrevToNextInt(int current, int val, StringBuilder sbr) {
        for (int i = current; i < val; i++) {
            sbr.append(i);
            sbr.append(',');
        }
    }
}

Body:
I would approach this by splitting your input string twice.  First, split by comma to get either single numbers or ranges with ellipsis.  For single numbers, simply add them to a list.  For ranges, do a second split on .. to obtain another list of numbers.  Then iterate over the range of each of these pairs to fill in the missing values.

Note one tricky point here is that we need to avoid double counting a number position in a range.  This is best explained by example:

3..6..8

For this range, we first add 3, 4, 5, 6.  But for the second ellipsis, we begin at 7, and then continue until hitting 8.

String input = "1,2,3..6..8,9..11";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();

for (String part : parts) {
    if (!part.contains("..")) {
        list.add(Integer.parseInt(part));
    }
    else {
        String[] ranges = part.split("\\.\\.");
        for (int i=0; i < ranges.length-1; ++i) {
            int start = Integer.parseInt(ranges[i]) + (i == 0 ? 0 : 1);
            int end = Integer.parseInt(ranges[i+1]);
            for (int j=start; j <= end; ++j) list.add(j);
        }
    }
}

// print list of numbers
for (int i=0; i < list.size(); ++i) {
    System.out.print((i > 0 ? ", " : "") + list.get(i));
}

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

Demo here:

Rextester


问:
How can I match fuzzy match strings from two datasets?
I've been working on a way to join two datasets based on a imperfect string, such as a name of a company. In the past I had to match two very dirty lists, one list had names and financial information, another list had names and address. Neither had unique IDs to match on! ASSUME THAT CLEANING HAS ALREADY BEEN APPLIED AND THERE MAYBE TYPOS AND INSERTIONS.

So far AGREP is the closest tool I've found that might work. I can use levenshtein distances in the AGREP package, which measure the number of deletions, insertions and substitutions between two strings. AGREP will return the string with the smallest distance (the most similar).

However, I've been having trouble turning this command from a single value to apply it to an entire data frame. I've crudely used a for loop to repeat the AGREP function, but there's gotta be an easier way.

See the following code:

```<code>a<-data.frame(name=c('Ace Co','Bayes', 'asd', 'Bcy', 'Baes', 'Bays'),price=c(10,13,2,1,15,1))
b<-data.frame(name=c('Ace Co.','Bayes Inc.','asdf'),qty=c(9,99,10))

for (i in 1:6){
    a$x[i] = agrep(a$name[i], b$name, value = TRUE, max = list(del = 0.2, ins = 0.3, sub = 0.4))
    a$Y[i] = agrep(a$name[i], b$name, value = FALSE, max = list(del = 0.2, ins = 0.3, sub = 0.4))
}
</code>```

答:
Here is a solution using the fuzzyjoin package. It uses dplyr-like syntax and stringdist as one of the possible types of fuzzy matching.

As suggested by @C8H10N4O2, the stringdist method="jw" creates the best matches for your example.

As suggested by @dgrtwo, the developer of fuzzyjoin, I used a large max_dist and then used dplyr::group_by and dplyr::slice_min to get only the best match with minimum distance. (slice_min replaces the older top_n and if the original order is important and not alphabetical, use mutate(rank = row_number(dist)) %>% filter(rank == 1))

a <- data.frame(name = c('Ace Co', 'Bayes', 'asd', 'Bcy', 'Baes', 'Bays'),
                price = c(10, 13, 2, 1, 15, 1))
b <- data.frame(name = c('Ace Co.', 'Bayes Inc.', 'asdf'),
                qty = c(9, 99, 10))

library(fuzzyjoin); library(dplyr);

stringdist_join(a, b,
                by = "name",
                mode = "left",
                ignore_case = FALSE,
                method = "jw",
                max_dist = 99,
                distance_col = "dist") %>%
  group_by(name.x) %>%
  slice_min(order_by = dist, n = 1)

#> # A tibble: 6 x 5
#> # Groups:   name.x [6]
#>   name.x price     name.y   qty       dist
#>   <fctr> <dbl>     <fctr> <dbl>      <dbl>
#> 1 Ace Co    10    Ace Co.     9 0.04761905
#> 2  Bayes    13 Bayes Inc.    99 0.16666667
#> 3    asd     2       asdf    10 0.08333333
#> 4    Bcy     1 Bayes Inc.    99 0.37777778
#> 5   Baes    15 Bayes Inc.    99 0.20000000
#> 6   Bays     1 Bayes Inc.    99 0.20000000
```

Body:
I've been working on a way to join two datasets based on a imperfect string, such as a name of a company. In the past I had to match two very dirty lists, one list had names and financial information, another list had names and address. Neither had unique IDs to match on! ASSUME THAT CLEANING HAS ALREADY BEEN APPLIED AND THERE MAYBE TYPOS AND INSERTIONS.

So far AGREP is the closest tool I've found that might work. I can use levenshtein distances in the AGREP package, which measure the number of deletions, insertions and substitutions between two strings. AGREP will return the string with the smallest distance (the most similar).

However, I've been having trouble turning this command from a single value to apply it to an entire data frame. I've crudely used a for loop to repeat the AGREP function, but there's gotta be an easier way.

See the following code:

a<-data.frame(name=c('Ace Co','Bayes', 'asd', 'Bcy', 'Baes', 'Bays'),price=c(10,13,2,1,15,1))
b<-data.frame(name=c('Ace Co.','Bayes Inc.','asdf'),qty=c(9,99,10))

for (i in 1:6){
    a$x[i] = agrep(a$name[i], b$name, value = TRUE, max = list(del = 0.2, ins = 0.3, sub = 0.4))
    a$Y[i] = agrep(a$name[i], b$name, value = FALSE, max = list(del = 0.2, ins = 0.3, sub = 0.4))
}

ContentLicense: CC BY-SA 4.0


问:
How to find direction of a vector path
I have a vector path (made up from lineto, curveTo points) and I want to determine its direction (clockwise, anticlockwise).

Is there any algorithm which can be used for the same?

The reason I want to do this is that I am getting two paths from different functions; one is always clockwise but the other function returns anticlockwise paths sometimes; when I combine these two paths and fill the resultant path then the non-zero winding fill rule creates a hole in the regions where the path overlaps.

So I am trying to solve the problem by converting all paths to clockwise direction before combining them.

答:
EDIT: see the comments below:

What is clockwise? Case in point. Do you consider this path clockwise?:

If you said yes, then what about this one?

Follows my original proposal which works fine for convex paths:

You can use the cross product of 3D vectors.

If a,b two vectors such that :

a = (a1, a2, a3)

b = (b1, b2, b3)

Then the cross product is

axb = (a2b3-a3b2, a3b1-a1b3, a1b2 - a2b1)

Now if you assume that the path you describe does not intersect itself (which nullifies the point of clockwise or counterclockwise) then all you need is the first three points of it in the order they are presented. And from them you create 2 vectors whose cross product you can calculate.

So assuming you have these points in order:

a = (a1, a2)

b = (b1, b2)

c = (c1, c2)

you create the following vectors:

A = (A1, A2) = ab = (b1-a1, b2-a2)

B = (B1, B2) = bc = (c1-b1, c2-b2)

and then all you need is the third coordinate of AxB which is:

A1B2 - A2B1

or

(b1-a1)(c2-b2) - (b2-a2)(c1-b1)

If this coordinate is positive then your path is counterclockwise, if it is negative then it is clockwise.

Title: How to find direction of a vector path

ContentLicense: CC BY-SA 2.5


答:
Update based on Posters Feedback

After searching around on stackoverflow to expand on my own solution to the problem, I found the answer to your question in another stackoverflow question.

Here's a fiddle slightly modified fiddle based on the original post

```<code> /*Credit to original author http://stackoverflow.com/a/7557433/1684970 */

var LoadVideo = function(player_id) {

var Program = {

  Init: function() {
    this.NewPlayer();
    this.EventHandler();
  },

  NewPlayer: function() {
    var _this = this;
    this.Player = new YT.Player(player_id, {});
    _this.Player.$element = $('#' + player_id);
  },

  Play: function() {
    if (this.Player.getPlayerState() === 1) return;
    this.Player.playVideo();
  },

  Pause: function() {
    if (this.Player.getPlayerState() === 2) return;
    this.Player.pauseVideo();
  },

  ScrollControl: function() {
    if (Utils.IsElementInViewport(this.Player.$element[0])) this.Play();
    else this.Pause();
  },

  EventHandler: function() {
    var _this = this;
    $(window).on('scroll', function() {
      _this.ScrollControl();
    });
  }

};

var Utils = {
  IsElementInViewport: function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

};

return Program.Init();

};

LoadVideo('playerA');
</code>```

Original Answer

Since you haven't specified if the video is in a iframe or anything, I will assume it's just embedded and offers the user play/pause/open in youtube options.

The first part is detecting if the element is currently in the viewport, and therefore visible. and then the click event if visible/not-visible.

```<code>$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();

    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // The element is visible, trigger play click event
        $("#element").playVideo()
    }
    else {
        // The element is not visible, trigger pause click event
        $("#element").pauseVideo()
    }
});
</code>```

Title: How to play and pause a Youtube video in a webpage while scrolling(using javascript or jquery)?

Body:
Update based on Posters Feedback

After searching around on stackoverflow to expand on my own solution to the problem, I found the answer to your question in another stackoverflow question.

Here's a fiddle slightly modified fiddle based on the original post

 /*Credit to original author http://stackoverflow.com/a/7557433/1684970 */

var LoadVideo = function(player_id) {

var Program = {

  Init: function() {
    this.NewPlayer();
    this.EventHandler();
  },

  NewPlayer: function() {
    var _this = this;
    this.Player = new YT.Player(player_id, {});
    _this.Player.$element = $('#' + player_id);
  },

  Play: function() {
    if (this.Player.getPlayerState() === 1) return;
    this.Player.playVideo();
  },

  Pause: function() {
    if (this.Player.getPlayerState() === 2) return;
    this.Player.pauseVideo();
  },

  ScrollControl: function() {
    if (Utils.IsElementInViewport(this.Player.$element[0])) this.Play();
    else this.Pause();
  },

  EventHandler: function() {
    var _this = this;
    $(window).on('scroll', function() {
      _this.ScrollControl();
    });
  }

};

var Utils = {
  IsElementInViewport: function(el) {
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0];
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

};

return Program.Init();

};

LoadVideo('playerA');

Original Answer

Since you haven't specified if the video is in a iframe or anything, I will assume it's just embedded and offers the user play/pause/open in youtube options.

The first part is detecting if the element is currently in the viewport, and therefore visible. and then the click event if visible/not-visible.

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).height();
    var top_of_screen = $(window).scrollTop();

    if((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // The element is visible, trigger play click event
        $("#element").playVideo()
    }
    else {
        // The element is not visible, trigger pause click event
        $("#element").pauseVideo()
    }
});


问:
React menu item hover
I am trying React MobX on hover over a list item. Here is my code

```<code>export default observer(
class SidebarContent extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    this.props.store.fetchSources()
  }

  toggleHover(){
    this.props.store.hover = !this.props.store.hover;
  }

  getArticles(src) {
    this.props.store.fetchArticles(src);
  }

 render() {
  const style1 = this.props.style ? {...styles.sidebar, ...this.props.style} : styles.sidebar;
  const { sources, hover  } = this.props.store

    var linkStyle;
    if (this.props.store.hover) {
      linkStyle = {backgroundColor: 'black'}
    } else {
      linkStyle = {backgroundColor: 'white'}
    }

  const links = sources.map( (src,index) => (
    <a key={index} href='javascript:;' style={styles.sidebarLink} onClick={this.getArticles.bind(this, src.id)} >
          <span style={linkStyle}  onMouseEnter={this.toggleHover.bind(this)} onMouseLeave={this.toggleHover.bind(this)}     >
            <img className="ui-avaatar image" src='{ src.urlsToLogos.small }' />
            <span className="side-news-item"> {src.name} </span>
          </span>
    </a>
  ))
  return (
    <MaterialTitlePanel title="Menu" style={style1}>
      <div style={styles.content}>
        <div style={styles.divider} />
        {links}
      </div>
    </MaterialTitlePanel>
  );
  }
}
);
const styles = {
  sidebar: {
    width: 256,
    height: '100%',
  },
  sidebarLink: {
    display: 'block',
    padding: '16px 0px',
    color: '#757575',
    textDecoration: 'none',
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575',
  },
  content: {
    padding: '16px',
    height: '100%',
    backgroundColor: 'white',
  },
};
</code>```

this.props.store.hover is a observable.
The problem is that when mouse over one item, all of the items get the hover effect. What did I do wrong?

答:
Do not set Component's props directly, set it on upper Component.
or you could use state feature, and always use setState() to change state.

write an subcomponent to control the Button State

code below maybe help

class SidebarContent extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    this.props.store.fetchSources()
  }

  getArticles(src) {
    this.props.store.fetchArticles(src);
  }

 render() {

  const links = sources.map( (src,index) => <Button />);
  return (
    <MaterialTitlePanel title="Menu" style={style1}>

        {links}

    </MaterialTitlePanel>
  );
  }
}

class Button extends React.Component {

  toggleHover(){
    this.setState({
      hover: !this.state.hover,
    });
  }

  render() {
    const style1 = this.props.style ? {...styles.sidebar, ...this.props.style} : styles.sidebar;
    const { sources  } = this.props.store
    const { hover } = this.state;

    var linkStyle;
    if (hover) {
      linkStyle = {backgroundColor: 'black'}
    } else {
      linkStyle = {backgroundColor: 'white'}
    }

    return (

             {src.name}

    );
  }

}

const styles = {
  sidebar: {
    width: 256,
    height: '100%',
  },
  sidebarLink: {
    display: 'block',
    padding: '16px 0px',
    color: '#757575',
    textDecoration: 'none',
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575',
  },
  content: {
    padding: '16px',
    height: '100%',
    backgroundColor: 'white',
  },
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

Title: React menu item hover

Body:
I am trying React MobX on hover over a list item. Here is my code

export default observer(
class SidebarContent extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    this.props.store.fetchSources()
  }

  toggleHover(){
    this.props.store.hover = !this.props.store.hover;
  }

  getArticles(src) {
    this.props.store.fetchArticles(src);
  }

 render() {
  const style1 = this.props.style ? {...styles.sidebar, ...this.props.style} : styles.sidebar;
  const { sources, hover  } = this.props.store

    var linkStyle;
    if (this.props.store.hover) {
      linkStyle = {backgroundColor: 'black'}
    } else {
      linkStyle = {backgroundColor: 'white'}
    }

  const links = sources.map( (src,index) => (

             {src.name}

  ))
  return (
    <MaterialTitlePanel title="Menu" style={style1}>

        {links}

    </MaterialTitlePanel>
  );
  }
}
);
const styles = {
  sidebar: {
    width: 256,
    height: '100%',
  },
  sidebarLink: {
    display: 'block',
    padding: '16px 0px',
    color: '#757575',
    textDecoration: 'none',
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575',
  },
  content: {
    padding: '16px',
    height: '100%',
    backgroundColor: 'white',
  },
};

this.props.store.hover is a observable.
The problem is that when mouse over one item, all of the items get the hover effect. What did I do wrong?

Body:
Do not set Component's props directly, set it on upper Component.
or you could use state feature, and always use setState() to change state.

write an subcomponent to control the Button State

code below maybe help

class SidebarContent extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    this.props.store.fetchSources()
  }

  getArticles(src) {
    this.props.store.fetchArticles(src);
  }

 render() {

  const links = sources.map( (src,index) => <Button />);
  return (
    <MaterialTitlePanel title="Menu" style={style1}>
      <div style={styles.content}>
        <div style={styles.divider} />
        {links}
      </div>
    </MaterialTitlePanel>
  );
  }
}

class Button extends React.Component {

  toggleHover(){
    this.setState({
      hover: !this.state.hover,
    });
  }

  render() {
    const style1 = this.props.style ? {...styles.sidebar, ...this.props.style} : styles.sidebar;
    const { sources  } = this.props.store
    const { hover } = this.state;

    var linkStyle;
    if (hover) {
      linkStyle = {backgroundColor: 'black'}
    } else {
      linkStyle = {backgroundColor: 'white'}
    }

    return (
        <a key={index} href='javascript:;' style={styles.sidebarLink} onClick={this.getArticles.bind(this, src.id)} >
          <span style={linkStyle}  onMouseEnter={this.toggleHover.bind(this)} onMouseLeave={this.toggleHover.bind(this)}     >
            <img className="ui-avaatar image" src='{ src.urlsToLogos.small }' />
            <span className="side-news-item"> {src.name} </span>
          </span>
    </a>
    );
  }

}

const styles = {
  sidebar: {
    width: 256,
    height: '100%',
  },
  sidebarLink: {
    display: 'block',
    padding: '16px 0px',
    color: '#757575',
    textDecoration: 'none',
  },
  divider: {
    margin: '8px 0',
    height: 1,
    backgroundColor: '#757575',
  },
  content: {
    padding: '16px',
    height: '100%',
    backgroundColor: 'white',
  },
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


问:
NiFi Dynamic Remote URL value
I am creating a dataflow that needs to get and process the responses from a dynamic endpoint with a numeric resource id. For example, http://my-rest-service:8080/resource/{id} where {id} ranges from 1 to 100

I was looking into using a Counter but it does not look like I can easily inject the value. Any suggestions would be much appreciated!

答:
@paolo de roxas,

You can use Looping to inject the values with following reference.

https://gist.github.com/ijokarumawak/01c4fd2d9291d3e74ec424a581659ca8

In that way,you can use InvokeHTTP to change url with respect to id from 1 to 100.

This may helpful for you.

Title: NiFi Dynamic Remote URL value


问:
css drop down according height not auto
Hi this dropdown has a set size in the tab-content. It is cut off if its larger than a certain length text. I need it to be auto so that the box adjusts to the size. I tried working the css but no luck, thanks.

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked~.tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox]+label::after {
  content: "+";
}

input[type=radio]+label::after {
  content: "\25BC";
}

input[type=checkbox]:checked+label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked+label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
  <input id="tab-one" type="checkbox" name="tabs">
  <label for="tab-one">Label One</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit
      amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing
      elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque</p>
  </div>
</div>
<div class="tab">
  <input id="tab-two" type="checkbox" name="tabs">
  <label for="tab-two">Label Two</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>
<div class="tab">
  <input id="tab-three" type="checkbox" name="tabs">
  <label for="tab-three">Label Three</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>
</div>

<div class="half">
  <p>Open <strong>one</strong></p>
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div></code>```

答:
You can replace max-height to height but your transition effect will be dead. because in css you have to pass a height value to get transition effect.

I posted editable answer with height:auto and opacity

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  height: 0;
  overflow: hidden;
  opacity: 0;
  background: #1abc9c;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked~.tab-content {
  height: auto;
  opacity: 1;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox]+label::after {
  content: "+";
}

input[type=radio]+label::after {
  content: "\25BC";
}

input[type=checkbox]:checked+label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked+label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
  <input id="tab-one" type="checkbox" name="tabs">
  <label for="tab-one">Label One</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit
      amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing
      elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur,
      architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo
      perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum,
      maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque</p>
  </div>
</div>
<div class="tab">
  <input id="tab-two" type="checkbox" name="tabs">
  <label for="tab-two">Label Two</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>
<div class="tab">
  <input id="tab-three" type="checkbox" name="tabs">
  <label for="tab-three">Label Three</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>

<div class="half">
  <p>Open <strong>one</strong></p>
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div></code>```

Title: css drop down according height not auto

Body:
Hi this dropdown has a set size in the tab-content. It is cut off if its larger than a certain length text. I need it to be auto so that the box adjusts to the size. I tried working the css but no luck, thanks.

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked~.tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox]+label::after {
  content: "+";
}

input[type=radio]+label::after {
  content: "\25BC";
}

input[type=checkbox]:checked+label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked+label::after {
  transform: rotateX(180deg);
}

  <input id="tab-one" type="checkbox" name="tabs">
  Label One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit
      amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing
      elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque

  <input id="tab-two" type="checkbox" name="tabs">
  Label Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

  <input id="tab-three" type="checkbox" name="tabs">
  Label Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

Open one

    <input id="tab-four" type="radio" name="tabs2">
    Label One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

Body:
You can replace max-height to height but your transition effect will be dead. because in css you have to pass a height value to get transition effect.

I posted editable answer with height:auto and opacity

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  height: 0;
  overflow: hidden;
  opacity: 0;
  background: #1abc9c;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked~.tab-content {
  height: auto;
  opacity: 1;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox]+label::after {
  content: "+";
}

input[type=radio]+label::after {
  content: "\25BC";
}

input[type=checkbox]:checked+label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked+label::after {
  transform: rotateX(180deg);
}

<div class="tab">
  <input id="tab-one" type="checkbox" name="tabs">
  <label for="tab-one">Label One</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit
      amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing
      elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur,
      architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.em ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo
      perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaqueem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum,
      maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque</p>
  </div>
</div>
<div class="tab">
  <input id="tab-two" type="checkbox" name="tabs">
  <label for="tab-two">Label Two</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>
<div class="tab">
  <input id="tab-three" type="checkbox" name="tabs">
  <label for="tab-three">Label Three</label>
  <div class="tab-content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
  </div>
</div>

<div class="half">
  <p>Open <strong>one</strong></p>
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>


问:
Exact Split is not happening using split function in R
https://www.dropbox.com/s/35w66sri5rauv5d/FlightDelays.csv?dl=0

I am reading a dataset from the above link which contains 2201 rows.using split function,i gave the ratio as 0.6.Then i should be getting two datasets conatining 1320 and 881 datasets respectively.Initally it was working fine,but now when i am splitting ,instead of 0.6 the split is happening for 0.53,Even though i specified 0.6 as my ratio in the split.what might be the issue for this sudden change.How to resolve this.Code is given below.

```<code>library(caTools)
originaldata.df<-read.csv("use csv from the link given above")
split<-sample.split(originaldata.df,SplitRatio = 0.6)
Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")

ExpectedOutput:
1320(2201*60/100)
881(2201*40/100)
Actualoutput:
1186
1015
</code>```

答:
Here's a customised split function that will derive two subset of rownumbers based on the given proportion:

```<code>splitFactor <- function(rows, prop){
  a <- sample(seq(rows), ceiling(rows*prop))
  b <- sample(seq(rows), floor(rows*(1-prop)))
  list(a[order(a)],b[order(b)])
}

sp.53 <- splitFactor(nrow(iris), .53)
lapply(sp.53, length)

# [[1]]
# [1] 80

# [[2]]
# [1] 70
</code>```

To derive training and test set with the function:

```<code>all.sets <- lapply(splitFactor(nrow(iris), .6),
                   function(x) iris[x,])

lapply(all.sets, dim)

# [[1]]
# [1] 90  5

# [[2]]
# [1] 60  5
</code>```

Body:
https://www.dropbox.com/s/35w66sri5rauv5d/FlightDelays.csv?dl=0

I am reading a dataset from the above link which contains 2201 rows.using split function,i gave the ratio as 0.6.Then i should be getting two datasets conatining 1320 and 881 datasets respectively.Initally it was working fine,but now when i am splitting ,instead of 0.6 the split is happening for 0.53,Even though i specified 0.6 as my ratio in the split.what might be the issue for this sudden change.How to resolve this.Code is given below.

library(caTools)
originaldata.df<-read.csv("use csv from the link given above")
split<-sample.split(originaldata.df,SplitRatio = 0.6)
Trainingdataset<-subset(originaldata.df,split == "TRUE")
Testingdataset<-subset(originaldata.df,split == "FALSE")

ExpectedOutput:
1320(2201*60/100)
881(2201*40/100)
Actualoutput:
1186
1015

Body:
Here's a customised split function that will derive two subset of rownumbers based on the given proportion:

splitFactor <- function(rows, prop){
  a <- sample(seq(rows), ceiling(rows*prop))
  b <- sample(seq(rows), floor(rows*(1-prop)))
  list(a[order(a)],b[order(b)])
}

sp.53 <- splitFactor(nrow(iris), .53)
lapply(sp.53, length)

# [[1]]
# [1] 80

# [[2]]
# [1] 70

To derive training and test set with the function:

all.sets <- lapply(splitFactor(nrow(iris), .6),
                   function(x) iris[x,])

lapply(all.sets, dim)

# [[1]]
# [1] 90  5

# [[2]]
# [1] 60  5


问:
NSIS: environment variable created doesn't work
I am creating a Env Variable and then appending it to the PATH variable in my NSIS installer script on Win7 - 64 bit.

```<code>Push "MyPath"
Push "D:\MyFolder\bin;D:\MyFolder\lib"
Call WriteEnvStr

Push "%MyPath%"
Call AddToPath
</code>```

Now after installation I can see both the variable in cmd prompt

```<code>MyPath=D:\MyFolder\bin;D:\MyFolder\lib
Path=%MyPath%;<my existsing path>
</code>```

But any exe/dll from  are not found at run time.
If I run the cmd prompt as Administrator and then run exe, it runs fine.
It also works if I run exe directly as an Administrator.

Also interesting is that if I open Environment editor, double click on MyPath variable and click OK (without changing anything), my exe's run fine without running as Administrator.
And now if I check Path in cmd prompt, MyPath variable is substituted

```<code>MyPath=D:\MyFolder\bin;D:\MyFolder\lib
Path=D:\MyFolder\bin;D:\MyFolder\lib;<my existsing path>
</code>```

I tried to add "Call EnvVarUpdate" after creating the env variable but it doesn't work.

I am using NSIS Unicode version 2.46.3

答:
Your chances of adding/modifying the path without losing data in path by truncating it would be much greater by using the registry.

```<code>ReadRegStr $0 HKCU "Environment" Path
StrCpy $1 "D:\MyFolder\bin;D:\MyFolder\lib"
StrCpy $2 "$0;$1"
WriteRegStr HKCU "Environment" Path "$2"
</code>```

If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored however. And this is more or less obsolete anyway.

But we could just continue with your method however just try a different means of acomplishing your goal. I have not tested this but you can try something similar to this:

```<code>StrCpy $R0 "MYPATH"
StrCpy $R1 "D:\MyFolder\bin;D:\MyFolder\lib"
System::Call `Kernel32::SetEnvironmentVariable(t"$R0",t"$R1")`
</code>```

Now include your new variable in the path like the following:

```<code>ReadEnvStr $R0 COMSPEC
ReadEnvStr $R1 MYPATH
ExecDos::Exec /TOSTACK `"$R0" /c "SetX PATH=%PATH%;$R1 -m"`
</code>```

You can now easily change that one variable %MYPATH% at any time in the future and the PATH will reflect the new value.

Body:
I am creating a Env Variable and then appending it to the PATH variable in my NSIS installer script on Win7 - 64 bit.

Push "MyPath"
Push "D:\MyFolder\bin;D:\MyFolder\lib"
Call WriteEnvStr

Push "%MyPath%"
Call AddToPath

Now after installation I can see both the variable in cmd prompt

MyPath=D:\MyFolder\bin;D:\MyFolder\lib
Path=%MyPath%;<my existsing path>

But any exe/dll from  are not found at run time.
If I run the cmd prompt as Administrator and then run exe, it runs fine.
It also works if I run exe directly as an Administrator.

Also interesting is that if I open Environment editor, double click on MyPath variable and click OK (without changing anything), my exe's run fine without running as Administrator.
And now if I check Path in cmd prompt, MyPath variable is substituted

MyPath=D:\MyFolder\bin;D:\MyFolder\lib
Path=D:\MyFolder\bin;D:\MyFolder\lib;<my existsing path>

I tried to add "Call EnvVarUpdate" after creating the env variable but it doesn't work.

I am using NSIS Unicode version 2.46.3

Body:
Your chances of adding/modifying the path without losing data in path by truncating it would be much greater by using the registry.

ReadRegStr $0 HKCU "Environment" Path
StrCpy $1 "D:\MyFolder\bin;D:\MyFolder\lib"
StrCpy $2 "$0;$1"
WriteRegStr HKCU "Environment" Path "$2"

If your system has an AUTOEXEC.BAT file then any PATH setting in AUTOEXEC.BAT will also be appended to the %PATH% environment variable. This is to provide compatibility with old installation routines which need to set the PATH. All other commands in AUTOEXEC.BAT are ignored however. And this is more or less obsolete anyway.

But we could just continue with your method however just try a different means of acomplishing your goal. I have not tested this but you can try something similar to this:

StrCpy $R0 "MYPATH"
StrCpy $R1 "D:\MyFolder\bin;D:\MyFolder\lib"
System::Call `Kernel32::SetEnvironmentVariable(t"$R0",t"$R1")`

Now include your new variable in the path like the following:

ReadEnvStr $R0 COMSPEC
ReadEnvStr $R1 MYPATH
ExecDos::Exec /TOSTACK `"$R0" /c "SetX PATH=%PATH%;$R1 -m"`

You can now easily change that one variable %MYPATH% at any time in the future and the PATH will reflect the new value.


问:
How to pass Azure AD authentication tokens so AngularJS can use them to call webapi
After successful AD authentication from my MVC web app, I set the token in the header so that client side scripts can make use of it to access the web api.

OnAuthorizationCodeReceived() after a successful login

```<code>    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
    {
        var code = context.Code;

        ClientCredential credential = new ClientCredential(clientId, appKey);
        string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));

        Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);

        HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + result.AccessToken);
    }
</code>```

In the last line I set the "Authorization" header. However I can't seem to make use of that from my AngularJS end to make api calls! What am I missing here? Requirement is that I don't have to use ADAL to authenticate from the AngularJS since web app already authenticates the user and have passed me the valid tokens.

答:
You could try to save the access token in cookie :

```<code>HttpCookie tokenCookies = new HttpCookie("token");
tokenCookies.Value = result.AccessToken;
tokenCookies.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Add(tokenCookies);
</code>```

Then making ajax call with access token from cookie on client side .

Body:
After successful AD authentication from my MVC web app, I set the token in the header so that client side scripts can make use of it to access the web api.

OnAuthorizationCodeReceived() after a successful login

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
    {
        var code = context.Code;

        ClientCredential credential = new ClientCredential(clientId, appKey);
        string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID));

        Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

        AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId);

        HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + result.AccessToken);
    }

In the last line I set the "Authorization" header. However I can't seem to make use of that from my AngularJS end to make api calls! What am I missing here? Requirement is that I don't have to use ADAL to authenticate from the AngularJS since web app already authenticates the user and have passed me the valid tokens.

Body:
You could try to save the access token in cookie :

HttpCookie tokenCookies = new HttpCookie("token");
tokenCookies.Value = result.AccessToken;
tokenCookies.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Add(tokenCookies);

Then making ajax call with access token from cookie on client side .


问:
I have a htm file can i read it as UTF-8 formatted file without doing anything to the file
I have a htm file can i read it as UTF-8 formatted file without doing anything to the file.
the file is saved in unicode(not sure) i want to read it as UTF-8 file other wise it gives me some boxes.. this has to be done using java

```<code>FileReader loInput = new FileReader(loFile);
BufferedReader loBufferReader = new BufferedReader(loInput);
String loLine; // String that holds current loFile loLine
int loCount = 0; // Line number of loCount
loLine = loBufferReader.readLine();
loCount++;
while (loLine != null) {
    loContent = loContent.concat(loLine);
    loLine = loBufferReader.readLine();
    loCount++;
}
loBufferReader.close();
</code>```

i tried this

EDIT: i have to get the data from HTML file and convert it into a DOM object for further processing

I am using

```<code>SAXBuilder loSaxBuilder=new SAXBuilder();
            Reader loStringReader=new StringReader(loContent);
            Document loDoc=loSaxBuilder.build(loStringReader);
            XPath loXpath = XPath.newInstance("/Div");
            Element loElement = (Element) loXpath.selectSingleNode(loDoc);
</code>```

to convert it to dom object

答:
Done using :

```<code>import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
public class CharsetToolkit{
private byte[] buffer;
private Charset defaultCharset;
private boolean enforce8Bit = false;
public CharsetToolkit(byte[] buffer)
{
    this.buffer = buffer;
    this.defaultCharset = getDefaultSystemCharset();
}
public CharsetToolkit(byte[] buffer, Charset defaultCharset)
{
    this.buffer = buffer;
    setDefaultCharset(defaultCharset);
}
public void setDefaultCharset(Charset defaultCharset)
{
    if (defaultCharset != null)
        this.defaultCharset = defaultCharset;
    else
        this.defaultCharset = getDefaultSystemCharset();
}
public void setEnforce8Bit(boolean enforce)

{

    this.enforce8Bit = enforce;

}

public boolean getEnforce8Bit()

{

    return this.enforce8Bit;

}

public Charset getDefaultCharset()
{
    return defaultCharset;
}

public Charset guessEncoding()
{
    if (hasUTF8Bom(buffer)) return Charset.forName("UTF-8");
    if (hasUTF16LEBom(buffer)) return Charset.forName("UTF-16LE");
if (hasUTF16BEBom(buffer)) return Charset.forName("UTF-16BE");
    boolean highOrderBit = false;
    boolean validU8Char = true;
int length = buffer.length;
    int i = 0;

while (i < length - 6)
    {
        byte b0 = buffer[i];
        byte b1 = buffer[i + 1];
        byte b2 = buffer[i + 2];
        byte b3 = buffer[i + 3];
        byte b4 = buffer[i + 4];
        byte b5 = buffer[i + 5];
        if (b0 < 0)

    {
        highOrderBit = true;
            // a two-bytes sequence was encoutered
            if (isTwoBytesSequence(b0))
            {
                if (!isContinuationChar(b1))
                validU8Char = false;
                else
                    i++;
            }
            // a three-bytes sequence was encoutered

            else if (isThreeBytesSequence(b0))

            {

                // there must be two continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2)))

                    validU8Char = false;

                else

                    i += 2;

            }

            // a four-bytes sequence was encoutered

            else if (isFourBytesSequence(b0))

            {

                // there must be three continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3)))

                    validU8Char = false;

                else

                    i += 3;

            }

            // a five-bytes sequence was encoutered

            else if (isFiveBytesSequence(b0))

            {

                // there must be four continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4)))

                    validU8Char = false;

                else

                    i += 4;

            }

            // a six-bytes sequence was encoutered

            else if (isSixBytesSequence(b0))

            {

                // there must be five continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4) && isContinuationChar(b5)))

                    validU8Char = false;

                else

                    i += 5;

            }

            else

                validU8Char = false;

        }

        if (!validU8Char) break;

        i++;

    }

    // if no byte with an high order bit set, the encoding is US-ASCII

    // (it might have been UTF-7, but this encoding is usually internally used only by mail systems)

    if (!highOrderBit)

    {

        // returns the default charset rather than US-ASCII if the enforce8Bit flag is set.

        if (this.enforce8Bit)

            return this.defaultCharset;

        else

            return Charset.forName("US-ASCII");

    }

    // if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8,

    // otherwise the file would not be human readable

    if (validU8Char) return Charset.forName("UTF-8");

    // finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding

    return this.defaultCharset;

}

public static Charset guessEncoding(File f, int bufferLength) throws FileNotFoundException, IOException

{

    FileInputStream fis = new FileInputStream(f);

    byte[] buffer = new byte[bufferLength];

    fis.read(buffer);

    fis.close();

    CharsetToolkit toolkit = new CharsetToolkit(buffer);

    toolkit.setDefaultCharset(getDefaultSystemCharset());

    return toolkit.guessEncoding();

}

public static Charset guessEncoding(File f, int bufferLength, Charset defaultCharset) throws FileNotFoundException, IOException

{

    FileInputStream fis = new FileInputStream(f);

    byte[] buffer = new byte[bufferLength];

    fis.read(buffer);

    fis.close();

    CharsetToolkit toolkit = new CharsetToolkit(buffer);

    toolkit.setDefaultCharset(defaultCharset);

    return toolkit.guessEncoding();

}

/**

 * If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character;

 *

 * @param b a byte.

 * @return true if it's a continuation char.

 */

private static boolean isContinuationChar(byte b)

{

    return -128 <= b && b <= -65;

}

/**

 * If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a two-bytes sequence.

 */

private static boolean isTwoBytesSequence(byte b)

{

    return -64 <= b && b <= -33;

}

/**

 * If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a three-bytes sequence.

 */

private static boolean isThreeBytesSequence(byte b)

{

    return -32 <= b && b <= -17;

}

/**

 * If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a four-bytes sequence.

 */

private static boolean isFourBytesSequence(byte b)

{

    return -16 <= b && b <= -9;

}
</code>```

private static boolean isFiveBytesSequence(byte b)
    {
        return -8 <= b && b <= -5;
    }

```<code>private static boolean isSixBytesSequence(byte b)
{
    return -4 <= b && b <= -3;
}
public static Charset getDefaultSystemCharset()
{
    return Charset.forName(System.getProperty("file.encoding"));
}
private static boolean hasUTF8Bom(byte[] bom)
{
    return (bom[0] == -17 && bom[1] == -69 && bom[2] == -65);
}
private static boolean hasUTF16LEBom(byte[] bom)
{
return (bom[0] == -1 && bom[1] == -2);
}
private static boolean hasUTF16BEBom(byte[] bom)
{
    return (bom[0] == -2 && bom[1] == -1);
}
public static Charset[] getAvailableCharsets()
{
    Collection collection = Charset.availableCharsets().values();
    return (Charset[]) collection.toArray(new Charset[collection.size()]);
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
File file = new File("windows-1252.txt");
    Charset guessedCharset = CharsetToolkit.guessEncoding(file, 4096);
    System.err.println("Charset found: " + guessedCharset.displayName());
FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, guessedCharset);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
    {
        System.out.println(line);

    }}}
</code>```

and by calling this

```<code>Charset guessedCharset = CharsetToolkit.guessEncoding(new File("filename.htm"), 4096);
    BufferedReader c = new BufferedReader(new InputStreamReader(new FileInputStream("filename.htm"), guessedCharset)) ;
</code>```

Body:
I have a htm file can i read it as UTF-8 formatted file without doing anything to the file.
the file is saved in unicode(not sure) i want to read it as UTF-8 file other wise it gives me some boxes.. this has to be done using java

FileReader loInput = new FileReader(loFile);
BufferedReader loBufferReader = new BufferedReader(loInput);
String loLine; // String that holds current loFile loLine
int loCount = 0; // Line number of loCount
loLine = loBufferReader.readLine();
loCount++;
while (loLine != null) {
    loContent = loContent.concat(loLine);
    loLine = loBufferReader.readLine();
    loCount++;
}
loBufferReader.close();

i tried this

EDIT: i have to get the data from HTML file and convert it into a DOM object for further processing

I am using

SAXBuilder loSaxBuilder=new SAXBuilder();
            Reader loStringReader=new StringReader(loContent);
            Document loDoc=loSaxBuilder.build(loStringReader);
            XPath loXpath = XPath.newInstance("/Div");
            Element loElement = (Element) loXpath.selectSingleNode(loDoc);

to convert it to dom object

Body:
Done using :

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
public class CharsetToolkit{
private byte[] buffer;
private Charset defaultCharset;
private boolean enforce8Bit = false;
public CharsetToolkit(byte[] buffer)
{
    this.buffer = buffer;
    this.defaultCharset = getDefaultSystemCharset();
}
public CharsetToolkit(byte[] buffer, Charset defaultCharset)
{
    this.buffer = buffer;
    setDefaultCharset(defaultCharset);
}
public void setDefaultCharset(Charset defaultCharset)
{
    if (defaultCharset != null)
        this.defaultCharset = defaultCharset;
    else
        this.defaultCharset = getDefaultSystemCharset();
}
public void setEnforce8Bit(boolean enforce)

{

    this.enforce8Bit = enforce;

}

public boolean getEnforce8Bit()

{

    return this.enforce8Bit;

}

public Charset getDefaultCharset()
{
    return defaultCharset;
}

public Charset guessEncoding()
{
    if (hasUTF8Bom(buffer)) return Charset.forName("UTF-8");
    if (hasUTF16LEBom(buffer)) return Charset.forName("UTF-16LE");
if (hasUTF16BEBom(buffer)) return Charset.forName("UTF-16BE");
    boolean highOrderBit = false;
    boolean validU8Char = true;
int length = buffer.length;
    int i = 0;

while (i < length - 6)
    {
        byte b0 = buffer[i];
        byte b1 = buffer[i + 1];
        byte b2 = buffer[i + 2];
        byte b3 = buffer[i + 3];
        byte b4 = buffer[i + 4];
        byte b5 = buffer[i + 5];
        if (b0 < 0)

    {
        highOrderBit = true;
            // a two-bytes sequence was encoutered
            if (isTwoBytesSequence(b0))
            {
                if (!isContinuationChar(b1))
                validU8Char = false;
                else
                    i++;
            }
            // a three-bytes sequence was encoutered

            else if (isThreeBytesSequence(b0))

            {

                // there must be two continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2)))

                    validU8Char = false;

                else

                    i += 2;

            }

            // a four-bytes sequence was encoutered

            else if (isFourBytesSequence(b0))

            {

                // there must be three continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3)))

                    validU8Char = false;

                else

                    i += 3;

            }

            // a five-bytes sequence was encoutered

            else if (isFiveBytesSequence(b0))

            {

                // there must be four continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4)))

                    validU8Char = false;

                else

                    i += 4;

            }

            // a six-bytes sequence was encoutered

            else if (isSixBytesSequence(b0))

            {

                // there must be five continuation bytes of the form 10xxxxxx,

                // otherwise the following characteris is not a valid UTF-8 construct

                if (!(isContinuationChar(b1) && isContinuationChar(b2) && isContinuationChar(b3) && isContinuationChar(b4) && isContinuationChar(b5)))

                    validU8Char = false;

                else

                    i += 5;

            }

            else

                validU8Char = false;

        }

        if (!validU8Char) break;

        i++;

    }

    // if no byte with an high order bit set, the encoding is US-ASCII

    // (it might have been UTF-7, but this encoding is usually internally used only by mail systems)

    if (!highOrderBit)

    {

        // returns the default charset rather than US-ASCII if the enforce8Bit flag is set.

        if (this.enforce8Bit)

            return this.defaultCharset;

        else

            return Charset.forName("US-ASCII");

    }

    // if no invalid UTF-8 were encountered, we can assume the encoding is UTF-8,

    // otherwise the file would not be human readable

    if (validU8Char) return Charset.forName("UTF-8");

    // finally, if it's not UTF-8 nor US-ASCII, let's assume the encoding is the default encoding

    return this.defaultCharset;

}

public static Charset guessEncoding(File f, int bufferLength) throws FileNotFoundException, IOException

{

    FileInputStream fis = new FileInputStream(f);

    byte[] buffer = new byte[bufferLength];

    fis.read(buffer);

    fis.close();

    CharsetToolkit toolkit = new CharsetToolkit(buffer);

    toolkit.setDefaultCharset(getDefaultSystemCharset());

    return toolkit.guessEncoding();

}

public static Charset guessEncoding(File f, int bufferLength, Charset defaultCharset) throws FileNotFoundException, IOException

{

    FileInputStream fis = new FileInputStream(f);

    byte[] buffer = new byte[bufferLength];

    fis.read(buffer);

    fis.close();

    CharsetToolkit toolkit = new CharsetToolkit(buffer);

    toolkit.setDefaultCharset(defaultCharset);

    return toolkit.guessEncoding();

}

/**

 * If the byte has the form 10xxxxx, then it's a continuation byte of a multiple byte character;

 *

 * @param b a byte.

 * @return true if it's a continuation char.

 */

private static boolean isContinuationChar(byte b)

{

    return -128 <= b && b <= -65;

}

/**

 * If the byte has the form 110xxxx, then it's the first byte of a two-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a two-bytes sequence.

 */

private static boolean isTwoBytesSequence(byte b)

{

    return -64 <= b && b <= -33;

}

/**

 * If the byte has the form 1110xxx, then it's the first byte of a three-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a three-bytes sequence.

 */

private static boolean isThreeBytesSequence(byte b)

{

    return -32 <= b && b <= -17;

}

/**

 * If the byte has the form 11110xx, then it's the first byte of a four-bytes sequence character.

 *

 * @param b a byte.

 * @return true if it's the first byte of a four-bytes sequence.

 */

private static boolean isFourBytesSequence(byte b)

{

    return -16 <= b && b <= -9;

}

private static boolean isFiveBytesSequence(byte b)
    {
        return -8 <= b && b <= -5;
    }

private static boolean isSixBytesSequence(byte b)
{
    return -4 <= b && b <= -3;
}
public static Charset getDefaultSystemCharset()
{
    return Charset.forName(System.getProperty("file.encoding"));
}
private static boolean hasUTF8Bom(byte[] bom)
{
    return (bom[0] == -17 && bom[1] == -69 && bom[2] == -65);
}
private static boolean hasUTF16LEBom(byte[] bom)
{
return (bom[0] == -1 && bom[1] == -2);
}
private static boolean hasUTF16BEBom(byte[] bom)
{
    return (bom[0] == -2 && bom[1] == -1);
}
public static Charset[] getAvailableCharsets()
{
    Collection collection = Charset.availableCharsets().values();
    return (Charset[]) collection.toArray(new Charset[collection.size()]);
}
public static void main(String[] args) throws FileNotFoundException, IOException
{
File file = new File("windows-1252.txt");
    Charset guessedCharset = CharsetToolkit.guessEncoding(file, 4096);
    System.err.println("Charset found: " + guessedCharset.displayName());
FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, guessedCharset);
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null)
    {
        System.out.println(line);

    }}}

and by calling this

Charset guessedCharset = CharsetToolkit.guessEncoding(new File("filename.htm"), 4096);
    BufferedReader c = new BufferedReader(new InputStreamReader(new FileInputStream("filename.htm"), guessedCharset)) ;


问:
How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?
A C# desktop application (on the Visual Studio Express edition) worked, but then it didn't work 5 seconds later.

I tried the following:

Ensure debug configuration, debug flag, and full debug information are set on all assemblies.

Delete all bin and obj folders and all DLL files related to the project from my entire machine.

Recreate projects causing the problem from scratch.

Reboot.

I have two Windows Forms projects in the solution. One of them loads the debug information, one doesn't. They both refer to the assembly I'm trying to get debug information on in exactly the same way in the project file. Any ideas?

I want to add here, mostly for myself when I come back to review this question, that symbols are not loaded until the assembly is loaded, and the assembly is not loaded until it is needed. If the breakpoint is in a library that is only used in one function in your main assembly, the symbols will not be loaded (and it will show the breakpoint as not being hit) until that function is called.

答:
Webapplications (IIS Express) only:

Rightclick IIS Express Tray and close the IIS.

Clean Solution


问:
ViewPager inside ScrollView not working
I want to put a ViewPager inside a CoordinatorLayout withing a NestedScrollView. The viewpager houses 3 fragments.

Problem is the fragments aren't visible. Tabs show up and the rest of the layout is visible and scrolls accordingly.

Below is the code for my layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <include layout="@layout/toolbar" />

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/DarkBodyBackground"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="500dp"
                android:background="@color/DarkBodyBackground"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <include layout="@layout/artist_header" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <include layout="@layout/loading_indicator" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabLayout"
                    style="@style/TabLayoutStyle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:tabGravity="fill"
                    app:tabMode="fixed" />

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:visibility="gone" />

            </RelativeLayout>
        </android.support.v4.widget.NestedScrollView>
    </android.support.design.widget.CoordinatorLayout>

</RelativeLayout>
</code>```

答: Use android:fillViewport="true" in ScrollView

Title: ViewPager inside ScrollView not working

Body:
I want to put a ViewPager inside a CoordinatorLayout withing a NestedScrollView. The viewpager houses 3 fragments.

Problem is the fragments aren't visible. Tabs show up and the rest of the layout is visible and scrolls accordingly.

Below is the code for my layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <include layout="@layout/toolbar" />

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayout"
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/DarkBodyBackground"
        android:fitsSystemWindows="true"
        android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="500dp"
                android:background="@color/DarkBodyBackground"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <include layout="@layout/artist_header" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <include layout="@layout/loading_indicator" />

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabLayout"
                    style="@style/TabLayoutStyle"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:layout_scrollFlags="scroll|enterAlways"
                    app:tabGravity="fill"
                    app:tabMode="fixed" />

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:visibility="gone" />

            </RelativeLayout>
        </android.support.v4.widget.NestedScrollView>
    </android.support.design.widget.CoordinatorLayout>

</RelativeLayout>


问:
How can I use argparse to input different type arguments on the command line?
To give more information, I have this program that I am working on that is an iTunes playlist parser and what I want to do is write a function that will take a playlist and write to a file of all of the songs in said playlist that have a specified rating. For example, on the command line I want to write something like "python playlist.py --rating 5 fileName" where fileName is the name of the playlist in which the rating search is happening (so that optional argument would cause the program to write to a file all of the songs with a 5 star rating). Can someone please explain the syntax for something like this using argparse? Thanks!</p>

答:
I'm sure that you've seen this tutorial:
https://docs.python.org/2/howto/argparse.html

But even that is a bit obtuse.
So here is a shortcut by way of example:

```<code>import argparse

def get_command_line_arguments():
    parser = argparse.ArgumentParser(description='Parse --foo and --bar from the command line')
    parser.add_argument('--foo', default=0, type=int, choices=[0, 1, 2], help="gives the foo argument")
    parser.add_argument('--bar', default=1.0, type=float, help="the bar floating scaler")
    parser.add_argument('--zoo', default="", help="zoo is an optional string")
    args = parser.parse_args()
    return args

def main():
    args = get_command_line_arguments()
    foo = args.foo
    bar = args.bar
    zoo = args.zoo
</code>```

And that is all there is to it - at least for a get started example.

Body:
I'm sure that you've seen this tutorial:
https://docs.python.org/2/howto/argparse.html

But even that is a bit obtuse.
So here is a shortcut by way of example:

import argparse

def get_command_line_arguments():
    parser = argparse.ArgumentParser(description='Parse --foo and --bar from the command line')
    parser.add_argument('--foo', default=0, type=int, choices=[0, 1, 2], help="gives the foo argument")
    parser.add_argument('--bar', default=1.0, type=float, help="the bar floating scaler")
    parser.add_argument('--zoo', default="", help="zoo is an optional string")
    args = parser.parse_args()
    return args

def main():
    args = get_command_line_arguments()
    foo = args.foo
    bar = args.bar
    zoo = args.zoo

And that is all there is to it - at least for a get started example.