问:
Failure to launch Amazon EC2 non free instances
I need to launch a Amazon EC2 instance, in particular a GPU accelerated one. I already tried with free tiers using t2.micro
instances and everything is fine. When I try to select a non free one such as g2.2xlarge I get this error

Launch Failed

You have requested more instances (1) than your current instance limit of 0 allows for the specified instance type. Please visit http://aws.amazon.com/contact-us/ec2-request to request an adjustment to this limit.

(Service: AmazonEC2; Status Code: 400; Error Code: InstanceLimitExceeded; Request ID: 4ebf71ee-e927-42c2-8377-697a3a6cfd4b)

I'm trying to use a machine with Deep Learning AMI Ubuntu Version (but I also tried with other ones). I get this error even if I'm not running any other instance and according to the documentation the limit for these one is 5 at a time.
I have also tried to select different regions (my country is not among the choices) but it doesn't seem to change the result.

My only guess about this issue is that somehow I'm registered as a free user and I'm not allowed to use the priced services, but I'm not so sure about that.

Edit: I have a credit card on file on Amazon (they require it to register) and they should charge me from that.

Am I missing something?

答:
Every amazon account has limits - even big corporate accounts. These limitations are set by Amazon, but you can request a limit increase. You can find your limits by clicking the Limits link in the top left hand side inside the EC2 Dashboard.

For example, if you have a t2.micro already running and you try to launch a g2.xlarge that had a limit of 1, you would not be able to since your limit of 1 has already been hit with your t2.micro that is running.

More Info:

How do I manage my AWS service limits?

AWS FAQ Overview

Q: How many instances can I run in Amazon EC2?

To request a limit increase, submit a support request through the AWS Support Center

To view your limits:


来源: stackexchange

问:
features type summary and progressbarwidget: percentage that the value of each row represents in relation to the sum of all values
In a grid with features type summary and progressbarwidget, is it possible to display in progressbarwidget the percentage that the value of each row represents in relation to the sum of the all values (in the feature summary)?

FIDDLE: https://fiddle.sencha.com/#view/editor&fiddle/1t4m

答:
You can use onWidgetAttach for any post-processing, and can sum values from the store itself. Using these, you can add the following to your widget column:

```<code>  onWidgetAttach: function(col, widget, record) {
      var sum = col.up("grid").getStore().sum("value")
      widget.setValue(record.get("value")/sum)
  }
</code>```

As demonstrated by this fiddle

ContentLicense: CC BY-SA 3.0

Body:
You can use onWidgetAttach for any post-processing, and can sum values from the store itself. Using these, you can add the following to your widget column:

  onWidgetAttach: function(col, widget, record) {
      var sum = col.up("grid").getStore().sum("value")
      widget.setValue(record.get("value")/sum)
  }

As demonstrated by this fiddle


问:
Set number of products in a row according to screen width
I want to set my number of products in a row according to the screen width.i.e on normal screen it would be 3 in a row .then on large screen it would be 4 on extra large screen it would be 5 and so on.I have checked a couple of solution but they did't work some are Stackoverflow1 stackoverflow2
outer container width is fixed i.e 1328 px.I am using bootstrap.

```<code><div class="container">
    <div class="col-md-12">
       <div class="col-md-2">
          //categories sidebar
       </div>
       <div class="col-md-8">
          //categories sidebar
       </div>
       <div class="col-md-2">
           //categories sidebar
       </div>
     </div>
</div>
</code>```

Thanks in advance.

答:
For non-Bootstrap cases - use CSS media queries.

Example:

```<code>.container {
    width: 1328px;
}
.container .column {
    width: 33%; /* 3 per-row */
}
@media screen and (max-width: 700px) {
    .container .column {
        width: 20%; /* 5 per-row */
    }
}
</code>```

For Bootstrap 3.x.x, you can use the same approach you are currently with some added classes. col-md-* classes are for medium-sized desktop screens, but you can also use col-xs-*, col-sm-* and col-lg-* alongside it for (according to documentation) phone, tablet and large-desktop sized screens respectively.

```<code><div class="container">
    <div class="col-md-12">
       <div class="col-md-2 col-lg-2">
          //categories sidebar
       </div>
       <div class="col-md-8 col-lg-4">
          //categories sidebar
       </div>
       <div class="col-md-2 col-lg-2">
           //categories sidebar
       </div>
       <div class="col-md-2 col-lg-4">
          //added column - wraps around to a new row on non-large screens
       </div>
    </div>
</div>
</code>```

Body:
I want to set my number of products in a row according to the screen width.i.e on normal screen it would be 3 in a row .then on large screen it would be 4 on extra large screen it would be 5 and so on.I have checked a couple of solution but they did't work some are Stackoverflow1 stackoverflow2
outer container width is fixed i.e 1328 px.I am using bootstrap.

          //categories sidebar

          //categories sidebar

           //categories sidebar

Thanks in advance.

Body:
For non-Bootstrap cases - use CSS media queries.

Example:

.container {
    width: 1328px;
}
.container .column {
    width: 33%; /* 3 per-row */
}
@media screen and (max-width: 700px) {
    .container .column {
        width: 20%; /* 5 per-row */
    }
}

For Bootstrap 3.x.x, you can use the same approach you are currently with some added classes. col-md-* classes are for medium-sized desktop screens, but you can also use col-xs-*, col-sm-* and col-lg-* alongside it for (according to documentation) phone, tablet and large-desktop sized screens respectively.

<div class="container">
    <div class="col-md-12">
       <div class="col-md-2 col-lg-2">
          //categories sidebar
       </div>
       <div class="col-md-8 col-lg-4">
          //categories sidebar
       </div>
       <div class="col-md-2 col-lg-2">
           //categories sidebar
       </div>
       <div class="col-md-2 col-lg-4">
          //added column - wraps around to a new row on non-large screens
       </div>
    </div>
</div>


问:
PyQt: How to get the root object from QQmlApplicationEngine
I try to display a dynamic object using PyQt and QML, But I get this error:

```<code>win = engine.rootObjects()[0]
</code>```

IndexError: list index out of range

Here is my code PyQt:

```<code>import sys
import os
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine,QQmlEngine, QQmlComponent
from PyQt5.QtCore import QObject, pyqtSlot, QVariant,QUrl

if __name__ == "__main__":
   app = QApplication(sys.argv)
   engine = QQmlApplicationEngine()
   engine.load('main.qml')
   win = QObject()
   win = engine.rootObjects()[0]
   win.show()
   sys.exit(app.exec_())
</code>```

(PS: with a non-dynamic object, my code runs okay)

this is my main.qml

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
id : root
visible: true
width: 1000
height: 800
title: qsTr("ACTEMIUM")
SwipeView {
    id: swipeView
    anchors.fill: parent
    currentIndex: tabBar.currentIndex
    Page1 {
        Label {
            text: qsTr("Page1")
            anchors.centerIn: parent
        }
    }

    Page2 {
        Label {
            text: qsTr("Second page")
            anchors.centerIn: parent
        }
    }

    Page3 {
        Label {
            text: qsTr("Troisieme page")
            anchors.centerIn: parent
        }
    }
}

footer: TabBar {
    id: tabBar
    currentIndex: swipeView.currentIndex

    TabButton {
        text: qsTr("First")
    }
    TabButton {
        text: qsTr("Second")
    }
    TabButton {
        text: qsTr("Trois")
    }
}
</code>```

}

and my Page1.qml
    import QtQuick 2.7

```<code>Page1Form {
id: root
button.onClicked: {
    console.log("OK. Entered text: " + textField.text);

    var component = Qt.createComponent("main2.qml")
    if( component.status != Component.Ready )
    {
        if( component.status == Component.Error )
            console.debug("Error:"+ component.errorString() );
        return; // or maybe throw
    }
    var window = component.createObject(root)
    window.show()

}

}
</code>```

Page1Form.ui.qml :

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

 Item {
property alias textField: textField
property alias button: button

Rectangle {

    id: rectangle
    x: 0
    y: 0

    width: 1000
    height: 800

    gradient: Gradient {
        GradientStop {
            position: 0.031
            color: "#ffffff"
        }

        GradientStop {
            position: 0.901
            color: "#000000"
        }

    }

    RowLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 20
        anchors.top: parent.top

        TextField {
            id: textField
            placeholderText: qsTr("ENTRER TEXTE")
        }

        Button {
            id: button
            text: qsTr("OK")

        }

    }

 }
 }
</code>```

答:
I am doing it this way:

```<code>app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("qmlapp", engine) #the string can be anything
engine.load('main.qml')
win = engine.rootObjects()[0]
win.show()
</code>```

But that is not likely your problem. I did see the error when I had a #character in the QML. For example, if you accidentally forget the quotes in the following:

```<code>background: Rectangle {
    id: rect
    border.color: menuBorderColor
    color: #AAA000  //forgot quotes
}
</code>```

This will cause python to complain about list index out of range. Check your QML code thoroughly for such mistakes.

Body:
I try to display a dynamic object using PyQt and QML, But I get this error:

win = engine.rootObjects()[0]

IndexError: list index out of range

Here is my code PyQt:

import sys
import os
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine,QQmlEngine, QQmlComponent
from PyQt5.QtCore import QObject, pyqtSlot, QVariant,QUrl

if __name__ == "__main__":
   app = QApplication(sys.argv)
   engine = QQmlApplicationEngine()
   engine.load('main.qml')
   win = QObject()
   win = engine.rootObjects()[0]
   win.show()
   sys.exit(app.exec_())

(PS: with a non-dynamic object, my code runs okay)

this is my main.qml

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
id : root
visible: true
width: 1000
height: 800
title: qsTr("ACTEMIUM")
SwipeView {
    id: swipeView
    anchors.fill: parent
    currentIndex: tabBar.currentIndex
    Page1 {
        Label {
            text: qsTr("Page1")
            anchors.centerIn: parent
        }
    }

    Page2 {
        Label {
            text: qsTr("Second page")
            anchors.centerIn: parent
        }
    }

    Page3 {
        Label {
            text: qsTr("Troisieme page")
            anchors.centerIn: parent
        }
    }
}

footer: TabBar {
    id: tabBar
    currentIndex: swipeView.currentIndex

    TabButton {
        text: qsTr("First")
    }
    TabButton {
        text: qsTr("Second")
    }
    TabButton {
        text: qsTr("Trois")
    }
}

}

and my Page1.qml
    import QtQuick 2.7

Page1Form {
id: root
button.onClicked: {
    console.log("OK. Entered text: " + textField.text);

    var component = Qt.createComponent("main2.qml")
    if( component.status != Component.Ready )
    {
        if( component.status == Component.Error )
            console.debug("Error:"+ component.errorString() );
        return; // or maybe throw
    }
    var window = component.createObject(root)
    window.show()

}

}

Page1Form.ui.qml :

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0

 Item {
property alias textField: textField
property alias button: button

Rectangle {

    id: rectangle
    x: 0
    y: 0

    width: 1000
    height: 800

    gradient: Gradient {
        GradientStop {
            position: 0.031
            color: "#ffffff"
        }

        GradientStop {
            position: 0.901
            color: "#000000"
        }

    }

    RowLayout {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.topMargin: 20
        anchors.top: parent.top

        TextField {
            id: textField
            placeholderText: qsTr("ENTRER TEXTE")
        }

        Button {
            id: button
            text: qsTr("OK")

        }

    }

 }
 }

Body:
I am doing it this way:

app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
ctx = engine.rootContext()
ctx.setContextProperty("qmlapp", engine) #the string can be anything
engine.load('main.qml')
win = engine.rootObjects()[0]
win.show()

But that is not likely your problem. I did see the error when I had a #character in the QML. For example, if you accidentally forget the quotes in the following:

background: Rectangle {
    id: rect
    border.color: menuBorderColor
    color: #AAA000  //forgot quotes
}

This will cause python to complain about list index out of range. Check your QML code thoroughly for such mistakes.


问:
Deploying AjaxToolkit causes script reference error
My site running locally works OK. Once deployed to web server I get the following error:

A script reference cannot be included multiple times in composite script references.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: A script reference cannot be included multiple times in composite script references.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

```<code>[InvalidOperationException: A script reference cannot be included multiple times in composite script references.]
   System.Web.UI.ScriptManager.RemoveDuplicates(List`1 scripts) +669
   System.Web.UI.ScriptManager.RegisterScripts() +376
   System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e) +113
   System.Web.UI.Page.OnPreRenderComplete(EventArgs e) +8698542
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1029

Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3614
</code>```

Anyone have any ideas on how to fix this? I have a script manager in my master page.

答: Turns out the clue was in the error message. There was a master page already loadnig the ajax javascript.</p>

ContentLicense: CC BY-SA 2.5

Body:
My site running locally works OK. Once deployed to web server I get the following error:

A script reference cannot be included multiple times in composite script references.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: A script reference cannot be included multiple times in composite script references.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: A script reference cannot be included multiple times in composite script references.]
   System.Web.UI.ScriptManager.RemoveDuplicates(List`1 scripts) +669
   System.Web.UI.ScriptManager.RegisterScripts() +376
   System.Web.UI.ScriptManager.OnPagePreRenderComplete(Object sender, EventArgs e) +113
   System.Web.UI.Page.OnPreRenderComplete(EventArgs e) +8698542
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1029

Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3614

Anyone have any ideas on how to fix this? I have a script manager in my master page.


问:
Angular 2 throttle the amount of event or action gets fired off on a countrol
In my application I have a inputbox where I search for the inputted value. I made it so it searches when the value inside the textbox has been changed.
The code is something like this:

```<code><input id="searchTextField" [(ngModel)]="searchText" (ngModelChange)="SearchTextChange()" />
</code>```

Back end Typescript code is like this :

```<code>private SearchTextChange(): void {
//do search
}
</code>```

Problem is that I realized this is highly inefficient, because I realized in most cases, when people type a word, I don't want it to search when people type the letter"a" or "app" when the intended word maybe "apple" or something like that.
Is there a way to limit the search amount gets triggered either in angular 2 or typescript?
so I either only perform a search max every 2 seconds, or only let angular fire off the event on the same control maximum 1 ngModelChange for every 2 seconds?

答:
Template :

```<code><input id="searchTextField" [(ngModel)]="searchText" />
</code>```

Put this code in your component :

```<code>searchText:string;

ngAfterViewInit()
{
    let inputElm = document.getElementById("searchTextField");
    Observable.fromEvent(inputElm , 'keyup').debounceTime(200).subscribe( res => {
        // this will wait for 200ms and then this will called on input
        // call you api here like
        // this.get(searchText).subscribe();
    });
}
</code>```

Body:
In my application I have a inputbox where I search for the inputted value. I made it so it searches when the value inside the textbox has been changed.
The code is something like this:

<input id="searchTextField" [(ngModel)]="searchText" (ngModelChange)="SearchTextChange()" />

Back end Typescript code is like this :

private SearchTextChange(): void {
//do search
}

Problem is that I realized this is highly inefficient, because I realized in most cases, when people type a word, I don't want it to search when people type the letter"a" or "app" when the intended word maybe "apple" or something like that.
Is there a way to limit the search amount gets triggered either in angular 2 or typescript?
so I either only perform a search max every 2 seconds, or only let angular fire off the event on the same control maximum 1 ngModelChange for every 2 seconds?

Body:
Template :

<input id="searchTextField" [(ngModel)]="searchText" />

Put this code in your component :

searchText:string;

ngAfterViewInit()
{
    let inputElm = document.getElementById("searchTextField");
    Observable.fromEvent(inputElm , 'keyup').debounceTime(200).subscribe( res => {
        // this will wait for 200ms and then this will called on input
        // call you api here like
        // this.get(searchText).subscribe();
    });
}


问:
How to retrieve cartridges ink level programmatically (Epson StatusMonitor + Mac OS X)?
I'm looking for a way to query the ink level for my Epson DX 4050 on Mac OS X. There is some UI called EPSON StatusMonitor to display cartridges levels graphically, but I'd like to get it from the command-line so it can feed a robot.

Any idea ?

答:
If the printer supports SNMP you might be lucky to query with any SNMP command-line tool. There are standard definitions for printers and they contain APIs to query the current and max ink levels.

Here's how I do it with simple unix shell commands (requires net-snmp installed). This is not strictly Mac but you should get an idea.

```<code>#!/bin/sh

me="${0##*/}"

host="${1:-wp4535}"

base=1.3.6.1.2.1.43.11.1.1

name="WP-4535"

type=$(snmpget -v1 -c public ${host} SNMPv2-MIB::sysDescr.0)

case "$type" in
"SNMPv2-MIB::sysDescr.0 = STRING: EPSON"*)
    type=epson
    ofs=1
;;
*)
    echo "! unknown printer type" 1>&2
    exit 1
;;
esac
echo "# $host $type $name"

# get current ink levels
eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.6.${ofs} |
perl -ne 'print "c[",++$c,"]=$1\n" if(m!"(\w+) ink!i);')

# get max ink level per cartridge
eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.8.${ofs} |
perl -ne 'print "max[",++$c,"]=$1\n" if(m!(\d+)!i);')

snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.9.${ofs} |
perl -ne '
    my @c=("","'${c[1]}'","'${c[2]}'","'${c[3]}'","'${c[4]}'");
    my @max=("","'${max[1]}'","'${max[2]}'","'${max[3]}'","'${max[4]}'");
    my $v=$c[++$c];
    printf"# $v=$1 (%.0f)\n",$1/$max[$c]*100 if(m!(\d+)!i);'
</code>```

OwnerDisplayName: Thibaut Barrère

Body:
If the printer supports SNMP you might be lucky to query with any SNMP command-line tool. There are standard definitions for printers and they contain APIs to query the current and max ink levels.

Here's how I do it with simple unix shell commands (requires net-snmp installed). This is not strictly Mac but you should get an idea.

#!/bin/sh

me="${0##*/}"

