问:
HTML/JS Audio playlist pause/resume on page exit
I'm not sure if what I'm being asked to do is possible, I still don't have much expertise in JS, so I've been googling and so far came up short.

We're using a program called RiseVision to run a presentation, it's basically automated & beefed-up Powerpoint. So we've got a slideshow, and I managed to get music running in the background on a playlist, however, sometimes we will set these presentations to exit, then switch to a youtube video, then start the presentation over again. What I'm being asked to do is get the music to resume from the point that it was at, or at least skip to the next song, once the slideshow starts up again after the video.

due to the nature of the RiseVision program, I'm kind of limited to what I can manipulate:

The music is running on an HTML widget hidden behind the slideshow, the widget will be closed when the video plays, then opened again after.

Since it's just a widget, I don't have the ability to manipulate file structure, so I've just stuck the JS in a  tag

There is no user input on these displays, so everything just runs automatically, and we can update the presentations remotely.

Any ideas would be greatly appreciated, I was thinking maybe I could use the eventlistener for a stop and save an index somehow

Here's the code I'm using, pretty much taken from this video:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Audio Player</title>
    <style>
        #playlist{
            list-style: none;
        }
        #playlist li a{
            color:black;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
    </style>
    <!-- Source Code From YouTube.com/MicroTechTutorials  you may remove this message on your webpage but please do not redistribtue -->
</head>
<body>
    <audio src="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>
    <ul id="playlist">
        <li class="current-song">
        <a href="Paralyzer.m4a">Paralyzer</a></li>
        <li><a href="Minority.m4a">Minority</a></li>
        <li><a href="YoureGonnaGoFarKid.m4a">You're Gonna Go Far, Kid</a></li>
    </ul>
    <script src="https://code.jquery.com/jquery-2.2.0.js"></script>
    <script language="javascript">

        function audioPlayer(){
            var currentSong = 0;
            $("#audioPlayer")[0].src = $("#playlist li a")[0];
            $("#audioPlayer")[0].play();
            $("#playlist li a").click(function(e){
               e.preventDefault();
               $("#audioPlayer")[0].src = this;
               $("#audioPlayer")[0].play();
               $("#playlist li").removeClass("current-song");
                currentSong = $(this).parent().index();
                $(this).parent().addClass("current-song");
            });

            $("#audioPlayer")[0].addEventListener("ended", function(){
               currentSong++;
                if(currentSong == $("#playlist li a").length)
                    currentSong = 0;
                $("#playlist li").removeClass("current-song");
                $("#playlist li:eq("+currentSong+")").addClass("current-song");
                $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
                $("#audioPlayer")[0].play();
            });
        }

    </script>
    <script>
        // loads the audio player
        audioPlayer();
    </script>
</body>
</html>
</code>```

答:
Finally got this working, answer was actually a lot simpler than I was trying to make it. I was able to use localStorage to save the index of the current song and load the next song in the list when the software resumes.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Audio Player</title>
    <style>
        #playlist{
            list-style: none;
        }
        #playlist li a{
            color:black;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
    </style>
</head>
<body>
    <!--Audio Player-->
    <audio src="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>
    <!-- List of songs -->
    <ul id="playlist">
        <li class="current-song">
        <a href="[Link to Song Here]">[Name of Song Here]</a></li>
        <li><a href="[Link to Song Here]">[Name of Song Here]</a></li>
        <li><a href="[Link to Song Here]">[Name of Song Here]</a></li>
    </ul>
    <script src="https://code.jquery.com/jquery-2.2.0.js"></script>
    <script language="javascript">

        function audioPlayer(){
            var currentSong = 0;
        //If the locally stored position doesn't exist yet, set it to currentSong, otherwise increment it by one
        if (localStorage.songPosition === "NaN"){
            localStorage.songPosition = currentSong
        }
        else{
            localStorage.songPosition++
        }
        //If the stored song position is greater than the length of the song index, reset it.
        if(localStorage.songPosition > $("#playlist li a").length-1)
                localStorage.songPosition = 0;
        //Play the song at the locally stored position
        $("#audioPlayer")[0].src = $("#playlist li a")[localStorage.songPosition];
        $("#audioPlayer")[0].play();
        //Allows you to click titles to change songs, this is mostly for an actual web page and not necessary for an automatic system.
        $("#playlist li a").click(function(e){
           e.preventDefault();
           $("#audioPlayer")[0].src = this;
           $("#audioPlayer")[0].play();
           $("#playlist li").removeClass("current-song");
            currentSong = $(localStorage.songPosition).parent().index();
            $(this).parent().addClass("current-song");
        });
        //Check for the end of the current song, increment the current song counter and play the next one.
        $("#audioPlayer")[0].addEventListener("ended", function(){
           currentSong++;
           localStorage.songPosition = currentSong;
            if(currentSong == $("#playlist li a").length)
                currentSong = 0;
            $("#playlist li").removeClass("current-song");
            $("#playlist li:eq("+currentSong+")").addClass("current-song");
            $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
            $("#audioPlayer")[0].play();
        });
    }

</script>
<script>
    // loads the audio player
    audioPlayer();
</script>
</code>```

Body:
I'm not sure if what I'm being asked to do is possible, I still don't have much expertise in JS, so I've been googling and so far came up short.

We're using a program called RiseVision to run a presentation, it's basically automated & beefed-up Powerpoint. So we've got a slideshow, and I managed to get music running in the background on a playlist, however, sometimes we will set these presentations to exit, then switch to a youtube video, then start the presentation over again. What I'm being asked to do is get the music to resume from the point that it was at, or at least skip to the next song, once the slideshow starts up again after the video.

due to the nature of the RiseVision program, I'm kind of limited to what I can manipulate:

The music is running on an HTML widget hidden behind the slideshow, the widget will be closed when the video plays, then opened again after.

Since it's just a widget, I don't have the ability to manipulate file structure, so I've just stuck the JS in a  tag

There is no user input on these displays, so everything just runs automatically, and we can update the presentations remotely.

Any ideas would be greatly appreciated, I was thinking maybe I could use the eventlistener for a stop and save an index somehow

Here's the code I'm using, pretty much taken from this video:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>HTML5 Audio Player</title>

    <audio src="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>

        Paralyzer

Minority

You're Gonna Go Far, Kid

Body:
Finally got this working, answer was actually a lot simpler than I was trying to make it. I was able to use localStorage to save the index of the current song and load the next song in the list when the software resumes.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Audio Player</title>
    <style>
        #playlist{
            list-style: none;
        }
        #playlist li a{
            color:black;
            text-decoration: none;
        }
        #playlist .current-song a{
            color:blue;
        }
    </style>
</head>
<body>
    <!--Audio Player-->
    <audio src="" controls id="audioPlayer">
        Sorry, your browser doesn't support html5!
    </audio>
    <!-- List of songs -->
    <ul id="playlist">
        <li class="current-song">
        <a href="[Link to Song Here]">[Name of Song Here]</a></li>
        <li><a href="[Link to Song Here]">[Name of Song Here]</a></li>
        <li><a href="[Link to Song Here]">[Name of Song Here]</a></li>
    </ul>
    <script src="https://code.jquery.com/jquery-2.2.0.js"></script>
    <script language="javascript">

        function audioPlayer(){
            var currentSong = 0;
        //If the locally stored position doesn't exist yet, set it to currentSong, otherwise increment it by one
        if (localStorage.songPosition === "NaN"){
            localStorage.songPosition = currentSong
        }
        else{
            localStorage.songPosition++
        }
        //If the stored song position is greater than the length of the song index, reset it.
        if(localStorage.songPosition > $("#playlist li a").length-1)
                localStorage.songPosition = 0;
        //Play the song at the locally stored position
        $("#audioPlayer")[0].src = $("#playlist li a")[localStorage.songPosition];
        $("#audioPlayer")[0].play();
        //Allows you to click titles to change songs, this is mostly for an actual web page and not necessary for an automatic system.
        $("#playlist li a").click(function(e){
           e.preventDefault();
           $("#audioPlayer")[0].src = this;
           $("#audioPlayer")[0].play();
           $("#playlist li").removeClass("current-song");
            currentSong = $(localStorage.songPosition).parent().index();
            $(this).parent().addClass("current-song");
        });
        //Check for the end of the current song, increment the current song counter and play the next one.
        $("#audioPlayer")[0].addEventListener("ended", function(){
           currentSong++;
           localStorage.songPosition = currentSong;
            if(currentSong == $("#playlist li a").length)
                currentSong = 0;
            $("#playlist li").removeClass("current-song");
            $("#playlist li:eq("+currentSong+")").addClass("current-song");
            $("#audioPlayer")[0].src = $("#playlist li a")[currentSong].href;
            $("#audioPlayer")[0].play();
        });
    }

</script>
<script>
    // loads the audio player
    audioPlayer();
</script>


来源: stackexchange

问:
How to check (and kill) javascript-scroll when bottom of webpage is reached
I've been working in Python for a couple of years and have recently started looking into Javascript (not jQuery or dependencies, just plain Javascript) for some browser automation tasks.

Scrolling sites with lazy load (like a Facebook-page, a Twitter-page or heck even the Wallmart site) in Python is straightforward using fx Selenium.

In Python a rough 'n' dirty solution could be a height-check and break out of a while-loop if the height stops increasing. Like so:

```<code>check_height = driver.execute_script("return document.body.scrollHeight;")
while True:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)
    height = driver.execute_script("return document.body.scrollHeight;")
    if height == check_height:
        break
    check_height = height
</code>```

So now I'm trying to accomplish the same thing in Javascript using the Chrome-console. So far a working code looks like this:

```<code>var scrollToBottom = function() {
    window.scrollTo(0, document.body.scrollHeight);
    }
var sleep = 1000;
var kill_ID = setInterval(scrollToBottom, sleep);
</code>```

The setInterval initiates a loop that goes on forever - with a second of sleep time between each call to scrollToBottom. And I can then - manually - kill it when no more content is loaded by issuing:

```<code>window.clearInterval(kill_ID);
</code>```

