问:
OpenID authentication to Google Apps via Perl and Net::OpenID::Consumer fails
I asked this over on Google's support forums for Apps integration, but got zero response. Maybe somebody here can help steer me in the right direction.

I'm trying to integrate a Perl application with Google Apps, and I'm having some trouble with the OpenID authentication. I've been using this PHP tutorial from Google as a kind of reference, since there are no Perl examples I can find.

My initial file, index.cgi (referred by manifest.xml, and the starting point of the OpenID transaction) is as follows:

```<code>use Net::OpenID::Consumer;
use CGI;
# ...

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}
# my website
my $root = 'http://www.example.com/';

my $csr = Net::OpenID::Consumer->new(
     # The user agent which sends the openid off to the server
     ua => LWP::UserAgent->new,
     # Who we are
     required_root => $root,
     # Consumer Key Secret from Google Apps Marketplace
     consumer_secret => 'Zzzzzz9zzAAAAA....'
);

my $claimed_id = $csr->claimed_identity(
    'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain);

if ($claimed_id) {
    my $check_url = $claimed_id->check_url(
        # Upon validation, the user will be returned here, and real
        # work may begin
        return_to => $root . '/return.cgi',
        trust_root => $root
    );
    print $q->redirect($check_url);
}
else {
    print $q->header(), "Error";
}
</code>```

This part seems to be working. That is, I get redirected to return.cgi with a bunch of openid.* parameters. However, at this point I get the following error:

no_identity_server The provided URL doesn't declare its OpenID identity server

I'm using the latest version of the Net::OpenID::Consumer module.

Here are the significant bits of return.cgi:

```<code>my $q = CGI->new();
my $csr = Net::OpenID::Consumer->new(
     ua => LWP::UserAgent->new,
     # The root of our URL
     required_root => 'http://www.example.com/',
     # Our password.
     consumer_secret => 'Zzzzzz9zzAAAAA....',
     # Where to get the information from.
     args  => $q
);

print $q->header();
$csr->handle_server_response(
     not_openid => sub {
         print "That's not an OpenID message. Did you just type in the URL?";
     },
     setup_required => sub {
         my $setup_url = shift;
         print 'You need to do something <a href="#">here</a>.';
     },
     cancelled => sub {
         print 'You cancelled your login.';
     },
     verified => sub {
         my $vident = shift;
         my $url = $vident->url;
         print "You are verified as '$url'. ** FIN **";
     },
     error => sub { die "Can't figure it out: ", @_; }
);
</code>```

As you can imagine, I'm wanting the verified sub to fire, but instead I'm getting an error. Anything obvious I'm missing? Any help would be appreciated.

答: In some cases, reportedly, this is caused by Perl missing Net::SSL, making it fail on Google's SSL URLs.</p>

Body:
I asked this over on Google's support forums for Apps integration, but got zero response. Maybe somebody here can help steer me in the right direction.

I'm trying to integrate a Perl application with Google Apps, and I'm having some trouble with the OpenID authentication. I've been using this PHP tutorial from Google as a kind of reference, since there are no Perl examples I can find.

My initial file, index.cgi (referred by manifest.xml, and the starting point of the OpenID transaction) is as follows:

use Net::OpenID::Consumer;
use CGI;
# ...

my $q = CGI->new();

my $domain = $q->param('domain');
if (!$domain) {
    print $q->header(), 'Provide domain please.';
    exit 0;
}
# my website
my $root = 'http://www.example.com/';

my $csr = Net::OpenID::Consumer->new(
     # The user agent which sends the openid off to the server
     ua => LWP::UserAgent->new,
     # Who we are
     required_root => $root,
     # Consumer Key Secret from Google Apps Marketplace
     consumer_secret => 'Zzzzzz9zzAAAAA....'
);

my $claimed_id = $csr->claimed_identity(
    'https://www.google.com/accounts/o8/site-xrds?hd=' . $domain);

if ($claimed_id) {
    my $check_url = $claimed_id->check_url(
        # Upon validation, the user will be returned here, and real
        # work may begin
        return_to => $root . '/return.cgi',
        trust_root => $root
    );
    print $q->redirect($check_url);
}
else {
    print $q->header(), "Error";
}

This part seems to be working. That is, I get redirected to return.cgi with a bunch of openid.* parameters. However, at this point I get the following error:

no_identity_server The provided URL doesn't declare its OpenID identity server

I'm using the latest version of the Net::OpenID::Consumer module.

Here are the significant bits of return.cgi:

my $q = CGI->new();
my $csr = Net::OpenID::Consumer->new(
     ua => LWP::UserAgent->new,
     # The root of our URL
     required_root => 'http://www.example.com/',
     # Our password.
     consumer_secret => 'Zzzzzz9zzAAAAA....',
     # Where to get the information from.
     args  => $q
);

print $q->header();
$csr->handle_server_response(
     not_openid => sub {
         print "That's not an OpenID message. Did you just type in the URL?";
     },
     setup_required => sub {
         my $setup_url = shift;
         print 'You need to do something here.';
     },
     cancelled => sub {
         print 'You cancelled your login.';
     },
     verified => sub {
         my $vident = shift;
         my $url = $vident->url;
         print "You are verified as '$url'. ** FIN **";
     },
     error => sub { die "Can't figure it out: ", @_; }
);

As you can imagine, I'm wanting the verified sub to fire, but instead I'm getting an error. Anything obvious I'm missing? Any help would be appreciated.


来源: stackexchange

问:
error while building the apk in android
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}
</code>```

答:
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your app-level build.gradle file, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}
</code>```

However, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

Modify the app-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}
</code>```

Create an Application class like this:

```<code>public class MyApplication extends MultiDexApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}
</code>```

Add this application class in Manifest.

You can also check this link:

https://developer.android.com/studio/build/multidex.html

ContentLicense: CC BY-SA 3.0

Title: error while building the apk in android

Body:
This is the my build.gradle and when I build the apk by clicking on the build apk this error shown.I have seen the some of the queries before but not able to figure out the problem solution

Error:Execution failed for task ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.example.ranjeet.location"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
}

Body:
If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your app-level build.gradle file, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}

However, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

Modify the app-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 25
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

Create an Application class like this:

public class MyApplication extends MultiDexApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Add this application class in Manifest.

You can also check this link:

https://developer.android.com/studio/build/multidex.html


问:
SFTP via JSch is throwing error 4: Failure
I am facing a peculiar issue while trying to SFTP a file from Windows to Unix server. The error "stack trace" is -

4: Failure
    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
    at com.jcraft.jsch.ChannelSftp.checkStatus(ChannelSftp.java:2459)
    at com.jcraft.jsch.ChannelSftp._sendCLOSE(ChannelSftp.java:2465)
    at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:683)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:475)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:365)
```

I have searched a lot on other forums but could not get to the root cause. I have observed one more thing - the file name, I am trying to SFTP, is *.xml when I change it to *.XML the SFTP is "successful". Very weird could not identify the issue. I am trying this using JSch Java API. But I have seen the same issue while trying the WinSCP front end.

答: I was facing the same issue. Please make sure that your SFTP service is running. And If it is already running then restarting this service should do the trick.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am facing a peculiar issue while trying to SFTP a file from Windows to Unix server. The error "stack trace" is -

4: Failure
    at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846)
    at com.jcraft.jsch.ChannelSftp.checkStatus(ChannelSftp.java:2459)
    at com.jcraft.jsch.ChannelSftp._sendCLOSE(ChannelSftp.java:2465)
    at com.jcraft.jsch.ChannelSftp._put(ChannelSftp.java:683)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:475)
    at com.jcraft.jsch.ChannelSftp.put(ChannelSftp.java:365)

I have searched a lot on other forums but could not get to the root cause. I have observed one more thing - the file name, I am trying to SFTP, is *.xml when I change it to *.XML the SFTP is "successful". Very weird could not identify the issue. I am trying this using JSch Java API. But I have seen the same issue while trying the WinSCP front end.


问:
Strings not going into the right txt file [discord.py]
I've got this code, basically what it's supposed to do is log a specific users messages when a person with the role 'ADMIN' or 'semi-mod' say '!log user'. The code puts the messages into a .txt file who's name is the id of the user being logged. If it doesn't find a txt file with the users unique ID, it creates a new one. However my problem is that if I log more than one person, messages will go into the other users text file etc.</p>

```<code>@commands.command(pass_context=True)
    async def log(self, ctx, user: discord.Member):
        if 'Administrator' or 'semi-mod' in [x.name for x in ctx.message.author.roles]:
            users2log.append(user.id)
            msg = """```
Member's Message Being Logged
{} messages are now being logged at the request of {}.
```""".format(ctx.message.mentions[0], ctx.message.author)
            await self.bot.send_message(discord.Object(id='320289509281628165'), msg)
            await self.bot.add_reaction(ctx.message, '\U00002611')

-----------------------
Part not working:
-----------------------

    async def on_message(self, message):
        if message.author.id in users2log:
            for user in users2log:
                try:
                    f = open(user, 'a')
                    msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
                    f.write(msg)
                    f.close()
                except FileNotFoundError:
                    os.system("touch " + user)
</code>```

答:
The messages get added to other user's files because you loop through the entire users2log array and append to each file even though you only want to log the message to one single user's file. It should work if you remove the for loop in on_message so you only append to the file matching the user's id:

```<code>async def on_message(self, message):
    if message.author.id in users2log:
        user = message.author.id
        try:
            f = open(user, 'a')
            msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
            f.write(msg)
            f.close()
        except FileNotFoundError:
            os.system("touch " + user)
</code>```