host="${1:-wp4535}"

base=1.3.6.1.2.1.43.11.1.1

name="WP-4535"

type=$(snmpget -v1 -c public ${host} SNMPv2-MIB::sysDescr.0)

case "$type" in
"SNMPv2-MIB::sysDescr.0 = STRING: EPSON"*)
    type=epson
    ofs=1
;;
*)
    echo "! unknown printer type" 1>&2
    exit 1
;;
esac
echo "# $host $type $name"

# get current ink levels
eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.6.${ofs} |
perl -ne 'print "c[",++$c,"]=$1\n" if(m!"(\w+) ink!i);')

# get max ink level per cartridge
eval $(snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.8.${ofs} |
perl -ne 'print "max[",++$c,"]=$1\n" if(m!(\d+)!i);')

snmpwalk -v1 -Ov -OQ -c public ${host} ${base}.9.${ofs} |
perl -ne '
    my @c=("","'${c[1]}'","'${c[2]}'","'${c[3]}'","'${c[4]}'");
    my @max=("","'${max[1]}'","'${max[2]}'","'${max[3]}'","'${max[4]}'");
    my $v=$c[++$c];
    printf"# $v=$1 (%.0f)\n",$1/$max[$c]*100 if(m!(\d+)!i);'


问:
clang: error: no such file or directory: 'ObjC' cannot compile my app anymore

I literally did everything to solve the problem.
But nothing helps. I hope you can help me out.
What specific must I do to resolve the error?

Thanks in advance.

答:
Look in your Project Settings for "Other Linker Flags" ...

It looks like you have ObjC there, when what you want is -ObjC

If it's not there, do a search in your project for the string ObjC - it should show up somewhere that it shouldn't be.


问:
installing net framework 4 upon windows 10 environment
i really need to install .net 4 for MATLAB R2016a compiler, the problem s windows 10 has .net 4.6 and don't allow any earlier version to be installed
 I followed the suggestions in a previous related question but unfortunatelly none of the mentioned packages installed</p>

答:
having .NET 4.6 installed (it's part of Windows 10 so you need not manually install it) means you have .NET 4.0, 4.5, 4.5.1, 4.5.2 and 4.6 installed and can run code targeting any of those framework versions without making any modifications to your Windows installation.

You cannot install .NET 4.0 when you have a later version installed as each version is an in-place update to the last.

Update: In my experience with SDK 7.1 and installing the required C compiler for Matlab on Windows 10, you can install SDK 7.1 from http://www.microsoft.com/en-us/download/details.aspx?id=8279

However, it fails to detect .NET framework 4. As a result you cannot install the required C++ compilers. You can download these manually at the following link: http://www.microsoft.com/en-us/download/details.aspx?id=4422

Now Matlab was able to set SDK 7.1 as C compiler. Hope it works for you as well

ContentLicense: CC BY-SA 4.0


问:
Ansible - Playbook returning error on bash command
I am running a bash command using Ansible.

```<code>kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2
</code>```

The output is supposed to be

```<code>   v1.2.0
</code>```

Playbook is ::

```<code>   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'

     register: version
</code>```

I have also used

```<code>     command: "kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2"
</code>```

But it keeps returning me the ERROR.

```<code># ansible-playbook upgrade_k8s.yaml -i ../env/platform
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/root/ejusnub/ansible/playbook/upgrade_k8s.yaml': line 40, column 50, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'
                                                 ^ here
</code>```

Ive even tried to escape every symbol but the same error occurs.

答:
Alternatively you can use kubectl version with the --short parameter whose purpose is to get the version number, here it is in a shell task:

```<code> - shell: 'kubectl version --short | cut -d: -f2'
</code>```

This will remove the need for the calls to head and awk.

Body:
I am running a bash command using Ansible.

kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2

The output is supposed to be

   v1.2.0

Playbook is ::

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'

     register: version

I have also used

     command: "kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2"

But it keeps returning me the ERROR.

# ansible-playbook upgrade_k8s.yaml -i ../env/platform
ERROR! Syntax Error while loading YAML.

The error appears to have been in '/root/ejusnub/ansible/playbook/upgrade_k8s.yaml': line 40, column 50, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

   - name: version of minion before upgrade.
     command: 'kubectl version  | head -1 | awk '{print $5}'| cut -d"\"" -f2'
                                                 ^ here

Ive even tried to escape every symbol but the same error occurs.

Body:
Alternatively you can use kubectl version with the --short parameter whose purpose is to get the version number, here it is in a shell task:

 - shell: 'kubectl version --short | cut -d: -f2'

This will remove the need for the calls to head and awk.


问:
Make survey at laravel 5.4 and MySQL
I need to make a survey for my website. I have this:

Route:

```<code>Route::resource('survey','surveyController');
</code>```

Controller:

```<code>public function index()
{
    $show=survey_title::find(1);
    return view('survey',compact('show'));
}
</code>```

Here we just read first survey.

Migrations:

```<code>Schema::create('survey_titles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->timestamps();
    });

    Schema::create('survey_questions', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('survey_title_id')->unsigned()->index();
        //$table->integer('user_id')->unsigned()->index();
        $table->foreign('survey_title_id')->references('id')->on('survey_titles')->onDelete('cascade')->onUpdate('cascade');
       // $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->string('answer');
        $table->integer('voted')->nullable();
        $table->timestamps();
    });
</code>```

Models:

survey_question:

```<code>public function survey_titles(){
    return $this->hasOne('App\survey_title');
}

public function users(){
      return $this->hasOne('App\User');
  }
</code>```

survey_title:

```<code> public function survey_questions(){
    return $this->hasMany('App\survey_question');
}
</code>```

user:

```<code>public function survey_questions(){
    return $this->hasOne('App\survey_question');
}
</code>```

View:

```<code> <div class="col-md-8 col-md-offset-2">

            <table class="table table-hover table-bordered table-striped">
                <thead>
                <tr>
                    <th>Voted by 0 People </th>
                    <th>{{$show->title}}</th>
                    <th>Question ID: {{$show->id}}</th>
                </tr>
                <tr>
                    <th>Check</th>
                    <th>Answer</th>
                    <th>ID</th>
                </tr>
                </thead>
                <tbody>
        @foreach($show->survey_questions as $ans)
                    <tr>
                        <td><input type="radio" name="check[]"></td>
                        <td>{{$ans['answer']}}</td>
                        <td>{{$ans['id']}}:</td>
                    </tr>
         @endforeach
                </tbody>
            </table>
            <a class="btn btn-primary" href="{{action('surveyController@update',$ans->id)}}">Vote</a>
        </div>
</code>```

Now I put data manually in database and I retrieve.

When click on my 'Vote' I want it to send my Answer Id but instead it always sends last ID from table.

What's wrong?

答:
This is happening because the:

```<code><a class="btn btn-primary" href="{{action('surveyController@update',$ans->id)}}">Vote</a>
</code>```

is out of the foreach loop, so after the loop is finished, the last id is being set to the link.

Put the href link inside the foreach loop, so it generates a link for each answer

```<code><tr>
    <th>Voted by 0 People </th>
    <th>{{$show->title}}</th>
    <th>Question ID: {{$show->id}}</th>
    <th>Vote</th>
</tr>

@foreach($show->survey_questions as $ans)
    <tr>
        <td><input type="radio" name="check[]"></td>
        <td>{{$ans['answer']}}</td>
        <td>{{$ans['id']}}:</td>
        <td><a class="btn btn-primary" href="{{action('surveyController@update',$ans->id)}}">Vote</a></td>
    </tr>
@endforeach
</code>```

Title: Make survey at laravel 5.4 and MySQL

Body:
I need to make a survey for my website. I have this:

Route:

Route::resource('survey','surveyController');

Controller:

public function index()
{
    $show=survey_title::find(1);
    return view('survey',compact('show'));
}

Here we just read first survey.

Migrations:

Schema::create('survey_titles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->timestamps();
    });

    Schema::create('survey_questions', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('survey_title_id')->unsigned()->index();
        //$table->integer('user_id')->unsigned()->index();
        $table->foreign('survey_title_id')->references('id')->on('survey_titles')->onDelete('cascade')->onUpdate('cascade');
       // $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
        $table->string('answer');
        $table->integer('voted')->nullable();
        $table->timestamps();
    });

Models:

survey_question:

public function survey_titles(){
    return $this->hasOne('App\survey_title');
}

public function users(){
      return $this->hasOne('App\User');
  }

survey_title:

 public function survey_questions(){
    return $this->hasMany('App\survey_question');
}

user:

public function survey_questions(){
    return $this->hasOne('App\survey_question');
}

View:

                    Voted by 0 People
                    {{$show->title}}
                    Question ID: {{$show->id}}

                    Check
                    Answer
                    ID

        @foreach($show->survey_questions as $ans)

                        <input type="radio" name="check[]">
                        {{$ans['answer']}}
                        {{$ans['id']}}:

         @endforeach

            id)}}">Vote

Now I put data manually in database and I retrieve.

When click on my 'Vote' I want it to send my Answer Id but instead it always sends last ID from table.