This is obviously not the best way to go about this. So there has to be a better way of accomplishing the task without having to manually kill the scrolling-process.

But the Python logic doesn't seem to work for me in Javascript. Anyone that will give me a couple of pointers as to how to accomplish this - I assume - basic task? Thanks in advance.

Update:
As there apparently are no easy fixes for this one, I went with a low tech solution and added an eventListener, that kills the scrolling when I click the mouse (trigger the clearInterval).

So an extra code snippet for this to work - fx as a bookmarklet - would just need to be:

```<code>window.addEventListener('click', function kill(){window.clearInterval(kill_ID)})
</code>```

Thanks for the helpfull comments, everyone.

答:
Your approach is correct and I think (and I may be wrong) it is as good as you can if you don't want to use async/await approaches.

With async/await you can define a loop, like this:

```<code>async function toTheBottom() {
  while (check if height has changed) {
    window.scrollTo(0, document.body.scrollHeight);
    await sleep(1000);
  }
}
</code>```

Where sleep might be defined as:

```<code>function sleep(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}
</code>```

Compatibility: https://caniuse.com/#feat=async-functions

ContentLicense: CC BY-SA 3.0

Body:
I've been working in Python for a couple of years and have recently started looking into Javascript (not jQuery or dependencies, just plain Javascript) for some browser automation tasks.

Scrolling sites with lazy load (like a Facebook-page, a Twitter-page or heck even the Wallmart site) in Python is straightforward using fx Selenium.

In Python a rough 'n' dirty solution could be a height-check and break out of a while-loop if the height stops increasing. Like so:

check_height = driver.execute_script("return document.body.scrollHeight;")
while True:
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)
    height = driver.execute_script("return document.body.scrollHeight;")
    if height == check_height:
        break
    check_height = height

So now I'm trying to accomplish the same thing in Javascript using the Chrome-console. So far a working code looks like this:

var scrollToBottom = function() {
    window.scrollTo(0, document.body.scrollHeight);
    }
var sleep = 1000;
var kill_ID = setInterval(scrollToBottom, sleep);

The setInterval initiates a loop that goes on forever - with a second of sleep time between each call to scrollToBottom. And I can then - manually - kill it when no more content is loaded by issuing:

window.clearInterval(kill_ID);

This is obviously not the best way to go about this. So there has to be a better way of accomplishing the task without having to manually kill the scrolling-process.

But the Python logic doesn't seem to work for me in Javascript. Anyone that will give me a couple of pointers as to how to accomplish this - I assume - basic task? Thanks in advance.

Update:
As there apparently are no easy fixes for this one, I went with a low tech solution and added an eventListener, that kills the scrolling when I click the mouse (trigger the clearInterval).

So an extra code snippet for this to work - fx as a bookmarklet - would just need to be:

window.addEventListener('click', function kill(){window.clearInterval(kill_ID)})

Thanks for the helpfull comments, everyone.

Body:
Your approach is correct and I think (and I may be wrong) it is as good as you can if you don't want to use async/await approaches.

With async/await you can define a loop, like this:

async function toTheBottom() {
  while (check if height has changed) {
    window.scrollTo(0, document.body.scrollHeight);
    await sleep(1000);
  }
}

Where sleep might be defined as:

function sleep(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

Compatibility: https://caniuse.com/#feat=async-functions


问:
Is there a way I can use inline styling and CSS class at the same time?
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

```<code><div class="col-md-6 col-xs-6 saleBanner"><a href="https://www.MyURL.com/product-sale"><!-- pagebreak --><img class="SaleCategory" src="https://cdn3.bigcommerce.com/s-mystore/product_images/uploaded_images/myimg.png" alt="" /></a></div>
</code>```

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you

答: Obviously inline styles work at the same time with external style classes. I just couldn't see the rounded corners because the border-color was white. Thanks guys for your help.

Body:
I've been trying to do some styling for a page on BigCommerce platform, and for some components, I cannot find the styles and/or I don't want to mess with them.
for an img inside a div as follows:

I tried to add style="border-radius: 50%" to the div tag, and nothing changed. I'm not sure if it doesn't work this way or the built-in "editor" that I'm using on that platform just wouldn't allow me to do that for whatever reason.
I know this may not be the proper way to style a component, but what would be the best method for styling elements on a page that is already styled?

Thank you


问:
Querying Firestore for uid document after authentification => IllegalStateException
I am using both Firebase Authentification and Firestore for my Android app. What I am trying to do is the following:

the user signs in

if it's the first time the user signs in a document named by his uid is created

if the user has already signed in before (hence document named by uid already exists) then I load some further data.

Here's my logic to solve this:

get the FirebaseUser from FirebaseAuth instance

from the FirebaseUser I get the uid

build a DocumentReference with this uid

use get() query on the DocumentReference

if DocumentSnapshot is != null then user already exists in firestore

if DocumentSnapshot == null the user doesn't exist and I create it in firestore

I was testing the code below:

```<code>    FirebaseUser user = mAuth.getCurrentUser();
    if(user != null) {
        // get uid from user
        String uid = user.getUid();

        // make a query to firestore db for uid
        DocumentReference userDoc = db.collection("users").document(uid);
        userDoc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {
                        Log.d(LOG_TAG, "DocumentSnapshot data: " + task.getResult().getData());
                    } else {
                        Log.d(LOG_TAG, "No such document");
                    }
                } else {
                    Log.d(LOG_TAG, "get failed with ", task.getException());
                }
            }
        });
    }
</code>```

When uid exists in firestore I get the log message with appropriate data but when it doesn't I get the following exception and I can't find a way to get to use DocumentSnapshot.exists():

```<code>java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.
</code>```

Can anyone help me understand what I am doing wrong ?

Thanks a million ! :)

答:
The object returned by get() is a DocumentSnapshot not the document itself.  The DocumentSnapshot is never null.  Use the exists() method to determine if the snapshot contains a document.  If exists() is true, you can
 safely use one of the getXXX() methods (in your case, getData() for a map) to obtain the value of the document.

```<code>@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot snapshot = task.getResult();
        if (snapshot.exists()) {
            Log.d(LOG_TAG, "DocumentSnapshot data: " + snapshot.getData());
        } else {
            Log.d(LOG_TAG, "No such document");
        }
    } else {
        Log.d(LOG_TAG, "get failed with ", task.getException());
    }
}
</code>```

Body:
I am using both Firebase Authentification and Firestore for my Android app. What I am trying to do is the following:

the user signs in

if it's the first time the user signs in a document named by his uid is created

if the user has already signed in before (hence document named by uid already exists) then I load some further data.

Here's my logic to solve this:

get the FirebaseUser from FirebaseAuth instance

from the FirebaseUser I get the uid

build a DocumentReference with this uid

use get() query on the DocumentReference

if DocumentSnapshot is != null then user already exists in firestore

if DocumentSnapshot == null the user doesn't exist and I create it in firestore

I was testing the code below:

    FirebaseUser user = mAuth.getCurrentUser();
    if(user != null) {
        // get uid from user
        String uid = user.getUid();

        // make a query to firestore db for uid
        DocumentReference userDoc = db.collection("users").document(uid);
        userDoc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null) {
                        Log.d(LOG_TAG, "DocumentSnapshot data: " + task.getResult().getData());
                    } else {
                        Log.d(LOG_TAG, "No such document");
                    }
                } else {
                    Log.d(LOG_TAG, "get failed with ", task.getException());
                }
            }
        });
    }

When uid exists in firestore I get the log message with appropriate data but when it doesn't I get the following exception and I can't find a way to get to use DocumentSnapshot.exists():

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

Can anyone help me understand what I am doing wrong ?

Thanks a million ! :)

Body:
The object returned by get() is a DocumentSnapshot not the document itself.  The DocumentSnapshot is never null.  Use the exists() method to determine if the snapshot contains a document.  If exists() is true, you can
 safely use one of the getXXX() methods (in your case, getData() for a map) to obtain the value of the document.

@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot snapshot = task.getResult();
        if (snapshot.exists()) {
            Log.d(LOG_TAG, "DocumentSnapshot data: " + snapshot.getData());
        } else {
            Log.d(LOG_TAG, "No such document");
        }
    } else {
        Log.d(LOG_TAG, "get failed with ", task.getException());
    }
}


问:
Playing two videos in one Video element React
I want to put a short intro video that plays before every video on my web app. This fiddle: http://jsfiddle.net/bnzqkpza/ has a lot of the functionality I'm looking for, but I am using React so I need to rewrite the jquery so it doesn't change the DOM. I'm new to React, can anyone help me with this?

HTML:

```<code><video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
</video>
</code>```

JS:

```<code>var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4",
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});
</code>```

答:
I created a sample in CodeSandbox. The Video component would look something like this:

```<code>import React from "react";
import ReactDOM from "react-dom";

export default class Video extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      src: this.props.videos[0]
    };
  }

  componentDidMount() {
    let video = ReactDOM.findDOMNode(this);
    video.addEventListener("ended", e => {
      if (this.state.index < this.props.videos.length - 1) {
        let nextIndex = this.state.index + 1;
        this.setState({
          index: nextIndex,
          src: this.props.videos[nextIndex]
        });
      }
    });
    video.play();
  }
  componentDidUpdate(prevProps, prevState) {
    let video = ReactDOM.findDOMNode(this);
    video.play();
  }
  render() {
    return (
      <video
        src={this.state.src}
        controls
        autplay="true"
        playsinline
        muted
        crossorigin
      />
    );
  }
}
</code>```

The code sandbox url: https://codesandbox.io/s/n7p9yvp260

Body:
I want to put a short intro video that plays before every video on my web app. This fiddle: http://jsfiddle.net/bnzqkpza/ has a lot of the functionality I'm looking for, but I am using React so I need to rewrite the jquery so it doesn't change the DOM. I'm new to React, can anyone help me with this?

HTML:

<video src="http://www.w3schools.com/html/mov_bbb.mp4" id="myvideo" width="320" height="240" controls style="background:black">
</video>

JS:

var myvid = document.getElementById('myvideo');
var myvids = [
  "http://www.w3schools.com/html/mov_bbb.mp4",
  "http://www.w3schools.com/html/movie.mp4"
  ];
var activeVideo = 0;

myvid.addEventListener('ended', function(e) {
  // update the active video index
  activeVideo = (++activeVideo) % myvids.length;

  // update the video source and play
  myvid.src = myvids[activeVideo];
  myvid.play();
});

Body:
I created a sample in CodeSandbox. The Video component would look something like this:

import React from "react";
import ReactDOM from "react-dom";

export default class Video extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0,
      src: this.props.videos[0]
    };
  }

  componentDidMount() {
    let video = ReactDOM.findDOMNode(this);
    video.addEventListener("ended", e => {
      if (this.state.index < this.props.videos.length - 1) {
        let nextIndex = this.state.index + 1;
        this.setState({
          index: nextIndex,
          src: this.props.videos[nextIndex]
        });
      }
    });
    video.play();
  }
  componentDidUpdate(prevProps, prevState) {
    let video = ReactDOM.findDOMNode(this);
    video.play();
  }
  render() {
    return (
      <video
        src={this.state.src}
        controls
        autplay="true"
        playsinline
        muted
        crossorigin
      />
    );
  }
}

The code sandbox url: https://codesandbox.io/s/n7p9yvp260


问:
Put Carousel buttons on top of image
I have a bootstrap carousel, and buttons, which I want to go on top of the images in order to change from image to image. No matter what I do, I cannot seem to get it to be on top, it always shows up under. </p>

<p>I have tried position relative on the outer most div, and position relative on the carousel-control div. Any suggestions? </p>

```<code>HTML:

<div id="carouselExampleControls" class="carousel slide"  data-interval="false" data-ride="carousel">
   <div class="carousel-inner" role="listbox">
     <div class="carousel-item active">
       <img class="mini-img" src="images/plane.png" alt="">
     </div>
     <div class="carousel-item active">
       <img class="mini-img" src="images/truck.png" alt="">
     </div>
     <div class="carousel-item active">
       <img class="mini-img" src="images/boat.png" alt="">
     </div>
     <div class="carousel-controls">
        <ul class="carousel-ul">
           <li>
             <button type="button" name="button"></button>
           </li>
           <li>
             <button type="button" name="button"></button>
           </li>
           <li>
             <button type="button" name="button"></button>
           </li>
           <li>
             <button type="button" name="button"></button>
           </li>
           <li>
             <button type="button" name="button"></button>
           </li>
        </ul>
      </div>
    </div>

CSS:

    #carouselExampleControls {
      position: relative;
    }

    .carousel-controls {
      position: absolute;
    }

    .carousel-ul {
      position: absolute;
      list-style-type: none;
    }
</code>```

答:
my suggestion is using jquery because when you want to custom bootstrap the best way is using jquery for example you can make a button outside your div and call a jquery function like this :
consider your buttons id is #nextButton and #prevButton

$('#nextButton').onClick(function(){
   $('.carousel').carousel('next');
})

$('#prevButton').onClick(function(){
   $('.carousel').carousel('prev');
})

and for more info you can check this link out

Title: Put Carousel buttons on top of image

Body:
I have a bootstrap carousel, and buttons, which I want to go on top of the images in order to change from image to image. No matter what I do, I cannot seem to get it to be on top, it always shows up under.

I have tried position relative on the outer most div, and position relative on the carousel-control div. Any suggestions?

HTML:

             <button type="button" name="button"></button>

             <button type="button" name="button"></button>

             <button type="button" name="button"></button>

             <button type="button" name="button"></button>

             <button type="button" name="button"></button>

CSS:

    #carouselExampleControls {
      position: relative;
    }

    .carousel-controls {
      position: absolute;
    }

    .carousel-ul {
      position: absolute;
      list-style-type: none;
    }


问:
bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)
I have a xml file with data like below

```<code><temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

```<code>sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml
</code>```

output : 20

desired output: 50

I appreciate the help. Thank you

答:
you should perhaps use a xml aware tool but grep can handle this with ease.

```<code>grep -Pom1 '(?<=total=")[^"]+' file | head -1
50
</code>```

this finds all total attribute values on the first matched line and gets the first of them.

Lacking look behind regex feature, you can fall back to

```<code>$ grep -Eo 'total="[^"]+"' file | awk -F\" '{print $2; exit}'

50
</code>```

Body:
I have a xml file with data like below

<temp>

</temp>

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml

output : 20

desired output: 50

I appreciate the help. Thank you

Body:
you should perhaps use a xml aware tool but grep can handle this with ease.

grep -Pom1 '(?<=total=")[^"]+' file | head -1
50

this finds all total attribute values on the first matched line and gets the first of them.

Lacking look behind regex feature, you can fall back to

$ grep -Eo 'total="[^"]+"' file | awk -F\" '{print $2; exit}'

50


问:
Why is my JavaScript function to plot all of the different combinations of various numbers stopping after only a few runs
I'm working on a TSP application that involves plotting various points on a map. I need each possible combination to be plotted once and only once. The code below logically makes sense to me, however it's not getting passed a few turns, which is many, many times fewer than it is meant to.

```<code>var dogs = [];
var totalDogs = 9;
var prevComps = [];
var count = 0;

function setup() {

  //Define the canvas
  createCanvas(700, 575);

  //Generate a random vector position for each dog
  for (var i = 0; i < totalDogs ; i++){
    var vectorPoints = createVector(random(width), random(height));
    dogs[i] = vectorPoints;
  }
}

function draw() {

  //Sets the background to black and the circles (ellipses) to white
  background(0);
  fill(255);
  for (var i = 0; i < dogs.length; i++){
    ellipse(dogs[i].x, dogs[i].y, 8, 8);
  }

  //Defines the lines/paths
  stroke(255);
  strokeWeight(2);
  noFill();
  beginShape();

  //Draw every dog on the map at their randomly generated vector point
  for (var i = 0; i < dogs.length; i++){
    vertex(dogs[i].x, dogs[i].y);
  }

  endShape();

  //Creates two random numbers within the range of our array and swaps them
  var i = floor(random(dogs.length));
  var j = floor(random(dogs.length));

  //Creates an array, stores the random numbers there to be compared and creates an "isNew" bool to determine if this pair has already been created
  var comp = [];
  comp.push(i);
  comp.push(j);
  var isNew = true;

  //Checks to see if the new combo has been used before and thus stored in our previous comparison array
  for(l = 0; l < prevComps.length; l++){
    if(prevComps[l][0] == comp[0] && prevComp[l][1] == comp[1]){
      isNew = false;
    }
  }

  //If isNew is still true, the combination must be unique and so increase our count, add it to the prevComp array and finally swap the elements
  if(isNew == true){

  count++;
  prevComps.push(comp);

  //testing purposes
  document.getElementById("demo").innerHTML = count;

  swap(dogs, i, j)

  }

}

//Simple swap function
function swap(a, i, j){

  var tempVar = a[i]
  a[i] = a[j];
  a[j] = tempVar;

}
</code>```

I hope I have commented this code ok and it is readable, if not I'd be happy to fill in any blanks. Thanks in advance

答:
If I correctly understand what you're trying to do, I think the problem is that you're remembering swaps (in prevComps), rather than full sequences..

So maybe try to work with index arrays - starting with indices = [0, 1, 2, 3, ...], draw the line via dogs[indices[i]] rather than dogs[i], then swap indices around (instead of modifying dogs), then store copies of whole indices in prevComps, rather than just the two numbers (i and j) which were swapped in one iteration.

Body:
I'm working on a TSP application that involves plotting various points on a map. I need each possible combination to be plotted once and only once. The code below logically makes sense to me, however it's not getting passed a few turns, which is many, many times fewer than it is meant to.

var dogs = [];
var totalDogs = 9;
var prevComps = [];
var count = 0;

function setup() {

  //Define the canvas
  createCanvas(700, 575);

  //Generate a random vector position for each dog
  for (var i = 0; i < totalDogs ; i++){
    var vectorPoints = createVector(random(width), random(height));
    dogs[i] = vectorPoints;
  }
}

function draw() {

  //Sets the background to black and the circles (ellipses) to white
  background(0);
  fill(255);
  for (var i = 0; i < dogs.length; i++){
    ellipse(dogs[i].x, dogs[i].y, 8, 8);
  }

  //Defines the lines/paths
  stroke(255);
  strokeWeight(2);
  noFill();
  beginShape();

  //Draw every dog on the map at their randomly generated vector point
  for (var i = 0; i < dogs.length; i++){
    vertex(dogs[i].x, dogs[i].y);
  }

  endShape();

  //Creates two random numbers within the range of our array and swaps them
  var i = floor(random(dogs.length));
  var j = floor(random(dogs.length));

  //Creates an array, stores the random numbers there to be compared and creates an "isNew" bool to determine if this pair has already been created
  var comp = [];
  comp.push(i);
  comp.push(j);
  var isNew = true;

  //Checks to see if the new combo has been used before and thus stored in our previous comparison array
  for(l = 0; l < prevComps.length; l++){
    if(prevComps[l][0] == comp[0] && prevComp[l][1] == comp[1]){
      isNew = false;
    }
  }

  //If isNew is still true, the combination must be unique and so increase our count, add it to the prevComp array and finally swap the elements
  if(isNew == true){

  count++;
  prevComps.push(comp);

  //testing purposes
  document.getElementById("demo").innerHTML = count;

  swap(dogs, i, j)

  }

}

//Simple swap function
function swap(a, i, j){

  var tempVar = a[i]
  a[i] = a[j];
  a[j] = tempVar;

}

I hope I have commented this code ok and it is readable, if not I'd be happy to fill in any blanks. Thanks in advance


问:
How to print to web page using Ruby and Sinatra
I'm calling a ruby function in a post method and I'm trying to output the contents from the function to the web page but it prints the output in my console instead. How do I get it to print to the page?

I've tried

<%=rsg(params[:grammar_file])%> inside an erb file

and

rsg(params[:grammar_file])

inside of the post method and both just print to the console

```<code>require 'sinatra'
require 'sinatra/reloader' if development? #gem install sinatra-contrib
require './rsg.rb'
enable :sessions