Body:
I've got this code, basically what it's supposed to do is log a specific users messages when a person with the role 'ADMIN' or 'semi-mod' say '!log user'. The code puts the messages into a .txt file who's name is the id of the user being logged. If it doesn't find a txt file with the users unique ID, it creates a new one. However my problem is that if I log more than one person, messages will go into the other users text file etc.

@commands.command(pass_context=True)
    async def log(self, ctx, user: discord.Member):
        if 'Administrator' or 'semi-mod' in [x.name for x in ctx.message.author.roles]:
            users2log.append(user.id)
            msg = """```
Member's Message Being Logged
{} messages are now being logged at the request of {}.
```""".format(ctx.message.mentions[0], ctx.message.author)
            await self.bot.send_message(discord.Object(id='320289509281628165'), msg)
            await self.bot.add_reaction(ctx.message, '\U00002611')

-----------------------
Part not working:
-----------------------

    async def on_message(self, message):
        if message.author.id in users2log:
            for user in users2log:
                try:
                    f = open(user, 'a')
                    msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
                    f.write(msg)
                    f.close()
                except FileNotFoundError:
                    os.system("touch " + user)

Body:
The messages get added to other user's files because you loop through the entire users2log array and append to each file even though you only want to log the message to one single user's file. It should work if you remove the for loop in on_message so you only append to the file matching the user's id:

async def on_message(self, message):
    if message.author.id in users2log:
        user = message.author.id
        try:
            f = open(user, 'a')
            msg = """
User: {}
Time: {}
Message: {}
\n""".format(message.author, time.localtime(), message.content)
            f.write(msg)
            f.close()
        except FileNotFoundError:
            os.system("touch " + user)


问:
Fast calculation of v-disparity with OpenCV-Function calcHist
Based on a disparity matrix from a passive stereo-camera system i need to calculate a v-disparity representation for obstacle detection with OpenCV.

A working implementation is not the problem. The problem is to do it fast...

(One) Reference for v-Disparity: Labayrade, R. and Aubert, D. and Tarel, J.P.
Real time obstacle detection in stereovision on non flat road geometry through v-disparity representation

The basic in short, to get the v-disparity (figure 1), is to analyze the rows of the disparity-matrix (figure 2) an represent the result as a histogram for each row over the disparity values. u-disparity (figure 3) is the same on the columns of the disparity-matrix. (All figures are false-colored.)

I have implement the "same" in Python and C++. The speed in Python is acceptable but in C++ i get for the u- and v-disparity a time round about a half second (0.5 s).

(1. edit: due to the separate time measurement, only the calculation of the u-histogram takes a big amount of time...)

This leads me to following questions:

Is it possible to avoid the loops for the line-wise calculation of the histogram? Is there a "trick" to do it with one call of calcHist-Function from OpenCV? Perhaps with the dimensions?

Is it in C++ just bad-coded and the runtime-issue are not related to the loops used for calculation?

Thanks, all

Working implementation in Python:

```<code>#!/usr/bin/env python2
#-*- coding: utf-8 -*-
#
# THIS SOURCE-CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED. IN NO  EVENT WILL THE AUTHOR BE HELD LIABLE FOR ANY DAMAGES ARISING FROM
# THE USE OF THIS SOURCE-CODE. USE AT YOUR OWN RISK.

import cv2
import numpy as np
import time

def draw_object(image, x, y, width=50, height=100):
    color = image[y, x]
    image[y-height:y, x-width//2:x+width//2] = color

IMAGE_HEIGHT = 600
IMAGE_WIDTH = 800

while True:

    max_disp = 200

    # create fake disparity
    image = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH), np.uint8)

    for c in range(IMAGE_HEIGHT)[::-1]:
        image[c, ...] = int(float(c) / IMAGE_HEIGHT * max_disp)

    draw_object(image, 275, 175)
    draw_object(image, 300, 200)
    draw_object(image, 100, 350)

    # calculate v-disparity
    vhist_vis = np.zeros((IMAGE_HEIGHT, max_disp), np.float)
    for i in range(IMAGE_HEIGHT):
        vhist_vis[i, ...] = cv2.calcHist(images=[image[i, ...]], channels=[0], mask=None, histSize=[max_disp],
                                         ranges=[0, max_disp]).flatten() / float(IMAGE_HEIGHT)

    vhist_vis = np.array(vhist_vis * 255, np.uint8)
    vblack_mask = vhist_vis < 5
    vhist_vis = cv2.applyColorMap(vhist_vis, cv2.COLORMAP_JET)
    vhist_vis[vblack_mask] = 0

    # calculate u-disparity
    uhist_vis = np.zeros((max_disp, IMAGE_WIDTH), np.float)
    for i in range(IMAGE_WIDTH):
        uhist_vis[..., i] = cv2.calcHist(images=[image[..., i]], channels=[0], mask=None, histSize=[max_disp],
                                         ranges=[0, max_disp]).flatten() / float(IMAGE_WIDTH)

    uhist_vis = np.array(uhist_vis * 255, np.uint8)
    ublack_mask = uhist_vis < 5
    uhist_vis = cv2.applyColorMap(uhist_vis, cv2.COLORMAP_JET)
    uhist_vis[ublack_mask] = 0

    image = cv2.applyColorMap(image, cv2.COLORMAP_JET)

    cv2.imshow('image', image)

    cv2.imshow('vhist_vis', vhist_vis)
    cv2.imshow('uhist_vis', uhist_vis)

    cv2.imwrite('disparity_image.png', image)
    cv2.imwrite('v-disparity.png', vhist_vis)
    cv2.imwrite('u-disparity.png', uhist_vis)

    if chr(cv2.waitKey(0)&255) == 'q':
        break
</code>```

Working implementation in C++:

```<code>#include <iostream>
#include <stdlib.h>

#include <ctime>

#include <opencv2/opencv.hpp>

using namespace std;

void draw_object(cv::Mat image, unsigned int x, unsigned int y, unsigned int width=50, unsigned int height=100)
{
    image(cv::Range(y-height, y), cv::Range(x-width/2, x+width/2)) = image.at<unsigned char>(y, x);
}

int main()
{
    unsigned int IMAGE_HEIGHT = 600;
    unsigned int IMAGE_WIDTH = 800;
    unsigned int MAX_DISP = 250;
    unsigned int CYCLE = 0;

    //setenv("QT_GRAPHICSSYSTEM", "native", 1);

    // === PREPERATIONS ==
    cv::Mat image = cv::Mat::zeros(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8U);
    cv::Mat uhist = cv::Mat::zeros(IMAGE_HEIGHT, MAX_DISP, CV_32F);
    cv::Mat vhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);

    cv::Mat tmpImageMat, tmpHistMat;

    float value_ranges[] = {(float)0, (float)MAX_DISP};
    const float* hist_ranges[] = {value_ranges};
    int channels[] = {0};
    int histSize[] = {MAX_DISP};

    struct timespec start, finish;
    double elapsed;

    while(1)
    {
        CYCLE++;

        // === CLEANUP ==
        image = cv::Mat::zeros(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8U);
        uhist = cv::Mat::zeros(IMAGE_HEIGHT, MAX_DISP, CV_32F);
        vhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);

        // === CREATE FAKE DISPARITY WITH OBJECTS ===
        for(int i = 0; i < IMAGE_HEIGHT; i++)
            image.row(i) = ((float)i / IMAGE_HEIGHT * MAX_DISP);

        draw_object(image, 200, 500);
        draw_object(image, 525 + CYCLE%100, 275);
        draw_object(image, 500, 300 + CYCLE%100);

        clock_gettime(CLOCK_MONOTONIC, &start);

        // === CALCULATE V-HIST ===
        for(int i = 0; i < IMAGE_HEIGHT; i++)
        {
            tmpImageMat = image.row(i);
            vhist.row(i).copyTo(tmpHistMat);

            cv::calcHist(&tmpImageMat, 1, channels, cv::Mat(), tmpHistMat, 1, histSize, hist_ranges, true, false);

            vhist.row(i) = tmpHistMat.t() / (float) IMAGE_HEIGHT;
        }

        clock_gettime(CLOCK_MONOTONIC, &finish);
        elapsed = (finish.tv_sec - start.tv_sec);
        elapsed += (finish.tv_nsec - start.tv_nsec) * 1e-9;
        cout << "V-HIST-TIME: " << elapsed << endl;

        clock_gettime(CLOCK_MONOTONIC, &start);

        // === CALCULATE U-HIST ===
        for(int i = 0; i < IMAGE_WIDTH; i++)
        {
            tmpImageMat = image.col(i);
            uhist.col(i).copyTo(tmpHistMat);

            cv::calcHist(&tmpImageMat, 1, channels, cv::Mat(), tmpHistMat, 1, histSize, hist_ranges, true, false);

            uhist.col(i) = tmpHistMat / (float) IMAGE_WIDTH;
        }

        clock_gettime(CLOCK_MONOTONIC, &finish);
        elapsed = (finish.tv_sec - start.tv_sec);
        elapsed += (finish.tv_nsec - start.tv_nsec) * 1e-9;
        cout << "U-HIST-TIME: " << elapsed << endl;

        // === PREPARE AND SHOW RESULTS ===

        uhist.convertTo(uhist, CV_8U, 255);
        cv::applyColorMap(uhist, uhist, cv::COLORMAP_JET);

        vhist.convertTo(vhist, CV_8U, 255);
        cv::applyColorMap(vhist, vhist, cv::COLORMAP_JET);

        cv::imshow("image", image);
        cv::imshow("uhist", uhist);
        cv::imshow("vhist", vhist);

        if ((cv::waitKey(1)&255) == 'q')
            break;
    }

    return 0;
}
</code>```

