问:
R: Looping a stats::filter through ddply
I'm attempting to run a series of different filters across some data, by a grouping variable. As an example, this code works to produce one filter (0.1) across a grouping variable (gear).

```<code>library(plyr)
library(BBmisc)
mtcars <- mtcars[order(mtcars$gear),]
mtcars2 <- ddply(mtcars,.(gear),transform,mpgfilter = as.numeric(stats::filter(mpg, filter=0.1, method="recursive")))
</code>```

But I want a method so I can feed in multiple filters. I was thinking of just nesting the code within a lapply function. As an example, here are the varying filters (as a list):

```<code>newdata <- as.data.frame(seq(from = 0.1, to = 0.9, by = 0.1))
newdata <- as.data.frame(t(newdata))
colnames(newdata) = newdata[1, ]
colnames(newdata) <- paste("V", colnames(newdata), sep = "_")
newlist <- convertColsToList(newdata)
</code>```

And here is what I was thinking for a solution (not working):

```<code>newlist3 <- lapply(newlist, function(y){
  mtcars2 <- ddply(mtcars,.(gear), transform, mpgfilter = as.numeric(stats::filter(mpg, filter=y, method="recursive")))
})
</code>```

Any suggestions? My final output would be a dataframe with each column showing the output from the different filters. Answer doesn't have to make use of lapply/ddply if there is a better way.

Thanks.

答:
I think I've answered my own question in a roundabout fashion, using the 'by' function instead of ddply:

```<code>new <- lapply(newlist, function(y){
by(mtcars, mtcars$gear, function(x) mpgfilter = as.numeric(stats::filter(x$mpg, filter=y, method="recursive")))})

new2 <- lapply(new, function(y){
  resultsdf <- as.data.frame(t(do.call(rbind,y)))})
df <- as.data.frame(ldply(new2, data.frame))
df2 <- melt(df)
df2 <- ddply(df2,".id",transform,ID=1:length(.id))
finaldata <- dcast(df2, ID + variable ~ .id, value.var = "value")
</code>```

Bit messy with the extra work required to get it back to a workable dataframe, but does the trick.

Body:
I'm attempting to run a series of different filters across some data, by a grouping variable. As an example, this code works to produce one filter (0.1) across a grouping variable (gear).

library(plyr)
library(BBmisc)
mtcars <- mtcars[order(mtcars$gear),]
mtcars2 <- ddply(mtcars,.(gear),transform,mpgfilter = as.numeric(stats::filter(mpg, filter=0.1, method="recursive")))

But I want a method so I can feed in multiple filters. I was thinking of just nesting the code within a lapply function. As an example, here are the varying filters (as a list):

newdata <- as.data.frame(seq(from = 0.1, to = 0.9, by = 0.1))
newdata <- as.data.frame(t(newdata))
colnames(newdata) = newdata[1, ]
colnames(newdata) <- paste("V", colnames(newdata), sep = "_")
newlist <- convertColsToList(newdata)

And here is what I was thinking for a solution (not working):

newlist3 <- lapply(newlist, function(y){
  mtcars2 <- ddply(mtcars,.(gear), transform, mpgfilter = as.numeric(stats::filter(mpg, filter=y, method="recursive")))
})

Any suggestions? My final output would be a dataframe with each column showing the output from the different filters. Answer doesn't have to make use of lapply/ddply if there is a better way.

Thanks.

Body:
I think I've answered my own question in a roundabout fashion, using the 'by' function instead of ddply:

new <- lapply(newlist, function(y){
by(mtcars, mtcars$gear, function(x) mpgfilter = as.numeric(stats::filter(x$mpg, filter=y, method="recursive")))})

new2 <- lapply(new, function(y){
  resultsdf <- as.data.frame(t(do.call(rbind,y)))})
df <- as.data.frame(ldply(new2, data.frame))
df2 <- melt(df)
df2 <- ddply(df2,".id",transform,ID=1:length(.id))
finaldata <- dcast(df2, ID + variable ~ .id, value.var = "value")

Bit messy with the extra work required to get it back to a workable dataframe, but does the trick.


来源: stackexchange

问:
CKEditor and KCfinder image preview on GoDaddy
I am having a problem with preview of image through KCFinder on CKEditor on GoDaddy hosting.

When I select the image from KCFinder the preview is loaded correctly on my local machine, but when I check on GoDaddy it is not showing correctly. Difference can be seen from below images.

I have configured the file browser in CKEditor as shown in below snippet.

```<code>config.filebrowserBrowseUrl = '../admin/kcfinder/browse.php?type=files';
config.filebrowserImageBrowseUrl = '../admin/kcfinder/browse.php?type=media';
config.filebrowserFlashBrowseUrl = '../admin/kcfinder/browse.php?type=flash';
config.filebrowserUploadUrl = '../admin/kcfinder/upload.php?type=files';
config.filebrowserImageUploadUrl = '../admin/kcfinder/upload.php?type=media';
config.filebrowserFlashUploadUrl = '../admin/kcfinder/upload.php?type=flash';
</code>```

And the KCFinder session is as follows

```<code>$_SESSION['KCFINDER']['uploadURL'] = "../upload";
$_SESSION['KCFINDER']['uploadDir'] = "../upload";
$_SESSION['KCFINDER']['disabled'] = false;
</code>```

Image preview in my localhost.

Image preview on GoDaddy hosting

The main problem I am unable to get the "upload/" directory in URL. You can see the difference in above images.

Can anyone help, how to resolve this problem?

Thanks in advance.

答:
I got the same problem, Googling for solution and I found this site. But finally I solve the problem and let me share here.

Just put the x image in the text area. By using menu 'source', check the image url. See what is the problem. If you find something like /plugins/ckeditor/file-manager/yourweb.com/...., it means that you are not put http:// in your upload dir. It should be like this :

```<code>'disabled' => false,
'uploadURL' => "https://mywebsite.com/img/upload/",
'uploadDir' => "/home/XXXXXXX/public_html/img/upload/",
'theme' => "default",
</code>```

Try to close the browser and restart again after changing that code. It works in goDaddy hosting. And I use sub domain to access the image by using https://img.mywebsite.com/upload/ ....the image.

ContentLicense: CC BY-SA 3.0

Body:
I am having a problem with preview of image through KCFinder on CKEditor on GoDaddy hosting.

When I select the image from KCFinder the preview is loaded correctly on my local machine, but when I check on GoDaddy it is not showing correctly. Difference can be seen from below images.

I have configured the file browser in CKEditor as shown in below snippet.

config.filebrowserBrowseUrl = '../admin/kcfinder/browse.php?type=files';
config.filebrowserImageBrowseUrl = '../admin/kcfinder/browse.php?type=media';
config.filebrowserFlashBrowseUrl = '../admin/kcfinder/browse.php?type=flash';
config.filebrowserUploadUrl = '../admin/kcfinder/upload.php?type=files';
config.filebrowserImageUploadUrl = '../admin/kcfinder/upload.php?type=media';
config.filebrowserFlashUploadUrl = '../admin/kcfinder/upload.php?type=flash';

And the KCFinder session is as follows

$_SESSION['KCFINDER']['uploadURL'] = "../upload";
$_SESSION['KCFINDER']['uploadDir'] = "../upload";
$_SESSION['KCFINDER']['disabled'] = false;

Image preview in my localhost.

Image preview on GoDaddy hosting

The main problem I am unable to get the "upload/" directory in URL. You can see the difference in above images.

Can anyone help, how to resolve this problem?

Thanks in advance.

Body:
I got the same problem, Googling for solution and I found this site. But finally I solve the problem and let me share here.

Just put the x image in the text area. By using menu 'source', check the image url. See what is the problem. If you find something like /plugins/ckeditor/file-manager/yourweb.com/...., it means that you are not put http:// in your upload dir. It should be like this :

'disabled' => false,
'uploadURL' => "https://mywebsite.com/img/upload/",
'uploadDir' => "/home/XXXXXXX/public_html/img/upload/",
'theme' => "default",

Try to close the browser and restart again after changing that code. It works in goDaddy hosting. And I use sub domain to access the image by using https://img.mywebsite.com/upload/ ....the image.


问:
Vertx SockJs Eventbus Authentication
I'm trying to make a sock.js connection from the frontend to the vertx backend.

my initial try looked like this:

```<code>let token = '<the token>';
let data = {'Authorization' : 'Bearer ' + token};
let eb = new EventBus("http://localhost:8080/eventbus");
  eb.onopen = function () {
  eb.registerHandler('notifications', data, (err, msg) =>  {
    // handle the response
  });
}
</code>```

this doesn't work since I need to send the auth data on EventBus creation, even though the official sock.js documentation states that this is not supported. Obviously now sending new EventBus("http://localhost:9090/eventbus", data) doesn't work either.

https://github.com/sockjs/sockjs-node#authorisation