get '/' do
 erb :index

end

post '/' do
rsg(params[:grammar_file])
erb :index

end

<% title = "RANDOM SENTENCE GENERATOR" %>
<!doctype html>
<html lang="en">
<head>
 <title><%= @title || "RSG" %></title>
 <meta charset="UTF8">
</head>
<body>
<h1>RubyRSG Demo</h1>
<p>Select grammar file to create randomly generated sentence</p>
<form action="/" method="post">
   <select name="grammar_file">
     <option value="Select" hidden>Select</option>
     <option value="Poem">Poem</option>
     <option value="Insult">Insult</option>
     <option value="Extension-request">Extension-request</option>
     <option value="Bond-movie">Bond-movie</option>
   </select>
<br><br>
<input type="submit" value="submit">
</form>

<section>
  <p>Here</p>
  <p><%= rsg(params[:grammar_file])%></p>

</section>

</body>
</html>
</code>```

答:
You need to tell your template what to do with the params.

This is what is happening:

```<code>post '/' do
  rsg(params[:grammar_file])
  # your rsg method produces some output. I guess you have a line the `puts` your params to stdout somewhere. Instead you should redirect the output into the template.
  erb :index
end
</code>```

Like this:

```<code>post '/' do
  erb :index, :locals => {:rsg => rsg(params[:grammar_file])}
end
</code>```

Then, in your :index template you have a line like:

```<code><%=rsg%>
</code>```

To output the generated String.

The problem might also be that you're tryng to return a puts statement instead of the plain string:

```<code>def rsg(p)
  puts "I love my daily #{p}. Good luck to you"
end
</code>```

This will just print to the console and nothing else (true to be precise)

Better:

```<code>def rsg(p)
  "I love my daily #{p}. Good luck to you"
end
</code>```

Here you will just return the String from your method and calling rsg("sandwich") will return:

```<code># => "I love my daily sandwich. Good luck to you"
</code>```

Body:
I'm calling a ruby function in a post method and I'm trying to output the contents from the function to the web page but it prints the output in my console instead. How do I get it to print to the page?

I've tried

<%=rsg(params[:grammar_file])%> inside an erb file

and

rsg(params[:grammar_file])

inside of the post method and both just print to the console

require 'sinatra'
require 'sinatra/reloader' if development? #gem install sinatra-contrib
require './rsg.rb'
enable :sessions

get '/' do
 erb :index

end

post '/' do
rsg(params[:grammar_file])
erb :index

end

<% title = "RANDOM SENTENCE GENERATOR" %>
<!doctype html>

 <title><%= @title || "RSG" %></title>
 <meta charset="UTF8">

RubyRSG Demo

Select grammar file to create randomly generated sentence

<form action="/" method="post">
   <select name="grammar_file">
     <option value="Select" hidden>Select</option>
     <option value="Poem">Poem</option>
     <option value="Insult">Insult</option>
     <option value="Extension-request">Extension-request</option>
     <option value="Bond-movie">Bond-movie</option>
   </select>

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

Here

<%= rsg(params[:grammar_file])%>

Body:
You need to tell your template what to do with the params.

This is what is happening:

post '/' do
  rsg(params[:grammar_file])
  # your rsg method produces some output. I guess you have a line the `puts` your params to stdout somewhere. Instead you should redirect the output into the template.
  erb :index
end

Like this:

post '/' do
  erb :index, :locals => {:rsg => rsg(params[:grammar_file])}
end

Then, in your :index template you have a line like:

<%=rsg%>

To output the generated String.

The problem might also be that you're tryng to return a puts statement instead of the plain string:

def rsg(p)
  puts "I love my daily #{p}. Good luck to you"
end

This will just print to the console and nothing else (true to be precise)

Better:

def rsg(p)
  "I love my daily #{p}. Good luck to you"
end

Here you will just return the String from your method and calling rsg("sandwich") will return:

# => "I love my daily sandwich. Good luck to you"


问:
WPF Treeview tooltip - dynamic
This is regards to MVVM & WPF -showing dynamic tooltip based on mouse location on a WPF Treeviewitems. Let say when the user hovers over a node which has got some business data based on that it should display tooltip.

Example: let say If i hover over manager items..should say -"locked" and for others "Ready to edit"..etc. Depends on the mouse over items data..tooltip text should guide the user to do further action. I'm trying to do some VM setting of tooltip text with the help of Tooltip opening event of TreeViewitem and trying to update the tooltip text..but facing some issue.

What are all the best and simple way to do it. Tried behavior and end up with some error.

```<code>System.Windows.Markup.XamlParseException occurred
  Message="Cannot add content of type 'x.x.Views.CustomTreeView.TreeTooltipBehavior' to an object of type 'System.Windows.Interactivity.BehaviorCollection'.  Error at object 'x.x.x.Views.CustomTreeView.TreeTooltipBehavior' in markup file 'x.x.x.Views;component/mypage.xaml' Line 72 Position 53."
  Source="PresentationFramework"
</code>```

Code:

```<code><MyMyControls:ExtendedTreeView x:Name="MyTreeView" ItemsSource="{Binding MyDriveCollection}"
             ItemContainerStyle="{StaticResource TVStyleTemplate}">
            <MyMyControls:ExtendedTreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type NavModel:TreeDataItem}" ItemsSource="{Binding MyDriveCollection}">
                    <MyControls:SimpleEditableTextBlock x:Name="TabLabel" Text="{Binding Path=MenuText, Mode=TwoWay}"
                          ToolTip="{Binding MenuText,Mode=TwoWay}">
                    </MyControls:SimpleEditableTextBlock>
                </HierarchicalDataTemplate>
            </MyControls:ExtendedTreeView.ItemTemplate>
            <MyControls:ExtendedTreeView.ContextMenu>
                <ContextMenu ItemsSource="{Binding ContextMenuItems}">
                    <ContextMenu.ItemTemplate>
                        <DataTemplate>
                            <MenuItem Header="{Binding MenuText}"
                                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
                                      AncestorType={x:Type TreeView}},Path=SelectedItem}" Command="{Binding Command}">
                            </MenuItem>
                        </DataTemplate>
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </MyControls:ExtendedTreeView.ContextMenu>
            <i:Interaction.Behaviors>
                <CustomTreeView:TreeTooltipBehavior CustomTreeView:ToolTipOpeningCommand="{Binding ToolTipOpeningCommand,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}" />
                <CustomTreeView:WorkspaceTreeViewContextMenuBehavior ContextMenuOpeningCommand="{Binding ContextMenuOpeningCommand}"/>
            </i:Interaction.Behaviors>
 </MyControls:ExtendedTreeView>
</code>```

TreeTooltipBehavior.cs

```<code> public class TreeTooltipBehavior : Behavior<ExtendedTreeViewItem>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.ToolTipOpening += new ToolTipEventHandler(AssociatedObject_ToolTipOpening);
        }

        void AssociatedObject_ToolTipOpening(object sender, ToolTipEventArgs e)
        {
            if (sender != null)
            {
                TreeDataItem hit = ((TreeDataItem) (((FrameworkElement) (sender)).DataContext));

                if (ToolTipOpeningCommand != null)
                {
                    ToolTipOpeningCommand.Execute(hit);
                }
            }
        }

        public static readonly DependencyProperty ToolTipOpeningCommandProperty = DependencyProperty.Register(
            "ToolTipOpeningCommand",
            typeof(ICommand),
            typeof(TreeTooltipBehavior),
            new PropertyMetadata(null));

        public ICommand ToolTipOpeningCommand
        {
            get { return (ICommand)GetValue(ToolTipOpeningCommandProperty); }
            set { SetValue(ToolTipOpeningCommandProperty, value); }
        }

    }