Figure 1: v-disparity

Figure 2: Fake disparity matrix

Figure 3: u-disparity

edit:

correct name for u- and v-disparity and separate time measurement in c++ example

small typo

答:
Very nice code and very illustrative. It helped me understand u-disparity.  However, your C/C++ code is broken. I fixed him with this code:</p>

```<code>cv::Mat uhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);
cv::Mat vhist = cv::Mat::zeros(IMAGE_WIDTH, MAX_DISP, CV_32F);
</code>```

Body:
Based on a disparity matrix from a passive stereo-camera system i need to calculate a v-disparity representation for obstacle detection with OpenCV.

A working implementation is not the problem. The problem is to do it fast...

(One) Reference for v-Disparity: Labayrade, R. and Aubert, D. and Tarel, J.P.
Real time obstacle detection in stereovision on non flat road geometry through v-disparity representation

The basic in short, to get the v-disparity (figure 1), is to analyze the rows of the disparity-matrix (figure 2) an represent the result as a histogram for each row over the disparity values. u-disparity (figure 3) is the same on the columns of the disparity-matrix. (All figures are false-colored.)

I have implement the "same" in Python and C++. The speed in Python is acceptable but in C++ i get for the u- and v-disparity a time round about a half second (0.5 s).

(1. edit: due to the separate time measurement, only the calculation of the u-histogram takes a big amount of time...)

This leads me to following questions:

Is it possible to avoid the loops for the line-wise calculation of the histogram? Is there a "trick" to do it with one call of calcHist-Function from OpenCV? Perhaps with the dimensions?

Is it in C++ just bad-coded and the runtime-issue are not related to the loops used for calculation?

Thanks, all

Working implementation in Python:

#!/usr/bin/env python2
#-*- coding: utf-8 -*-
#
# THIS SOURCE-CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED. IN NO  EVENT WILL THE AUTHOR BE HELD LIABLE FOR ANY DAMAGES ARISING FROM
# THE USE OF THIS SOURCE-CODE. USE AT YOUR OWN RISK.

import cv2
import numpy as np
import time

def draw_object(image, x, y, width=50, height=100):
    color = image[y, x]
    image[y-height:y, x-width//2:x+width//2] = color

IMAGE_HEIGHT = 600
IMAGE_WIDTH = 800

while True:

    max_disp = 200

    # create fake disparity
    image = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH), np.uint8)

    for c in range(IMAGE_HEIGHT)[::-1]:
        image[c, ...] = int(float(c) / IMAGE_HEIGHT * max_disp)

    draw_object(image, 275, 175)
    draw_object(image, 300, 200)
    draw_object(image, 100, 350)

    # calculate v-disparity
    vhist_vis = np.zeros((IMAGE_HEIGHT, max_disp), np.float)
    for i in range(IMAGE_HEIGHT):
        vhist_vis[i, ...] = cv2.calcHist(images=[image[i, ...]], channels=[0], mask=None, histSize=[max_disp],
                                         ranges=[0, max_disp]).flatten() / float(IMAGE_HEIGHT)

    vhist_vis = np.array(vhist_vis * 255, np.uint8)
    vblack_mask = vhist_vis < 5
    vhist_vis = cv2.applyColorMap(vhist_vis, cv2.COLORMAP_JET)
    vhist_vis[vblack_mask] = 0

    # calculate u-disparity
    uhist_vis = np.zeros((max_disp, IMAGE_WIDTH), np.float)
    for i in range(IMAGE_WIDTH):
        uhist_vis[..., i] = cv2.calcHist(images=[image[..., i]], channels=[0], mask=None, histSize=[max_disp],
                                         ranges=[0, max_disp]).flatten() / float(IMAGE_WIDTH)

    uhist_vis = np.array(uhist_vis * 255, np.uint8)
    ublack_mask = uhist_vis < 5
    uhist_vis = cv2.applyColorMap(uhist_vis, cv2.COLORMAP_JET)
    uhist_vis[ublack_mask] = 0

    image = cv2.applyColorMap(image, cv2.COLORMAP_JET)

    cv2.imshow('image', image)

    cv2.imshow('vhist_vis', vhist_vis)
    cv2.imshow('uhist_vis', uhist_vis)

    cv2.imwrite('disparity_image.png', image)
    cv2.imwrite('v-disparity.png', vhist_vis)
    cv2.imwrite('u-disparity.png', uhist_vis)

    if chr(cv2.waitKey(0)&255) == 'q':
        break

Working implementation in C++:

#include <iostream>
#include <stdlib.h>

#include <ctime>

#include <opencv2/opencv.hpp>

using namespace std;

void draw_object(cv::Mat image, unsigned int x, unsigned int y, unsigned int width=50, unsigned int height=100)
{
    image(cv::Range(y-height, y), cv::Range(x-width/2, x+width/2)) = image.at<unsigned char>(y, x);
}

int main()
{
    unsigned int IMAGE_HEIGHT = 600;
    unsigned int IMAGE_WIDTH = 800;
    unsigned int MAX_DISP = 250;
    unsigned int CYCLE = 0;

    //setenv("QT_GRAPHICSSYSTEM", "native", 1);

    // === PREPERATIONS ==
    cv::Mat image = cv::Mat::zeros(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8U);
    cv::Mat uhist = cv::Mat::zeros(IMAGE_HEIGHT, MAX_DISP, CV_32F);
    cv::Mat vhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);

    cv::Mat tmpImageMat, tmpHistMat;

    float value_ranges[] = {(float)0, (float)MAX_DISP};
    const float* hist_ranges[] = {value_ranges};
    int channels[] = {0};
    int histSize[] = {MAX_DISP};

    struct timespec start, finish;
    double elapsed;

    while(1)
    {
        CYCLE++;

        // === CLEANUP ==
        image = cv::Mat::zeros(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8U);
        uhist = cv::Mat::zeros(IMAGE_HEIGHT, MAX_DISP, CV_32F);
        vhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);

        // === CREATE FAKE DISPARITY WITH OBJECTS ===
        for(int i = 0; i < IMAGE_HEIGHT; i++)
            image.row(i) = ((float)i / IMAGE_HEIGHT * MAX_DISP);

        draw_object(image, 200, 500);
        draw_object(image, 525 + CYCLE%100, 275);
        draw_object(image, 500, 300 + CYCLE%100);

        clock_gettime(CLOCK_MONOTONIC, &start);

        // === CALCULATE V-HIST ===
        for(int i = 0; i < IMAGE_HEIGHT; i++)
        {
            tmpImageMat = image.row(i);
            vhist.row(i).copyTo(tmpHistMat);

            cv::calcHist(&tmpImageMat, 1, channels, cv::Mat(), tmpHistMat, 1, histSize, hist_ranges, true, false);

            vhist.row(i) = tmpHistMat.t() / (float) IMAGE_HEIGHT;
        }

        clock_gettime(CLOCK_MONOTONIC, &finish);
        elapsed = (finish.tv_sec - start.tv_sec);
        elapsed += (finish.tv_nsec - start.tv_nsec) * 1e-9;
        cout << "V-HIST-TIME: " << elapsed << endl;

        clock_gettime(CLOCK_MONOTONIC, &start);

        // === CALCULATE U-HIST ===
        for(int i = 0; i < IMAGE_WIDTH; i++)
        {
            tmpImageMat = image.col(i);
            uhist.col(i).copyTo(tmpHistMat);

            cv::calcHist(&tmpImageMat, 1, channels, cv::Mat(), tmpHistMat, 1, histSize, hist_ranges, true, false);

            uhist.col(i) = tmpHistMat / (float) IMAGE_WIDTH;
        }

        clock_gettime(CLOCK_MONOTONIC, &finish);
        elapsed = (finish.tv_sec - start.tv_sec);
        elapsed += (finish.tv_nsec - start.tv_nsec) * 1e-9;
        cout << "U-HIST-TIME: " << elapsed << endl;

        // === PREPARE AND SHOW RESULTS ===

        uhist.convertTo(uhist, CV_8U, 255);
        cv::applyColorMap(uhist, uhist, cv::COLORMAP_JET);

        vhist.convertTo(vhist, CV_8U, 255);
        cv::applyColorMap(vhist, vhist, cv::COLORMAP_JET);

        cv::imshow("image", image);
        cv::imshow("uhist", uhist);
        cv::imshow("vhist", vhist);

        if ((cv::waitKey(1)&255) == 'q')
            break;
    }

    return 0;
}

Figure 1: v-disparity

Figure 2: Fake disparity matrix

Figure 3: u-disparity

edit:

correct name for u- and v-disparity and separate time measurement in c++ example

small typo

Body:
Very nice code and very illustrative. It helped me understand u-disparity.  However, your C/C++ code is broken. I fixed him with this code:

cv::Mat uhist = cv::Mat::zeros(MAX_DISP, IMAGE_WIDTH, CV_32F);
cv::Mat vhist = cv::Mat::zeros(IMAGE_WIDTH, MAX_DISP, CV_32F);


问:
Adwords Scripts Search for 301 Redirects
I have a question about catching a 301 redirects by using Google Adwords scripts.
What I'm trying to filter is only the url-s that redirect to other domain, but not the ones that redirect for example from mysite.com to www.mysite.com.
Is there a way to do that?
I guess I have to use the UrlFetchApp method and then to compare the original url with the one returned in  the header.