my backend handler for this:

```<code>final BridgeOptions bridgeOptions = new BridgeOptions()
  .addOutboundPermitted(new PermittedOptions().setAddress("notifications"))

final SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(bridgeOptions, event -> {
  event.complete(true);
});

router.route("/eventbus/*").handler(ctx -> {
  String token = ctx.request().getHeader("Authorization"); // null
});
router.route("/eventbus/*").handler(sockJSHandler);
</code>```

whatever I tried the header field Authroization is always null.

What is the standard way to authenticate the sock.js connection and register to an eventbus request in vertx?

答:
SockJS uses WebSockets by default. You can't add custom headers (Authorization, etc) using JavaScript WebSocket API. Read this thread for more explanation.

I see 2 ways, how you can add authorization:

Just add token parameter to URL:

```<code>let eb = new EventBus("http://localhost:8080/eventbus?token=" + token);
</code>```

and here's how you can get it on a server:

```<code>String token = ctx.request().getParam("token");
</code>```

Send authorization message after connecting to the server. It can be some JSON object, which contains token field.

I think, 1st option is enough, however, 2nd one can be harder to implement in terms of Event Bus and SockJS.

Title: Vertx SockJs Eventbus Authentication

Body:
I'm trying to make a sock.js connection from the frontend to the vertx backend.

my initial try looked like this:

let token = '<the token>';
let data = {'Authorization' : 'Bearer ' + token};
let eb = new EventBus("http://localhost:8080/eventbus");
  eb.onopen = function () {
  eb.registerHandler('notifications', data, (err, msg) =>  {
    // handle the response
  });
}

this doesn't work since I need to send the auth data on EventBus creation, even though the official sock.js documentation states that this is not supported. Obviously now sending new EventBus("http://localhost:9090/eventbus", data) doesn't work either.

https://github.com/sockjs/sockjs-node#authorisation

my backend handler for this:

final BridgeOptions bridgeOptions = new BridgeOptions()
  .addOutboundPermitted(new PermittedOptions().setAddress("notifications"))

final SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(bridgeOptions, event -> {
  event.complete(true);
});

router.route("/eventbus/*").handler(ctx -> {
  String token = ctx.request().getHeader("Authorization"); // null
});
router.route("/eventbus/*").handler(sockJSHandler);

whatever I tried the header field Authroization is always null.

What is the standard way to authenticate the sock.js connection and register to an eventbus request in vertx?

Body:
SockJS uses WebSockets by default. You can't add custom headers (Authorization, etc) using JavaScript WebSocket API. Read this thread for more explanation.

I see 2 ways, how you can add authorization:

Just add token parameter to URL:

let eb = new EventBus("http://localhost:8080/eventbus?token=" + token);

and here's how you can get it on a server:

String token = ctx.request().getParam("token");

Send authorization message after connecting to the server. It can be some JSON object, which contains token field.

I think, 1st option is enough, however, 2nd one can be harder to implement in terms of Event Bus and SockJS.


问:
bootstrap sidebar no bg color
Hey i have tried a lot to give the background color of my sidebar from my bootstrap a color but it doesnt work.

here is my code from the page

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <title>ToolsForEver</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1""> <!-- een viewport is de userscreen  dus we gebruiken 100% normale zoom -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="../style.css">
</head>

<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container-fluid">
    <!-- Dit is voor de logo en dat de je een kleine soort dropdown ziet waarmee je op kleinere toestellen ook beter kan besturen -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="../afbeeldingen/tools.png">ToolsForEver</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">contact <span class="sr-only">(current)</span></a></li>
        <li><a href="#">Link</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>    <a href="uitloggen.php" class="btn btn-info" role="button">Uitloggen</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->

</nav>
            <!-- Sidebar -->
        <div id="sidebar">
            <ul class="sidebar-nav">
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
                <li>
                    <a href="#">Beheer Medewerkers</a>
                </li>
                <li>
                    <a href="#">Beheer Locaties</a>
                </li>
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
                <li>
                    <a href="#">Beheer Voorraad</a>
                </li>
            </ul>
        </div>

<div class = "container">
    <div class = "jumbotron">
        <img src="../afbeeldingen/toolsforever.jpg" alt="ToolsForever" class="img-responsive">
    </div>
</body>
</html>

<?php session_start();
//als session leeg is dan doe je dit
if(empty($_SESSION['email']))
{
    header("location:../index.php");
}

    include 'footer.php';
?>
</code>```

Here is my code of my css file

```<code>body {
    padding-top: 65px;
    padding-left: 135px;
}

.container{
    padding-top: 65px;
    padding-left: 135px;
}

#sidebar{
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    color: blue;
}

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: black;
}
</code>```

Can you guys please help me ;)

thank you!

答: I think you would actually need to set background: blue on the sidebar-nav class instead of the sidebar id

Title: bootstrap sidebar no bg color

Body:
Hey i have tried a lot to give the background color of my sidebar from my bootstrap a color but it doesnt work.

here is my code from the page

<!DOCTYPE html>

    <title>ToolsForEver</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1"">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="../style.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      ToolsForEver

contact (current)

Link

    Uitloggen

                    Beheer Voorraad

                    Beheer Medewerkers

                    Beheer Locaties

                    Beheer Voorraad

                    Beheer Voorraad

<?php session_start();
//als session leeg is dan doe je dit
if(empty($_SESSION['email']))
{
    header("location:../index.php");
}

    include 'footer.php';
?>

Here is my code of my css file

body {
    padding-top: 65px;
    padding-left: 135px;
}

.container{
    padding-top: 65px;
    padding-left: 135px;
}

#sidebar{
    position: fixed;
    left: 250px;
    width: 0;
    height: 100%;
    margin-left: -250px;
    color: blue;
}

.sidebar-nav {
    position: absolute;
    top: 0;
    width: 250px;
    margin: 0;
    padding: 0;
    list-style: none;
}

.sidebar-nav li {
    text-indent: 20px;
    line-height: 40px
}

.sidebar-nav li a {
    display: block;
    text-decoration: none;
    color: black;
}

Can you guys please help me ;)

thank you!


问:
Set magic line width to the anchor not the list item
Hello I am using a magic line and I get it working, but the width of the magic line is taking the width of the
 element, but I want it to take the width of the  element. Can anyone help me edit the jquery code to do this?

Here is the html:

```<code><ul id="menu-main-menu">
    <li><a href="#">text</a></li>
    <li><a href="#">text text</a></li>
    <li><a href="#">text text text</a></li>
    <li><a href="#">text text text text</a></li>