</code>```

In my view model I'm expecting to handle the ToolTipOpeningCommand and declared enough to get the event via Behavior class.

interestingly the contextmenu behavior works fine but tooltip behavior throws xaml parser exception..

1) Am i defined at the right place (for behavior) ?
2) If Contextmenu behavior works then why not tooltipbehavior ?
3) Any clue from the exception pasted at the top ?

I'm expecting to,
 (Xaml)-tooltip behavior -> to invoke tooltipopening event in the (behavior class) -> which in turns invoke the command defined in the ViewModel. I tried this similar way for context menu and works fine.

Pls provide some hint about fixing this issue.

答:
The XAML parser error is because you are trying to attach a Behavior that only applies to ExtendedTreeViewItem to an ExtendedTreeView element.  In other words, if you change Behavior<ExtendedTreeViewItem> to Behavior<ExtendedTreeView>, you will fix the parse error.

Although we cannot see from the code you presented, the reason the ContextMenu works is probably because WorkspaceTreeViewContextMenuBehavior derives from a Behavior with a generic type parameter that is compatible with ExtendedTreeView, such as FrameworkElement.

ContentLicense: CC BY-SA 2.5

Title: WPF Treeview tooltip - dynamic

Body:
This is regards to MVVM & WPF -showing dynamic tooltip based on mouse location on a WPF Treeviewitems. Let say when the user hovers over a node which has got some business data based on that it should display tooltip.

Example: let say If i hover over manager items..should say -"locked" and for others "Ready to edit"..etc. Depends on the mouse over items data..tooltip text should guide the user to do further action. I'm trying to do some VM setting of tooltip text with the help of Tooltip opening event of TreeViewitem and trying to update the tooltip text..but facing some issue.

What are all the best and simple way to do it. Tried behavior and end up with some error.

System.Windows.Markup.XamlParseException occurred
  Message="Cannot add content of type 'x.x.Views.CustomTreeView.TreeTooltipBehavior' to an object of type 'System.Windows.Interactivity.BehaviorCollection'.  Error at object 'x.x.x.Views.CustomTreeView.TreeTooltipBehavior' in markup file 'x.x.x.Views;component/mypage.xaml' Line 72 Position 53."
  Source="PresentationFramework"

Code:

<MyMyControls:ExtendedTreeView x:Name="MyTreeView" ItemsSource="{Binding MyDriveCollection}"
             ItemContainerStyle="{StaticResource TVStyleTemplate}">
            <MyMyControls:ExtendedTreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type NavModel:TreeDataItem}" ItemsSource="{Binding MyDriveCollection}">
                    <MyControls:SimpleEditableTextBlock x:Name="TabLabel" Text="{Binding Path=MenuText, Mode=TwoWay}"
                          ToolTip="{Binding MenuText,Mode=TwoWay}">
                    </MyControls:SimpleEditableTextBlock>
                </HierarchicalDataTemplate>
            </MyControls:ExtendedTreeView.ItemTemplate>
            <MyControls:ExtendedTreeView.ContextMenu>
                <ContextMenu ItemsSource="{Binding ContextMenuItems}">
                    <ContextMenu.ItemTemplate>
                        <DataTemplate>
                            <MenuItem Header="{Binding MenuText}"
                                      CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,
                                      AncestorType={x:Type TreeView}},Path=SelectedItem}" Command="{Binding Command}">
                            </MenuItem>
                        </DataTemplate>
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </MyControls:ExtendedTreeView.ContextMenu>

                <CustomTreeView:TreeTooltipBehavior CustomTreeView:ToolTipOpeningCommand="{Binding ToolTipOpeningCommand,Mode=TwoWay,diag:PresentationTraceSources.TraceLevel=High}" />
                <CustomTreeView:WorkspaceTreeViewContextMenuBehavior ContextMenuOpeningCommand="{Binding ContextMenuOpeningCommand}"/>

 </MyControls:ExtendedTreeView>

TreeTooltipBehavior.cs

 public class TreeTooltipBehavior : Behavior<ExtendedTreeViewItem>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.ToolTipOpening += new ToolTipEventHandler(AssociatedObject_ToolTipOpening);
        }

        void AssociatedObject_ToolTipOpening(object sender, ToolTipEventArgs e)
        {
            if (sender != null)
            {
                TreeDataItem hit = ((TreeDataItem) (((FrameworkElement) (sender)).DataContext));

                if (ToolTipOpeningCommand != null)
                {
                    ToolTipOpeningCommand.Execute(hit);
                }
            }
        }

        public static readonly DependencyProperty ToolTipOpeningCommandProperty = DependencyProperty.Register(
            "ToolTipOpeningCommand",
            typeof(ICommand),
            typeof(TreeTooltipBehavior),
            new PropertyMetadata(null));

        public ICommand ToolTipOpeningCommand
        {
            get { return (ICommand)GetValue(ToolTipOpeningCommandProperty); }
            set { SetValue(ToolTipOpeningCommandProperty, value); }
        }

    }

In my view model I'm expecting to handle the ToolTipOpeningCommand and declared enough to get the event via Behavior class.

interestingly the contextmenu behavior works fine but tooltip behavior throws xaml parser exception..

1) Am i defined at the right place (for behavior) ?
2) If Contextmenu behavior works then why not tooltipbehavior ?
3) Any clue from the exception pasted at the top ?

I'm expecting to,
 (Xaml)-tooltip behavior -> to invoke tooltipopening event in the (behavior class) -> which in turns invoke the command defined in the ViewModel. I tried this similar way for context menu and works fine.

Pls provide some hint about fixing this issue.


问:
Have cmake modify object files before linking static library
I am really new to cmake but I am trying to see if there is a way to modify object files that cmake has made before linking them into a static library.  My cmake file looks like this right now:

```<code>set(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -g")
set(SOURCES
    file1.cpp
    file2.cpp
)
add_library(my_proj STATIC ${SOURCES})
add_custom_command(
    TARGET my_proj
    PRE_LINK
    COMMAND <run objcopy on some of the object files here>
    COMMENT " Running PRE_LINK action "
)
</code>```

I don't see a good way with cmake to get the object file names so that I can loop over some of them and strip out debug symbols from some while leaving debug symbols for other objects. This would then allow me to create a smaller static library with symbols added for only the objects I need.  Is there any cmake variable that can give me all the object file names so I could selectively call objcopy and strip out debug symbols for some of the object files?

答:
As far as I can tell I think the best you can do is specify a command to run on the entirety of the target, as opposed to just some of the target's object files. For example, to manually strip a static library you could do:

```<code>add_library(my_proj STATIC ${SOURCES})
add_custom_command(TARGET my_proj POST_BUILD
    COMMAND objcopy -S $<TARGET_FILE:my_proj>
    COMMENT "Stripping my_proj"
)
</code>```

Which will run objcopy on my_proj.a after it has been built. If you need finer granularity on which object files are operated on, I suggest you split up the library into a few smaller static libraries, and operate accordingly on each one.

ContentLicense: CC BY-SA 4.0

Body:
I am really new to cmake but I am trying to see if there is a way to modify object files that cmake has made before linking them into a static library.  My cmake file looks like this right now:

set(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -g")
set(SOURCES
    file1.cpp
    file2.cpp
)
add_library(my_proj STATIC ${SOURCES})
add_custom_command(
    TARGET my_proj
    PRE_LINK
    COMMAND <run objcopy on some of the object files here>
    COMMENT " Running PRE_LINK action "
)

I don't see a good way with cmake to get the object file names so that I can loop over some of them and strip out debug symbols from some while leaving debug symbols for other objects. This would then allow me to create a smaller static library with symbols added for only the objects I need.  Is there any cmake variable that can give me all the object file names so I could selectively call objcopy and strip out debug symbols for some of the object files?

Body:
As far as I can tell I think the best you can do is specify a command to run on the entirety of the target, as opposed to just some of the target's object files. For example, to manually strip a static library you could do:

add_library(my_proj STATIC ${SOURCES})
add_custom_command(TARGET my_proj POST_BUILD
    COMMAND objcopy -S $<TARGET_FILE:my_proj>
    COMMENT "Stripping my_proj"
)

Which will run objcopy on my_proj.a after it has been built. If you need finer granularity on which object files are operated on, I suggest you split up the library into a few smaller static libraries, and operate accordingly on each one.


问:
Entity Framework Code First: How to map to stored procedures with less parameters than model properties?
I have a model named File with properties CreatedOn and ModifiedOn mapped to columns CreatedOn and ModifiedOn on table File. I don't want values of these columns to be set by users instead, they will be set by using the function GETDATE() in SQL. Following is my code:

This is my model (simplified for test):

```<code>public class File
{
    public int? Id { get; set; }
    public DateTime? CreatedOn { get; set; }
    public string Name { get; set; }
    public DateTime? ModifiedOn { get; set; }
}
</code>```

My model mapping to stored procedures:

```<code>public class FileMap: EntityTypeConfiguration<File>
{
    public FileMap()
    {
        MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name")));
    }
}
</code>```

My migration:

```<code>public partial class AddInsertStoredProcedure: DbMigration
{
    public override void Up()
    {
        CreateStoredProcedure(
            "dbo.InsertFile",
            p => new
            {
                Name = p.String(),
            },
            body:
                @"INSERT [dbo].[Files]([CreatedOn], [ModifiedOn], [Name])
                  VALUES (GETDATE(), GETDATE(), @Name)

                  DECLARE @Id int
                  SELECT @Id = [Id]
                  FROM [dbo].[Files]
                  WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()

                  SELECT t0.[Id]
                  FROM [dbo].[Files] AS t0
                  WHERE @@ROWCOUNT > 0 AND t0.[Id] = @Id"
            );
     /* ... */
}
</code>```

My test class:

```<code>   class Program
{
    static void Main(string[] args)
    {
        var context = new EntityContext();
        context.Files.Add(new File { Name = "File 1" });
        context.Files.Add(new File { Name = "File 2" });
        context.Files.Add(new File { Name = "File 3" });
        context.Files.Add(new File { Name = "File 4" });
        context.SaveChanges();
        Console.WriteLine("Done");
        Console.ReadLine();
    }
}
</code>```

When running it I receive an exception {"Procedure or function InsertFile has too many arguments specified."}. It seems that EF passed all the properties of my model to the stored procedure InsertFile so there were extra arguments. Can I have EF pass only the property Name?

答:
Try adding attributes to your properties, if you don't need them in the stored procedure:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.None)]
</code>```

If you want to get your properties from the stored procedure use:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
</code>```

and map in Fluent.api like this :

```<code>    public FileMap()
    {
        MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name").Result(f => f.ModifiedOn,"ModifiedOn"));
}
</code>```

For example, this is what I'm using for this:

model:

```<code>public partial class Order
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MasterFID { get; set; }

    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int ID { get; set; }

    [StringLength(50)]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string Number { get; set; }

    public int? OutletID { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? OrderDate { get; set; }

    [StringLength(250)]
    public string Comment { get; set; }

    public decimal? Sum { get; set; }
</code>```

Fluent.Api Mapping:

```<code>modelBuilder.Entity<Order>()
                .MapToStoredProcedures(sp =>
                {
                    sp.Insert(i => i.HasName("web_DS_Set_DocHeaders")
                                    .Parameter(p => p.OutletID, "mfID")
                                    .Parameter(p => p.DocTypeID, "orType")
                                    .Parameter(p => p.Comment, "orComment")
                                    .Parameter(p => p.Sum, "orSum")

                                    .Result(r => r.Number, "orNumber")
                                    .Result(r => r.OrderDate,"orDate")
                                    .Result(r => r.ID, "orID"));
                });
</code>```

And at the end of my stored procedure, I have something like this for return inserted row:

```<code>Select orNumber, orDate, orId from Orders where --parameters for last inserted|updated row
</code>```

Body:
I have a model named File with properties CreatedOn and ModifiedOn mapped to columns CreatedOn and ModifiedOn on table File. I don't want values of these columns to be set by users instead, they will be set by using the function GETDATE() in SQL. Following is my code:

This is my model (simplified for test):

public class File
{
    public int? Id { get; set; }
    public DateTime? CreatedOn { get; set; }
    public string Name { get; set; }
    public DateTime? ModifiedOn { get; set; }
}

My model mapping to stored procedures:

public class FileMap: EntityTypeConfiguration<File>
{
    public FileMap()
    {
        MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name")));
    }
}

My migration:

public partial class AddInsertStoredProcedure: DbMigration
{
    public override void Up()
    {
        CreateStoredProcedure(
            "dbo.InsertFile",
            p => new
            {
                Name = p.String(),
            },
            body:
                @"INSERT [dbo].[Files]([CreatedOn], [ModifiedOn], [Name])
                  VALUES (GETDATE(), GETDATE(), @Name)

                  DECLARE @Id int
                  SELECT @Id = [Id]
                  FROM [dbo].[Files]
                  WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()

                  SELECT t0.[Id]
                  FROM [dbo].[Files] AS t0
                  WHERE @@ROWCOUNT > 0 AND t0.[Id] = @Id"
            );
     /* ... */
}

My test class:

   class Program
{
    static void Main(string[] args)
    {
        var context = new EntityContext();
        context.Files.Add(new File { Name = "File 1" });
        context.Files.Add(new File { Name = "File 2" });
        context.Files.Add(new File { Name = "File 3" });
        context.Files.Add(new File { Name = "File 4" });
        context.SaveChanges();
        Console.WriteLine("Done");
        Console.ReadLine();
    }
}

When running it I receive an exception {"Procedure or function InsertFile has too many arguments specified."}. It seems that EF passed all the properties of my model to the stored procedure InsertFile so there were extra arguments. Can I have EF pass only the property Name?

Body:
Try adding attributes to your properties, if you don't need them in the stored procedure:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

If you want to get your properties from the stored procedure use:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]

and map in Fluent.api like this :

    public FileMap()
    {
        MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name").Result(f => f.ModifiedOn,"ModifiedOn"));
}

For example, this is what I'm using for this:

model:

public partial class Order
{
    [Key]
    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int MasterFID { get; set; }

    [Key]
    [Column(Order = 0)]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public int ID { get; set; }

    [StringLength(50)]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string Number { get; set; }

    public int? OutletID { get; set; }

    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? OrderDate { get; set; }

    [StringLength(250)]
    public string Comment { get; set; }

    public decimal? Sum { get; set; }

Fluent.Api Mapping:

modelBuilder.Entity<Order>()
                .MapToStoredProcedures(sp =>
                {
                    sp.Insert(i => i.HasName("web_DS_Set_DocHeaders")
                                    .Parameter(p => p.OutletID, "mfID")
                                    .Parameter(p => p.DocTypeID, "orType")
                                    .Parameter(p => p.Comment, "orComment")
                                    .Parameter(p => p.Sum, "orSum")

                                    .Result(r => r.Number, "orNumber")
                                    .Result(r => r.OrderDate,"orDate")
                                    .Result(r => r.ID, "orID"));
                });

And at the end of my stored procedure, I have something like this for return inserted row:

Select orNumber, orDate, orId from Orders where --parameters for last inserted|updated row


问:
Integration Flex sdk with Eclipse or Netbeans
I want to know how can we integrate flex with eclipse and netbeans. I want to know steps. I want an help on this.</p>

答: If you build an Eclipse RCP application, you can use an HTML widget in your UI to host/embed your Flex component.</p>


问:
Access is denied when running mkdir command from Jenkins
I am trying to create a new directory and copy files to it. So I'm using a job of "Execute batch command".

First I tried to run: robocopy source destination /e.

Then I tried: mkdir destination. In both cases I got an "Access is denied" mssage.

If I try it myself manualy I am able to create a directory and copy files to it.

The destination is a remote computer's shared folder: \computerName\sharedFolder\

Anyone knows how to get access rights with Jenkins?

答:
In my setup, the Jenkins slave service runs under a specific user (named jenkins).

It makes it easy to verify the access rights for that specific user.

Of course jenkins needs to have write access on the remote folder, both on the physical disk and the share.


问:
Ethereum Advance token sample
In this example https://www.ethereum.org/token#full-coin-code i have 2 question.

MyAdvanceToken - why the _transfer method is using > instead of >= for checking require(balanceOf[_from] > _value); while the TokenERC20 in this link is using >= ( require(balanceOf[_from] >= _value);)

Since inheritance will be in development only, the _transfer method base on this example is internal in TokenERC20, is it safe to assume that once deployed no one can use this internal function except from this contract ? There is no other contract that can inherit  and use this internal method since inheritance is in development only?

Many thanks in advance

答:
Using > instead of >= is a typo and >= sign should be preferred over >. Imagine you have 15 tokens and want to send all of them - you'll not pass the require with > sign.

It is safe because no one can use once deployed contract to inherit from. To create malignant inheritance you need to use parent contract code in the same or different file and deploy it one more time, creating the second base contract, distinct from the first one and not able to take its tokens.

Title: Ethereum Advance token sample


问:
How to update a progress bar in a loop inside a loop inside an ajax async call inside a loop
I have an application using kendoGrid where i update selected rows after saving them to our db.

Sometimes we have 1000+ rows so i have to partition the rows in order not to bog down the application. This takes quite a long time so i wanted to display a progress bar to help users see the progress on the updates.

The problem is that the progress bar doesn't update in each iteration. As i step through using chrome debugger i can see the progress bar update. but when i run the script in real time nothing happens.

HTML

```<code><div id="progressbar-wrapper">
    <div id="progressbar-outer" style="display: table;margin: 0 auto;background-color: #FFFFFF;border: 5px solid #000000;width: 50%;height: 30px;opacity: 1;z-index: 9998">
        <div id="progressbar" style="float:left;width: 0;height: 30px;background-color:#000000;border: 0;opacity: 1;z-index: 99999">
        </div>
    </div>
    <div id="loading-animation" style="position: fixed;top: 150px;left: 0;height: 120px;width: 100%;font-size: 100px;line-height: 120px;text-align: center;color: #000000;z-index: 9999;">
        ...SAVING...<br /><small>Saving Lines</small>
    </div>
</div>
</code>```

JAVASCRIPT

```<code>var progressbar = {};
$(function () {

    progressbar = {

        /** initial progress */
        progress: 0,

        /** maximum width of progressbar */
        progress_max: 0,

        /** The inner element of the progressbar (filled box). */
        $progress_bar: $('#progressbar'),

        /** Method to set the progressbar.
         */
        set: function (num) {
            if (this.progress_max && num) {
                this.progress = num / this.progress_max * 100;
                console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
                this.$progress_bar.width(String(this.progress) + '%');
            }
        },

        fn_wrap: function (num) {
            setTimeout(function () {
                this.set(num);
            }, 0);
        }

    };

});

var processedPartitions = 0;
var partitions = saveData.partition(30); //saveData is the selected saved rows

//Iterate through partitions
for (var i = 0; i < partitions.length; i++) {

    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[i]),
        async: true,
        complete: function () {
            processedPartitions++;
            if (processedPartitions === partitions.length) {

                //PROGRESS BAR (DOESNT WORK, Doesnt show or update the progressbar in real time) ==========================================

                //Get the full number of rows getting updated.
                var iterations = 0;
                for (var i = 0; i < partitions.length; i++) {
                    iterations = iterations + partitions[i].length;
                }

                //add total number of records to update as the iterations
                progressbar.progress_max = iterations;

                //make the progress bar visable before updating //does not show
                $("#progressbar-wrapper").css("display", "block");

                //start counter of rows updated
                var recordsUpdated = 0;

                //begin update loop
                var mainGrid = $("#mainGrid").data("kendoGrid");
                $.each(mainGrid.dataSource.data(), function () {

                    if (this.RowSelected === true) {

                        for (var i = 0; i < partitions.length; i++) {
                            for (var j = 0; j < partitions[i].length; j++) {

                                    var row = mainGrid.dataSource.getByUid(this.uid);
                                    row.set("RowSelected", "false");
                                    row.set("dirty", "false");

                                    //after update iterate recordsupdated
                                    recordsUpdated++;

                                //update the progress bar if not complete //doesnt update in realtime
                                if (iterations >= recordsUpdated) {
                                    progressbar.set(recordsUpdated);
                                }
                            }
                        }
                    }
                });

                //turn off progressbar after complete // never shows in realtime, never shown closing
                $("#progressbar-wrapper").css("display", "none");

                //Success message
                alert("Saved");
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText);
        }
    });
}
</code>```

So stepping through the code line by line, I can see that everything works. But when running in real-time. The progress bar never shows. Its like the entire page freezes.

答:
So i figured it out. Just had to separate the two processes. The ajax completes and sends the complete flag to a following method to update the grid using event loops.

```<code>//Get the number of saved data rows. That = total iteration
var iterations = saveData.length; //get data