Thanks :)

答:
You can use UrlFetchApp in combination with getResponseCode()

```<code> // The code below logs the HTTP status code from the response received
 // when fetching the Google home page.
 // It should be 200 if the request succeeded.
 var response = UrlFetchApp.fetch("http://www.google.com/");
 Logger.log(response.getResponseCode());
</code>```

So in your case you can check if the response code is 301

Body:
You can use UrlFetchApp in combination with getResponseCode()

 // The code below logs the HTTP status code from the response received
 // when fetching the Google home page.
 // It should be 200 if the request succeeded.
 var response = UrlFetchApp.fetch("http://www.google.com/");
 Logger.log(response.getResponseCode());

So in your case you can check if the response code is 301


问:
How to update specific entry in SQL database
```<code>Private Sub cmdRRupdate_Click(sender As Object, e As EventArgs) Handles cmdRRupdate.Click
        Dim i As Integer
        Dim o As Integer
        i = DataGridView1.CurrentRow.Index
        o = DataGridView1.CurrentCell.ColumnIndex

        cn.Open()
        cmd.CommandText = "update RepairRenovation Set Project_ID = '" & txtRRprojectID.Text & "', Date = '" & rrIdate.Value & "', Source_of_Fund = '" & txtRRsof.Text & "', Contractor = '" & txtRRcontractor.Text & "', Scope_of_Works = '" & txtRRsow.Text & "' where convert (varchar, ID_Number) = '" & DataGridView4.Item(0, i).Value & "'"
        cmd.ExecuteNonQuery()
        cn.Close()
        txtRRprojectID.Text = ""
        txtRRsof.Text = ""
        txtRRcontractor.Text = ""
        txtRRsof.Text = ""
        txtRRsow.Text = ""
        ref3()
    End Sub
</code>```

I used where convert (varchar, Project_ID) but whenever I update one entry, it updates the entry of all who have the same Project_ID. So, I used ID_Number as Primary Key to update the specific entry. But whenever I try to update it, the entry doesn't change/update.

答:
try this:

```<code>cmd.CommandText = "update RepairRenovation Set Project_ID = '" & txtRRprojectID.Text & "', Date = '" & rrIdate.Value & "', Source_of_Fund = '" & txtRRsof.Text & "', Contractor = '" & txtRRcontractor.Text & "', Scope_of_Works = '" & txtRRsow.Text & "' where ID_Number = " & DataGridView4.Item(0, i).Value
</code>```

Did You debug Your code? Have You looked at what is inside that string that is command text?

Body:
Private Sub cmdRRupdate_Click(sender As Object, e As EventArgs) Handles cmdRRupdate.Click
        Dim i As Integer
        Dim o As Integer
        i = DataGridView1.CurrentRow.Index
        o = DataGridView1.CurrentCell.ColumnIndex

        cn.Open()
        cmd.CommandText = "update RepairRenovation Set Project_ID = '" & txtRRprojectID.Text & "', Date = '" & rrIdate.Value & "', Source_of_Fund = '" & txtRRsof.Text & "', Contractor = '" & txtRRcontractor.Text & "', Scope_of_Works = '" & txtRRsow.Text & "' where convert (varchar, ID_Number) = '" & DataGridView4.Item(0, i).Value & "'"
        cmd.ExecuteNonQuery()
        cn.Close()
        txtRRprojectID.Text = ""
        txtRRsof.Text = ""
        txtRRcontractor.Text = ""
        txtRRsof.Text = ""
        txtRRsow.Text = ""
        ref3()
    End Sub

I used where convert (varchar, Project_ID) but whenever I update one entry, it updates the entry of all who have the same Project_ID. So, I used ID_Number as Primary Key to update the specific entry. But whenever I try to update it, the entry doesn't change/update.

Body:
try this:

cmd.CommandText = "update RepairRenovation Set Project_ID = '" & txtRRprojectID.Text & "', Date = '" & rrIdate.Value & "', Source_of_Fund = '" & txtRRsof.Text & "', Contractor = '" & txtRRcontractor.Text & "', Scope_of_Works = '" & txtRRsow.Text & "' where ID_Number = " & DataGridView4.Item(0, i).Value

Did You debug Your code? Have You looked at what is inside that string that is command text?


问:
How to convert this LINQ query syntax that connects two objects to method syntax?
How to do this in method syntax form:

```<code>foreach (var o in from o in orders
                  from oi in o.OrderItems
                  where oi.ProductName == "Widgets"
                  select o.OrderID)
    Console.WriteLine("{0}", o);
</code>```

tried this but not working:

```<code>foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new {<<idk what to put here>> })
    .Where(oi => oi.ProductName == "Widget"))
{
    Console.WriteLine("WIDGET: {0}", o.OrderID);
}
</code>```

Finally I used this code and it worked!

```<code>foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new { o.OrderID, oi.ProductName })
    .Where(oi => oi.ProductName == "Widgets"))
{
    Console.WriteLine("{0}", o.OrderID);
}
</code>```

答:
Here's the solution to your problem.
You should be using something like this :

```<code>foreach (var item in orders.SelectMany(x => x.OrderItems).Where(y => y.ProductName == "Widgets"))
            {
                Console.WriteLine("{0}", item.OrderId);
            }
</code>```

I have created a working sample to your problem : Click Here

Hope this solves your problem. Thanks!!

Body:
How to do this in method syntax form:

foreach (var o in from o in orders
                  from oi in o.OrderItems
                  where oi.ProductName == "Widgets"
                  select o.OrderID)
    Console.WriteLine("{0}", o);

tried this but not working:

foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new {<<idk what to put here>> })
    .Where(oi => oi.ProductName == "Widget"))
{
    Console.WriteLine("WIDGET: {0}", o.OrderID);
}

Finally I used this code and it worked!

foreach (var o in orders
    .SelectMany(o => o.OrderItems, (o, oi) => new { o.OrderID, oi.ProductName })
    .Where(oi => oi.ProductName == "Widgets"))
{
    Console.WriteLine("{0}", o.OrderID);
}

Body:
Here's the solution to your problem.
You should be using something like this :

foreach (var item in orders.SelectMany(x => x.OrderItems).Where(y => y.ProductName == "Widgets"))
            {
                Console.WriteLine("{0}", item.OrderId);
            }

I have created a working sample to your problem : Click Here

Hope this solves your problem. Thanks!!


问:
R edit file, how to suppress R [1] and quotes in output
I'm doing very simple thing (I thought) and having this line # brackets and double quotes in my output file, how to suppress this? My goal just replace string in file, and either to edit it or create new file.

```<code>d <- readLines("C:\\R\\MX1_vx.txt")
d
d1 <-   paste(substr(d,1,15),"  00000")
d1
sink('out_v5.txt')
d1
sink()
</code>```

and this my console output.

```<code>> d
[1] "01 Alpha   1400101211101100110011101111111100 1"
[2] "02 Bravo   2500101211101100110011101111111100 2"
[3] "03 Charlie 3600101211101100110011101111111100 3"
</code>```

In out_v5 file I see those chars, I actually that, there only 2 lines.

```<code>[1] "01 Alpha   1400   00000" "02 Bravo   2500   00000"
[3] "03 Charlie 3600   00000"
</code>```

答:
Using write() instead of sink() , I get the output without [1] and "s like this :

01 Alpha   1400   00000

02 Bravo   2500   00000

03 Charlie 3600   00000

```<code>    d <- readLines("C:\\R\\MX1_vx.txt")
    d1 <-   paste(substr(d,1,15),"  00000")
    write(d1, "out.txt")
</code>```

Body:
I'm doing very simple thing (I thought) and having this line # brackets and double quotes in my output file, how to suppress this? My goal just replace string in file, and either to edit it or create new file.

d <- readLines("C:\\R\\MX1_vx.txt")
d
d1 <-   paste(substr(d,1,15),"  00000")
d1
sink('out_v5.txt')
d1
sink()

and this my console output.

> d
[1] "01 Alpha   1400101211101100110011101111111100 1"
[2] "02 Bravo   2500101211101100110011101111111100 2"
[3] "03 Charlie 3600101211101100110011101111111100 3"

In out_v5 file I see those chars, I actually that, there only 2 lines.

[1] "01 Alpha   1400   00000" "02 Bravo   2500   00000"
[3] "03 Charlie 3600   00000"

Body:
Using write() instead of sink() , I get the output without [1] and "s like this :

01 Alpha   1400   00000

02 Bravo   2500   00000

03 Charlie 3600   00000

    d <- readLines("C:\\R\\MX1_vx.txt")
    d1 <-   paste(substr(d,1,15),"  00000")
    write(d1, "out.txt")


问:
ValueError: invalid fill value with a <class 'pandas.core.frame.DataFrame'>
I am practising on a loan prediction practise problem and trying to fill missing values in my data. I obtained the data from here. To complete this problem I am following this tutorial.

You can find the entire code (file name model.py) I am using  and the data here on GitHub.

The DataFrame looks like this:

```<code>df[['Loan_ID', 'Self_Employed', 'Education', 'LoanAmount']].head(10)
Out:
    Loan_ID Self_Employed     Education  LoanAmount
0  LP001002            No      Graduate         NaN
1  LP001003            No      Graduate       128.0
2  LP001005           Yes      Graduate        66.0
3  LP001006            No  Not Graduate       120.0
4  LP001008            No      Graduate       141.0
5  LP001011           Yes      Graduate       267.0
6  LP001013            No  Not Graduate        95.0
7  LP001014            No      Graduate       158.0
8  LP001018            No      Graduate       168.0
9  LP001020            No      Graduate       349.0
</code>```