</ul>
</code>```

css:

```<code>#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}
</code>```

jquery (sorry about the length)

```<code>jQuery(function() {

    var $el, leftPos, newWidth,
        $mainNav = jQuery("#menu-main-menu");

    $mainNav.append("<li id='magic-line'></li>");
    var $magicLine = jQuery("#magic-line");

    if( jQuery('#menu-main-menu .current-menu-ancestor').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().position().left;
    }

    if( jQuery('#menu-main-menu .current-menu-item').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-item > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-item > a').parent().position().left;
    }

    $magicLine
        .width(currentPageWidth)
        .css("left", currentPageLeft)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    jQuery("#menu-main-menu li").hover(function() {
        $el = jQuery(this);
        leftPos = $el.position().left;
        newWidth = $el.width();
        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });

    jQuery("#menu-main-menu li .sub-menu li").hover(function() {
        $magicLine.stop()
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
}, 1500);
</code>```

and the jsfiddle

here

Thanks!

答:
I forked your fiddle.

A note before we start: for simplicity, I stripped out parts of your function not related to the actual markup included in the fiddle, but you may need to modify what you had if it's relevant to your actual project.

So the first problem was that the variables currentPageWidth and currentPageLeft were undefined because there was no element in the HTML matching their definition. Since you wanted the width of the link and not the li, I created new variables for this purpose:

```<code>var linkWidth = $($mainNav).find('li:first-child a').width();
var linkLeft = $($mainNav).find('li:first-child a').offset().left;
</code>```

Then we update the hover function to refer to the links within each li instead of the li directly:

```<code>jQuery($mainNav).find('li').hover(function() {
  leftPos = jQuery(this).find('a').offset().left;
  newWidth = jQuery(this).find('a').width();
  ...
</code>```

Finally, I changed your use of .position() to .offset() so that we would get the left distance of each link relative to the document. Left positioning did not seem to work as intended with .position() after the above changes were made.

(Also I changed the hover function to use the $mainNav variable you had already created.)

Hope that helps.

jQuery(function() {

        var $el, leftPos, newWidth,
            $mainNav = jQuery("#menu-main-menu");

        $mainNav.append("

");
        var $magicLine = jQuery("#magic-line");

        var linkWidth = $($mainNav).find('li:first-child a').width();
        var linkLeft = $($mainNav).find('li:first-child a').offset().left;

        $magicLine
            .width(linkWidth)
            .css("left", linkLeft)
            .data("origLeft", $magicLine.offset().left)
            .data("origWidth", $magicLine.width());

          jQuery($mainNav).find('li').hover(function() {
              leftPos = jQuery(this).find('a').offset().left;
              newWidth = jQuery(this).find('a').width();
              $magicLine.stop().animate({
                  left: leftPos,
                  width: newWidth
              });
          }, function() {
              $magicLine.stop().animate({
                  left: $magicLine.data("origLeft"),
                  width: $magicLine.data("origWidth")
              });
          });

    }, 1500);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}</code>```

text

text text

text text text

text text text text

```

Body:
Hello I am using a magic line and I get it working, but the width of the magic line is taking the width of the
 element, but I want it to take the width of the  element. Can anyone help me edit the jquery code to do this?

Here is the html:

text

text text

text text text

text text text text

css:

#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}

jquery (sorry about the length)

jQuery(function() {

    var $el, leftPos, newWidth,
        $mainNav = jQuery("#menu-main-menu");

    $mainNav.append("

");
    var $magicLine = jQuery("#magic-line");

    if( jQuery('#menu-main-menu .current-menu-ancestor').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-ancestor > a').parent().position().left;
    }

    if( jQuery('#menu-main-menu .current-menu-item').length ) {
        var currentPageWidth = jQuery('#menu-main-menu .current-menu-item > a').parent().width();
        var currentPageLeft = jQuery('#menu-main-menu .current-menu-item > a').parent().position().left;
    }

    $magicLine
        .width(currentPageWidth)
        .css("left", currentPageLeft)
        .data("origLeft", $magicLine.position().left)
        .data("origWidth", $magicLine.width());

    jQuery("#menu-main-menu li").hover(function() {
        $el = jQuery(this);
        leftPos = $el.position().left;
        newWidth = $el.width();
        $magicLine.stop().animate({
            left: leftPos,
            width: newWidth
        });
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });

    jQuery("#menu-main-menu li .sub-menu li").hover(function() {
        $magicLine.stop()
    }, function() {
        $magicLine.stop().animate({
            left: $magicLine.data("origLeft"),
            width: $magicLine.data("origWidth")
        });
    });
}, 1500);

and the jsfiddle

here

Thanks!

Body:
I forked your fiddle.

A note before we start: for simplicity, I stripped out parts of your function not related to the actual markup included in the fiddle, but you may need to modify what you had if it's relevant to your actual project.

So the first problem was that the variables currentPageWidth and currentPageLeft were undefined because there was no element in the HTML matching their definition. Since you wanted the width of the link and not the li, I created new variables for this purpose:

var linkWidth = $($mainNav).find('li:first-child a').width();
var linkLeft = $($mainNav).find('li:first-child a').offset().left;

Then we update the hover function to refer to the links within each li instead of the li directly:

jQuery($mainNav).find('li').hover(function() {
  leftPos = jQuery(this).find('a').offset().left;
  newWidth = jQuery(this).find('a').width();
  ...

Finally, I changed your use of .position() to .offset() so that we would get the left distance of each link relative to the document. Left positioning did not seem to work as intended with .position() after the above changes were made.

(Also I changed the hover function to use the $mainNav variable you had already created.)

Hope that helps.

jQuery(function() {

        var $el, leftPos, newWidth,
            $mainNav = jQuery("#menu-main-menu");

        $mainNav.append("<li id='magic-line'></li>");
        var $magicLine = jQuery("#magic-line");

        var linkWidth = $($mainNav).find('li:first-child a').width();
        var linkLeft = $($mainNav).find('li:first-child a').offset().left;

        $magicLine
            .width(linkWidth)
            .css("left", linkLeft)
            .data("origLeft", $magicLine.offset().left)
            .data("origWidth", $magicLine.width());

          jQuery($mainNav).find('li').hover(function() {
              leftPos = jQuery(this).find('a').offset().left;
              newWidth = jQuery(this).find('a').width();
              $magicLine.stop().animate({
                  left: leftPos,
                  width: newWidth
              });
          }, function() {
              $magicLine.stop().animate({
                  left: $magicLine.data("origLeft"),
                  width: $magicLine.data("origWidth")
              });
          });

    }, 1500);

#menu-main-menu {
  display: flex;
}

#menu-main-menu li {
  flex: 1 1 100%;
  text-align: center;
  list-style-type: none;
  position: relative;
}

#menu-main-menu li a {
  padding: 0 10px;
}

#magic-line {
    position: absolute !important;
    top: 0px;
    left: 0;
    width: 100px;
    height: 2px;
    background: #000;
    padding-top: 0 !important;
    margin-right: 0 !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu-main-menu">
    <li><a href="#">text</a></li>
    <li><a href="#">text text</a></li>
    <li><a href="#">text text text</a></li>
    <li><a href="#">text text text text</a></li>
</ul>


问:
Worst & Best Player based on PPG
I'm trying to output the best and worst players based on their points-per-game.

My issue is with calculating worstPlayer. I don't know how to keep track of bestPPG relative to my other if-statement, or else I feel that I have the right idea. I've tried this for 2 days, no luck.

By the way, I'm not trying to use functions, just conditional statements, unless I have to? Then why not. Also, ignore the unnecessary use of headers, learning via tutorials at the moment.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main() {
    int i;
    int player[5] = {58, 66, 68, 71, 87};
    int goals[5] = {26, 39, 25, 29, 31};
    int gamesPlayed[5] = {30,30,28,30,26};
    float ppg[5];
    float bestPPG = 0.0;
    float worstPPG = 0.0;
    int bestPlayer;
    int worstPlayer;

    for(i=0; i<5; i++) {

        ppg[i] = (float)goals[i] / (float)gamesPlayed[i];
        printf("%d \t %d \t %d \t %.2f \n",player[i],goals[i],
gamesPlayed[i],ppg[i]);

        if ( ppg[i] > bestPPG ) {

            if(bestPPG == 0.0)
            {
                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            if (ppg[i] < worstPPG)
            {

                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            bestPPG = ppg[i];
            bestPlayer = player[i];

        }

        if ( ppg[i] < bestPPG )
        {
            if ( ppg[i] < worstPPG ) {

                worstPPG = ppg[i];
                worstPlayer = ppg[i];
            }
        }

    }

    printf("\nThe best player is: %d \n", bestPlayer);
    printf("The worst player is: %d \n", worstPlayer);

    return 0;

}
</code>```

Thank you!

答:
Try to keep it simple : when you compute a new ppg either it is better than the bestPPG you have in memory (then you update the variable bestPPG with ppg) or it is lower than the worstPPG (then you update the variable worstPPG with ppg) or it is between (then you do nothing)

Beware of the initialisation of your variables : worstPPG is initialized to 0 but you'll never get a ppg under 0. Either you initialize it to plus infinity (see this post for that), or you initilize it with the first value you compute.

In the loop, your code should look like that :

```<code>//compute ppg and display
if(ppg[i] < worstPPG){
    worstPPPG = ppg[i];
    worstPlayer = player[i];
}
else if(ppg[i] > bestPPG){
    bestPPG = ppg[i];
    besPlayer = player[i];
}
</code>```

Title: Worst & Best Player based on PPG

Body:
I'm trying to output the best and worst players based on their points-per-game.

My issue is with calculating worstPlayer. I don't know how to keep track of bestPPG relative to my other if-statement, or else I feel that I have the right idea. I've tried this for 2 days, no luck.

By the way, I'm not trying to use functions, just conditional statements, unless I have to? Then why not. Also, ignore the unnecessary use of headers, learning via tutorials at the moment.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main() {
    int i;
    int player[5] = {58, 66, 68, 71, 87};
    int goals[5] = {26, 39, 25, 29, 31};
    int gamesPlayed[5] = {30,30,28,30,26};
    float ppg[5];
    float bestPPG = 0.0;
    float worstPPG = 0.0;
    int bestPlayer;
    int worstPlayer;

    for(i=0; i<5; i++) {

        ppg[i] = (float)goals[i] / (float)gamesPlayed[i];
        printf("%d \t %d \t %d \t %.2f \n",player[i],goals[i],
gamesPlayed[i],ppg[i]);

        if ( ppg[i] > bestPPG ) {

            if(bestPPG == 0.0)
            {
                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            if (ppg[i] < worstPPG)
            {

                worstPPG = ppg[i];
                worstPlayer = player[i];
            }

            bestPPG = ppg[i];
            bestPlayer = player[i];

        }

        if ( ppg[i] < bestPPG )
        {
            if ( ppg[i] < worstPPG ) {

                worstPPG = ppg[i];
                worstPlayer = ppg[i];
            }
        }

    }

    printf("\nThe best player is: %d \n", bestPlayer);
    printf("The worst player is: %d \n", worstPlayer);

    return 0;

}

Thank you!

Body:
Try to keep it simple : when you compute a new ppg either it is better than the bestPPG you have in memory (then you update the variable bestPPG with ppg) or it is lower than the worstPPG (then you update the variable worstPPG with ppg) or it is between (then you do nothing)

Beware of the initialisation of your variables : worstPPG is initialized to 0 but you'll never get a ppg under 0. Either you initialize it to plus infinity (see this post for that), or you initilize it with the first value you compute.

In the loop, your code should look like that :

//compute ppg and display
if(ppg[i] < worstPPG){
    worstPPPG = ppg[i];
    worstPlayer = player[i];
}
else if(ppg[i] > bestPPG){
    bestPPG = ppg[i];
    besPlayer = player[i];
}


问:
Equivalent of reference 'Copy Local' in ASP.NET Web Site project
I don't see any exact duplicates in the Related Questions above, so here goes.  Please don't stone me if it is a duplicate.

Is there any way to achieve the same end as setting 'Copy Local' to True on a web application reference?  I could probably map a custom config section to the <compilation><assemblies> config section, and simple copy all assemblies to local, but that would be quite rude.  Should I be looking at tapping into a build provider or something?  I think the main issue here is identifying listed assemblies not normally present on the target platform, but this seems a very difficult task to me without simply using a hard-coded list, which will be out of date very quickly.

答:
You could add the necessary references to copy in the post-build event perhaps?
or edit the .csproj file in any other way that would help achieve it.

For example you could have the copy section only happen during release builds.

ContentLicense: CC BY-SA 2.5


问:
JQuery .serializeArray() How to get access data in Json Object
I'm using jquery .serializeArray() to get all the <input> in a <form>.
I'm putting the Json object that comes out of .serializeArray() into jquery .data()

How do I find the data I want out of the Json object?

Jquery getJson() needs a url but I'm I already have the Json Object.

答:
jQuery.serializeArray() returns an array

```<code>[{
   name: "a",
   value: "1"
 },{
   name: "b",
   value: "2"
 },{
   name: "c",
   value: "3"
 },{
   name: "d",
   value: "4"
 },{
   name: "e",
   value: "5"
 }
]
</code>```

this code relies on Array.prototype.reduce

```<code>var formArray = $('#formid).serializeArray();
formArray.reduce(function(acc, cur, i) {
  acc[cur.name] = cur.value;
  return acc;
}, {});
</code>```

to yield this object

```<code>{
    a: "1",
    b: "2",
    c: "3",
    d: "4",
    e: "5"
}
</code>```

Body:
jQuery.serializeArray() returns an array

[{
   name: "a",
   value: "1"
 },{
   name: "b",
   value: "2"
 },{
   name: "c",
   value: "3"
 },{
   name: "d",
   value: "4"
 },{
   name: "e",
   value: "5"
 }
]

this code relies on Array.prototype.reduce

var formArray = $('#formid).serializeArray();
formArray.reduce(function(acc, cur, i) {
  acc[cur.name] = cur.value;
  return acc;
}, {});

to yield this object

{
    a: "1",
    b: "2",
    c: "3",
    d: "4",
    e: "5"
}


问:
reasonml - array or list of tuples
I have tuple type foo = (string, string);.

How to create type - array of foo tuples?

What is the difference if use array of tuples or list of tuples?

How to access array of tuples values?
JS analog:

```<code>const foo1 = [1, 2];
const foo2 = [3, 4];
const arrayOfFoo =[foo1, foo2];

console.log(arrayOfFoo[0][0]) // 1
console.log(arrayOfFoo[1][1]) // 4
</code>```

UPDATE: I found excelent gitbook

https://kennetpostigo.gitbooks.io/an-introduction-to-reason/content/

```<code>/* create tuple type*/
type t = (int, int);

/* create array of tuples */
type arrayOfT = array t;

/* create array of tuples */
type listOfT = list t;

/* create list of tuples value */
let values: listOfT = [(0, 1), (2, 3)];

/* get first tuple  */
let firstTyple: t = List.nth values 0;

/* get first tuple values  */
let (f, s) = firstTyple;
</code>```

Is this correct? Ot there is more useful way to do this?

答:
let x: list (int, int) = [(1,2), (3,4)] /* etc */

2.

An Array fixed-length & mutable, and provides easy random access. It is very similar to a JavaScript list. Use it for things that need random access (read/write) much more than append/pop.

A List is a singly-linked list & is immutable. It will be familiar to folks coming from functional traditions. Use it for things where accessing the first element or pushing/popping from the front is more common than random access.

In practice, I use List for just about everything, but Array for some performance-intensive situations.

3.

Getting the first thing from a list is super common. Often, you want to both do something with the first thing, and then do something with the "rest" of the list. To be thorough, you also want to handle the case where the list is empty. Here's what that looks like:

```<code>switch (somelist) {
  | [] => Js.log "nothing there" /* what we do if the list is empty */
  | [firstItem, ...rest] => Js.log firstItem /* we have things! */
}
</code>```

If you just want to get the first item, and you're ok w/ your program crashing if it happens to be empty, you can do List.hd mylist.

Getting items out of a tuple is like you put, let (a, b) = sometuple. If you only care about the first one, you can do let (a, _) = sometuple (_ is a special placeholder that means "I don't care what this is"). For length-2 tuples there are special helper functions fst and snd, which get the first and second items out for you.

Title: reasonml - array or list of tuples

Body:
I have tuple type foo = (string, string);.

How to create type - array of foo tuples?

What is the difference if use array of tuples or list of tuples?

How to access array of tuples values?
JS analog:

const foo1 = [1, 2];
const foo2 = [3, 4];
const arrayOfFoo =[foo1, foo2];

console.log(arrayOfFoo[0][0]) // 1
console.log(arrayOfFoo[1][1]) // 4

UPDATE: I found excelent gitbook

https://kennetpostigo.gitbooks.io/an-introduction-to-reason/content/

/* create tuple type*/
type t = (int, int);

/* create array of tuples */
type arrayOfT = array t;

/* create array of tuples */
type listOfT = list t;

/* create list of tuples value */
let values: listOfT = [(0, 1), (2, 3)];

/* get first tuple  */
let firstTyple: t = List.nth values 0;

/* get first tuple values  */
let (f, s) = firstTyple;

Is this correct? Ot there is more useful way to do this?

Body:
let x: list (int, int) = [(1,2), (3,4)] /* etc */

2.

An Array fixed-length & mutable, and provides easy random access. It is very similar to a JavaScript list. Use it for things that need random access (read/write) much more than append/pop.

A List is a singly-linked list & is immutable. It will be familiar to folks coming from functional traditions. Use it for things where accessing the first element or pushing/popping from the front is more common than random access.

In practice, I use List for just about everything, but Array for some performance-intensive situations.

3.

Getting the first thing from a list is super common. Often, you want to both do something with the first thing, and then do something with the "rest" of the list. To be thorough, you also want to handle the case where the list is empty. Here's what that looks like:

switch (somelist) {
  | [] => Js.log "nothing there" /* what we do if the list is empty */
  | [firstItem, ...rest] => Js.log firstItem /* we have things! */
}

If you just want to get the first item, and you're ok w/ your program crashing if it happens to be empty, you can do List.hd mylist.

Getting items out of a tuple is like you put, let (a, b) = sometuple. If you only care about the first one, you can do let (a, _) = sometuple (_ is a special placeholder that means "I don't care what this is"). For length-2 tuples there are special helper functions fst and snd, which get the first and second items out for you.


问:
How to pass a parameter as a default?
I want to use the default of a parameter, but include its name in the call. I thought that setting the parameter to None would do that, but it doesn't.

For example:

```<code>def a(num=3):
    print(num)

a(num=None) #returns "None", not "3" like I want it to.
</code>```

How can I use the default of a named parameter while including it in the call? (Is it even possible?)

Just to explain why I would want to do something like this (since maybe it's a problem in my overall coding style):

I often times have code like this

```<code>def add(num, numToAdd=1):
    return num+numToAdd

def addTwice(num, numToAdd=None):
    for i in range(2):
        num=add(num, numToAdd=numToAdd)
    return num

addTwice(3) #throws an error instead of returning 5
</code>```

What I want is for addTwice's numToAdd to always use the default of add's numToAdd, no matter what it is.

The reason: maybe later in the code I realize that it's better to add 2 as the default when executing add than it is to add 1.

So I change it to

```<code>def add(num, numToAdd=2):
        return num+numToAdd
</code>```

But, this won't help anything unless I can always specify in addTwice to use the default if it receives a default.

So, that's the rationale.

In other words: I'm having a function (the first function) call another function (the second function), and if the first function has to use a default value, I want it to default to being the default value on the second function. That way, I only have to change the default value on the second function (not every single function that calls it as well) in order to change the default functionality.

答: No, you can't: that's a contradiction in terms.  The default value is used if and only if you do not supply a value in the arguments list.  If you supply a value, then the default cannot be used within the routine.

Title: How to pass a parameter as a default?

Body:
I want to use the default of a parameter, but include its name in the call. I thought that setting the parameter to None would do that, but it doesn't.

For example:

def a(num=3):
    print(num)

a(num=None) #returns "None", not "3" like I want it to.

How can I use the default of a named parameter while including it in the call? (Is it even possible?)

Just to explain why I would want to do something like this (since maybe it's a problem in my overall coding style):

I often times have code like this

def add(num, numToAdd=1):
    return num+numToAdd

def addTwice(num, numToAdd=None):
    for i in range(2):
        num=add(num, numToAdd=numToAdd)
    return num

addTwice(3) #throws an error instead of returning 5

What I want is for addTwice's numToAdd to always use the default of add's numToAdd, no matter what it is.

The reason: maybe later in the code I realize that it's better to add 2 as the default when executing add than it is to add 1.

So I change it to

def add(num, numToAdd=2):
        return num+numToAdd

But, this won't help anything unless I can always specify in addTwice to use the default if it receives a default.

So, that's the rationale.

In other words: I'm having a function (the first function) call another function (the second function), and if the first function has to use a default value, I want it to default to being the default value on the second function. That way, I only have to change the default value on the second function (not every single function that calls it as well) in order to change the default functionality.


答:
```<code>def a(num=None):
    if num is None:
       num = 3
    print(num)

a(num=None)  # prints 3
a() # prints 3
</code>```

... I guess ... maybe

alternatively to explain default params

```<code>def a(num=3):
   print(num)

a(num=None) # prints None
a() # prints 3
</code>```

Title: How to pass a parameter as a default?

Body:
def a(num=None):
    if num is None:
       num = 3
    print(num)

a(num=None)  # prints 3
a() # prints 3

... I guess ... maybe

alternatively to explain default params

def a(num=3):
   print(num)

a(num=None) # prints None
a() # prints 3


问:
YouTube Data API - Retrieve my uploads (getting started tutorial)
I try to get started with the YouTube Data v3 API. I found this example on the official site.

My attempt (censored API-Key and other sensitive data):

index.html

```<code><!doctype html>
<html>
  <head>
    <title>My Uploads</title>
    <link rel="stylesheet" type="text/css" href="my_uploads.css">
  </head>
  <body>

    <!--Add buttons to initiate auth sequence and sign out-->
    <button id="authorize-button" style="display: none;">Authorize</button>
    <button id="signout-button" style="display: none;">Sign Out</button>

    <div id="content"></div>

    <div id="login-container" class="pre-auth">
      This application requires access to your YouTube account.
      Please <a href="#" id="login-link">authorize</a> to continue.
    </div>

    <div id="video-container"></div>
    <div class="button-container">
      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="auth.js"></script>
    <script type="text/javascript" src="my_uploads.js"></script>
    <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
  </body>
</html>
</code>```

my_upload.js

```<code>// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;

// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
  requestUserUploadsPlaylistId();
}

// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
  // See https://developers.google.com/youtube/v3/docs/channels/list
  var request = gapi.client.youtube.channels.list({
    mine: true,
    part: 'contentDetails'
  });
  request.execute(function(response) {
    playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
    requestVideoPlaylist(playlistId);
  });
}

// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 10
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    // Only show pagination buttons if there is a pagination token for the
    // next or previous page of results.
    nextPageToken = response.result.nextPageToken;
    var nextVis = nextPageToken ? 'visible' : 'hidden';
    $('#next-button').css('visibility', nextVis);
    prevPageToken = response.result.prevPageToken
    var prevVis = prevPageToken ? 'visible' : 'hidden';
    $('#prev-button').css('visibility', prevVis);

    var playlistItems = response.result.items;
    if (playlistItems) {
      $.each(playlistItems, function(index, item) {
        displayResult(item.snippet);
      });

 } else {
      $('#video-container').html('Sorry you have no uploaded videos');
    }
  });
}

// Create a listing for a video.
function displayResult(videoSnippet) {
  var title = videoSnippet.title;
  var videoId = videoSnippet.resourceId.videoId;
  $('#video-container').append('<p>' + title + ' - ' + videoId + '</p>');
}

// Retrieve the next page of videos in the playlist.
function nextPage() {
  requestVideoPlaylist(playlistId, nextPageToken);
}

// Retrieve the previous page of videos in the playlist.
function previousPage() {
  requestVideoPlaylist(playlistId, prevPageToken);
}
</code>```

auth.js

```<code>var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}

  // Enter an API key from the Google API Console:
  //   https://console.developers.google.com/apis/credentials
  var apiKey = "censored";

  // Enter the API Discovery Docs that describes the APIs you want to
  // access. In this example, we are accessing the People API, so we load
  // Discovery Doc found here: https://developers.google.com/people/api/rest/
  var discoveryDocs = ["https://people.googleapis.com/discovery/rest?version=v1"];

  // Enter a client ID for a web application from the Google API Console:
  //   https://console.developers.google.com/apis/credentials?project=_
  // In your API Console project, add a JavaScript origin that corresponds
  //   to the domain where you will be running the script.
  var clientId = myInfos.web.client_id;

  // Enter one or more authorization scopes. Refer to the documentation for
  // the API or https://developers.google.com/people/v1/how-tos/authorizing
  // for details.
  var scopes = 'profile';
  var authorizeButton = document.getElementById('authorize-button');
  var signoutButton = document.getElementById('signout-button');
  function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
  }
  function initClient() {
    gapi.client.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
    }
  }
  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
  }
</code>```

my_uploads.css

```<code>.paging-button {
  visibility: hidden;
}

.button-container {
  clear: both;
}
</code>```

But I only get a blank page with the following result:

This application requires access to your YouTube account. Please authorize to continue.

And If I click the link, then nothing happens. What might be the problem?

答:
Your error seems to be associated with this:

"Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
  If the currently logged-in Google Account has previously authorized
  the client specified as the OAUTH2_CLIENT_ID, then the authorization
  succeeds with no user intervention. Otherwise, it fails and the user
  interface that prompts for authorization needs to display"

function checkAuth() {
  gapi.auth.authorize({
    client_id: OAUTH2_CLIENT_ID,
    scope: OAUTH2_SCOPES,
    immediate: true
  }, handleAuthResult);
}

"Otherwise, it fails and the user interface that prompts for
  authorization needs to display".

^^ Gives you :

"This application requires access to your YouTube account. Please
  authorize to continue."

You need to authorize the google account currently logged in.

Use these sources and it'll solve your issue:

https://developers.google.com/youtube/v3/guides/authentication

https://developers.google.com/youtube/registering_an_application

Body:
I try to get started with the YouTube Data v3 API. I found this example on the official site.

My attempt (censored API-Key and other sensitive data):

index.html

<!doctype html>

    <title>My Uploads</title>
    <link rel="stylesheet" type="text/css" href="my_uploads.css">

    <button id="authorize-button" style="display: none;">Authorize</button>
    <button id="signout-button" style="display: none;">Sign Out</button>

      This application requires access to your YouTube account.
      Please authorize to continue.

      <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
      <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>

my_upload.js

// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;

// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
  requestUserUploadsPlaylistId();
}

// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
  // See https://developers.google.com/youtube/v3/docs/channels/list
  var request = gapi.client.youtube.channels.list({
    mine: true,
    part: 'contentDetails'
  });
  request.execute(function(response) {
    playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
    requestVideoPlaylist(playlistId);
  });
}

// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 10
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    // Only show pagination buttons if there is a pagination token for the
    // next or previous page of results.
    nextPageToken = response.result.nextPageToken;
    var nextVis = nextPageToken ? 'visible' : 'hidden';
    $('#next-button').css('visibility', nextVis);
    prevPageToken = response.result.prevPageToken
    var prevVis = prevPageToken ? 'visible' : 'hidden';
    $('#prev-button').css('visibility', prevVis);

    var playlistItems = response.result.items;
    if (playlistItems) {
      $.each(playlistItems, function(index, item) {
        displayResult(item.snippet);
      });

 } else {
      $('#video-container').html('Sorry you have no uploaded videos');
    }
  });
}

// Create a listing for a video.
function displayResult(videoSnippet) {
  var title = videoSnippet.title;
  var videoId = videoSnippet.resourceId.videoId;
  $('#video-container').append('
' + title + ' - ' + videoId + '
');
}

// Retrieve the next page of videos in the playlist.
function nextPage() {
  requestVideoPlaylist(playlistId, nextPageToken);
}

// Retrieve the previous page of videos in the playlist.
function previousPage() {
  requestVideoPlaylist(playlistId, prevPageToken);
}

auth.js

var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}

  // Enter an API key from the Google API Console:
  //   https://console.developers.google.com/apis/credentials
  var apiKey = "censored";

  // Enter the API Discovery Docs that describes the APIs you want to
  // access. In this example, we are accessing the People API, so we load
  // Discovery Doc found here: https://developers.google.com/people/api/rest/
  var discoveryDocs = ["https://people.googleapis.com/discovery/rest?version=v1"];

  // Enter a client ID for a web application from the Google API Console:
  //   https://console.developers.google.com/apis/credentials?project=_
  // In your API Console project, add a JavaScript origin that corresponds
  //   to the domain where you will be running the script.
  var clientId = myInfos.web.client_id;

  // Enter one or more authorization scopes. Refer to the documentation for
  // the API or https://developers.google.com/people/v1/how-tos/authorizing
  // for details.
  var scopes = 'profile';
  var authorizeButton = document.getElementById('authorize-button');
  var signoutButton = document.getElementById('signout-button');
  function handleClientLoad() {
    // Load the API client and auth2 library
    gapi.load('client:auth2', initClient);
  }
  function initClient() {
    gapi.client.init({
        apiKey: apiKey,
        discoveryDocs: discoveryDocs,
        clientId: clientId,
        scope: scopes
    }).then(function () {
      // Listen for sign-in state changes.
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      // Handle the initial sign-in state.
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton.onclick = handleAuthClick;
      signoutButton.onclick = handleSignoutClick;
    });
  }
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      authorizeButton.style.display = 'none';
      signoutButton.style.display = 'block';
    } else {
      authorizeButton.style.display = 'block';
      signoutButton.style.display = 'none';
    }
  }
  function handleAuthClick(event) {
    gapi.auth2.getAuthInstance().signIn();
  }
  function handleSignoutClick(event) {
    gapi.auth2.getAuthInstance().signOut();
  }