var processedPartitions = 0;
var partitions = saveData.partition(30); partition data

//write buyer to Database First (Quickest method)
for (var p = 0; p < partitions.length; p++) {
    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[p]),
        async: true,
        beforeSend: function () {

        },
        success: function (result) {
            successComplete = 1; //1 means success
        },
        complete: function () {
            processedPartitions++;
            //check if all partitions processed
            if (processedPartitions === partitions.length) {
                successComplete = successComplete + 1; //2 means successful completion
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText); //0 means error
        }
    });
}

//PROGRESS BAR ================================================
//max progress bar
progressbar.progress_max = iterations;

var mainGrid = $("#mainGrid").data("kendoGrid");

var i = 0; //partition #
var j = 0; //line #
var linesUpdated = 0; //update complete #

//make the progress bar visable before updating
$("#progressbar-wrapper").css("display", "block");

//then loop through update grid methods
(function innerloop() {

    try {
        //If end
        var testPart = (partitions[i].length - 1); //30 but starts at 0
    } catch (err) {
        //exit loop
        return;
    }

    //Get the length of the partition
    var thisPartitionLength = (partitions[i].length - 1); //30 but starts at 0

    if (thisPartitionLength >= j && successComplete === 2) {

        $.each(mainGrid.dataSource.data(),
            function () {

                if (this.RowSelected === true) {

                    //get id
                    var row = mainGrid.dataSource.getByUid(this.uid);

                    //unselect and turn off dirty
                    row.set("RowSelected", "false");
                    row.set("dirty", "false");
                    linesUpdated++;
                }
            });
        //update line #
        j++;
        //update progressbar
        progressbar.set(linesUpdated);
    }

    if (j <= thisPartitionLength) {
        //loop if not complete with partition
        setTimeout(innerloop, 0);
    } else {
        if (j > thisPartitionLength) {
            //if end of partition reset the line # and increase partition # and continue loop
            i++;
            j = 0;
            setTimeout(innerloop, 0);
        }

        //on complete
        if (linesUpdated === iterations) {

            //Success message
            alert("Saved");
        }
    }
})();
</code>```

UPDATE

Ugh!! this doesn't work in IE11!

Body:
I have an application using kendoGrid where i update selected rows after saving them to our db.

Sometimes we have 1000+ rows so i have to partition the rows in order not to bog down the application. This takes quite a long time so i wanted to display a progress bar to help users see the progress on the updates.

The problem is that the progress bar doesn't update in each iteration. As i step through using chrome debugger i can see the progress bar update. but when i run the script in real time nothing happens.

HTML

        ...SAVING...
Saving Lines

JAVASCRIPT

var progressbar = {};
$(function () {

    progressbar = {

        /** initial progress */
        progress: 0,

        /** maximum width of progressbar */
        progress_max: 0,

        /** The inner element of the progressbar (filled box). */
        $progress_bar: $('#progressbar'),

        /** Method to set the progressbar.
         */
        set: function (num) {
            if (this.progress_max && num) {
                this.progress = num / this.progress_max * 100;
                console.log('percent: ' + this.progress + '% - ' + num + '/' + this.progress_max);
                this.$progress_bar.width(String(this.progress) + '%');
            }
        },

        fn_wrap: function (num) {
            setTimeout(function () {
                this.set(num);
            }, 0);
        }

    };

});

var processedPartitions = 0;
var partitions = saveData.partition(30); //saveData is the selected saved rows

//Iterate through partitions
for (var i = 0; i < partitions.length; i++) {

    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[i]),
        async: true,
        complete: function () {
            processedPartitions++;
            if (processedPartitions === partitions.length) {

                //PROGRESS BAR (DOESNT WORK, Doesnt show or update the progressbar in real time) ==========================================

                //Get the full number of rows getting updated.
                var iterations = 0;
                for (var i = 0; i < partitions.length; i++) {
                    iterations = iterations + partitions[i].length;
                }

                //add total number of records to update as the iterations
                progressbar.progress_max = iterations;

                //make the progress bar visable before updating //does not show
                $("#progressbar-wrapper").css("display", "block");

                //start counter of rows updated
                var recordsUpdated = 0;

                //begin update loop
                var mainGrid = $("#mainGrid").data("kendoGrid");
                $.each(mainGrid.dataSource.data(), function () {

                    if (this.RowSelected === true) {

                        for (var i = 0; i < partitions.length; i++) {
                            for (var j = 0; j < partitions[i].length; j++) {

                                    var row = mainGrid.dataSource.getByUid(this.uid);
                                    row.set("RowSelected", "false");
                                    row.set("dirty", "false");

                                    //after update iterate recordsupdated
                                    recordsUpdated++;

                                //update the progress bar if not complete //doesnt update in realtime
                                if (iterations >= recordsUpdated) {
                                    progressbar.set(recordsUpdated);
                                }
                            }
                        }
                    }
                });

                //turn off progressbar after complete // never shows in realtime, never shown closing
                $("#progressbar-wrapper").css("display", "none");

                //Success message
                alert("Saved");
            }

        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText);
        }
    });
}

So stepping through the code line by line, I can see that everything works. But when running in real-time. The progress bar never shows. Its like the entire page freezes.

Body:
So i figured it out. Just had to separate the two processes. The ajax completes and sends the complete flag to a following method to update the grid using event loops.

//Get the number of saved data rows. That = total iteration
var iterations = saveData.length; //get data

var processedPartitions = 0;
var partitions = saveData.partition(30); partition data

//write buyer to Database First (Quickest method)
for (var p = 0; p < partitions.length; p++) {
    var urlForWindow = "/Data/Save/";
    $.ajax({
        url: urlForWindow,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(partitions[p]),
        async: true,
        beforeSend: function () {

        },
        success: function (result) {
            successComplete = 1; //1 means success
        },
        complete: function () {
            processedPartitions++;
            //check if all partitions processed
            if (processedPartitions === partitions.length) {
                successComplete = successComplete + 1; //2 means successful completion
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.resonseText); //0 means error
        }
    });
}

//PROGRESS BAR ================================================
//max progress bar
progressbar.progress_max = iterations;

var mainGrid = $("#mainGrid").data("kendoGrid");

var i = 0; //partition #
var j = 0; //line #
var linesUpdated = 0; //update complete #

//make the progress bar visable before updating
$("#progressbar-wrapper").css("display", "block");

//then loop through update grid methods
(function innerloop() {

    try {
        //If end
        var testPart = (partitions[i].length - 1); //30 but starts at 0
    } catch (err) {
        //exit loop
        return;
    }

    //Get the length of the partition
    var thisPartitionLength = (partitions[i].length - 1); //30 but starts at 0

    if (thisPartitionLength >= j && successComplete === 2) {

        $.each(mainGrid.dataSource.data(),
            function () {

                if (this.RowSelected === true) {

                    //get id
                    var row = mainGrid.dataSource.getByUid(this.uid);

                    //unselect and turn off dirty
                    row.set("RowSelected", "false");
                    row.set("dirty", "false");
                    linesUpdated++;
                }
            });
        //update line #
        j++;
        //update progressbar
        progressbar.set(linesUpdated);
    }

    if (j <= thisPartitionLength) {
        //loop if not complete with partition
        setTimeout(innerloop, 0);
    } else {
        if (j > thisPartitionLength) {
            //if end of partition reset the line # and increase partition # and continue loop
            i++;
            j = 0;
            setTimeout(innerloop, 0);
        }

        //on complete
        if (linesUpdated === iterations) {

            //Success message
            alert("Saved");
        }
    }
})();

UPDATE

Ugh!! this doesn't work in IE11!


答:
The following will print total attributes for all a elements in your file, one to a line:

```<code>xmlstarlet sel -t -m '//a[@total]' -v ./@total -n <your-file.xml
</code>```

If you don't have XMLStarlet, you can do this with xsltproc (which is available almost everywhere). Given the following xslt file (generated as output of xmlstarlet sel -C -t -m '//a[@total]' -v ./@total -n):

```<code><?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exslt="http://exslt.org/common" version="1.0" extension-element-prefixes="exslt">
  <xsl:output omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/">
    <xsl:for-each select="//a[@total]">
      <xsl:call-template name="value-of-template">
        <xsl:with-param name="select" select="./@total"/>
      </xsl:call-template>
      <xsl:value-of select="'