What's wrong?

Body:
This is happening because the:

<a class="btn btn-primary" href="{{action('surveyController@update',$ans->id)}}">Vote</a>

is out of the foreach loop, so after the loop is finished, the last id is being set to the link.

Put the href link inside the foreach loop, so it generates a link for each answer

<tr>
    <th>Voted by 0 People </th>
    <th>{{$show->title}}</th>
    <th>Question ID: {{$show->id}}</th>
    <th>Vote</th>
</tr>

@foreach($show->survey_questions as $ans)
    <tr>
        <td><input type="radio" name="check[]"></td>
        <td>{{$ans['answer']}}</td>
        <td>{{$ans['id']}}:</td>
        <td><a class="btn btn-primary" href="{{action('surveyController@update',$ans->id)}}">Vote</a></td>
    </tr>
@endforeach


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
From my first BASIC book (BASIC for kids I believe):

```<code>10 INPUT A
20 INPUT B
30 LET C = A + B
40 PRINT C
</code>```

That was on the cover of the book, and I was thrilled with the possibilities (it could do my homework!)... It took me like a couple of weeks to grasp that simple concept, but once I got it, the world of programming opened up for me.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
From my first BASIC book (BASIC for kids I believe):

10 INPUT A
20 INPUT B
30 LET C = A + B
40 PRINT C

That was on the cover of the book, and I was thrilled with the possibilities (it could do my homework!)... It took me like a couple of weeks to grasp that simple concept, but once I got it, the world of programming opened up for me.

OwnerDisplayName: Ivan


问:
How can I choose which port a web application should use during deployment
I am using Visual Studio 2010/C#. My goal is to deploy a web application on a windows 2008 R2 server. My main challenge is "how to choose port during the installation".

I have tried the standard deployment project for web projects that are shipped with Visual Studio. However - the choice of deploying the application to use a specific port is not something that I can find easily.

Can someone tell me if it is possible to specify this using the "standard" web deployment installer in VS2010, or do I have to get my hands on something else in order to do this?

(Main reason for this is that other ports are used for other applications on that server, and I would like that the 'deployer' do not have to do anything in the IIS).

答:
You will need to implement a custom action (installation component) in order to change the port - or many other settings in Internet Information Services.

Details of how to do this are available here:

http://msdn.microsoft.com/en-us/library/aa289522(VS.71).aspx

The example in the link shows how to query the port, shouldn't be too difficult to change it to update the port.


问:
The project was not built since its path is incomplete. Cannot find the class file for com.sun.jersey.api.view.viewable.
So, I updated jersey version to the latest and while deploying the app I started getting this error. This class doesn't even exist in the latest version of jersey so I cannot add (missing jar file) in the classpath but somehow classloader is still referencing it. How can I fix this issue.

Steps done already:

clean and build

update project via maven

restart ide

Thanks

答:
This may not be an ideal solution but the only way to get rid of this issue for me was to add the lower version of the jersey jars. As I said, this is not the right approach because now I got two version of Jersey jars in my classpath.

We have to carefully build the project and test all the services just to make sure they are working as expected because jersey get confuse what to pick up if there are two version of jars.

In these kind of cases, usually the third party api breaks because of the fact that you don't provide the implementation of certain interfaces or abstract classes which are not in the latest version but the compiler refers to the lower version and look for an implementation. Therefore I don't like this approach at all.


问:
How to use a promise or callback to delay script actions
I've written a node script which generates a set of files and populates them automatically. However I've noticed in the output that the success messages come quite a bit after the call message.

I am not very familiar with promises or callbacks apart from when I use them in pre-existing code. How would I go about writing the following to run in a step-by-step manner?

```<code>var fileGen = function(componentName) {
    // Each createFile instance should run only after the previous one has completed.
    createFile('view.php', componentName)
    createFile('style.styl', componentName)
    createFile('script.js', componentName)
    createFile('style.print.styl', componentName)
    // finishUp should only run when all createFile instances have completed.
    finishUp()
}

var createFile = function (fileName, componentName, doc) {
  // Tell the user what is happening
  console.log(chalk.blue('\nCreating', fileName, '...'))
  // Bring in the view.php scaffold file
  var scaffold = './scaffold/' + fileName
  fs.readFile(scaffold, 'utf8', function (err, data) {
    if (err) return console.log(chalk.red(err))
    var result = data.replace(/%cname%/g, componentName)
    if (doc) {
      var d = new Date()
      result = result.replace(/%cfname%/g, doc.componentName)
      result = result.replace(/%cdesc%/g, doc.componentDesc)
      result = result.replace(/%cauthor%/g, doc.userName)
      result = result.replace(/%cagithub%/g, doc.userGithub)
      result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
    }

    fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
      if (err) return console.log(chalk.red(err))
      console.log(chalk.green(fileName, 'created!'))
    })
  })
}
</code>```

I feel like this is something I should be able to do (and probably have done before) but for some reason I can't get my brain around it today.

答:
Promise: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise</p>

```<code>var fileGen = function(componentName) {
    // Each createFile instance should run only after the previous one has completed.
    createFile('view.php', componentName)
    .then(() => {
        createFile('style.styl', componentName);
    })
    .then(() => {
        createFile('script.js', componentName)
    })
    .then(() => {
        createFile('style.print.styl', componentName)
    })
    .then(() => {
        // finishUp should only run when all createFile instances have completed.
        finishUp()
    });
}

var createFile = function (fileName, componentName, doc) {
  // Tell the user what is happening
  console.log(chalk.blue('\nCreating', fileName, '...'))
  // Bring in the view.php scaffold file
  var scaffold = './scaffold/' + fileName

  return new Promise((resolve, reject) => {
    fs.readFile(scaffold, 'utf8', function (err, data) {
      if (err) {
        console.log(chalk.red(err))
        reject(err)
        return
      }
      var result = data.replace(/%cname%/g, componentName)
      if (doc) {
        var d = new Date()
        result = result.replace(/%cfname%/g, doc.componentName)
        result = result.replace(/%cdesc%/g, doc.componentDesc)
        result = result.replace(/%cauthor%/g, doc.userName)
        result = result.replace(/%cagithub%/g, doc.userGithub)
        result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
      }

      fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
        if (err) {
            console.log(chalk.red(err))
            reject(err)
            return
        } else {
          console.log(chalk.green(fileName, 'created!'))
          resolve(); // promise is now fulfilled, the next chained `then` will be called   }
      })
    })
  });
}
</code>```

Body:
I've written a node script which generates a set of files and populates them automatically. However I've noticed in the output that the success messages come quite a bit after the call message.

I am not very familiar with promises or callbacks apart from when I use them in pre-existing code. How would I go about writing the following to run in a step-by-step manner?

var fileGen = function(componentName) {
    // Each createFile instance should run only after the previous one has completed.
    createFile('view.php', componentName)
    createFile('style.styl', componentName)
    createFile('script.js', componentName)
    createFile('style.print.styl', componentName)
    // finishUp should only run when all createFile instances have completed.
    finishUp()
}

var createFile = function (fileName, componentName, doc) {
  // Tell the user what is happening
  console.log(chalk.blue('\nCreating', fileName, '...'))
  // Bring in the view.php scaffold file
  var scaffold = './scaffold/' + fileName
  fs.readFile(scaffold, 'utf8', function (err, data) {
    if (err) return console.log(chalk.red(err))
    var result = data.replace(/%cname%/g, componentName)
    if (doc) {
      var d = new Date()
      result = result.replace(/%cfname%/g, doc.componentName)
      result = result.replace(/%cdesc%/g, doc.componentDesc)
      result = result.replace(/%cauthor%/g, doc.userName)
      result = result.replace(/%cagithub%/g, doc.userGithub)
      result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
    }

    fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
      if (err) return console.log(chalk.red(err))
      console.log(chalk.green(fileName, 'created!'))
    })
  })
}

I feel like this is something I should be able to do (and probably have done before) but for some reason I can't get my brain around it today.

Body:
Promise: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

var fileGen = function(componentName) {
    // Each createFile instance should run only after the previous one has completed.
    createFile('view.php', componentName)
    .then(() => {
        createFile('style.styl', componentName);
    })
    .then(() => {
        createFile('script.js', componentName)
    })
    .then(() => {
        createFile('style.print.styl', componentName)
    })
    .then(() => {
        // finishUp should only run when all createFile instances have completed.
        finishUp()
    });
}