After the last line is executed (corresponds to line 60 in the model.py file)

```<code>url = 'https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'
df = pd.read_csv(url)
df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)
df['Self_Employed'].fillna('No',inplace=True)

table = df.pivot_table(values='LoanAmount', index='Self_Employed' ,columns='Education', aggfunc=np.median)
# Define function to return value of this pivot_table
def fage(x):
 return table.loc[x['Self_Employed'],x['Education']]
# Replace missing values
df['LoanAmount'].fillna(df[df['LoanAmount'].isnull()].apply(fage, axis=1), inplace=True)
</code>```

I am getting this error :

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-40-5146e49c2460> in <module>()
----> 1 df['LoanAmount'].fillna(df[df['LoanAmount'].isnull()].apply(fage, axis=1), inplace=True)

/usr/local/lib/python2.7/dist-packages/pandas/core/series.pyc in fillna(self, value, method, axis, inplace, limit, downcast, **kwargs)
   2368                                           axis=axis, inplace=inplace,
   2369                                           limit=limit, downcast=downcast,
-> 2370                                           **kwargs)
   2371
   2372     @Appender(generic._shared_docs['shift'] % _shared_doc_kwargs)

/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in fillna(self, value, method, axis, inplace, limit, downcast)
   3264                 else:
   3265                     raise ValueError("invalid fill value with a %s" %
-> 3266                                      type(value))
   3267
   3268                 new_data = self._data.fillna(value=value, limit=limit,

ValueError: invalid fill value with a <class 'pandas.core.frame.DataFrame'>
</code>```

How do I fill the missing values without getting this error?

答:
It seems author of tutorial want replace NaN by values of table.

But need first create Series by unstack and set_index for align data.

First remove replacing to NaN by mean:

```<code>url='https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'

df = pd.read_csv(url) #Reading the dataset in a dataframe using Pandas

#df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)

df['Self_Employed'].fillna('No',inplace=True)
</code>```

```<code>table = df.pivot_table(values='LoanAmount',
                       index='Self_Employed',
                       columns='Education',
                       aggfunc=np.median)

print (table.unstack())
Education     Self_Employed
Graduate      No               130.0
              Yes              157.5
Not Graduate  No               113.0
              Yes              130.0
dtype: float64
</code>```

```<code>#check all values with NaN in LoanAmount column
print (df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate         NaN
35             No      Graduate         NaN
63             No      Graduate         NaN
81            Yes      Graduate         NaN
95             No      Graduate         NaN
102            No      Graduate         NaN
103            No      Graduate         NaN
113           Yes      Graduate         NaN
127            No      Graduate         NaN
202            No  Not Graduate         NaN
284            No      Graduate         NaN
305            No  Not Graduate         NaN
322            No  Not Graduate         NaN
338            No  Not Graduate         NaN
387            No  Not Graduate         NaN
435            No      Graduate         NaN
437            No      Graduate         NaN
479            No      Graduate         NaN
524            No      Graduate         NaN
550           Yes      Graduate         NaN
551            No  Not Graduate         NaN
605            No  Not Graduate         NaN
</code>```

```<code>#for check get all indexes where NaNs
idx = df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']].index
print (idx)
Int64Index([  0,  35,  63,  81,  95, 102, 103, 113, 127, 202, 284, 305, 322,
            338, 387, 435, 437, 479, 524, 550, 551, 605],

# Replace missing values
df = df.set_index(['Education','Self_Employed'])
df['LoanAmount'].fillna(table.unstack(), inplace=True)
df = df.reset_index()
</code>```

```<code>#check output - filter only indexes where NaNs before
print (df.loc[df.index.isin(idx), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate       130.0
35             No      Graduate       130.0
63             No      Graduate       130.0
81            Yes      Graduate       157.5
95             No      Graduate       130.0
102            No      Graduate       130.0
103            No      Graduate       130.0
113           Yes      Graduate       157.5
127            No      Graduate       130.0
202            No  Not Graduate       113.0
284            No      Graduate       130.0
305            No  Not Graduate       113.0
322            No  Not Graduate       113.0
338            No  Not Graduate       113.0
387            No  Not Graduate       113.0
435            No      Graduate       130.0
437            No      Graduate       130.0
479            No      Graduate       130.0
524            No      Graduate       130.0
550           Yes      Graduate       157.5
551            No  Not Graduate       113.0
605            No  Not Graduate       113.0
</code>```

EDIT:

Better solution is groupby with apply where replace NaN by median:

```<code>url='https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'

df = pd.read_csv(url) #Reading the dataset in a dataframe using Pandas

#df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)

df['Self_Employed'].fillna('No',inplace=True)

print (df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate         NaN
35             No      Graduate         NaN
63             No      Graduate         NaN
81            Yes      Graduate         NaN
95             No      Graduate         NaN
102            No      Graduate         NaN
103            No      Graduate         NaN
113           Yes      Graduate         NaN
127            No      Graduate         NaN
202            No  Not Graduate         NaN
284            No      Graduate         NaN
305            No  Not Graduate         NaN
322            No  Not Graduate         NaN
338            No  Not Graduate         NaN
387            No  Not Graduate         NaN
435            No      Graduate         NaN
437            No      Graduate         NaN
479            No      Graduate         NaN
524            No      Graduate         NaN
550           Yes      Graduate         NaN
551            No  Not Graduate         NaN
605            No  Not Graduate         NaN
</code>```

```<code>idx = df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']].index
print (idx)
Int64Index([  0,  35,  63,  81,  95, 102, 103, 113, 127, 202, 284, 305, 322,
            338, 387, 435, 437, 479, 524, 550, 551, 605],
           dtype='int64')

# Replace missing values
df['LoanAmount'] = df.groupby(['Education','Self_Employed'])['LoanAmount']
                     .apply(lambda x: x.fillna(x.median()))
</code>```

```<code>print (df.loc[df.index.isin(idx), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate       130.0
35             No      Graduate       130.0
63             No      Graduate       130.0
81            Yes      Graduate       157.5
95             No      Graduate       130.0
102            No      Graduate       130.0
103            No      Graduate       130.0
113           Yes      Graduate       157.5
127            No      Graduate       130.0
202            No  Not Graduate       113.0
284            No      Graduate       130.0
305            No  Not Graduate       113.0
322            No  Not Graduate       113.0
338            No  Not Graduate       113.0
387            No  Not Graduate       113.0
435            No      Graduate       130.0
437            No      Graduate       130.0
479            No      Graduate       130.0
524            No      Graduate       130.0
550           Yes      Graduate       157.5
551            No  Not Graduate       113.0
605            No  Not Graduate       113.0
</code>```

EDIT:

There is another problem:

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

And solution is replace NaNs:

```<code>df['Loan_Status'].fillna('No',inplace=True)
df['Credit_History'].fillna(0,inplace=True)

outcome_var = 'Loan_Status'
model = LogisticRegression()
predictor_var = ['Credit_History']

classification_model(model, df, predictor_var,outcome_var)
</code>```

Body:
I am practising on a loan prediction practise problem and trying to fill missing values in my data. I obtained the data from here. To complete this problem I am following this tutorial.

You can find the entire code (file name model.py) I am using  and the data here on GitHub.

The DataFrame looks like this:

df[['Loan_ID', 'Self_Employed', 'Education', 'LoanAmount']].head(10)
Out:
    Loan_ID Self_Employed     Education  LoanAmount
0  LP001002            No      Graduate         NaN
1  LP001003            No      Graduate       128.0
2  LP001005           Yes      Graduate        66.0
3  LP001006            No  Not Graduate       120.0
4  LP001008            No      Graduate       141.0
5  LP001011           Yes      Graduate       267.0
6  LP001013            No  Not Graduate        95.0
7  LP001014            No      Graduate       158.0
8  LP001018            No      Graduate       168.0
9  LP001020            No      Graduate       349.0

After the last line is executed (corresponds to line 60 in the model.py file)

url = 'https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'
df = pd.read_csv(url)
df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)
df['Self_Employed'].fillna('No',inplace=True)

table = df.pivot_table(values='LoanAmount', index='Self_Employed' ,columns='Education', aggfunc=np.median)
# Define function to return value of this pivot_table
def fage(x):
 return table.loc[x['Self_Employed'],x['Education']]
# Replace missing values
df['LoanAmount'].fillna(df[df['LoanAmount'].isnull()].apply(fage, axis=1), inplace=True)

I am getting this error :

ValueError                                Traceback (most recent call last)
<ipython-input-40-5146e49c2460> in <module>()
----> 1 df['LoanAmount'].fillna(df[df['LoanAmount'].isnull()].apply(fage, axis=1), inplace=True)

/usr/local/lib/python2.7/dist-packages/pandas/core/series.pyc in fillna(self, value, method, axis, inplace, limit, downcast, **kwargs)
   2368                                           axis=axis, inplace=inplace,
   2369                                           limit=limit, downcast=downcast,
-> 2370                                           **kwargs)
   2371
   2372     @Appender(generic._shared_docs['shift'] % _shared_doc_kwargs)

/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in fillna(self, value, method, axis, inplace, limit, downcast)
   3264                 else:
   3265                     raise ValueError("invalid fill value with a %s" %
-> 3266                                      type(value))
   3267
   3268                 new_data = self._data.fillna(value=value, limit=limit,

ValueError: invalid fill value with a <class 'pandas.core.frame.DataFrame'>

How do I fill the missing values without getting this error?

Body:
It seems author of tutorial want replace NaN by values of table.

But need first create Series by unstack and set_index for align data.

First remove replacing to NaN by mean:

url='https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'

df = pd.read_csv(url) #Reading the dataset in a dataframe using Pandas

#df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)

df['Self_Employed'].fillna('No',inplace=True)

table = df.pivot_table(values='LoanAmount',
                       index='Self_Employed',
                       columns='Education',
                       aggfunc=np.median)

print (table.unstack())
Education     Self_Employed
Graduate      No               130.0
              Yes              157.5
Not Graduate  No               113.0
              Yes              130.0
dtype: float64

#check all values with NaN in LoanAmount column
print (df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate         NaN
35             No      Graduate         NaN
63             No      Graduate         NaN
81            Yes      Graduate         NaN
95             No      Graduate         NaN
102            No      Graduate         NaN
103            No      Graduate         NaN
113           Yes      Graduate         NaN
127            No      Graduate         NaN
202            No  Not Graduate         NaN
284            No      Graduate         NaN
305            No  Not Graduate         NaN
322            No  Not Graduate         NaN
338            No  Not Graduate         NaN
387            No  Not Graduate         NaN
435            No      Graduate         NaN
437            No      Graduate         NaN
479            No      Graduate         NaN
524            No      Graduate         NaN
550           Yes      Graduate         NaN
551            No  Not Graduate         NaN
605            No  Not Graduate         NaN

#for check get all indexes where NaNs
idx = df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']].index
print (idx)
Int64Index([  0,  35,  63,  81,  95, 102, 103, 113, 127, 202, 284, 305, 322,
            338, 387, 435, 437, 479, 524, 550, 551, 605],

# Replace missing values
df = df.set_index(['Education','Self_Employed'])
df['LoanAmount'].fillna(table.unstack(), inplace=True)
df = df.reset_index()

#check output - filter only indexes where NaNs before
print (df.loc[df.index.isin(idx), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate       130.0
35             No      Graduate       130.0
63             No      Graduate       130.0
81            Yes      Graduate       157.5
95             No      Graduate       130.0
102            No      Graduate       130.0
103            No      Graduate       130.0
113           Yes      Graduate       157.5
127            No      Graduate       130.0
202            No  Not Graduate       113.0
284            No      Graduate       130.0
305            No  Not Graduate       113.0
322            No  Not Graduate       113.0
338            No  Not Graduate       113.0
387            No  Not Graduate       113.0
435            No      Graduate       130.0
437            No      Graduate       130.0
479            No      Graduate       130.0
524            No      Graduate       130.0
550           Yes      Graduate       157.5
551            No  Not Graduate       113.0
605            No  Not Graduate       113.0

EDIT:

Better solution is groupby with apply where replace NaN by median:

url='https://raw.githubusercontent.com/Aniruddh-SK/Loan-Prediction-Problem/master/train.csv'

df = pd.read_csv(url) #Reading the dataset in a dataframe using Pandas

#df['LoanAmount'].fillna(df['LoanAmount'].mean(), inplace=True)

df['Self_Employed'].fillna('No',inplace=True)

print (df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate         NaN
35             No      Graduate         NaN
63             No      Graduate         NaN
81            Yes      Graduate         NaN
95             No      Graduate         NaN
102            No      Graduate         NaN
103            No      Graduate         NaN
113           Yes      Graduate         NaN
127            No      Graduate         NaN
202            No  Not Graduate         NaN
284            No      Graduate         NaN
305            No  Not Graduate         NaN
322            No  Not Graduate         NaN
338            No  Not Graduate         NaN
387            No  Not Graduate         NaN
435            No      Graduate         NaN
437            No      Graduate         NaN
479            No      Graduate         NaN
524            No      Graduate         NaN
550           Yes      Graduate         NaN
551            No  Not Graduate         NaN
605            No  Not Graduate         NaN

idx = df.loc[df['LoanAmount'].isnull(), ['Self_Employed','Education', 'LoanAmount']].index
print (idx)
Int64Index([  0,  35,  63,  81,  95, 102, 103, 113, 127, 202, 284, 305, 322,
            338, 387, 435, 437, 479, 524, 550, 551, 605],
           dtype='int64')

# Replace missing values
df['LoanAmount'] = df.groupby(['Education','Self_Employed'])['LoanAmount']
                     .apply(lambda x: x.fillna(x.median()))

print (df.loc[df.index.isin(idx), ['Self_Employed','Education', 'LoanAmount']])
    Self_Employed     Education  LoanAmount
0              No      Graduate       130.0
35             No      Graduate       130.0
63             No      Graduate       130.0
81            Yes      Graduate       157.5
95             No      Graduate       130.0
102            No      Graduate       130.0
103            No      Graduate       130.0
113           Yes      Graduate       157.5
127            No      Graduate       130.0
202            No  Not Graduate       113.0
284            No      Graduate       130.0
305            No  Not Graduate       113.0
322            No  Not Graduate       113.0
338            No  Not Graduate       113.0
387            No  Not Graduate       113.0
435            No      Graduate       130.0
437            No      Graduate       130.0
479            No      Graduate       130.0
524            No      Graduate       130.0
550           Yes      Graduate       157.5
551            No  Not Graduate       113.0
605            No  Not Graduate       113.0

EDIT:

There is another problem:

ValueError: Input contains NaN, infinity or a value too large for dtype('float64').

And solution is replace NaNs:

df['Loan_Status'].fillna('No',inplace=True)
df['Credit_History'].fillna(0,inplace=True)

outcome_var = 'Loan_Status'
model = LogisticRegression()
predictor_var = ['Credit_History']

classification_model(model, df, predictor_var,outcome_var)


问:
Extract all hrefs from an HTML url
I want to extract all hrefs  from:

https://plugins.svn.wordpress.org/

and add to a foreach loop.

I've tried using PHP Simple HTML DOM Parser http://simplehtmldom.sourceforge.net/

But it just times out....
Any help would be appreciated.
here is my code:

```<code>// Create DOM from URL or file
$html = file_get_html('https://plugins.svn.wordpress.org/');

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>';
</code>```

OR
Using Object orient way:

```<code>// Create a DOM object
$html = new simple_html_dom();

// Load HTML from a URL
$html->load_file('https://plugins.svn.wordpress.org/');

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>';
</code>```

答:
Solved your issue please use this code will help you better

```<code><?php
$html = file_get_contents('http://niraj140792.wordpress.com/');
//Create a new DOM document
$dom = new DOMDocument;

@$dom->loadHTML($html);

$links = $dom->getElementsByTagName('a');

foreach ($links as $link){
    //Extract and show the "href" attribute.
    echo $link->nodeValue;
    echo $link->getAttribute('href'), '<br>';
}
?>
</code>```

Title: Extract all hrefs from an HTML url

Body:
I want to extract all hrefs  from:

https://plugins.svn.wordpress.org/

and add to a foreach loop.

I've tried using PHP Simple HTML DOM Parser http://simplehtmldom.sourceforge.net/

But it just times out....
Any help would be appreciated.
here is my code:

// Create DOM from URL or file
$html = file_get_html('https://plugins.svn.wordpress.org/');

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '
';

OR
Using Object orient way:

// Create a DOM object
$html = new simple_html_dom();

// Load HTML from a URL
$html->load_file('https://plugins.svn.wordpress.org/');

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '
';

Body:
Solved your issue please use this code will help you better

<?php
$html = file_get_contents('http://niraj140792.wordpress.com/');
//Create a new DOM document
$dom = new DOMDocument;

@$dom->loadHTML($html);

$links = $dom->getElementsByTagName('a');

foreach ($links as $link){
    //Extract and show the "href" attribute.
    echo $link->nodeValue;
    echo $link->getAttribute('href'), '<br>';
}
?>


问:
Static final field in a class vs Interface field in java
I need to create a 100 or more static final constants in my application and I can achieve this is following two ways as per my understanding:

Creating a simple java class and create static final field in that

Creating an interface an put all variable in that because all field in an interface is implicitly static final

I have these question in above approach:

Which one is right approach to achieve this?

Which one is memory efficient approach?

Is there any design pattern to achieve this?

答:
I think that convenient way is to keep them in one place, if they are have common nature. Anyway, they should be grouped by some attribute. You can create class for them like this:

```<code>public final class Consts {
    public static class GroupA {...}
    public static class GroupB {...}
    //and so on
}
</code>```

With groups this class becomes much readable and a little bit better manageable. About memory consumption, try to use primitives for your constants, because they do not require additional space for meta information.

Body:
I think that convenient way is to keep them in one place, if they are have common nature. Anyway, they should be grouped by some attribute. You can create class for them like this:

public final class Consts {
    public static class GroupA {...}
    public static class GroupB {...}
    //and so on
}

With groups this class becomes much readable and a little bit better manageable. About memory consumption, try to use primitives for your constants, because they do not require additional space for meta information.


问:
Laravel Conditional Clause When()
I am new to Laravel and have encountered a problem using when() function. To start this  I do have a form consisting of 3 input fields named: name, email, and password.

```<code><form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>
</code>```

Also I have this code inside a controller file.

```<code>$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();
</code>```

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

```<code>$role = $request->input('name');
</code>```

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.

答: The when method will execute the given callback when the first argument given to the method evaluates to true.</p>

Title: Laravel Conditional Clause When()

Body:
I am new to Laravel and have encountered a problem using when() function. To start this  I do have a form consisting of 3 input fields named: name, email, and password.

<form method="post" action="/users">
    <?php echo csrf_field(); ?>
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
<input type="submit" value="Create">
</form>

Also I have this code inside a controller file.

$role = $request->input('role');

        $first = User::when($role,function ($query) use ($role){
            return $query->where('username',$role);
        })->get();

Based on Laravel documentation this shouldn't work as no elements named 'role' in the form that I submitted and $role variable must return false. But when I loop the $first variable, It has all the records inside of Users table. So I tried correcting and put

$role = $request->input('name');

So it works perfectly when I put a name that is inside the User table. But when I type nothing at (input type='text' name='name') element and submit the form. It shows all the records inside of Users table again. I am really confused, I think it has something to do with the 'false' or 'empty' returned by the $request->input(). Please advise. Thanks.


答:
Create a so called tally table (see e. g. here: https://dwaincsql.com/2014/03/27/tally-tables-in-t-sql/) and use it to create all dates between "from" and "to" date.

```<code>SELECT TOP 1000000 N=IDENTITY(INT, 1, 1)
INTO dbo.Tally
FROM master.dbo.syscolumns a CROSS JOIN master.dbo.syscolumns  b;
go

declare @dateFrom datetime = '20170101';
declare @dateTo   datetime = '20170105';

select dateadd(day, N - 1, @dateFrom)
  from Tally
 where N between 1 and datediff(day, @dateFrom, @dateTo) + 1
</code>```

Or:

```<code>select dateadd(day, t.N - 1, o.DateFrom)
  from Tally t
 cross join OtherTable o
 where t.N between 1 and datediff(day, o.DateFrom, o.DateTo) + 1
</code>```

A tally table is very useful for such cases, it could also be filled with dates in a second column, starting from 1900-01-01 or so.

Title: sql server print all dates between two date columns

Body:
i have a table containing 3 columns. ID,Start_Date,End_Date.i want to print all the days between Start_Date and End_Date along with ID.
For Example i have table

+----+------------+------------+
| ID | Start_Date | End_Date   |
+----+------------+------------+
| 1  | 2017-01-01 | 2017-01-05 |
+----+------------+------------+

and i want result like

+----+------------+
| ID | Date       |
+----+------------+
| 1  | 2017-01-01 |
| 1  | 2017-01-02 |
| 1  | 2017-01-03 |
| 1  | 2017-01-04 |
| 1  | 2017-04-05 |
+----+------------+

Body:
Create a so called tally table (see e. g. here: https://dwaincsql.com/2014/03/27/tally-tables-in-t-sql/) and use it to create all dates between "from" and "to" date.

SELECT TOP 1000000 N=IDENTITY(INT, 1, 1)
INTO dbo.Tally
FROM master.dbo.syscolumns a CROSS JOIN master.dbo.syscolumns  b;
go

declare @dateFrom datetime = '20170101';
declare @dateTo   datetime = '20170105';

select dateadd(day, N - 1, @dateFrom)
  from Tally
 where N between 1 and datediff(day, @dateFrom, @dateTo) + 1

Or:

select dateadd(day, t.N - 1, o.DateFrom)
  from Tally t
 cross join OtherTable o
 where t.N between 1 and datediff(day, o.DateFrom, o.DateTo) + 1

A tally table is very useful for such cases, it could also be filled with dates in a second column, starting from 1900-01-01 or so.


问:
NullReferenceException 6
I am getting wrong .Plz anyone help

** System.NullReferenceException: Object reference not set to an instance of an object.

//Line 35:   SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);

```<code> if(!IsPostBack)

    {
        if( Session["Login"] == null && Request.Cookies["Login"]==null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {

            string cs = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);
                cmd.CommandType = CommandType.StoredProcedure;
                 con.Open();
                 using (SqlDataReader rdr = cmd.ExecuteReader())
                 {
                     while (rdr.Read())
                     {
                       LabelUN.Text = rdr["UserName"].ToString();
                     }
                 }
                 con.Close();
            }

            Response.ClearHeaders();
            Response.AddHeader("Cache-Control", "no-cache,no-store,max-age=0,must-revalidate");
            Response.AddHeader("Pragma", "no-cache");

        }
    }

}
</code>```

答:
First check value of Request.Cookies["Login"] and Request.Cookies["Login"]["UserName"] in quick watch. Add check of null in if condition on it.

```<code>if(Request.Cookies["Login"] != null AND Request.Cookies["Login"]["UserName"].ToString() != null)
{
 /// Your implementation.
}
</code>```

FROM is missing in your query. Add FROM like Select * FROM UserInfm

Title: NullReferenceException 6

Body:
I am getting wrong .Plz anyone help

** System.NullReferenceException: Object reference not set to an instance of an object.

//Line 35:   SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);

 if(!IsPostBack)

    {
        if( Session["Login"] == null && Request.Cookies["Login"]==null)
        {
            Response.Redirect("Login.aspx");
        }
        else
        {

            string cs = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd = new SqlCommand("Select * UserInfm where UserName = '" + Request.Cookies["Login"]["UserName"].ToString() + "' ", con);
                cmd.CommandType = CommandType.StoredProcedure;
                 con.Open();
                 using (SqlDataReader rdr = cmd.ExecuteReader())
                 {
                     while (rdr.Read())
                     {
                       LabelUN.Text = rdr["UserName"].ToString();
                     }
                 }
                 con.Close();
            }

            Response.ClearHeaders();
            Response.AddHeader("Cache-Control", "no-cache,no-store,max-age=0,must-revalidate");
            Response.AddHeader("Pragma", "no-cache");

        }
    }

}

Body:
First check value of Request.Cookies["Login"] and Request.Cookies["Login"]["UserName"] in quick watch. Add check of null in if condition on it.

if(Request.Cookies["Login"] != null AND Request.Cookies["Login"]["UserName"].ToString() != null)
{
 /// Your implementation.
}

FROM is missing in your query. Add FROM like Select * FROM UserInfm


问:
how to get a node's private IP using kubernetes go-client?
In my kubernetes cluster, all nodes have both a public IP and a private IP. I am using kubernetes go-client and want to get node's private IP like below code snippet:

```<code>for _, addr := range n.Status.Addresses {
    if addr.Type == kube_api.NodeInternalIP && addr.Address != "" {
        fmt.Println("internal IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
    if addr.Type == kube_api.NodeExternalIP && addr.Address != "" {
        fmt.Println("external IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
    if addr.Type == kube_api.NodeLegacyHostIP && addr.Address != "" {
        fmt.Println("lgeacyhost IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
}
</code>```

However, the NodeInternalIP and NodeExternalIP all returns the public IP.

Is there a way to get the private IP of a node?

Thanks a lot.

答:
This should provide you the node's Internal private IP

```<code>kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
</code>```

172.20.38.232 172.20.48.54 172.20.53.226 172.20.55.210

Body:
In my kubernetes cluster, all nodes have both a public IP and a private IP. I am using kubernetes go-client and want to get node's private IP like below code snippet:

for _, addr := range n.Status.Addresses {
    if addr.Type == kube_api.NodeInternalIP && addr.Address != "" {
        fmt.Println("internal IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
    if addr.Type == kube_api.NodeExternalIP && addr.Address != "" {
        fmt.Println("external IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
    if addr.Type == kube_api.NodeLegacyHostIP && addr.Address != "" {
        fmt.Println("lgeacyhost IP")
        nodeIP = addr.Address
        fmt.Println(nodeIP)
    }
}

However, the NodeInternalIP and NodeExternalIP all returns the public IP.

Is there a way to get the private IP of a node?

Thanks a lot.

Body:
This should provide you the node's Internal private IP

kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'

172.20.38.232 172.20.48.54 172.20.53.226 172.20.55.210


问:
how to find which word has maximum tfidf in a tfidf matrix for a single document?
I'm curently using the following code. I have stored the tfidf matrix for all the documents, now I need the top n words for a particular document?
I am confused on how to get it?

This is the code I used till now. I need to find the words now from each document with highest tfidf

```<code>import glob
import pandas as pd
import math
filenames=[]
corpus = []
df=pd.DataFrame(columns=['article','similar','score'])
for file in glob.glob("*.txt"):
    with open(file, "r") as paper:
    corpus.append((file, paper.read()))
    filenames.append(file)
from sklearn.feature_extraction.text import TfidfVectorizer

tf = TfidfVectorizer(analyzer='word', ngram_range=(1,1), min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform([content for file, content in corpus])
</code>```

答:
You can get the index using np.argmax then use this to lookup the corresponding word in the TfidfVectorizer._vocabulary, as:

```<code>vocab_lookup = {v:k for k,v in tf.vocabulary_.items()}
[vocab_lookup[np.argmax(v)] for v in tfidf_matrix]
</code>```

Body:
I'm curently using the following code. I have stored the tfidf matrix for all the documents, now I need the top n words for a particular document?
I am confused on how to get it?

This is the code I used till now. I need to find the words now from each document with highest tfidf

import glob
import pandas as pd
import math
filenames=[]
corpus = []
df=pd.DataFrame(columns=['article','similar','score'])
for file in glob.glob("*.txt"):
    with open(file, "r") as paper:
    corpus.append((file, paper.read()))
    filenames.append(file)
from sklearn.feature_extraction.text import TfidfVectorizer

tf = TfidfVectorizer(analyzer='word', ngram_range=(1,1), min_df = 0, stop_words = 'english')
tfidf_matrix =  tf.fit_transform([content for file, content in corpus])

Body:
You can get the index using np.argmax then use this to lookup the corresponding word in the TfidfVectorizer._vocabulary, as:

vocab_lookup = {v:k for k,v in tf.vocabulary_.items()}
[vocab_lookup[np.argmax(v)] for v in tfidf_matrix]


问:
git stash apply version
I have 2 branches: master | design

Working in design I did a stash and switched to master, made some adjustments. Switched back to design and did a stash apply only to lose all my changes in the design branch.

I am hoping all my work is within a stash as I have not cleared or removed these.

If I do a stash list I get 4 results:

```<code>stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust
</code>```

If I try git stash apply f2c0c72 I am getting an error:

```<code>fatal: Needed a single revision
f2c0c72: no valid stashed state found
</code>```

How can I apply a specific stash?

答:
Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}".
So now instead of using:

```<code>git stash apply "stash@{n}"
</code>```

You can type:

```<code>git stash apply n
</code>```

For example, in your list:

```<code>stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust
</code>```

If you want to apply stash@{1} you could type:

```<code>git stash apply 1
</code>```

Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:

```<code>error: Your local changes to the following files would be overwritten by merge:
        file
Please commit your changes or stash them before you merge.
</code>```

In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.

Git release notes:

Release Notes 2.11

The user always has to say "stash@{$N}" when naming a single element
  in the default location of the stash, i.e. reflogs in refs/stash.  The
  "git stash" command learned to accept "git stash apply 4" as a
  short-hand for "git stash apply stash@{4}"

Release Notes 1.7.5.1

git stash apply" used to refuse to work if there was any change in the
  working tree, even when the change did not overlap with the change the
  stash recorded

Title: git stash apply version

Body:
I have 2 branches: master | design

Working in design I did a stash and switched to master, made some adjustments. Switched back to design and did a stash apply only to lose all my changes in the design branch.

I am hoping all my work is within a stash as I have not cleared or removed these.

If I do a stash list I get 4 results:

stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust

If I try git stash apply f2c0c72 I am getting an error:

fatal: Needed a single revision
f2c0c72: no valid stashed state found

How can I apply a specific stash?

Body:
Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}".
So now instead of using:

git stash apply "stash@{n}"

You can type:

git stash apply n

For example, in your list:

stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust

If you want to apply stash@{1} you could type:

git stash apply 1

Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:

error: Your local changes to the following files would be overwritten by merge:
        file
Please commit your changes or stash them before you merge.

In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.

Git release notes:

Release Notes 2.11

The user always has to say "stash@{$N}" when naming a single element
  in the default location of the stash, i.e. reflogs in refs/stash.  The
  "git stash" command learned to accept "git stash apply 4" as a
  short-hand for "git stash apply stash@{4}"

Release Notes 1.7.5.1

git stash apply" used to refuse to work if there was any change in the
  working tree, even when the change did not overlap with the change the
  stash recorded


问:
laravel 5.4 update composer show warning PHP start up :unable to load dynamics library 'ext\php_pdo_oci.dll'
I try to update composer by type composer update in command prompt , it take a long time and then this happens(see picture)

PHP warning:
 I don't know what wrong and how should i do?

答:
You need to enable the PDO and PDO_MYSQL extensions in your php.ini file.

On a windows server you can add the following lines in your php.ini

```<code>extension=php_pdo.dll
extension=php_pdo_mysql.dll
</code>```

On a Linux server you can compile php with the following option --with-pdo-mysql In your php.ini, add the following lines

```<code>extension=pdo.so
extension=pdo_mysql.so
</code>```

Body:
You need to enable the PDO and PDO_MYSQL extensions in your php.ini file.

On a windows server you can add the following lines in your php.ini

extension=php_pdo.dll
extension=php_pdo_mysql.dll

On a Linux server you can compile php with the following option --with-pdo-mysql In your php.ini, add the following lines

extension=pdo.so
extension=pdo_mysql.so


问:
Can't figure out why Wix won't overwrite old version
I can't figure out why WIX installer won't overwrite the old version of the program. It keeps just installing a new second program. Here's my wix coding... (yes i'm new to XML and WIX)</p>
```<code>    <?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"><?define AMTechEU_TargetDir=$(var.AMTechEU.TargetDir)?>
    <Product Id="*" Name="AMTechEU" Language="1033" Version="1.0.0.1" Manufacturer="AM Technologies" UpgradeCode="9a48ed21-f1a0-410f-babd-09b3c95a779c">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <Media Id="1" Cabinet="Cab1.cab" EmbedCab="yes" />
    <MajorUpgrade
  AllowDowngrades="no"
  AllowSameVersionUpgrades="no"
  IgnoreRemoveFailure="no"
  DowngradeErrorMessage="loc.NewerVersionInstalled"
  Schedule="afterInstallInitialize"/>

</code>```

答:
Check the Upgrade Code. The Upgrade Code must be identically to the previous versions install package otherwise it could not identify itself as an Upgrade to the previous version.

To upgrade multiple installation packages by one new installation package you need to use the upgrade table.

Fix your version number, windows installer only use major.minor.build.

Body:
I can't figure out why WIX installer won't overwrite the old version of the program. It keeps just installing a new second program. Here's my wix coding... (yes i'm new to XML and WIX)

    <?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"><?define AMTechEU_TargetDir=$(var.AMTechEU.TargetDir)?>
    <Product Id="*" Name="AMTechEU" Language="1033" Version="1.0.0.1" Manufacturer="AM Technologies" UpgradeCode="9a48ed21-f1a0-410f-babd-09b3c95a779c">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />
    <Media Id="1" Cabinet="Cab1.cab" EmbedCab="yes" />
    <MajorUpgrade
  AllowDowngrades="no"
  AllowSameVersionUpgrades="no"
  IgnoreRemoveFailure="no"
  DowngradeErrorMessage="loc.NewerVersionInstalled"
  Schedule="afterInstallInitialize"/>


问:
Merge two arrays and remove duplicates in Java
I am having trouble removing the duplicates from two arrays that have been merged into one. I have written the following code that merges the arrays, yet I'm not sure how to remove the duplicates from the final array. Assume the arrays are already sorted.</p>

```<code>public static int[] merge(int[] list1, int[] list2) {
    int[] result = new int[list1.length + list2.length];

    int i = 0;
    int j = 0;

    for (int k = 0; k < (list1.length + list2.length); k++) {
        if (i >= list1.length) {
            result[k] = list2[j];
            j++;
        }
        else if (j >= list2.length) {
            result[k] = list1[i];
            i++;
        }
        else {
            if (list1[i] < list2[j]) {
                result[k] = list1[i];
                i++;
            } else {
                result[k] = list2[j];
                j++;
            }
        }
    }
    return result;
}
</code>```

答:
package com.string.merge;

import java.util.ArrayList;

public class MergeArrayAndRemoveDuplicate {
    public static void main(String[] args) {
        int[] a = {1, 2, 2, 3, 1, 5, 3};
        int[] b = {4, 3, 1, 5, 7, 8, 4, 2};

        ArrayList<Integer> l = new ArrayList<>();
        for (int i = 0; i < (a.length > b.length ? a.length : b.length); i++) {
            if (i < a.length) {
                int c = 0;
                while (c <= l.size()) {
                    if (l.contains(a[i]) == false) {
                        l.add(a[i]);
                    }
                    c++;
                }
            }
            if (i < b.length) {
                int c = 0;
                while (c <= l.size()) {
                    if (l.contains(b[i]) == false) {
                        l.add(b[i]);
                    }
                    c++;
                }
            }
        }
        System.out.println(l);
    }
}
```
```o/p-[1, 4, 2, 3, 5, 7, 8]
```

Body:
I am having trouble removing the duplicates from two arrays that have been merged into one. I have written the following code that merges the arrays, yet I'm not sure how to remove the duplicates from the final array. Assume the arrays are already sorted.

public static int[] merge(int[] list1, int[] list2) {
    int[] result = new int[list1.length + list2.length];

    int i = 0;
    int j = 0;

    for (int k = 0; k < (list1.length + list2.length); k++) {
        if (i >= list1.length) {
            result[k] = list2[j];
            j++;
        }
        else if (j >= list2.length) {
            result[k] = list1[i];
            i++;
        }
        else {
            if (list1[i] < list2[j]) {
                result[k] = list1[i];
                i++;
            } else {
                result[k] = list2[j];
                j++;
            }
        }
    }
    return result;
}

Body:
package com.string.merge;

import java.util.ArrayList;

public class MergeArrayAndRemoveDuplicate {
    public static void main(String[] args) {
        int[] a = {1, 2, 2, 3, 1, 5, 3};
        int[] b = {4, 3, 1, 5, 7, 8, 4, 2};

        ArrayList<Integer> l = new ArrayList<>();
        for (int i = 0; i < (a.length > b.length ? a.length : b.length); i++) {
            if (i < a.length) {
                int c = 0;
                while (c <= l.size()) {
                    if (l.contains(a[i]) == false) {
                        l.add(a[i]);
                    }
                    c++;
                }
            }
            if (i < b.length) {
                int c = 0;
                while (c <= l.size()) {
                    if (l.contains(b[i]) == false) {
                        l.add(b[i]);
                    }
                    c++;
                }
            }
        }
        System.out.println(l);
    }
}

o/p-[1, 4, 2, 3, 5, 7, 8]