'"/>
    </xsl:for-each>
  </xsl:template>
  <xsl:template name="value-of-template">
    <xsl:param name="select"/>
    <xsl:value-of select="$select"/>
    <xsl:for-each select="exslt:node-set($select)[position()>1]">
      <xsl:value-of select="'
'"/>
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

...you can run:

```<code>xsltproc extract-totals.xslt your-file.xml
</code>```

Title: bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)

Body:
The following will print total attributes for all a elements in your file, one to a line:

xmlstarlet sel -t -m '//a[@total]' -v ./@total -n <your-file.xml

If you don't have XMLStarlet, you can do this with xsltproc (which is available almost everywhere). Given the following xslt file (generated as output of xmlstarlet sel -C -t -m '//a[@total]' -v ./@total -n):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exslt="http://exslt.org/common" version="1.0" extension-element-prefixes="exslt">
  <xsl:output omit-xml-declaration="yes" indent="no"/>
  <xsl:template match="/">
    <xsl:for-each select="//a[@total]">
      <xsl:call-template name="value-of-template">
        <xsl:with-param name="select" select="./@total"/>
      </xsl:call-template>
      <xsl:value-of select="'&#10;'"/>
    </xsl:for-each>
  </xsl:template>
  <xsl:template name="value-of-template">
    <xsl:param name="select"/>
    <xsl:value-of select="$select"/>
    <xsl:for-each select="exslt:node-set($select)[position()&gt;1]">
      <xsl:value-of select="'&#10;'"/>
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

...you can run:

xsltproc extract-totals.xslt your-file.xml


问:
Ionic Framework interferes with contenteditable divs + WYSIWYG editors
Ionic framework (v 1.3) is interfering with contenteditable = 'true' DIVs. As far as I can tell it is preventing my click and drag events from propagating properly, which (in my case) is preventing me from using pretty much any WYSIWYG text editor.

I am unable to focus the cursor in a contenteditable DIV, nor am I able to select text from one. When I use the Trix editor (which also uses this), I can get an initial focus, but cannot place the cursor anywhere or select any text.

Is there a way to override Ionic's behavior here?

I have created a Plunker here with two panes demonstrating the basic contenteditable issue and the issue in conjunction with the Trix editor.

Demonstration usage:

```<code><ion-view title="ContentEditable Example">
  <ion-content class="has-header padding">
    <div contenteditable="true" style="user-select: all; -webkit-user-select: all;">
      <p>ContentEditable Text. This is a DIV with contenteditable set to true, AND user-select set to all. Note how you cannot click and edit the text!</p>
    </div>
  </ion-content>
</ion-view>
</code>```

答:
I found a solution that enables the use of a contenteditable div as well as the Trix editor in Ionic. I applied this class to the CSS and am now not experiencing any issues, either testing in a browser or on a real device:

```<code>.editable{
    user-select: text;
    -webkit-user-select: text;
    pointer-events: all !important;
    -webkit-user-modify:read-write !important;
}
</code>```

Body:
Ionic framework (v 1.3) is interfering with contenteditable = 'true' DIVs. As far as I can tell it is preventing my click and drag events from propagating properly, which (in my case) is preventing me from using pretty much any WYSIWYG text editor.

I am unable to focus the cursor in a contenteditable DIV, nor am I able to select text from one. When I use the Trix editor (which also uses this), I can get an initial focus, but cannot place the cursor anywhere or select any text.