var createFile = function (fileName, componentName, doc) {
  // Tell the user what is happening
  console.log(chalk.blue('\nCreating', fileName, '...'))
  // Bring in the view.php scaffold file
  var scaffold = './scaffold/' + fileName

  return new Promise((resolve, reject) => {
    fs.readFile(scaffold, 'utf8', function (err, data) {
      if (err) {
        console.log(chalk.red(err))
        reject(err)
        return
      }
      var result = data.replace(/%cname%/g, componentName)
      if (doc) {
        var d = new Date()
        result = result.replace(/%cfname%/g, doc.componentName)
        result = result.replace(/%cdesc%/g, doc.componentDesc)
        result = result.replace(/%cauthor%/g, doc.userName)
        result = result.replace(/%cagithub%/g, doc.userGithub)
        result = result.replace(/%creationdate%/g, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear())
      }

      fs.writeFile('./src/components/' + componentName + '/' + fileName, result, function (err) {
        if (err) {
            console.log(chalk.red(err))
            reject(err)
            return
        } else {
          console.log(chalk.green(fileName, 'created!'))
          resolve(); // promise is now fulfilled, the next chained `then` will be called   }
      })
    })
  });
}


问:
Why are my PostgreSQL random numbers right-padded with zeroes?
I have written a PostgreSQL function to generate a random number with (up to) 40 digits.

After running the function a couple of times, it seems that the generated numbers only have their leading (up to) 15 digits actually randomized (range 0-9). The following digits are all zero.

That was very unexpected to me. Is this due to a restriction that I am not aware of, e.g. in the DECIMAL type, or in the OS, or in the multiplication operation?

Sample output:

9690529912293880000000000000000000000000

3876745014239130000000000000000000000000

8298320658130730000000000000000000000000

Thanks

```<code>CREATE OR REPLACE FUNCTION test_random()
  RETURNS DECIMAL(40) AS
$BODY$
DECLARE
    r DECIMAL(40) := 0;
    pos INTEGER := NULL;
BEGIN

    FOR pos IN 1..40 LOOP
        r := r * 10 + FLOOR(random() * 10);
    END LOOP;

    RETURN r;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

SELECT test_random();
</code>```

答:
random returns double precision which has a limited precision. numeric + double precision yields double precision. To avoid that cast it to numeric:

```<code>r := r * 10 + floor(random()::numeric * 10);
</code>```

Body:
I have written a PostgreSQL function to generate a random number with (up to) 40 digits.

After running the function a couple of times, it seems that the generated numbers only have their leading (up to) 15 digits actually randomized (range 0-9). The following digits are all zero.

That was very unexpected to me. Is this due to a restriction that I am not aware of, e.g. in the DECIMAL type, or in the OS, or in the multiplication operation?

Sample output:

9690529912293880000000000000000000000000

3876745014239130000000000000000000000000

8298320658130730000000000000000000000000

Thanks

CREATE OR REPLACE FUNCTION test_random()
  RETURNS DECIMAL(40) AS
$BODY$
DECLARE
    r DECIMAL(40) := 0;
    pos INTEGER := NULL;
BEGIN

    FOR pos IN 1..40 LOOP
        r := r * 10 + FLOOR(random() * 10);
    END LOOP;

    RETURN r;
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

SELECT test_random();

Body:
random returns double precision which has a limited precision. numeric + double precision yields double precision. To avoid that cast it to numeric:

r := r * 10 + floor(random()::numeric * 10);


问:
Hive Join Query throws Error
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

```<code>SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;
</code>```

When I try to run this hive query I get the below error

```<code>SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'
</code>```

Can Someone tell me what went wrong on this hive query and how do I fix this ?

答:
```<code>select a.userid, a.unix_timestamp(event_timestamp,'yyyy/MM/dd hh:MM') as min
    from sports_views a
    inner join (select userid, first_value(1) over(order by time desc) as max
        from(select userid,unix_timestamp(event_timestamp,'yyyy/MM/dd hh:MM') as time
        from sports_views)sv )e)
where a.min=max
</code>```

Title: Hive Join Query throws Error

Body:
If a user_id  has multiple records then keep the latest record as per event_timestamp .

My HIVE query :

SELECT
 a.user_id,
 unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM') as  converted_event_timestamp,
 a.user_name,
 a.user_location
 FROM
 sports_views a
 INNER JOIN
 (SELECT user_id,MAX(unix_timestamp(event_timestamp,'dd/MM/YYYY HH:MM')) as max_event_timestamp FROM sports_views GROUP BY user_id )b
 ON( a.user_id =b.user_id AND a.converted_event_timestamp =b.max_event_timestamp)
 LIMIT 10;

When I try to run this hive query I get the below error

SemanticException [Error 10002]: Line 8:43 Invalid column reference 'converted_event_timestamp'

Can Someone tell me what went wrong on this hive query and how do I fix this ?


问:
Receiving "No resource found" when passing an object to a WebApi using HttpClient
Background

Currently have an api which I have created a while back which is a helper api.  This api has a controller that receives an object, and then processes it accordingly.

Problem

When I am making a call to this my receiving api I get an error the following error message.

{"Message":"No HTTP resource was found that matches the request URI
  'http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'.","MessageDetail":"No
  action was found on the controller 'DataServices' that matches the
  request."}

However, the controller is operational because I can call out another function in the control which can give me all clients.  I made sure my route attribute matches my request url but still have no success.

Code

Sending Web Api

```<code>public static async Task<bool> CreateDBF(string dPath)
{
    var postObject = (new DBFPostModel
    {
        destinationPath = dPath,
        fileName = "CustomDBF"
    });
    List<string> uniqueID = new List<string>();
    try
    {
        string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF";

        HttpClient hc = new HttpClient();

        var method = new HttpMethod("POST");

        var values = new Dictionary<string, string>()
        {
            { "Id", "6"},
            { "Name", "Skis"},
            { "Price", "100"},
            { "Category", "Sports"}
        };

        var content = new FormUrlEncodedContent(values);

        var hrm = await hc.PostAsync(requestUrl, content);
        if (hrm.IsSuccessStatusCode)
        {
            var responseData = await hrm.Content.ReadAsStringAsync();
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (Exception ex)
    {
        // TODO Log
        return false;
    }
}
</code>```

Receiving Api

```<code>public class IncomingDbfModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Price { get; set; }
    public string Catergory { get; set; }
}

public class DataServicesController : ApiController
{
      [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam)
    {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}
</code>```

Error

```<code>HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 15:17:38 GMT
Content-Length: 232

{"Message":"No HTTP resource was found that matches the request URI 'http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'.","MessageDetail":"No action was found on the controller 'DataServices' that matches the request."}
</code>```

Routing Config

```<code> public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        log4net.Config.XmlConfigurator.Configure();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
</code>```

答:
By default the convention-based route template for web api excludes the action name in the URL template "api/{controller}/{id}". The example above includes the action name in the requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF" with matches the attribute route. [Route("api/DataServices/CreateDBF")]

So the assumption is that you meant to use attribute routing.

Apply HttpPost attribute to the action so that route knows how to handle the POST request

```<code>public class DataServicesController : ApiController {
    //POST api/DataServices/CreateDBF
    [HttpPost]
    [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam) {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}
</code>```

Source: Attribute Routing in ASP.NET Web API 2 - HTTP Methods

Web API also selects actions based on the HTTP method of the request
  (GET, POST, etc). By default, Web API looks for a case-insensitive
  match with the start of the controller method name.

You can override this convention by decorating the mathod with any the
  following attributes:

```<code>[HttpDelete]
[HttpGet]
[HttpHead]
[HttpOptions]
[HttpPatch]
[HttpPost]
[HttpPut]
</code>```

Body:
Background

Currently have an api which I have created a while back which is a helper api.  This api has a controller that receives an object, and then processes it accordingly.

Problem

When I am making a call to this my receiving api I get an error the following error message.

{"Message":"No HTTP resource was found that matches the request URI
  'http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'.","MessageDetail":"No
  action was found on the controller 'DataServices' that matches the
  request."}

However, the controller is operational because I can call out another function in the control which can give me all clients.  I made sure my route attribute matches my request url but still have no success.

Code

Sending Web Api

public static async Task<bool> CreateDBF(string dPath)
{
    var postObject = (new DBFPostModel
    {
        destinationPath = dPath,
        fileName = "CustomDBF"
    });
    List<string> uniqueID = new List<string>();
    try
    {
        string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF";

        HttpClient hc = new HttpClient();

        var method = new HttpMethod("POST");

        var values = new Dictionary<string, string>()
        {
            { "Id", "6"},
            { "Name", "Skis"},
            { "Price", "100"},
            { "Category", "Sports"}
        };

        var content = new FormUrlEncodedContent(values);

        var hrm = await hc.PostAsync(requestUrl, content);
        if (hrm.IsSuccessStatusCode)
        {
            var responseData = await hrm.Content.ReadAsStringAsync();
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (Exception ex)
    {
        // TODO Log
        return false;
    }
}

Receiving Api

public class IncomingDbfModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Price { get; set; }
    public string Catergory { get; set; }
}

public class DataServicesController : ApiController
{
      [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam)
    {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}

Error

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 15:17:38 GMT
Content-Length: 232

{"Message":"No HTTP resource was found that matches the request URI 'http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'.","MessageDetail":"No action was found on the controller 'DataServices' that matches the request."}

Routing Config

 public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        log4net.Config.XmlConfigurator.Configure();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

Body:
By default the convention-based route template for web api excludes the action name in the URL template "api/{controller}/{id}". The example above includes the action name in the requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF" with matches the attribute route. [Route("api/DataServices/CreateDBF")]

So the assumption is that you meant to use attribute routing.

Apply HttpPost attribute to the action so that route knows how to handle the POST request

public class DataServicesController : ApiController {
    //POST api/DataServices/CreateDBF
    [HttpPost]
    [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam) {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}

Source: Attribute Routing in ASP.NET Web API 2 - HTTP Methods

Web API also selects actions based on the HTTP method of the request
  (GET, POST, etc). By default, Web API looks for a case-insensitive
  match with the start of the controller method name.

You can override this convention by decorating the mathod with any the
  following attributes:

[HttpDelete]
[HttpGet]
[HttpHead]
[HttpOptions]
[HttpPatch]
[HttpPost]
[HttpPut]


问:
Autofac DI error in WebApi2 with OWIN
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

```<code>{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}
</code>```

Startup.cs

```<code>public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}
</code>```

ValuesController.cs

```<code>[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}
</code>```

ITestRepository.cs

```<code>public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}
</code>```

TestRepository.cs

```<code>public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}
</code>```

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.

答:
You need to tell WebApi how to create your controllers.  I like to do it by creating a composition root.  Mark Seemann has an excellent article on it here.  My implementation looks like this.  I am using StructureMap, but AutoFac will have a similar setup.  In the constructor, I am passing on the IoC container and in the Create method I get the instance of the controller out of the container using the controllerType parameter.

```<code>public class CompositionRoot : IHttpControllerActivator
{
    private readonly IContainer _container;

    public CompositionRoot(IContainer container)
    {
        if (container == null) throw new ArgumentNullException(nameof(container));
        _container = container;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        var controller = (IHttpController) _container.GetInstance(controllerType);

        return controller;
    }
</code>```

You wire it up in your startup.cs like this (again, using StructureMap):

```<code>config.Services.Replace(typeof (IHttpControllerActivator), new CompositionRoot(container));
</code>```

This is a more manual wiring up, and it means that you probably won't need these lines:

```<code>app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
</code>```

Hope that helps

Title: Autofac DI error in WebApi2 with OWIN

Body:
I have problem with DI in WebApi. I have add autofac accordingly with the instruction. But something is wrong with resolving controller.

I get an error:

{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Type 'WebApiOwinAutoFac.Controllers.ValuesController' does not have a default constructor",
"ExceptionType": "System.ArgumentException",
"StackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
   }
}

Startup.cs

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();

        // STANDARD WEB API SETUP:

        // Get your HttpConfiguration. In OWIN, you'll create one
        // rather than using GlobalConfiguration.
        var config = new HttpConfiguration();

        // Register your Web API controllers.
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

        // builder.RegisterType<ApplicationDbContext>().AsSelf().InstancePerLifetimeScope();
        builder.RegisterType<TestRepository>().As<ITestRepository>();

        // Run other optional steps, like registering filters,
        // per-controller-type services, etc., then set the dependency resolver
        // to be Autofac.
        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        // OWIN WEB API SETUP:

        // Register the Autofac middleware FIRST, then the Autofac Web API middleware,
        // and finally the standard Web API middleware.
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

        ConfigureAuth(app);
    }
}

ValuesController.cs

[RoutePrefix("api/Values")]
public class ValuesController : ApiController
{
    private ITestRepository _context { get; set; }

    public ValuesController(ITestRepository context)
    {
        _context = context;
    }

    // GET api/values/5
    [HttpGet]
    public string GetTest()
    {
        var testList = _context.GetAll();
        return String.Join(",", testList.Select(s => s.Name));
    }
}

ITestRepository.cs

public interface ITestRepository
{
    IEnumerable<TestModel> GetAll();
}

TestRepository.cs

public class TestRepository : ITestRepository
{
    private ApplicationDbContext _context = new ApplicationDbContext();

    public IEnumerable<TestModel> GetAll()
    {
        return _context.Tests;
    }
}

My sample project where I try to make it works, is available on GitHub:
Thank you for any help.

Body:
You need to tell WebApi how to create your controllers.  I like to do it by creating a composition root.  Mark Seemann has an excellent article on it here.  My implementation looks like this.  I am using StructureMap, but AutoFac will have a similar setup.  In the constructor, I am passing on the IoC container and in the Create method I get the instance of the controller out of the container using the controllerType parameter.

public class CompositionRoot : IHttpControllerActivator
{
    private readonly IContainer _container;

    public CompositionRoot(IContainer container)
    {
        if (container == null) throw new ArgumentNullException(nameof(container));
        _container = container;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        var controller = (IHttpController) _container.GetInstance(controllerType);

        return controller;
    }

You wire it up in your startup.cs like this (again, using StructureMap):

config.Services.Replace(typeof (IHttpControllerActivator), new CompositionRoot(container));

This is a more manual wiring up, and it means that you probably won't need these lines:

app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);

Hope that helps


问:
adding button to the cell in Jtable in netbeans
How to add button in the cell of Jtable in netbeans???</p>

答:
As shown in the Button Table Example we will create a class that extends JButton and implements TableCellRenderer.

```<code>class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);
  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}
</code>```

You then need to create a Cell Editor for the column also.

```<code>class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
      //
      //
      JOptionPane.showMessageDialog(button, label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String(label);
  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}
</code>```

We will then set an instance of the ButtonRender as the cell render for that column and an instance of ButtonEditor as the cell editor.

```<code>\\"Button" is the column name
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(
    new ButtonEditor(new JCheckBox()));
</code>```

The example in the link provided has the complete runnable example.

Body:
As shown in the Button Table Example we will create a class that extends JButton and implements TableCellRenderer.

class ButtonRenderer extends JButton implements TableCellRenderer {

  public ButtonRenderer() {
    setOpaque(true);
  }

  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
}

You then need to create a Cell Editor for the column also.

class ButtonEditor extends DefaultCellEditor {
  protected JButton button;

  private String label;

  private boolean isPushed;

  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }

  public Component getTableCellEditorComponent(JTable table, Object value,
      boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else {
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
  }

  public Object getCellEditorValue() {
    if (isPushed) {
      //
      //
      JOptionPane.showMessageDialog(button, label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String(label);
  }

  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }

  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

We will then set an instance of the ButtonRender as the cell render for that column and an instance of ButtonEditor as the cell editor.

\\"Button" is the column name
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(
    new ButtonEditor(new JCheckBox()));

The example in the link provided has the complete runnable example.


问:
Set li wrap padding
I have tried but can not make li tag wrap completely a tag inside with its padding. I want the width of the li depends on a''s padding but how ever I try, it doesn't work, if you know whats wrong, Please help me?</p>

```<code>  <ul>
     <li><a href="#">TAB 1</a><br />
       <ul class="sub-ul">
          <li>TEXT1</li>
          <li>TEXT1</li>
       </ul>
    </li>
    <li><a href="#">TAB 2</a><br />
      <ul class="sub-ul">
         <li>TEXT2</li>
         <li>TEXT2</li>
     </ul>
 </li>
</ul>

//STYLE
ul >li {display: inline-block; margin-left: 0;}
ul >li > a {padding: 10px 15px;}  I need li wrapping around this padding.
</code>```

答:
I think this is what you are looking for. Hope it helps.</p>

```<code>li {
    display: inline-block;
    margin-left: 0;
}
li > a {
    padding: 10px 15px;
}
li ul li {
    display: block;
}
</code>```

Title: Set li wrap padding

Body:
I have tried but can not make li tag wrap completely a tag inside with its padding. I want the width of the li depends on a''s padding but how ever I try, it doesn't work, if you know whats wrong, Please help me?

TAB 1

TEXT1

TEXT1

TAB 2

TEXT2

TEXT2

//STYLE
ul >li {display: inline-block; margin-left: 0;}
ul >li > a {padding: 10px 15px;}  I need li wrapping around this padding.

Body:
I think this is what you are looking for. Hope it helps.

li {
    display: inline-block;
    margin-left: 0;
}
li > a {
    padding: 10px 15px;
}
li ul li {
    display: block;
}


问:
Using COUNT on two MySQL fields (then need the sum of the two fields)
I have the following MySQL query which works fine to give me the Count of the "smconnectivity_b" field.

We added in a second field called: "smconnectivity_c" which can also have values.

I need to include any of these new values in the same Count logic below:

```<code>    SELECT smconnectivity_b, COUNT(smconnectivity_b) AS Used, LEFT(smconnectivity_b, 4) AS Collo, 144 - COUNT(smconnectivity_b) AS Available, concat(round(( COUNT(smconnectivity_b)/144 * 100 ),1),'%') AS percentage, (round(( COUNT(smconnectivity_b)/144 * 100 ),1)) AS percentage2,

CASE
        WHEN COUNT(smconnectivity_b) >= 25 AND COUNT(smconnectivity_b) < 121 THEN 'Yellow'
        WHEN COUNT(smconnectivity_b) >= 121 AND COUNT(smconnectivity_b) < 145 THEN 'Red'

ELSE 'Green'
END AS Color

FROM     tblsplicemapping

GROUP BY smconnectivity_b
ORDER BY smconnectivity_b
</code>```

答:
Thanks to @peufeu I have updated the query & used UNION ALL to combine the two field counts. thanks.

Here is the final updated query:

```<code>(SELECT  smconnectivity_b, Used,
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
)

UNION ALL

(SELECT  smconnectivity_c AS smconnectivity_b, Used,
        LEFT(smconnectivity_c, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_c, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_c
    ) subselect
)
ORDER BY smconnectivity_b
</code>```

Body:
I have the following MySQL query which works fine to give me the Count of the "smconnectivity_b" field.

We added in a second field called: "smconnectivity_c" which can also have values.

I need to include any of these new values in the same Count logic below:

    SELECT smconnectivity_b, COUNT(smconnectivity_b) AS Used, LEFT(smconnectivity_b, 4) AS Collo, 144 - COUNT(smconnectivity_b) AS Available, concat(round(( COUNT(smconnectivity_b)/144 * 100 ),1),'%') AS percentage, (round(( COUNT(smconnectivity_b)/144 * 100 ),1)) AS percentage2,

CASE
        WHEN COUNT(smconnectivity_b) >= 25 AND COUNT(smconnectivity_b) < 121 THEN 'Yellow'
        WHEN COUNT(smconnectivity_b) >= 121 AND COUNT(smconnectivity_b) < 145 THEN 'Red'

ELSE 'Green'
END AS Color

FROM     tblsplicemapping

GROUP BY smconnectivity_b
ORDER BY smconnectivity_b

Body:
Thanks to @peufeu I have updated the query & used UNION ALL to combine the two field counts. thanks.

Here is the final updated query:

(SELECT  smconnectivity_b, Used,
        LEFT(smconnectivity_b, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_b, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_b
    ) subselect
)

UNION ALL

(SELECT  smconnectivity_c AS smconnectivity_b, Used,
        LEFT(smconnectivity_c, 4) AS Collo, 144 - Used AS Available,
        concat(round(( Used/144 * 100 ),1),'%') AS percentage,
        (round(( Used/144 * 100 ),1)) AS percentage2,
        CASE
        WHEN Used >= 25 AND Used < 121 THEN 'Yellow'
        WHEN Used >= 121 AND Used < 145 THEN 'Red'
        ELSE 'Green' END AS Color

FROM (
    SELECT smconnectivity_c, count(*) AS Used
        FROM     tblsplicemapping
        GROUP BY smconnectivity_c
    ) subselect
)
ORDER BY smconnectivity_b


问:
Authorize Rrecurring billing subscribes
Can I configure my recurring billing that customers can pay for subscribe not every month but for example: 1 pay,after 35 days next pay, and after 50 day next pay? </p>

答: Authorize.Net Recurring Billing does not currently support non-standard intervals.  See https://developer.authorize.net/api/reference/#recurring-billing</p>

Title: Authorize Rrecurring billing subscribes


问:
Batch (.bat): get the name of the first script, not the current one
I have first.bat and second.bat.

first.bat is: call second.bat

Second is: echo %~n0 (displays filename of the executing batch)

The output is Second.bat, but I want it to display the caller filename, not it's own.

Is this possible?

答:
This batch detects the name of the caller script or even if it's called directly from the command line

```<code>@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)
REM *** Get the name of the caller
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:mainFunc\..%~pnx0" %*
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:mainFunc\..%~pnx0" %*"
    )
    endlocal
)
echo NEVER REACHED
exit /b

:mainFunc
echo :mainFunc of %~nx0 arg1=%1 is called from '%caller%'/%callType%
exit /b
</code>```

It uses the fact, that a (goto) statement will remove one level from the stack.

This results into leaving the current batch file and %~f0 will be the name of the caller script (and %~0 the current function of that batch) or the text %~f0 in the case of called from the command line.

Then the own script is called again with "%~d0\:mainFunc\..%~pnx0"

External Script

For easy use you could add a helper batch file.

Use it in your own scripts with this line

```<code>@echo off
<:GetCaller <nul call GetCaller.bat myCallerVar
echo This batch was called from "%myCallerVar%"
</code>```

Name the helper batch file GetCaller.bat

```<code>@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)

REM *** STEP1
REM *** Get the filename of the caller of this script, needed for later restart that
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion %= it could be reenabled by the GOTO =%
    set "_returnVar=%~1"
    call set "_lastCaller=%%~f0"
    call set "_argToLastCaller=%%*"
    call "%~d0\:Step2\..%~pnx0" %*
)
exit /b %= This is never reached =%

:Step2
REM *** STEP2
REM *** Get the filename/cmd-line of the caller of the script
(
    (goto) 2>nul
    (goto) 2>nul
    setlocal DisableDelayedExpansion %= it could be reenabled by the GOTO =%
    set "_returnVar=%_returnVar%"
    set "_lastCaller=%_lastCaller%"
    set "_argToLastCaller=%_argToLastCaller%"
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:Step3batch\..%~pnx0"
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:Step3batch\..%~pnx0" "
    )
    endlocal
)
exit /b %= This is never reached =%

:Step3batch
REM *** STEP3 Restart the requester batch, but jump to the label :GetCaller
call :GetCaller
exit /b %= This is never reached =%

:GetCaller
REM *** This uses the trick, that starting a batch without CALL will jump to the last used label
if "%_returnVar%" NEQ "" set "%_returnVar%=%_caller%"
%_lastCaller% %_argToLastCaller%

echo #6 never reached
</code>```

Body:
This batch detects the name of the caller script or even if it's called directly from the command line

@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)
REM *** Get the name of the caller
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:mainFunc\..%~pnx0" %*
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:mainFunc\..%~pnx0" %*"
    )
    endlocal
)
echo NEVER REACHED
exit /b

:mainFunc
echo :mainFunc of %~nx0 arg1=%1 is called from '%caller%'/%callType%
exit /b

It uses the fact, that a (goto) statement will remove one level from the stack.

This results into leaving the current batch file and %~f0 will be the name of the caller script (and %~0 the current function of that batch) or the text %~f0 in the case of called from the command line.

Then the own script is called again with "%~d0\:mainFunc\..%~pnx0"

External Script

For easy use you could add a helper batch file.

Use it in your own scripts with this line

@echo off
<:GetCaller <nul call GetCaller.bat myCallerVar
echo This batch was called from "%myCallerVar%"

Name the helper batch file GetCaller.bat

@echo off
setlocal DisableDelayedExpansion
set "func=%~0"
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X"
if ":" == "%func:~0,1%" (
    goto %func%
)

REM *** STEP1
REM *** Get the filename of the caller of this script, needed for later restart that
(
    (goto) 2>nul
    setlocal DisableDelayedExpansion %= it could be reenabled by the GOTO =%
    set "_returnVar=%~1"
    call set "_lastCaller=%%~f0"
    call set "_argToLastCaller=%%*"
    call "%~d0\:Step2\..%~pnx0" %*
)
exit /b %= This is never reached =%

:Step2
REM *** STEP2
REM *** Get the filename/cmd-line of the caller of the script
(
    (goto) 2>nul
    (goto) 2>nul
    setlocal DisableDelayedExpansion %= it could be reenabled by the GOTO =%
    set "_returnVar=%_returnVar%"
    set "_lastCaller=%_lastCaller%"
    set "_argToLastCaller=%_argToLastCaller%"
    call set "caller=%%~f0"
    call set _caller=%%caller:*%%~f0=%%
    if defined _caller (
        set "callType=batch"
        call "%~d0\:Step3batch\..%~pnx0"
    ) ELSE (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:Step3batch\..%~pnx0" "
    )
    endlocal
)
exit /b %= This is never reached =%

:Step3batch
REM *** STEP3 Restart the requester batch, but jump to the label :GetCaller
call :GetCaller
exit /b %= This is never reached =%

:GetCaller
REM *** This uses the trick, that starting a batch without CALL will jump to the last used label
if "%_returnVar%" NEQ "" set "%_returnVar%=%_caller%"
%_lastCaller% %_argToLastCaller%

echo #6 never reached


问:
ADAL page fails to load on UWP within corporate network when using ADFS
We are developing a cross-platform mobile app using Xamarin.Forms that uses Azure Active Directory Authentication. For that case we use Microsoft.IdentityModel.Clients.ActiveDirectory nuget. It works fine with any case other than this one:

UWP user is trying to login with a corporate account while being connected to a network that hosts the ADFS - after typing user@domain the adal page tries to redirect to organization login page and fails with message - We can't connect to the service you need right now. Check your network connection or try this later.

The problem does not appear when we are running the app from Visual Studio. It only appears when the app is installed through .appx.

The problem does not appear when user is connected to other network - I have tried to log in while being connected to a HotSpot set on my Android phone and I successfully logged in.

The problem does not appear when user is connected to the corporate network, but logs in with account that is not in our ADFS.

The method we use to log in:

AuthenticationContext.AcquireTokenAsync(resource, clientId, RedirectUri, platformParameters)

We set parameter useCorporateNetwork for platformParameters to true, in project properties -> Package Manifest -> Capabilities, we set flags like Private Networks (Client & Server)

When trying to login without setting RedirectUri, then the corporate login page will appear and you will be able to type your password/login and have them validated, but it will be useless for us as we need to Redirect the login to our API - when logging in like that you will have error that specified redirectUri is other than configured for used clientId.

I have been trying different approaches like using native WebAuthenticationCoreManager, but it doesnt support RedirectUri (if it does and will work please write how!), setting Loopback Exempts for our app and AuthHost.exe (nothing changed).

I am happy to use anything that will work, it can be native UWP approach as we can use platform dependency.

EDIT

When I am trying to connect through VPN then when logging in I get the message - We can't connect to the service you need right now. Check your network connection or try this later. - even when I am running the app from visual studio.

As for trying to find the cause of the problem with Fiddler I was stunned - when I monitor the authhost.exe process with fiddler (I select the authentication popup window as target process) - then the authentication finishes successfully. The moment I stop monitoring with fiddler - it fails again.

答:
Interesting that you got it working with Fiddler attached to AuthHost. In your troubleshooting have you tried the following options?

Enable capabilities in AppPackage manifest

privateNetworkClientServer

enterpriseAuthentication

sharedUserCertificate

Add loopback exemptions

```<code>CheckNetIsolation.exe LoopbackExempt -a -n=<YourPackageFamilyName>
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.a_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.a.p_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.sso_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.sso.p_8wekyb3d8bbwe
</code>```

Enable private network for AuthHost

```<code>REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\authhost.exe" /v EnablePrivateNetwork  /t REG_DWORD /d 1 /f
</code>```

Body:
Interesting that you got it working with Fiddler attached to AuthHost. In your troubleshooting have you tried the following options?

Enable capabilities in AppPackage manifest

privateNetworkClientServer

enterpriseAuthentication

sharedUserCertificate

Add loopback exemptions

CheckNetIsolation.exe LoopbackExempt -a -n=<YourPackageFamilyName>
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.a_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.a.p_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.sso_8wekyb3d8bbwe
CheckNetIsolation.exe LoopbackExempt -a -n=microsoft.windows.authhost.sso.p_8wekyb3d8bbwe

Enable private network for AuthHost

REG ADD "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\authhost.exe" /v EnablePrivateNetwork  /t REG_DWORD /d 1 /f


问:
How to obtain RMSE out of lm result?
I know there is a small difference between $sigma and the concept of root mean squared error. So, i am wondering what is the easiest way to obtain RMSE out of lm function in R?

```<code>res<-lm(randomData$price ~randomData$carat+
                     randomData$cut+randomData$color+
                     randomData$clarity+randomData$depth+
                     randomData$table+randomData$x+
                     randomData$y+randomData$z)

length(coefficients(res))
</code>```

contains 24 coefficient, and I cannot make my model manually anymore.
So, how can I evaluate the RMSE based on coefficients derived from lm?

答:
Residual sum of squares:

```<code>RSS <- c(crossprod(res$residuals))
</code>```

Mean squared error:

```<code>MSE <- RSS / length(res$residuals)
</code>```

Root MSE:

```<code>RMSE <- sqrt(MSE)
</code>```

Pearson estimated residual variance (as returned by summary.lm):

```<code>sig2 <- RSS / res$df.residual
</code>```

Statistically, MSE is the maximum likelihood estimator of residual variance, but is biased (downward). The Pearson one is the restricted maximum likelihood estimator of residual variance, which is unbiased.

Remark

Given two vectors x and y, c(crossprod(x, y)) is equivalent to sum(x * y) but much faster. c(crossprod(x)) is likewise faster than sum(x ^ 2).

sum(x) / length(x) is also faster than mean(x).

Title: How to obtain RMSE out of lm result?

Body:
I know there is a small difference between $sigma and the concept of root mean squared error. So, i am wondering what is the easiest way to obtain RMSE out of lm function in R?

res<-lm(randomData$price ~randomData$carat+
                     randomData$cut+randomData$color+
                     randomData$clarity+randomData$depth+
                     randomData$table+randomData$x+
                     randomData$y+randomData$z)

length(coefficients(res))

contains 24 coefficient, and I cannot make my model manually anymore.
So, how can I evaluate the RMSE based on coefficients derived from lm?

Body:
Residual sum of squares:

RSS <- c(crossprod(res$residuals))

Mean squared error:

MSE <- RSS / length(res$residuals)

Root MSE:

RMSE <- sqrt(MSE)

Pearson estimated residual variance (as returned by summary.lm):

sig2 <- RSS / res$df.residual

Statistically, MSE is the maximum likelihood estimator of residual variance, but is biased (downward). The Pearson one is the restricted maximum likelihood estimator of residual variance, which is unbiased.

Remark

Given two vectors x and y, c(crossprod(x, y)) is equivalent to sum(x * y) but much faster. c(crossprod(x)) is likewise faster than sum(x ^ 2).

sum(x) / length(x) is also faster than mean(x).


问:
How do I start MSDE2000A (mssql$netsdk) from cmd in Windows 7?
I'm trying to install MSDE2000A on a Windows 7 machine, and the database book I'm using described doing so through the command line.  First I installed it to C:\< folder >.  Everything went fine (except for a Windows 7 compatibility issue notice), until I started to actually run it.  I was in the directory in the command line, and I typed net start mssql$netsdk.  As a result I get the response

"System error 5 has occurred.

Acess is denied."

After trying to look up a solution, I found that Windows 7 had an issue with developer stuff being put outside of users' directories, so then I installed it again, this time in C:\Users\< username >\< folder >.  The same problem occurred.

Where do I go from here?

Thanks!

答:
If you are trying to start the service from a command line window start the window in administrative mode.  This will allow you to start and stop services.

The command line command to start the service is:

```<code>NET START MSSQL$*ServiceName*
</code>```

Body:
If you are trying to start the service from a command line window start the window in administrative mode.  This will allow you to start and stop services.

The command line command to start the service is:

NET START MSSQL$*ServiceName*


问:
Unable to map JSON response to a predefined class in C# / dynamic property name
I have a class which basically contains a property like this:

```<code>public class Msg
{
    [JsonProperty(PropertyName = "XD1703301059485299")]
    public Shipping shipping { get; set; }
}
</code>```

the problem is in this part:

```<code> [JsonProperty(PropertyName = "XD1703301059485299")]
</code>```

And the dynamic property name that I get from server...

This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:

```<code>XS12394124912841
</code>```

The object is the null....

How can I resolve property name to be dynamic ? Can someone help me out?

P.S. This is the JSON response itself:

```<code>{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}
</code>```

答:
You can implement something like this with the help of System.Web.Helpers

```<code>using (StreamReader r = new StreamReader("sample.json"))
{
    string json = r.ReadToEnd();
    dynamic data = Json.Decode(json);
    Console.WriteLine(data["your_property"]);
}
</code>```

Here sample.json contains your sample JSON response.

Body:
I have a class which basically contains a property like this:

public class Msg
{
    [JsonProperty(PropertyName = "XD1703301059485299")]
    public Shipping shipping { get; set; }
}

the problem is in this part:

 [JsonProperty(PropertyName = "XD1703301059485299")]

And the dynamic property name that I get from server...

This property name can be any name that server returns. In this particular case it's able to map the JSON to my class since the property names are same... But when server returns something like this:

XS12394124912841

The object is the null....

How can I resolve property name to be dynamic ? Can someone help me out?

P.S. This is the JSON response itself:

{"status":1,"msg":{"dynamic_name":{"order_sn":"12312313123123123","order_status":"0","shipping_info":[{"shipping_name":"","shipping_no":"","shipping_img":"","shipping_code":"","shipping_time":"","track_goods":""}]}},"errcode":0}

Body:
You can implement something like this with the help of System.Web.Helpers

using (StreamReader r = new StreamReader("sample.json"))
{
    string json = r.ReadToEnd();
    dynamic data = Json.Decode(json);
    Console.WriteLine(data["your_property"]);
}

Here sample.json contains your sample JSON response.


问:
give space above and below a DIV
I want to give a DIV space above and under its content.

How can I do this using CSS?

my DIV code is:

```<code><div class="input">
    <label for="pseudo">choisir un pseudo*:</label>
    <br>
    <input type="text" name="pseudo">
</div>
</code>```

答:
In case you want additional space ( more than the default ) between div rows then you can add the following code before/after the start of the div row depending on where you want the additional space.

```<code><div class="row">
   </br>
 </div>
</code>```

This is easier but will add a fixed amount of gap. If you want the gap to be more specific then you can use the padding options described above.

Title: give space above and below a DIV

Body:
I want to give a DIV space above and under its content.

How can I do this using CSS?

my DIV code is:

    choisir un pseudo*:

    <input type="text" name="pseudo">

Body:
In case you want additional space ( more than the default ) between div rows then you can add the following code before/after the start of the div row depending on where you want the additional space.

<div class="row">
   </br>
 </div>

This is easier but will add a fixed amount of gap. If you want the gap to be more specific then you can use the padding options described above.