my_uploads.css

.paging-button {
  visibility: hidden;
}

.button-container {
  clear: both;
}

But I only get a blank page with the following result:

This application requires access to your YouTube account. Please authorize to continue.

And If I click the link, then nothing happens. What might be the problem?


问:
How do update a scheduled quartz Job?
Both of the below snippets give this error:

org.quartz.SchedulerException: Jobs added with no trigger must be
  durable.

```<code>  JobDetail job = scheduler.getJobDetail(jobKey(jobInfo));
  job.getJobDataMap().put(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo));
  scheduler.addJob(job, true);

  JobDetail job = JobBuilder
        .newJob(MyJob.class)
        .usingJobData(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo))
        .withIdentity(jobKey(jobInfo))
        .build();
  scheduler.addJob(job, true);
</code>```

答: addJob() is for adding jobs with no triggers attached: if that is what you want, just add a call to storeDurably() to the JobBuilder; if, as I can only guess, you want to otherwise update the job while retaining the old trigger, you will need to retrieve the existing trigger first, then, if the trigger will not need changes, scheduler.scheduleJob(newJob, oldTrigger); otherwise get a builder for it using TriggerBuilder.getTriggerBuilder(); to build a copy, make your changes, and eventually call scheduler.scheduleJob(newJob, newTrigger).