Is there a way to override Ionic's behavior here?

I have created a Plunker here with two panes demonstrating the basic contenteditable issue and the issue in conjunction with the Trix editor.

Demonstration usage:

<ion-view title="ContentEditable Example">
  <ion-content class="has-header padding">

ContentEditable Text. This is a DIV with contenteditable set to true, AND user-select set to all. Note how you cannot click and edit the text!

  </ion-content>
</ion-view>

Body:
I found a solution that enables the use of a contenteditable div as well as the Trix editor in Ionic. I applied this class to the CSS and am now not experiencing any issues, either testing in a browser or on a real device:

.editable{
    user-select: text;
    -webkit-user-select: text;
    pointer-events: all !important;
    -webkit-user-modify:read-write !important;
}


问:
Application Freezing after some idle time
I am developing a software using C# 2.0 which uses about 200MB of memory and occasionally high CPU. The problem is, when i am leaving my machine idle for about 20-30 mins with the application running, after i come back and try to use the application, it freezes for about 2 mins, then becomes interactive.

Why does this happen? Is there any way to avoid this?

Thank you all.

Regards,

-Rakib

答:
I know this is old thread, but I stumbled on this upon searching answer for similar problem.

For me using timer triggered renderTargetBitmap during display turn off on idle (Vista, control panel) used pretty soon all of the memory and computer freezed.

You can find more details here:

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/4a4ab601-f832-49ac-aca5-1f537fec1d04

(MSDN Forums - .Net development Forums - WPF - Huge memory consumption starts after 20 minutes


问:
On Azure, bunyan stops logging after a few seconds
I have a NodeJS web app and I've added logging via bunyan. Works perfectly on my desktop. On Azure it works perfectly for 1-10 seconds and then nothing else is ever logged. The app continues to run and operates correctly otherwise. I can't figure out why this is happening. Logging to a plain local file, not a blob or Azure Storage.

Log type is rotating-file, set to rotate 1/day and keep 3 days. The web app has Always On and ARR Affinity set to On, and Application Logging (Filesystem) though I'm not sure that factors here. Instance Count is 1 and Autoscale is not enabled. Node version is 8.7.0. In Console:

```<code>> df -h .
D:\home\site\wwwroot\logs
Filesystem      Size  Used Avail Use% Mounted on
-               100G -892G   99G 113% /d/home/site
</code>```

Frankly I don't know what that's trying to tell me. Somehow we've used 113% of something, which is impossible. We've used a negative amount, which is impossible. There is still 99G/100G available, so we really are only using 1%. So is it a 'disk full' problem? I don't know. I haven't seen such an error message anywhere.

Prior, the app was using console.log(). We added code to intercept console.X and write to a file first, then call the normal function. The same thing happened - it would work for a few seconds and then not log anything else. I had assumed it was because some component of Azure was also intercepting console calls in order to redirect them to XXX-stdout.txt, and both of us doing that somehow broke it. Now it seems the cause may have been something else.

Does anyone know why this is happening?

11/12 - Created from scratch an app to log a heartbeat once/second and it worked fine. Also worked once/minute. I'll have to add in pieces from the failing project until it breaks.

11/13 - I don't think there's anything special about the logger configuration.

```<code>'use strict'

const bunyan = require('bunyan');
const fs = require('fs');
const path = require('path');

const logname = 'tracker';
const folder = 'logs';
const filename = path.join(folder, logname + ".json");

if (!fs.existsSync(folder)) {
    fs.mkdirSync(folder);
}

var log = bunyan.createLogger({
    name: logname,
    streams: [{
        type: 'rotating-file',
        path: filename,
        level: process.env.LOG_LEVEL || "info",
        period: '1d',   // daily rotation
        count: 3        // keep 3 back copies
    }]
});

module.exports = { log };
</code>```

Still working on reproducing it with something less than the entire project.

11/14 - I've satisfied myself that after the bunyan logging stops the app is still continuing to call it. The "calling log2" console.logs are visible in the Azure Log Stream, but beyond ~30 seconds nothing more gets added to the bunyan log. I never see the "ERROR" logged. This is still in the context of the project, I still can't reproduce it separately.

```<code>var log2 = bunyan.createLogger({
    name: logname,
    streams: [{
        type: 'rotating-file',
        path: filename,
        level: process.env.LOG_LEVEL || "info",
        period: '1d',   // daily rotation
        count: 3        // keep 3 back copies
    }]
});

var log = {};

log.info = function() {
    console.log("calling log2.info");
    try {
    log2.info(...arguments);
    } catch(err) {
        console.log("log.info ERROR " + err);
    }
}
</code>```

11/14 - Changed from 'rotating-file' to 'file', same behavior. Enabled xxx logging and it prints the "writing log rec" message but does not add to the file. Something happened to the file stream? Added code to catch close/finish/cork right where we catch 'error' from the stream, didn't catch any of those events.

11/15 - I can see from pids and log messages that Azure is restarting my app. I don't know why, nothing in logging-errors.txt, nothing dire on stderr. I also don't know why that second run isn't logging to the file, when the first one did. But if I can figure out why it's restarting and prevent that, then I won't care about the second problem. Azure is so opaque to me.

答: After much head-banging we've determined that what we're trying to do isn't compatible with an Azure web app. We'll need to stand up a VM. Closing this question.</p>

Body:
I have a NodeJS web app and I've added logging via bunyan. Works perfectly on my desktop. On Azure it works perfectly for 1-10 seconds and then nothing else is ever logged. The app continues to run and operates correctly otherwise. I can't figure out why this is happening. Logging to a plain local file, not a blob or Azure Storage.

Log type is rotating-file, set to rotate 1/day and keep 3 days. The web app has Always On and ARR Affinity set to On, and Application Logging (Filesystem) though I'm not sure that factors here. Instance Count is 1 and Autoscale is not enabled. Node version is 8.7.0. In Console:

> df -h .
D:\home\site\wwwroot\logs
Filesystem      Size  Used Avail Use% Mounted on
-               100G -892G   99G 113% /d/home/site

Frankly I don't know what that's trying to tell me. Somehow we've used 113% of something, which is impossible. We've used a negative amount, which is impossible. There is still 99G/100G available, so we really are only using 1%. So is it a 'disk full' problem? I don't know. I haven't seen such an error message anywhere.

Prior, the app was using console.log(). We added code to intercept console.X and write to a file first, then call the normal function. The same thing happened - it would work for a few seconds and then not log anything else. I had assumed it was because some component of Azure was also intercepting console calls in order to redirect them to XXX-stdout.txt, and both of us doing that somehow broke it. Now it seems the cause may have been something else.

Does anyone know why this is happening?

11/12 - Created from scratch an app to log a heartbeat once/second and it worked fine. Also worked once/minute. I'll have to add in pieces from the failing project until it breaks.

11/13 - I don't think there's anything special about the logger configuration.

'use strict'

const bunyan = require('bunyan');
const fs = require('fs');
const path = require('path');

const logname = 'tracker';
const folder = 'logs';
const filename = path.join(folder, logname + ".json");

if (!fs.existsSync(folder)) {
    fs.mkdirSync(folder);
}

var log = bunyan.createLogger({
    name: logname,
    streams: [{
        type: 'rotating-file',
        path: filename,
        level: process.env.LOG_LEVEL || "info",
        period: '1d',   // daily rotation
        count: 3        // keep 3 back copies
    }]
});

module.exports = { log };

Still working on reproducing it with something less than the entire project.

11/14 - I've satisfied myself that after the bunyan logging stops the app is still continuing to call it. The "calling log2" console.logs are visible in the Azure Log Stream, but beyond ~30 seconds nothing more gets added to the bunyan log. I never see the "ERROR" logged. This is still in the context of the project, I still can't reproduce it separately.

var log2 = bunyan.createLogger({
    name: logname,
    streams: [{
        type: 'rotating-file',
        path: filename,
        level: process.env.LOG_LEVEL || "info",
        period: '1d',   // daily rotation
        count: 3        // keep 3 back copies
    }]
});

var log = {};

log.info = function() {
    console.log("calling log2.info");
    try {
    log2.info(...arguments);
    } catch(err) {
        console.log("log.info ERROR " + err);
    }
}

11/14 - Changed from 'rotating-file' to 'file', same behavior. Enabled xxx logging and it prints the "writing log rec" message but does not add to the file. Something happened to the file stream? Added code to catch close/finish/cork right where we catch 'error' from the stream, didn't catch any of those events.

11/15 - I can see from pids and log messages that Azure is restarting my app. I don't know why, nothing in logging-errors.txt, nothing dire on stderr. I also don't know why that second run isn't logging to the file, when the first one did. But if I can figure out why it's restarting and prevent that, then I won't care about the second problem. Azure is so opaque to me.


问:
How to create a filter that returns a forbidden result
I want to create a web api filter that checks if the request header has the correct Api key.

If it doesn't, I want to return 403 response code and halt execution (forbidden action)

```<code>public class ApiPermission : ActionFilterAttribute
{
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
}
</code>```

Using the filterContext I know I can do something like:

```<code>filterContext.Result = new RedirectTo...
</code>```

But how can I change the status code to 403 and just return a string and halt execution and stop processing other filters and the controller action?

答:
If you don't want to throw an exception, you can instead return an HttpStatusCodeResult

```<code>public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.Result != null) return;   //Another filter has already returned a result so pass it on

    //Do your filtering

    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Forbidden");
}
</code>```

Body:
I want to create a web api filter that checks if the request header has the correct Api key.

If it doesn't, I want to return 403 response code and halt execution (forbidden action)

public class ApiPermission : ActionFilterAttribute
{
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
}

Using the filterContext I know I can do something like:

filterContext.Result = new RedirectTo...

But how can I change the status code to 403 and just return a string and halt execution and stop processing other filters and the controller action?

Body:
If you don't want to throw an exception, you can instead return an HttpStatusCodeResult

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.Result != null) return;   //Another filter has already returned a result so pass it on

    //Do your filtering

    filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Forbidden");
}