Title: How do update a scheduled quartz Job?

Body:
Both of the below snippets give this error:

org.quartz.SchedulerException: Jobs added with no trigger must be
  durable.

  JobDetail job = scheduler.getJobDetail(jobKey(jobInfo));
  job.getJobDataMap().put(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo));
  scheduler.addJob(job, true);

  JobDetail job = JobBuilder
        .newJob(MyJob.class)
        .usingJobData(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo))
        .withIdentity(jobKey(jobInfo))
        .build();
  scheduler.addJob(job, true);


问:
python3 UnicodeEncodeError: 'charmap' codec can't encode characters in position 95-98: character maps to <undefined>
A month ago I encountered this Github: https://github.com/taraslayshchuk/es2csv

I installed this package via pip3 in Linux ubuntu. When I wanted to use this package, I encountered the problem that this package is meant for python2. I dived into the code and soon I found the problem.

```<code>                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_dict_utf8)
            output_file.close()
            bar.finish()
        else:
            print('There is no docs with selected field(s): %s.' % ','.join(self.opts.fields))
</code>```

The code did a check for unicode, this is not necessary within python3 Therefore, I changed the code to the code below. As result, The package worked properly under Ubuntu 16.

```<code>                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                # line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_as_dict)
            output_file.close()
            bar.finish()
        else:
            print('There is no docs with selected field(s): %s.' % ','.join(self.opts.fields))
</code>```

But a month later, it was necessary to get the es2csv package working on a Windows 10 operating system. After doing the exact same adjustments with es2csv under Windows 10, I received the following error message after I tried to run es2csv:

```<code>    PS C:\> es2csv -u 192.168.230.151:9200 -i scrapy -o database.csv -q '*'
Found 218 results
Run query [#######################################################################################################################] [218/218] [100%] [0:00:00] [Time: 0:00:00] [  2.3 Kidocs/s]
Write to csv [#                                                                                ] [2/218] [  0%] [0:00:00] [ETA: 0:00:00] [  3.9 Kilines/s]T
raceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python36\Scripts\es2csv-script.py", line 11, in <module>
    load_entry_point('es2csv==5.2.1', 'console_scripts', 'es2csv')()
  File "c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\es2csv.py", line 284, in main
    es.write_to_csv()
  File "c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\es2csv.py", line 238, in write_to_csv
    csv_writer.writerow(line_as_dict)
  File "c:\users\admin\appdata\local\programs\python\python36\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "c:\users\admin\appdata\local\programs\python\python36\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 95-98: character maps to <undefined>
</code>```

Does anyone has an idea how to fix this error message?

答:
It's due to the default behaviour of open in Python 3. By default, Python 3 will open files in Text mode, which means that it also has to apply a text decoding, such as utf-8 or ASCII, for every character it reads.

Python will use your locale to determine the most suitable encoding. On OS X and Linux, this is usually UTF-8. On Windows, it'll use an 8-bit character set, such windows-1252, to match the behaviour of Notepad.

As an 8-bit character set only has a limited number of characters, it's very easy to end up trying to write a character not supported by the character set. For example, if you tried to write a Hebrew character with Windows-1252, the Western European character set.

To resolve your problem, you simply need to override the automatic encoding selection in open and hardcode it to use UTF-8:

```<code>for line in open(self.tmp_file, 'r', encoding='utf-8'):
</code>```

Body:
A month ago I encountered this Github: https://github.com/taraslayshchuk/es2csv

I installed this package via pip3 in Linux ubuntu. When I wanted to use this package, I encountered the problem that this package is meant for python2. I dived into the code and soon I found the problem.

                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_dict_utf8)
            output_file.close()
            bar.finish()
        else:
            print('There is no docs with selected field(s): %s.' % ','.join(self.opts.fields))

The code did a check for unicode, this is not necessary within python3 Therefore, I changed the code to the code below. As result, The package worked properly under Ubuntu 16.

                for line in open(self.tmp_file, 'r'):
                timer += 1
                bar.update(timer)
                line_as_dict = json.loads(line)
                # line_dict_utf8 = {k: v.encode('utf8') if isinstance(v, unicode) else v for k, v in line_as_dict.items()}
                csv_writer.writerow(line_as_dict)
            output_file.close()
            bar.finish()
        else:
            print('There is no docs with selected field(s): %s.' % ','.join(self.opts.fields))

But a month later, it was necessary to get the es2csv package working on a Windows 10 operating system. After doing the exact same adjustments with es2csv under Windows 10, I received the following error message after I tried to run es2csv:

    PS C:\> es2csv -u 192.168.230.151:9200 -i scrapy -o database.csv -q '*'
Found 218 results
Run query [#######################################################################################################################] [218/218] [100%] [0:00:00] [Time: 0:00:00] [  2.3 Kidocs/s]
Write to csv [#                                                                                ] [2/218] [  0%] [0:00:00] [ETA: 0:00:00] [  3.9 Kilines/s]T
raceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python36\Scripts\es2csv-script.py", line 11, in <module>
    load_entry_point('es2csv==5.2.1', 'console_scripts', 'es2csv')()
  File "c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\es2csv.py", line 284, in main
    es.write_to_csv()
  File "c:\users\admin\appdata\local\programs\python\python36\lib\site-packages\es2csv.py", line 238, in write_to_csv
    csv_writer.writerow(line_as_dict)
  File "c:\users\admin\appdata\local\programs\python\python36\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "c:\users\admin\appdata\local\programs\python\python36\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 95-98: character maps to <undefined>

Does anyone has an idea how to fix this error message?

Body:
It's due to the default behaviour of open in Python 3. By default, Python 3 will open files in Text mode, which means that it also has to apply a text decoding, such as utf-8 or ASCII, for every character it reads.

Python will use your locale to determine the most suitable encoding. On OS X and Linux, this is usually UTF-8. On Windows, it'll use an 8-bit character set, such windows-1252, to match the behaviour of Notepad.

As an 8-bit character set only has a limited number of characters, it's very easy to end up trying to write a character not supported by the character set. For example, if you tried to write a Hebrew character with Windows-1252, the Western European character set.

To resolve your problem, you simply need to override the automatic encoding selection in open and hardcode it to use UTF-8:

for line in open(self.tmp_file, 'r', encoding='utf-8'):


问:
Electron app using python throws zmq.node error
Full disclosure I'm a node/npm/electron noob but I'm attempting to build an electron app to interface with an existing python module I wrote and I came across this Github repo. So I cloned it and I'm trying to run it from linux mint cinnamon version 3.2.7. The electron app starts however the python component doesn't work. When I open the developer tools the console displays this error message;

```<code>Uncaught Error: Cannot find module '../build/Release/zmq.node'
    at Module._resolveFilename (module.js:470:15)
    at Function.Module._resolveFilename (/home/jad/Github/electron-python-example/node_modules/electron/dist/resources/electron.asar/common/reset-search-paths.js:35:12)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/jad/Github/electron-python-example/node_modules/zeromq/lib/index.js:6:11)
    at Object.<anonymous> (/home/jad/Github/electron-python-example/node_modules/zeromq/lib/index.js:839:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
</code>```

Turns out that others have had this problem and a solution was posted where this SO answer is referenced however when I run the following;

```<code>npm install --save-dev electron-rebuild
./node_modules/.bin/electron-rebuild
</code>```

I get the following error messages;

```<code>An unhandled error occurred inside electron-rebuild
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.1
gyp info using node@7.10.0 | linux | x64
gyp http GET https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http 200 https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http GET https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp http 200 https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp info spawn /usr/bin/python2
gyp info spawn args [ '/home/jad/Github/electron-python-example/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/zeromq/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8',
gyp info spawn args   '-Dnode_gyp_dir=/home/jad/Github/electron-python-example/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=iojs.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/jad/Github/electron-python-example/node_modules/zeromq',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
  CXX(target) Release/obj.target/zmq/binding.o
  SOLINK_MODULE(target) Release/obj.target/zmq.node
g++: error: ./Release/../../zmq/lib/libzmq.a: No such file or directory
zmq.target.mk:123: recipe for target 'Release/obj.target/zmq.node' failed
make: Leaving directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
make: *** [Release/obj.target/zmq.node] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/jad/Github/electron-python-example/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:194:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 4.4.0-78-generic
gyp ERR! command "/usr/local/bin/node" "/home/jad/Github/electron-python-example/node_modules/.bin/node-gyp" "rebuild" "--target=1.6.8" "--arch=x64" "--dist-url=https://atom.io/download/electron" "--build-from-source"
gyp ERR! cwd /home/jad/Github/electron-python-example/node_modules/zeromq
gyp ERR! node -v v7.10.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok

Failed with exit code: 1

Error: gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.1
gyp info using node@7.10.0 | linux | x64
gyp http GET https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http 200 https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http GET https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp http 200 https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp info spawn /usr/bin/python2
gyp info spawn args [ '/home/jad/Github/electron-python-example/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/zeromq/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8',
gyp info spawn args   '-Dnode_gyp_dir=/home/jad/Github/electron-python-example/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=iojs.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/jad/Github/electron-python-example/node_modules/zeromq',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
  CXX(target) Release/obj.target/zmq/binding.o
  SOLINK_MODULE(target) Release/obj.target/zmq.node
g++: error: ./Release/../../zmq/lib/libzmq.a: No such file or directory
zmq.target.mk:123: recipe for target 'Release/obj.target/zmq.node' failed
make: Leaving directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
make: *** [Release/obj.target/zmq.node] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/jad/Github/electron-python-example/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:194:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 4.4.0-78-generic
gyp ERR! command "/usr/local/bin/node" "/home/jad/Github/electron-python-example/node_modules/.bin/node-gyp" "rebuild" "--target=1.6.8" "--arch=x64" "--dist-url=https://atom.io/download/electron" "--build-from-source"
gyp ERR! cwd /home/jad/Github/electron-python-example/node_modules/zeromq
gyp ERR! node -v v7.10.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok

Failed with exit code: 1
    at SafeSubscriber._error (/home/jad/Github/electron-python-example/node_modules/spawn-rx/lib/src/index.js:262:84)
    at SafeSubscriber.__tryOrUnsub (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:238:16)
    at SafeSubscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:197:26)
    at Subscriber._error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:128:26)
    at Subscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:102:18)
    at MapSubscriber.Subscriber._error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:128:26)
    at MapSubscriber.Subscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:102:18)
    at SafeSubscriber._next (/home/jad/Github/electron-python-example/node_modules/spawn-rx/lib/src/index.js:236:65)
    at SafeSubscriber.__tryOrSetError (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:247:16)
    at SafeSubscriber.next (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:187:27)
</code>```

Is there any way that I get fix/get-around this issue?

答:
i had same problem, my solution was using this npm rebuild zeromq --runtime=electron --target=1.6.2(you're version) before run npm start

All info here

Body:
Full disclosure I'm a node/npm/electron noob but I'm attempting to build an electron app to interface with an existing python module I wrote and I came across this Github repo. So I cloned it and I'm trying to run it from linux mint cinnamon version 3.2.7. The electron app starts however the python component doesn't work. When I open the developer tools the console displays this error message;

Uncaught Error: Cannot find module '../build/Release/zmq.node'
    at Module._resolveFilename (module.js:470:15)
    at Function.Module._resolveFilename (/home/jad/Github/electron-python-example/node_modules/electron/dist/resources/electron.asar/common/reset-search-paths.js:35:12)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/jad/Github/electron-python-example/node_modules/zeromq/lib/index.js:6:11)
    at Object.<anonymous> (/home/jad/Github/electron-python-example/node_modules/zeromq/lib/index.js:839:3)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)

Turns out that others have had this problem and a solution was posted where this SO answer is referenced however when I run the following;

npm install --save-dev electron-rebuild
./node_modules/.bin/electron-rebuild

I get the following error messages;

An unhandled error occurred inside electron-rebuild
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.1
gyp info using node@7.10.0 | linux | x64
gyp http GET https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http 200 https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http GET https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp http 200 https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp info spawn /usr/bin/python2
gyp info spawn args [ '/home/jad/Github/electron-python-example/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/zeromq/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8',
gyp info spawn args   '-Dnode_gyp_dir=/home/jad/Github/electron-python-example/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=iojs.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/jad/Github/electron-python-example/node_modules/zeromq',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
  CXX(target) Release/obj.target/zmq/binding.o
  SOLINK_MODULE(target) Release/obj.target/zmq.node
g++: error: ./Release/../../zmq/lib/libzmq.a: No such file or directory
zmq.target.mk:123: recipe for target 'Release/obj.target/zmq.node' failed
make: Leaving directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
make: *** [Release/obj.target/zmq.node] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/jad/Github/electron-python-example/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:194:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 4.4.0-78-generic
gyp ERR! command "/usr/local/bin/node" "/home/jad/Github/electron-python-example/node_modules/.bin/node-gyp" "rebuild" "--target=1.6.8" "--arch=x64" "--dist-url=https://atom.io/download/electron" "--build-from-source"
gyp ERR! cwd /home/jad/Github/electron-python-example/node_modules/zeromq
gyp ERR! node -v v7.10.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok

Failed with exit code: 1

Error: gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.1
gyp info using node@7.10.0 | linux | x64
gyp http GET https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http 200 https://atom.io/download/electron/v1.6.8/iojs-v1.6.8.tar.gz
gyp http GET https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp http 200 https://atom.io/download/electron/v1.6.8/SHASUMS256.txt
gyp info spawn /usr/bin/python2
gyp info spawn args [ '/home/jad/Github/electron-python-example/node_modules/node-gyp/gyp/gyp_main.py',
gyp info spawn args   'binding.gyp',
gyp info spawn args   '-f',
gyp info spawn args   'make',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/zeromq/build/config.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/Github/electron-python-example/node_modules/node-gyp/addon.gypi',
gyp info spawn args   '-I',
gyp info spawn args   '/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8/common.gypi',
gyp info spawn args   '-Dlibrary=shared_library',
gyp info spawn args   '-Dvisibility=default',
gyp info spawn args   '-Dnode_root_dir=/home/jad/.electron-gyp/.node-gyp/iojs-1.6.8',
gyp info spawn args   '-Dnode_gyp_dir=/home/jad/Github/electron-python-example/node_modules/node-gyp',
gyp info spawn args   '-Dnode_lib_file=iojs.lib',
gyp info spawn args   '-Dmodule_root_dir=/home/jad/Github/electron-python-example/node_modules/zeromq',
gyp info spawn args   '-Dnode_engine=v8',
gyp info spawn args   '--depth=.',
gyp info spawn args   '--no-parallel',
gyp info spawn args   '--generator-output',
gyp info spawn args   'build',
gyp info spawn args   '-Goutput_dir=.' ]
gyp info spawn make
gyp info spawn args [ 'BUILDTYPE=Release', '-C', 'build' ]
make: Entering directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
  CXX(target) Release/obj.target/zmq/binding.o
  SOLINK_MODULE(target) Release/obj.target/zmq.node
g++: error: ./Release/../../zmq/lib/libzmq.a: No such file or directory
zmq.target.mk:123: recipe for target 'Release/obj.target/zmq.node' failed
make: Leaving directory '/home/jad/Github/electron-python-example/node_modules/zeromq/build'
make: *** [Release/obj.target/zmq.node] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/home/jad/Github/electron-python-example/node_modules/node-gyp/lib/build.js:285:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:194:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Linux 4.4.0-78-generic
gyp ERR! command "/usr/local/bin/node" "/home/jad/Github/electron-python-example/node_modules/.bin/node-gyp" "rebuild" "--target=1.6.8" "--arch=x64" "--dist-url=https://atom.io/download/electron" "--build-from-source"
gyp ERR! cwd /home/jad/Github/electron-python-example/node_modules/zeromq
gyp ERR! node -v v7.10.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok

Failed with exit code: 1
    at SafeSubscriber._error (/home/jad/Github/electron-python-example/node_modules/spawn-rx/lib/src/index.js:262:84)
    at SafeSubscriber.__tryOrUnsub (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:238:16)
    at SafeSubscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:197:26)
    at Subscriber._error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:128:26)
    at Subscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:102:18)
    at MapSubscriber.Subscriber._error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:128:26)
    at MapSubscriber.Subscriber.error (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:102:18)
    at SafeSubscriber._next (/home/jad/Github/electron-python-example/node_modules/spawn-rx/lib/src/index.js:236:65)
    at SafeSubscriber.__tryOrSetError (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:247:16)
    at SafeSubscriber.next (/home/jad/Github/electron-python-example/node_modules/rxjs/Subscriber.js:187:27)

Is there any way that I get fix/get-around this issue?


问:
JavaScript: Variables not working outside function?
Why cannot I call variables that I have defined inside a function? This is my code...

```<code>  var username;
  var rank;
  var steamid;
  var avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            var infoArr = JSON.parse(this.responseText);
            var username = infoArr.username;
            var rank = infoArr.rank;
            var steamid = infoArr.steamid;
            var avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}
</code>```

Function testIt() is returning: undefined

What my code does is to get info from a JSON encoded page and make variables.

答:
If you want to use the variables outside of the function, they need to be defined outside of the function.</p>

```<code>var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            infoArr = JSON.parse(this.responseText);
            username = infoArr.username;
            rank = infoArr.rank;
            steamid = infoArr.steamid;
            avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}
</code>```

Body:
Why cannot I call variables that I have defined inside a function? This is my code...

  var username;
  var rank;
  var steamid;
  var avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            var infoArr = JSON.parse(this.responseText);
            var username = infoArr.username;
            var rank = infoArr.rank;
            var steamid = infoArr.steamid;
            var avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}

Function testIt() is returning: undefined

What my code does is to get info from a JSON encoded page and make variables.

Body:
If you want to use the variables outside of the function, they need to be defined outside of the function.

var username, rank, steamid, avatar, infoArr, username, rank, steamid, avatar;

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {

        if (this.responseText == "null") {
        } else {
            infoArr = JSON.parse(this.responseText);
            username = infoArr.username;
            rank = infoArr.rank;
            steamid = infoArr.steamid;
            avatar = infoArr.avatar;
            testIt();
      }
    }
};

xhr.open("GET", "../getInfo.php", true);
xhr.send();

function testIt() {
  alert(username);
}


答:
There's no built-in support to explicitly use the default value of a parameter. If you don't want to leave the parameter out at the call site, you'd have to retrieve the default value very manually:

```<code>import inspect

a(num=inspect.signature(a).parameters['num'].default)
</code>```

which wouldn't be worth it in most cases.

Title: How to pass a parameter as a default?

Body:
There's no built-in support to explicitly use the default value of a parameter. If you don't want to leave the parameter out at the call site, you'd have to retrieve the default value very manually:

import inspect

a(num=inspect.signature(a).parameters['num'].default)

which wouldn't be worth it in most cases.


问:
How to Delete data in Both Tables in SQL Server?
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

```<code>DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)
</code>```

But how can I make sure the top 1000 BId got deleted?

Thanks

答:
One way to go would be to create a table variable, stored the 1000 ID's and reference that in both deletes. Of course I have no idea if they're integers or not, so change the data type if required. There are other ways, as I'm sure others will point out but this is my standard approach if I need consistency.</p>

```<code>DECLARE @keyValues TABLE (keyValue INT);

INSERT INTO @keyValues
SELECT TOP 1000 FROM TABLEA WHERE AID IN (SELECT BID FROM TABLEB);

DELETE FROM TABLEB WHERE BID IN (SELECT keyValue FROM @keyValues);
DELETE FROM TABLEA WHERE AID IN (SELECT keyValue FROM @keyValues);
</code>```

Body:
I have a table TableA, its PK is AId. I have another table TableB, its only column is BId. BId is actually is a subset of AId. Now, we can not use FK (because of this and that reason).

How can I Delete the TOP 1000 rows in TableB and its related rows (if the same id exists in table A) in table A?

A solution is to SELECT TOP 100) from tableB and save to temp table, then use it to delete the data in table A, then delete rows in tableB.

But it should have a more efficient way to do this.

I also tried:

DELETE TOP (1000) FROM tableA WHERE AId IN (SELECT BId FROM TableB)

But how can I make sure the top 1000 BId got deleted?

Thanks

Body:
One way to go would be to create a table variable, stored the 1000 ID's and reference that in both deletes. Of course I have no idea if they're integers or not, so change the data type if required. There are other ways, as I'm sure others will point out but this is my standard approach if I need consistency.

DECLARE @keyValues TABLE (keyValue INT);

INSERT INTO @keyValues
SELECT TOP 1000 FROM TABLEA WHERE AID IN (SELECT BID FROM TABLEB);

DELETE FROM TABLEB WHERE BID IN (SELECT keyValue FROM @keyValues);
DELETE FROM TABLEA WHERE AID IN (SELECT keyValue FROM @keyValues);


问:
Using the ASP.NET MVC dynamic model/viewbag only a bad idea?
As the sole developer of an app, would using a dynamic model, or the new ViewBag in ASP.NET MVC 3, exclusively be a bad idea (i.e., not building strongly typed classes)?

Currently, I have a strongly typed viewdata strategy that breaks the built-in html form helpers (like Html.TextBoxFor). My viewdata looks like this:

```<code>public class BaselineViewData {
  ...properties all views will need...
  public Area1ViewData Area1ViewData {get;set;}
  public Area2ViewData Area2ViewData {get;set;}
}
</code>```

Some properties of the BaselineViewData are viewdata classes themselves. So far it's been great, but the form helpers don't work well. They output something like this:

@Html.TextBoxFor(u => u.Username) outputs

<input id="BaselineViewData.Area1ViewData.Username" ... />

With that naming, the built-in unobtrusive validation doesn't work.

I started this app with MVC 1, it's ported to MVC 3... but not taking advantage of all the benefits of MVC 3. So I decided I'm going to totally rewrite the app now, which will be much easier than it was then... now that there's so much handled for you. ;D

答:
I'll be going with a hybrid strongly typed/viewbag viewdata strategy. I'll follow the example give in the accountmodels file in a default asp.net mvc 3 app.

Thanks!

Body:
As the sole developer of an app, would using a dynamic model, or the new ViewBag in ASP.NET MVC 3, exclusively be a bad idea (i.e., not building strongly typed classes)?

Currently, I have a strongly typed viewdata strategy that breaks the built-in html form helpers (like Html.TextBoxFor). My viewdata looks like this:

public class BaselineViewData {
  ...properties all views will need...
  public Area1ViewData Area1ViewData {get;set;}
  public Area2ViewData Area2ViewData {get;set;}
}

Some properties of the BaselineViewData are viewdata classes themselves. So far it's been great, but the form helpers don't work well. They output something like this:

@Html.TextBoxFor(u => u.Username) outputs

<input id="BaselineViewData.Area1ViewData.Username" ... />

With that naming, the built-in unobtrusive validation doesn't work.

I started this app with MVC 1, it's ported to MVC 3... but not taking advantage of all the benefits of MVC 3. So I decided I'm going to totally rewrite the app now, which will be much easier than it was then... now that there's so much handled for you. ;D