问:
MVC 5 Owin CAS Logoff action doesn't log off
I'm trying to implement noelbundick's CAS authentication for Owin in my MVC 5 application, but with a twist. We want this to be the only way you can log in or out, so we started the application with no authentication, and used this tutorial to set up all the authentication, also using another new solution with the built-in external authentication just as a way to compare what I'm doing.

So I've switched out all the google stuff with CAS stuff, and everything works great, except for some reason, the logout button doesn't work. Specifically, the action here

```<code>// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    return RedirectToAction("Index", "Home");
}
</code>```

seems to skip over the SignOut() function, and go straight to the RedirectToAction(). I'll give you some more code that may help, but I'm really not sure what else could help. The references in the first paragraph have all the code that I've used, along with any default code from whatever Visual Studio gives you on a basic MVC site with external authentication.

Authentication manager:

```<code>private IAuthenticationManager AuthenticationManager
{
    get { return HttpContext.GetOwinContext().Authentication; }
}
</code>```

Startup.Auth.cs

```<code>private void ConfigureAuth(IAppBuilder app)
{
    var cookieOptions = new CookieAuthenticationOptions
    {
        LoginPath = new PathString("/Account/Login")
    };
    app.UseCookieAuthentication(cookieOptions);
    app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);
    CasAuthenticationOptions casOptions = new CasAuthenticationOptions()
    {
        CasServerUrlBase = "https://cas.ourserver.com/cas"
    };
    app.UseCasAuthentication(casOptions);
}
</code>```

Startup.cs

```<code>public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}
</code>```

ChallengeResult:

```<code>private class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
    }
     public string LoginProvider { get; set; }
     public string RedirectUri { get; set; }
     public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
        context.HttpContext.GetOwinContext()
            .Authentication.Challenge(properties, LoginProvider);
    }
}
</code>```

To be clear, I don't need it to log off of the CAS server, just the website. It's fine if the CAS cookie remains. The problem is that it still says "Welcome, User!" and "Log off" at the top.

Please let me know if there's anything else I can give you that would help. I've googled everything and can't find a solution online or on StackOverflow, but that may be because I didn't google the correct terms as well, so that's also welcome.

答:
I was trying a million different solutions, and on my current code I had

```<code>// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    //AuthenticationManager.SignOut(
    //  DefaultAuthenticationTypes.ApplicationCookie,
    //  DefaultAuthenticationTypes.ExternalCookie);
    //Session.Abandon();
    //return RedirectToAction("Index", "Home");

    HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
    HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Response.Cache.SetNoStore();

    Session.Clear();
    Session.Abandon();
    Session.RemoveAll();
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
 }
</code>```

When I changed it back to the original LogOff action above, it worked all of the sudden. Sorry!

Body:
I'm trying to implement noelbundick's CAS authentication for Owin in my MVC 5 application, but with a twist. We want this to be the only way you can log in or out, so we started the application with no authentication, and used this tutorial to set up all the authentication, also using another new solution with the built-in external authentication just as a way to compare what I'm doing.

So I've switched out all the google stuff with CAS stuff, and everything works great, except for some reason, the logout button doesn't work. Specifically, the action here

// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
    return RedirectToAction("Index", "Home");
}

seems to skip over the SignOut() function, and go straight to the RedirectToAction(). I'll give you some more code that may help, but I'm really not sure what else could help. The references in the first paragraph have all the code that I've used, along with any default code from whatever Visual Studio gives you on a basic MVC site with external authentication.

Authentication manager:

private IAuthenticationManager AuthenticationManager
{
    get { return HttpContext.GetOwinContext().Authentication; }
}

Startup.Auth.cs

private void ConfigureAuth(IAppBuilder app)
{
    var cookieOptions = new CookieAuthenticationOptions
    {
        LoginPath = new PathString("/Account/Login")
    };
    app.UseCookieAuthentication(cookieOptions);
    app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);
    CasAuthenticationOptions casOptions = new CasAuthenticationOptions()
    {
        CasServerUrlBase = "https://cas.ourserver.com/cas"
    };
    app.UseCasAuthentication(casOptions);
}

Startup.cs

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}

ChallengeResult:

private class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
    }
     public string LoginProvider { get; set; }
     public string RedirectUri { get; set; }
     public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
        context.HttpContext.GetOwinContext()
            .Authentication.Challenge(properties, LoginProvider);
    }
}

To be clear, I don't need it to log off of the CAS server, just the website. It's fine if the CAS cookie remains. The problem is that it still says "Welcome, User!" and "Log off" at the top.

Please let me know if there's anything else I can give you that would help. I've googled everything and can't find a solution online or on StackOverflow, but that may be because I didn't google the correct terms as well, so that's also welcome.

Body:
I was trying a million different solutions, and on my current code I had

// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    //AuthenticationManager.SignOut(
    //  DefaultAuthenticationTypes.ApplicationCookie,
    //  DefaultAuthenticationTypes.ExternalCookie);
    //Session.Abandon();
    //return RedirectToAction("Index", "Home");

    HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
    HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Response.Cache.SetNoStore();

    Session.Clear();
    Session.Abandon();
    Session.RemoveAll();
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Home");
 }

When I changed it back to the original LogOff action above, it worked all of the sudden. Sorry!


来源: stackexchange

问:
Javascript setInterval: first interval is abrupt
When using JavaScript's setInterval method in the example below with jQuery effects, the initial display does not appear to engage the fadeIn method. "text" is displayed suddenly.

Subsequent iterations through the chain of effects starting with fadeIn() execute as expected. It is just the first pass where the "text" is displayed suddenly without the fadeIn effect.

Any ideas as to why this occurs?
Thanks - a JavaScript beginner.

```<code>setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').fadeIn(1500).html("text").delay(2750).fadeOut(1500).delay(1000;
};
</code>```

答:
Assuming your text is initially blank and hidden, you are fading in an empty element and then setting the text to text only after the element is faded in. Reverse those steps:

```<code>$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);
</code>```

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myId { display: none; }</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
When using JavaScript's setInterval method in the example below with jQuery effects, the initial display does not appear to engage the fadeIn method. "text" is displayed suddenly.

Subsequent iterations through the chain of effects starting with fadeIn() execute as expected. It is just the first pass where the "text" is displayed suddenly without the fadeIn effect.

Any ideas as to why this occurs?
Thanks - a JavaScript beginner.

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').fadeIn(1500).html("text").delay(2750).fadeOut(1500).delay(1000;
};

Body:
Assuming your text is initially blank and hidden, you are fading in an empty element and then setting the text to text only after the element is faded in. Reverse those steps:

$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);
};

#myId { display: none; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myId">

</div>


问:
Fail to install Xgboost in R (Windows)
I have installed RTool34 in R and checked with Sys.getenv('PATH').

R version: 3.3.3

For some reasons, I had to install Xgboost 0.4-x on my computer (Windows).
I'm using devtools to install.

Error Message I got:

make: *** [xgboost_R.o] Error 1 Warning: running command 'make -f
  "Makevars.win" -f "C:/PROGRA~1/R/R-33~1.3/etc/i386/Makeconf" -f
  "C:/PROGRA~1/R/R-33~1.3/share/make/winshlib.mk"
  SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)'
  SHLIB="xgboost.dll" ' had status 2

ERROR: compilation failed for package 'xgboost'

答: Can you check your c++ compiler version as well? you would need greater than 4.8 to install the latest version of it. I am not sure if you meant you are not able to install xgboost version 0.4 itself.</p>

Title: Fail to install Xgboost in R (Windows)


问:
Parsing Elmah error logs using a console application
In an effort to minimize time spent on reading error logs, I have created the following small plugin that will parse relevant information contained within Elmah error logs, and eventually produce an Excel spreadsheet. For the time being I am using a WriteLine to test. The issue I am facing is that inside the second foreach loop I am seeing a null reference exception in each of the node.attribute items. The expected outcome of this code is to produce a list of "attribute" values from within the <error> tag of each of the XML documents.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;

namespace ExcelSortingAutomation
{
    public class Program
    {
        public static void Main(string[] args)
        {
            DirectoryInfo Exceptions = new DirectoryInfo("C:\\ErrorsMay2017");
            FileInfo[] ExceptionFiles = Exceptions.GetFiles("*.xml");

            foreach (var exception in ExceptionFiles)
            {
                string xml = "<error></error>";
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                foreach (XmlNode node in doc.SelectNodes("//error"))
                {
                    string errorId = node.Attributes["errorId"].Value;
                    string type = node.Attributes["type"].Value;
                    string message = node.Attributes["message"].Value;
                    string time = node.Attributes["time"].Value;
                    Console.WriteLine("{0} - {1} - {2} = {3}", errorId, type, message, time);
                }
            }
        }
    }
}
</code>```

My question is, Why would the logs, which should be pulled and parsed by this point, not be receiving the Attribute values?

Edit 1: upon closer inspection, the XmlNode Node value is returning without "HasAttributes"

答: The line string xml = "<error></error>"; should be replace with string xml = File.ReadAllText(exception.FullName));

Body:
In an effort to minimize time spent on reading error logs, I have created the following small plugin that will parse relevant information contained within Elmah error logs, and eventually produce an Excel spreadsheet. For the time being I am using a WriteLine to test. The issue I am facing is that inside the second foreach loop I am seeing a null reference exception in each of the node.attribute items. The expected outcome of this code is to produce a list of "attribute" values from within the <error> tag of each of the XML documents.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;

namespace ExcelSortingAutomation
{
    public class Program
    {
        public static void Main(string[] args)
        {
            DirectoryInfo Exceptions = new DirectoryInfo("C:\\ErrorsMay2017");
            FileInfo[] ExceptionFiles = Exceptions.GetFiles("*.xml");

            foreach (var exception in ExceptionFiles)
            {
                string xml = "<error></error>";
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                foreach (XmlNode node in doc.SelectNodes("//error"))
                {
                    string errorId = node.Attributes["errorId"].Value;
                    string type = node.Attributes["type"].Value;
                    string message = node.Attributes["message"].Value;
                    string time = node.Attributes["time"].Value;
                    Console.WriteLine("{0} - {1} - {2} = {3}", errorId, type, message, time);
                }
            }
        }
    }
}

My question is, Why would the logs, which should be pulled and parsed by this point, not be receiving the Attribute values?

Edit 1: upon closer inspection, the XmlNode Node value is returning without "HasAttributes"


问:
How to create MD5 hash with HMAC module in Ruby?
Using Google + Bing didn't yield an answer to what should be a simple question:

How are you supposed to use the HMAC module in Ruby to create a HMAC with MD5 (that uses a secret)?

The HMAC docs seem awfully thin.

Thanks!

答:
Probably you just want HMAC::MD5.new(SECRET).digest

Lookup "salting" a hash first. It depends on your usage, but adding a fixed string does help by making your hashes different than the hashes from other apps. Thus, a dictionary attack is harder. But that's just generally speaking.

ContentLicense: CC BY-SA 2.5


问:
Keeping classes loosely coupled and sharing data
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

```<code>class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent
</code>```

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

答:
Keep it simple.py:

```<code>def doStuff(window):
    #do work here
    return window

def parseStuff(stuff):
    pass
</code>```

really.py:

```<code>from simple import doStuff, parseStuff

def really_simple(window):
    okay = doStuff(window)
    return parseStuff(okay)
</code>```

don't complicate the class:

```<code>from really import really_simple
really_simple(window)
</code>```

imo: classes are overly complicated objects, and in a lot of cases more confusing than they need to be, plus they hold references and modify stuff, and can be difficult to decouple once they have been tied to other classes. if there isn't a clear reason why a class needs to be used, then it probably doesn't need to be used.

Body:
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

Body:
Keep it simple.py:

def doStuff(window):
    #do work here
    return window

def parseStuff(stuff):
    pass

really.py:

from simple import doStuff, parseStuff

def really_simple(window):
    okay = doStuff(window)
    return parseStuff(okay)

don't complicate the class:

from really import really_simple
really_simple(window)

imo: classes are overly complicated objects, and in a lot of cases more confusing than they need to be, plus they hold references and modify stuff, and can be difficult to decouple once they have been tied to other classes. if there isn't a clear reason why a class needs to be used, then it probably doesn't need to be used.


问:
Internally called JVM functions upon JNI
When a method defined in C is called from Java (using JNI), what are the methods that are invoked inside the JVM? What does the execution flow look like?

i.e. consider a method public native void display(). When this method is called from the java code as object.display(), what are the internal JVM methods that are called as execution proceeds towards the native code?

Where can I find more documentation about this? Alternatively, which JVM function in the source can I look at and trace?

答:
If you want to take a look at exact chain of execution I suggest to connect to JVM using gdb (or CLion) and take a look at backtrace.

Take a look here to see how to do it:

http://www.owsiak.org/?p=2095

You can also take a look here:

https://www.youtube.com/watch?v=8Cjeq4l5COU

Once you are attached to JVM, you can set breakpoint in your C code and check the backtrace from top to bottom.

Alternatively, you can create SIGSEGV and generate full backtrace of JVM (take a look here: http://jnicookbook.owsiak.org/recipe-No-015/)


问:
Bash User Select Volume
I'm trying to make a script for macOS and in that the user needs to select the Volume the System is installed onto. Problem is the Volume name isn't working (Not a valid install). It currently looks like this,

```<code># Ask the user what drive macOS is installed on
while [ ! -e /Volumes/$VOLUME/boot ]; do
     printf "\nPlease enter the name of the disk macOS is installed on (Leave blank to exit):\n"
     read VOLUME
     if [ -z $VOLUME ]; then #if no value was entered
         exit 1
     fi
     if [ -e /Volumes/$VOLUME/boot ]; then
         break
     else
         printf "\nNot a valid install!\n"
     fi
done
</code>```

Where did I go wrong?

Thanks.

答:
Managed to fix this. Changed this,

```<code>if [ -e /Volumes/$VOLUME/boot ]; then
</code>```

To This,

```<code>if [ -e /Volumes/$VOLUME ]; then
</code>```

Title: Bash User Select Volume

Body:
I'm trying to make a script for macOS and in that the user needs to select the Volume the System is installed onto. Problem is the Volume name isn't working (Not a valid install). It currently looks like this,

# Ask the user what drive macOS is installed on
while [ ! -e /Volumes/$VOLUME/boot ]; do
     printf "\nPlease enter the name of the disk macOS is installed on (Leave blank to exit):\n"
     read VOLUME
     if [ -z $VOLUME ]; then #if no value was entered
         exit 1
     fi
     if [ -e /Volumes/$VOLUME/boot ]; then
         break
     else
         printf "\nNot a valid install!\n"
     fi
done

Where did I go wrong?

Thanks.

Body:
Managed to fix this. Changed this,

if [ -e /Volumes/$VOLUME/boot ]; then

To This,

if [ -e /Volumes/$VOLUME ]; then


问:
What does using something::something::something mean (c++)?
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

```<code>using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;
</code>```

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.

答: This is a using-declaration. It introduces a single name from another namespace into the current scope so that it can be used without qualification. It's not the same as a using-directive, which begins with using namespace.

Body:
So I just started as an intern and the code that I'm supposed to be working on is scattered within like 10 different directories and 100 files and who knows how many namespaces. I've never worked with this before, and I'm really confused how they are all being linked together.

I keep seeing these sorts of statements one after the other, ex:

using something10::something2::something6;
using isThisANamespace::iHaveNoIdeaIfThisIsAClassNameOrWhat::something599;
using randomName::otherRandomName::randomName99999;
using something4::something3::something8766678788787987987698;

Whenever I try to google what using does, I only find results with using namespace. Is using now just a shorter way of using namespace? Some of the things they are using appear to be folder names and file names though. My company mentor doesn't know c++ so he can't help me alas.

Also, if these are all namespaces, then wouldn't using so many of them conflict? Can you call namespace::classname::function? And when you do this do you still have to include the filename for that class?

Please help me learn how to call a function buried in another directory that is also in 4 namespaces. I'm very lost.


问:
TextIO. Read multiple files from GCS using pattern {}
I tried using the following

```<code>TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

That pattern didn't work, as I get

```<code>java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}
</code>```

Even though those 2 files do exist. And I tried with a local file using a similar expression

```<code>TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")
</code>```

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?

答:
Glob patterns work slightly differently in Google Cloud Storage vs. the local filesystem. Apache Beam's TextIO.Read transform will defer to the underlying filesystem to interpret the glob.

GCS glob wildcard patterns are documented here (Wildcard Names).

In the case above, you could use:

```<code>TextIO.Read.from("gs://xyz.abc/xxx_2017-06-*.csv")
</code>```

Note however that this will also include any other matching files.

Body:
I tried using the following

TextIO.Read.from("gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv")

That pattern didn't work, as I get

java.lang.IllegalStateException: Unable to find any files matching StaticValueProvider{value=gs://xyz.abc/xxx_{2017-06-06,2017-06-06}.csv}

Even though those 2 files do exist. And I tried with a local file using a similar expression

TextIO.Read.from("somefolder/xxx_{2017-06-06,2017-06-06}.csv")

And that did work just fine.

I would've thought there would be support for all kinds of globs for files in GCS, but nope. Why is that? is there away to accomplish what I'm looking for?

Body:
Glob patterns work slightly differently in Google Cloud Storage vs. the local filesystem. Apache Beam's TextIO.Read transform will defer to the underlying filesystem to interpret the glob.

GCS glob wildcard patterns are documented here (Wildcard Names).

In the case above, you could use:

TextIO.Read.from("gs://xyz.abc/xxx_2017-06-*.csv")

Note however that this will also include any other matching files.


问:
Interdisciplinary Algorithm Construction with Non-developers
Yeah, I know the title is a mouthful...

What I mean is to say is how do you communicate with a subject matter expert who needs a theory coded and tested?

For example, weather simulation is a collaboration between meteorologists, computer scientists, and software engineers.  The computer scientists and software engineers generally speak the same language, but he meteorologist is in a completely different world.

How do you increase the level of communication and understanding between disciplines?  And not necessarily just for weather, other sciences too.

答:
Act as a programmer, and use the "loosest coupling possible" approach.

For the meteorologist case, I know a little the field, and meteorologists and programmers hardly communicate on the actual code. Those programmers know enough math to implement whatever equations meteorologists want, and then meteorologists are geek enough to use the software.

I could also relate the traders vs quants vs programmers case, which is even worse...

They don't discuss meteorology, and they don't discuss code.

OwnerDisplayName: dacracot

LastEditorDisplayName: mquander


问:
Google Cloud VPN error: peer didn't accept DH group MODP_1024, it requested MODP_1024
I have an issue with Google Cloud Platform, punctually with a VPN that we have mounted between our client and GCP, we have falls in a fixed period of approximately 5 hours. (5 hours up and 5 hours down.)

The issue is:

peer didn't accept DH group MODP_1024, it requested MODP_1024

The usually is 5 hours up and 5 hours down.
https : // i.stack.imgur.com/tWU66.png

Our client receives the following information
https : // i.stack.imgur.com/za5xo.png

The complete log is:

```<code>{
"textPayload": "peer didn't accept DH group MODP_1024, it requested MODP_1024"
"insertId": "1xygt3f4zil3t"
"resource": {
    "type": "vpn_gateway"
    "labels": {
        "gateway_id": "3128708644582367778"
        "project_id": "xxxxxxx-compensar"
        "region": "us-west1"
        }
    }
"timestamp": "2017-05-26T20:47:44.780876927Z"
"severity": "DEBUG"
"logName": "projects/xxxxxxx-compensar/logs/cloud.googleapis.com%2Fipsec_events"
"receiveTimestamp": "2017-05-26T20:47:44.825563989Z"
}
</code>```

The configuration on Client Services is:
https : // i.stack.imgur.com/eyMd4.png

The configuration on GCP is:

```<code>{
"creationTimestamp": "2017-02-20T08:43:58.085-08:00",
"description": "",
"forwardingRules": [
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp"
],
"id": "3128708644582367778",
"kind": "compute#targetVpnGateway",
"name": "cliente-chile-vpn",
"network": "projects/xxxxxxx/global/networks/cliente-chile",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn",
"status": "READY",
"tunnels": [
    "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1"
]
}

{
"creationTimestamp": "2017-05-24T12:46:01.059-07:00",
"description": "",
"detailedStatus": "Handshake with peer broken for unknown reason. Trying again soon.",
"id": "5377869613206363158",
"ikeVersion": 2,
"kind": "compute#vpnTunnel",
"localTrafficSelector": [
    "10.110.0.0/20",
    "10.100.0.0/20"
],
"name": "cliente-chile-vpn-tunnel-1",
"peerIp": "000.00.00.00",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1",
"sharedSecret": "*************",
"sharedSecretHash": "xxxxxxxxxxxxxxxxxxxxx",
"status": "FIRST_HANDSHAKE",
"targetVpnGateway": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:05.802-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "7352555096091566650",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp4500",
"portRange": "4500-4500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:04.428-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "8789138583346127419",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp500",
"portRange": "500-500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:03.043-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "ESP",
"id": "2497873112390345276",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-esp",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}
</code>```

答:
Your Screenshot shows two mismatches from the Cloud VPN docs:

You use SHA-256 when SHA-1 is required

Cloud VPN uses pre-shared keys, but it looks like no pre-shared secret is set up.

IPSec requires configurations to match closely, so try swiching to SHA-1 and ensuring the two sides of the VPN have the same pre-shared key.

Body:
I have an issue with Google Cloud Platform, punctually with a VPN that we have mounted between our client and GCP, we have falls in a fixed period of approximately 5 hours. (5 hours up and 5 hours down.)

The issue is:

peer didn't accept DH group MODP_1024, it requested MODP_1024

The usually is 5 hours up and 5 hours down.
https : // i.stack.imgur.com/tWU66.png

Our client receives the following information
https : // i.stack.imgur.com/za5xo.png

The complete log is:

{
"textPayload": "peer didn't accept DH group MODP_1024, it requested MODP_1024"
"insertId": "1xygt3f4zil3t"
"resource": {
    "type": "vpn_gateway"
    "labels": {
        "gateway_id": "3128708644582367778"
        "project_id": "xxxxxxx-compensar"
        "region": "us-west1"
        }
    }
"timestamp": "2017-05-26T20:47:44.780876927Z"
"severity": "DEBUG"
"logName": "projects/xxxxxxx-compensar/logs/cloud.googleapis.com%2Fipsec_events"
"receiveTimestamp": "2017-05-26T20:47:44.825563989Z"
}

The configuration on Client Services is:
https : // i.stack.imgur.com/eyMd4.png

The configuration on GCP is:

{
"creationTimestamp": "2017-02-20T08:43:58.085-08:00",
"description": "",
"forwardingRules": [
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp"
],
"id": "3128708644582367778",
"kind": "compute#targetVpnGateway",
"name": "cliente-chile-vpn",
"network": "projects/xxxxxxx/global/networks/cliente-chile",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn",
"status": "READY",
"tunnels": [
    "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1"
]
}

{
"creationTimestamp": "2017-05-24T12:46:01.059-07:00",
"description": "",
"detailedStatus": "Handshake with peer broken for unknown reason. Trying again soon.",
"id": "5377869613206363158",
"ikeVersion": 2,
"kind": "compute#vpnTunnel",
"localTrafficSelector": [
    "10.110.0.0/20",
    "10.100.0.0/20"
],
"name": "cliente-chile-vpn-tunnel-1",
"peerIp": "000.00.00.00",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1",
"sharedSecret": "*************",
"sharedSecretHash": "xxxxxxxxxxxxxxxxxxxxx",
"status": "FIRST_HANDSHAKE",
"targetVpnGateway": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:05.802-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "7352555096091566650",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp4500",
"portRange": "4500-4500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:04.428-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "8789138583346127419",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp500",
"portRange": "500-500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:03.043-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "ESP",
"id": "2497873112390345276",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-esp",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}


问:
Gurobi in Python: best way to read csv file
I'm learning how to solve combinatorial optimization problems in Gurobi using Python. I would like to know what is the best option to read a csv file to use the data as model parameters. I'm using 'genfromtxt' to read the csv file, but I'm having difficulties in using it for constraint construction (Gurobi doesn't support this type - see error).

Here my code and error message, my_data is composed by 4 columns: node index, x coordinate, y coordinate and maximum degree.

```<code>from gurobipy import *
from numpy import genfromtxt
import math

# Read data from csv file
my_data = genfromtxt('prob25.csv', delimiter=',')

# Number of vertices
n = len(my_data)

# Function to calculate euclidean distancces
dist = {(i,j) :
    math.sqrt(sum((my_data[i][k]-my_data[j][k])**2 for k in [1,2]))
    for i in range(n) for j in range(i)}

# Create a new model
m = Model("dcstNarula")

# Create variables

vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction

m.update()

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
             for i in range(n)), name='degree')

GurobiError: Unsupported type (<type 'numpy.ndarray'>) for LinExpr addition argument
</code>```

First two lines of data

```<code>1,19.007,35.75,1
2,4.4447,6.0735,2
</code>```

答:
Actually it was a problem of indexing instead of data type. In the code:

```<code># Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
         for i in range(n)), name='degree')
</code>```

It should be used vars.sum('*',i) instead of vars.sum('*',j) and my_data[i,3] instead of my_data[:,3]

Body:
I'm learning how to solve combinatorial optimization problems in Gurobi using Python. I would like to know what is the best option to read a csv file to use the data as model parameters. I'm using 'genfromtxt' to read the csv file, but I'm having difficulties in using it for constraint construction (Gurobi doesn't support this type - see error).

Here my code and error message, my_data is composed by 4 columns: node index, x coordinate, y coordinate and maximum degree.

from gurobipy import *
from numpy import genfromtxt
import math

# Read data from csv file
my_data = genfromtxt('prob25.csv', delimiter=',')

# Number of vertices
n = len(my_data)

# Function to calculate euclidean distancces
dist = {(i,j) :
    math.sqrt(sum((my_data[i][k]-my_data[j][k])**2 for k in [1,2]))
    for i in range(n) for j in range(i)}

# Create a new model
m = Model("dcstNarula")

# Create variables

vars = m.addVars(dist.keys(), obj=dist, vtype=GRB.BINARY, name='e')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction

m.update()

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
             for i in range(n)), name='degree')

GurobiError: Unsupported type (<type 'numpy.ndarray'>) for LinExpr addition argument

First two lines of data

1,19.007,35.75,1
2,4.4447,6.0735,2

Body:
Actually it was a problem of indexing instead of data type. In the code:

# Add degree-b constraint
m.addConstrs((vars.sum('*',j) <= my_data[:,3]
         for i in range(n)), name='degree')

It should be used vars.sum('*',i) instead of vars.sum('*',j) and my_data[i,3] instead of my_data[:,3]


问:
Will the depth of a file within a filesystem change the time taken to copy it?
I am trying to figure out if whether or not the depth of a file in a filesystem will change the amount of time it takes to execute a "cp" bash command with that file.

By depth I mean how many parent directories its contained in.

I tried running a few tests, but my results are pretty inconclusive, and when I try to logically answer, I can think of reasons of why it would be either way.

答:
What is the purpose of this?

Provided nothing is cached, the deeper the directory tree the more data has to be read from storage to get to the file - you have to find the name of the second dir, then the third within the second and so on. On the other hand if the file is big, the time needed to do this can be negligible in comparison.

Also mere startup of a command like cp is not without its cost.

If you are interested in how file systems work read this free book: http://www.nobius.org/~dbg/practical-file-system-design.pdf

Performance is a complicated subject, especially so when hard media is involved. Without proper understanding of how this works and proper understanding of statistics, you can't perform a correct test.


问:
can't delete from specific row from generate table from mySQL
Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?

Thank you!

<?php
 $result= mysql_query("SELECT * from Staff ORDER BY status");
 $count=1;

 while($row=mysql_fetch_array($result)){
?>

       <?php echo $count; ?>
    <?php echo $row['staffId']; ?>
    <?php echo $row['name']; ?>
    <?php echo $row['address'];?>
    <?php echo $row['pNum'];?>
    <?php echo $row['status'];?>
    <?php echo $row['type'];?>
                <input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
             <input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">

<?php
 $count++; }
 if(isset($_POST['deleteStaff'])){
  $id=$_POST['staffId1'];
  $result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
  if($result){
   echo '';
   }
   else{
    ?>

                <?PHP
    }
  }
?>```

答:
I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.

Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.

example

```<code><form action="deletion_script.php?staffid=<?php echo $staffid; ?>">
</code>```

Put that inside of the td tag

Then in your deletion_script.php file, put something like this

```<code><?php
//get staffid from URI
$staffid = $_GET['staffid'];

$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>
</code>```

This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.

Body:
I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.

Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.

example

<form action="deletion_script.php?staffid=<?php echo $staffid; ?>">

Put that inside of the td tag

Then in your deletion_script.php file, put something like this

<?php
//get staffid from URI
$staffid = $_GET['staffid'];

$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>

This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.


问:
Express + Node application deployed to Azure can't connect to CosmosDB/DocumentDB
I created an app using Nodejs, express and DocumentDB and deployed it to Azure(App Service\Web App). Everything is working fine except it is not connecting to DocumentDB. It works fine in my local environment.

I am new to this environment so not sure what additional information can be provided.

Only difference between my local environment and azure is that I added following web.config because site was not starting

答:
This has been really frustrating last couple of days.

URI listed in CosmosDB settings is https://xxxxxxxxpoc5.documents.azure.com:443/

and URI that worked for me is https://xxxxxxxxpoc5.documents.azure.com/, without port number 443.

Note: Both URIs worked from my local system.


问:
How can I pass a reference to an existing callback to @HostListener?
I have a single callback that I'd like triggered by multiple events. I tried

```<code>userIsActive(){
  //do something
}
@HostListener('document:mousemove') this.userIsActive;
@HostListener('document:keypress') this.userIsActive;
@...
</code>```

But it doesn't work, duplicate identifier 'userIsActive'. I know I can define new functions as callbacks,

```<code>@HostListener('document:mousemove') foo1(){ userIsActive(); };
@HostListener('document:keypress') foo2(){ userIsActive(); };
@...
</code>```

but creating 2 new functions with arbitrary numbers seems unnecessary and less readable. Is there a way to pass a reference to an existing callback to @HostListener?

答:
There is no need to define multiple methods, you can just decorate the same method multiple times.

For example:

  @HostListener('window:keyup')
  @HostListener('window:keydown')
  handle() {
    console.log('happened')
  }
```

Body:
I have a single callback that I'd like triggered by multiple events. I tried

userIsActive(){
  //do something
}
@HostListener('document:mousemove') this.userIsActive;
@HostListener('document:keypress') this.userIsActive;
@...

But it doesn't work, duplicate identifier 'userIsActive'. I know I can define new functions as callbacks,

@HostListener('document:mousemove') foo1(){ userIsActive(); };
@HostListener('document:keypress') foo2(){ userIsActive(); };
@...

but creating 2 new functions with arbitrary numbers seems unnecessary and less readable. Is there a way to pass a reference to an existing callback to @HostListener?


问:
font awesome animated spinner through background
I am using font awesome spin icon through CSS background for loading the page.

    /* Styles go here */
.loading-icon {
  position: relative;
  width: 20px;
  height: 20px;
  margin:50px auto;
}

.loading-icon:before {
  content: "\f110";
  font-family: FontAwesome;
  font-size:20px;
  position: absolute;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <link data-require="fontawesome@*" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div class="loading-icon"></div>
</body>

</html></code>```

The icon is rendering successfully in the page, but it is a static.
How can I use the animated spinning icon using font awesome as a background?
Kindly assist.

答:
Font Awesome 4.7

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

```
</div>
</div>
</p>
<h1>Font Awesome 5+</h1>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

<i class="fas fa-spinner fa-spin"></i>
<i class="fas fa-circle-notch fa-spin"></i>
<i class="fas fa-sync fa-spin"></i>
<i class="fas fa-cog fa-spin"></i>
<i class="fas fa-spinner fa-pulse"></i>
<i class="fas fa-stroopwafel fa-spin"></i></code>```

Font Awesome 5 Spinner documentation:

https://fontawesome.com/how-to-use/on-the-web/styling/animating-icons

Font Awesome 5 Spinner Icon list:

https://fontawesome.com/icons?c=spinners

Body:
I am using font awesome spin icon through CSS background for loading the page.

    /* Styles go here */
.loading-icon {
  position: relative;
  width: 20px;
  height: 20px;
  margin:50px auto;
}

.loading-icon:before {
  content: "\f110";
  font-family: FontAwesome;
  font-size:20px;
  position: absolute;
  top: 0;
}

<!DOCTYPE html>

  <link data-require="fontawesome@*" data-semver="4.5.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css" />
  <link rel="stylesheet" href="style.css" />

The icon is rendering successfully in the page, but it is a static.
How can I use the animated spinning icon using font awesome as a background?
Kindly assist.

Body:
Font Awesome 4.7

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<i class="fa fa-spinner fa-spin fa-fw"></i>
<i class="fa fa-circle-o-notch fa-spin fa-fw"></i>
<i class="fa fa-refresh fa-spin fa-fw"></i>
<i class="fa fa-cog fa-spin fa-fw"></i>
<i class="fa fa-spinner fa-pulse fa-fw"></i>

Font Awesome 5+

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

<i class="fas fa-spinner fa-spin"></i>
<i class="fas fa-circle-notch fa-spin"></i>
<i class="fas fa-sync fa-spin"></i>
<i class="fas fa-cog fa-spin"></i>
<i class="fas fa-spinner fa-pulse"></i>
<i class="fas fa-stroopwafel fa-spin"></i>

Font Awesome 5 Spinner documentation:

https://fontawesome.com/how-to-use/on-the-web/styling/animating-icons

Font Awesome 5 Spinner Icon list:

https://fontawesome.com/icons?c=spinners

ContentLicense: CC BY-SA 4.0


问:
Vertically-rotating 3D Bootstrap carousel
I would like to extend Bootstrap's carousel so that it has a rotating effect similar to these examples:

https://desandro.github.io/3dtransforms/docs/carousel.html
https://codepen.io/nopr/pen/rfBJx

I've tried to use this vertical bootstrap slider as an example, as it seems to have the CSS I need:

https://codepen.io/danbhala/pen/eNZrQW/

However, so far I've only managed to get the inactive items (or rather, their contents) to scale, rather than rotate around the Y axis, even when using these CSS rules:

```<code>.carousel.vertical .carousel-inner > .item.next, .carousel.vertical
.carousel-inner > .item.active.right {
  -webkit-transform: translate3d(0, 100%, 0) rotateY( 90deg );
          transform: translate3d(0, 100%, 0) rotateY( 90deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.prev, .carousel.vertical
.carousel-inner > .item.active.left {
  -webkit-transform: translate3d(0, -100%, 0) rotateY( -90deg );
          transform: translate3d(0, -100%, 0) rotateY( -90deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.next.left, .carousel.vertical
.carousel-inner > .item.prev.right, .carousel.vertical .carousel-inner >
.item.active {
  -webkit-transform: translate3d(0, 0, 0) rotateY( 0deg );
          transform: translate3d(0, 0, 0) rotateY( 0deg );
  top: 0;
}
</code>```

Is there any way to achieve the same effect, regardless of the number of slides?

答:
The answer was actually really simple -- I had the rotating axis wrong:

Example: https://codepen.io/kenshin23/pen/awvBGQ

```<code>.carousel.vertical .carousel-inner > .item.next, .carousel.vertical
.carousel-inner > .item.active.right {
      -webkit-transform: translate3d(0, 100%, 0) rotateX( 120deg );
          transform: translate3d(0, 100%, 0) rotateX( 120deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.prev, .carousel.vertical
.carousel-inner > .item.active.left {
  -webkit-transform: translate3d(0, -100%, 0) rotateX( -120deg );
          transform: translate3d(0, -100%, 0) rotateX( -120deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.next.left,
.carousel.vertical .carousel-inner > .item.prev.right,
.carousel.vertical .carousel-inner > .item.active {
  -webkit-transform: translate3d(0, 0, 0) rotateX( 0deg );
          transform: translate3d(0, 0, 0) rotateX( 0deg );
  top: 0;
}
</code>```

Body:
I would like to extend Bootstrap's carousel so that it has a rotating effect similar to these examples:

https://desandro.github.io/3dtransforms/docs/carousel.html
https://codepen.io/nopr/pen/rfBJx

I've tried to use this vertical bootstrap slider as an example, as it seems to have the CSS I need:

https://codepen.io/danbhala/pen/eNZrQW/

However, so far I've only managed to get the inactive items (or rather, their contents) to scale, rather than rotate around the Y axis, even when using these CSS rules:

.carousel.vertical .carousel-inner > .item.next, .carousel.vertical
.carousel-inner > .item.active.right {
  -webkit-transform: translate3d(0, 100%, 0) rotateY( 90deg );
          transform: translate3d(0, 100%, 0) rotateY( 90deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.prev, .carousel.vertical
.carousel-inner > .item.active.left {
  -webkit-transform: translate3d(0, -100%, 0) rotateY( -90deg );
          transform: translate3d(0, -100%, 0) rotateY( -90deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.next.left, .carousel.vertical
.carousel-inner > .item.prev.right, .carousel.vertical .carousel-inner >
.item.active {
  -webkit-transform: translate3d(0, 0, 0) rotateY( 0deg );
          transform: translate3d(0, 0, 0) rotateY( 0deg );
  top: 0;
}

Is there any way to achieve the same effect, regardless of the number of slides?

Body:
The answer was actually really simple -- I had the rotating axis wrong:

Example: https://codepen.io/kenshin23/pen/awvBGQ

.carousel.vertical .carousel-inner > .item.next, .carousel.vertical
.carousel-inner > .item.active.right {
      -webkit-transform: translate3d(0, 100%, 0) rotateX( 120deg );
          transform: translate3d(0, 100%, 0) rotateX( 120deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.prev, .carousel.vertical
.carousel-inner > .item.active.left {
  -webkit-transform: translate3d(0, -100%, 0) rotateX( -120deg );
          transform: translate3d(0, -100%, 0) rotateX( -120deg );
  top: 0;
}
.carousel.vertical .carousel-inner > .item.next.left,
.carousel.vertical .carousel-inner > .item.prev.right,
.carousel.vertical .carousel-inner > .item.active {
  -webkit-transform: translate3d(0, 0, 0) rotateX( 0deg );
          transform: translate3d(0, 0, 0) rotateX( 0deg );
  top: 0;
}


问:
Save cookies after post method, perl, mechanize, redirect
I want to login via perl script to http://www.tennisinsight.com/match_previews.htm and download the page. I am stuck at login into the site via the script

1 The site uses cookies to store login data.

2 The login form is triggered by javascript, but that is not important, because a simple web page on local that containts only:

```<code>  <form action="http://www.tennisinsight.com/myTI.php" method="POST">
      <input name="username" type="text" size="25" />
      <input name="password" type="password"  size="25" />
      <input name="mySubmit" type="submit" value="Submit!" />
 </form>
</code>```

given the right username and pass will send the needed data, and the site will redirect to main page, user logged, and cookies are created. In short, a simple post with correct data does it all on the client side.

3.I have successfully  tried and fetched the page I need with curl, once the correct cookies were provided.

I think that posting to myTI.php, storing the returned cookies and then opening the correct page while reading the cookies will do the trick, but I am failing at the save cookies part....

Here is the script I try to get cookies, it prints them in stdout at the moment

```<code>use warnings;
use HTML::Tree;
use LWP::Simple;
use WWW::Mechanize;
use HTTP::Request::Common;
use Data::Dumper;

my $username = "user";
my $password = "pass";
my $site_url = 'http://www.tennisinsight.com/myTI.php';
my $mech = WWW::Mechanize->new( autocheck => 1 );

# print $mech->content;

my $response = $mech->post($site_url ,
    [
       'username' => $username,
       'password' => $password,
    ]) ;
my $cookie_jar = HTTP::Cookies->new;
$cookie_jar->extract_cookies( $response );

print $cookie_jar;
</code>```

EDIT:
I have found the examples how to store cookies, the problem is that I get an empty file ( or empty stdout... It seems the called php will redirect before the cookies are stored and login will fail

I am sorry, but I am new to perl in general, seems I am missing something

答:
I had the same problem, what looked like Mechanize not passing cookies between requests. To debug, I had Mechanize write the cookies to disk

```<code>my $mech = WWW::Mechanize->new(file => "/path/to/cookies");
</code>```

When I did that, I got a file with this as the contents (i.e. the "empty" cookies file):

```<code>#LWP-Cookies-1.0
</code>```

As gangabass suggested, I changed my user agent

```<code>$mech->agent_alias('Linux Mozilla');
</code>```

and then cookies started appearing in the file and they were passed between subsequent requests. Problem solved.

It was the agent_alias call that fixed it, not writing the cookies to disk.

Body:
I want to login via perl script to http://www.tennisinsight.com/match_previews.htm and download the page. I am stuck at login into the site via the script

1 The site uses cookies to store login data.

2 The login form is triggered by javascript, but that is not important, because a simple web page on local that containts only:

  <form action="http://www.tennisinsight.com/myTI.php" method="POST">
      <input name="username" type="text" size="25" />
      <input name="password" type="password"  size="25" />
      <input name="mySubmit" type="submit" value="Submit!" />
 </form>

given the right username and pass will send the needed data, and the site will redirect to main page, user logged, and cookies are created. In short, a simple post with correct data does it all on the client side.

3.I have successfully  tried and fetched the page I need with curl, once the correct cookies were provided.

I think that posting to myTI.php, storing the returned cookies and then opening the correct page while reading the cookies will do the trick, but I am failing at the save cookies part....

Here is the script I try to get cookies, it prints them in stdout at the moment

use warnings;
use HTML::Tree;
use LWP::Simple;
use WWW::Mechanize;
use HTTP::Request::Common;
use Data::Dumper;

my $username = "user";
my $password = "pass";
my $site_url = 'http://www.tennisinsight.com/myTI.php';
my $mech = WWW::Mechanize->new( autocheck => 1 );

# print $mech->content;

my $response = $mech->post($site_url ,
    [
       'username' => $username,
       'password' => $password,
    ]) ;
my $cookie_jar = HTTP::Cookies->new;
$cookie_jar->extract_cookies( $response );

print $cookie_jar;

EDIT:
I have found the examples how to store cookies, the problem is that I get an empty file ( or empty stdout... It seems the called php will redirect before the cookies are stored and login will fail

I am sorry, but I am new to perl in general, seems I am missing something

Body:
I had the same problem, what looked like Mechanize not passing cookies between requests. To debug, I had Mechanize write the cookies to disk

my $mech = WWW::Mechanize->new(file => "/path/to/cookies");

When I did that, I got a file with this as the contents (i.e. the "empty" cookies file):

#LWP-Cookies-1.0

As gangabass suggested, I changed my user agent

$mech->agent_alias('Linux Mozilla');

and then cookies started appearing in the file and they were passed between subsequent requests. Problem solved.

It was the agent_alias call that fixed it, not writing the cookies to disk.


问:
Parameter Validation on Reports
I'm new to SSRS, so I apologize if this question is too simple:

I have a report which accepts a parameter called "Amount". I want to constrain valid inputs to currency values >= 0, and pop open an error message if the user enters improper values.

I don't want to validate inputs in my stored procedure and throw exceptions, because SSRS displays a very generic "Query execution failed for 'someTable'" message to users who access the report from another machine, and my business does not want to turn on the "Enable Remote Errors" flag.

How do I add input validation to report parameters and notify users of bad input?

Yes, I've googled around, but haven't had much luck. Thanks in advance :)

答:
I don't think there's a whole lot you can do in the reporting tool itself.  It's pretty rudimentary.

However, you can provide an ASP.net web interface or a form that you can use to ask the users for the parameter values in any format .NET allows, and use the ReportViewer control to display the report.  It sounds daunting, but it's actually pretty straight-forward, particularly if you already have a project you can build on.

Microsoft gives tutorials for using the ReportViewer controls.

OwnerDisplayName: Princess

Title: Parameter Validation on Reports

OwnerDisplayName: Darcy Casselman


问:
WordPress the_permalink() outputting nothing
I can outputting all of my posts in a custom post type called Featured Projects.
The outputting of the psots work fine, as do the custom post values from the custom meta box.
What doesn't output is the_permalink() and the_title(). They are just blank.

If you have any clue what I screwed up or what I can check, I would appreciate it!

```<code><ul id="projects-nav">
  <?php query_posts('post_type=featured-projects&order=ASC&orderby=menu_order&posts_per_page=-1'); ?>
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <?php $agency = get_post_custom_values('agency'); ?>
  <?php $production = get_post_custom_values('production'); ?>
  <?php $post = get_post_custom_values('post'); ?>
  <?php $video_url = get_post_custom_values('video_url_1'); ?>
  <?php $thumb_url = get_post_custom_values('thumb_url_1'); ?>
  <li>
  <a href="<?php the_permalink(); ?>"><img alt="<?php the_title(); ?>" src="<?php echo $thumb_url[0]; ?>" width="185" height="113"></a>
  <h4><?php the_title(''); ?></h4>
  <?php the_content(""); ?>
  <?php if($agency[0] != '') { ?><p>Agency: <?php echo $agency[0]; ?></p><?php } ?>
  <?php if($production[0] != '') { ?><p>Production: <?php echo $production[0]; ?></p><?php } ?>
  <?php if($post[0] != '') { ?><p>Post: <?php echo $post[0]; ?></p><?php } ?>
 </li>
 <?php endwhile; endif; ?>
</ul>
</code>```

答:
For the permalink, you can use the following alternative:

Also did you try removing the quotes inside the ? That could be messing with it.

Body:
I can outputting all of my posts in a custom post type called Featured Projects.
The outputting of the psots work fine, as do the custom post values from the custom meta box.
What doesn't output is the_permalink() and the_title(). They are just blank.

If you have any clue what I screwed up or what I can check, I would appreciate it!

  <?php query_posts('post_type=featured-projects&order=ASC&orderby=menu_order&posts_per_page=-1'); ?>
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <?php $agency = get_post_custom_values('agency'); ?>
  <?php $production = get_post_custom_values('production'); ?>
  <?php $post = get_post_custom_values('post'); ?>
  <?php $video_url = get_post_custom_values('video_url_1'); ?>
  <?php $thumb_url = get_post_custom_values('thumb_url_1'); ?>

  <a href="<?php the_permalink(); ?>"><img alt="<?php the_title(); ?>" src="<?php echo $thumb_url[0]; ?>" width="185" height="113">

<?php the_title(''); ?>

  <?php the_content(""); ?>
  <?php if($agency[0] != '') { ?>
Agency: <?php echo $agency[0]; ?>
<?php } ?>
  <?php if($production[0] != '') { ?>
Production: <?php echo $production[0]; ?>
<?php } ?>
  <?php if($post[0] != '') { ?>
Post: <?php echo $post[0]; ?>
<?php } ?>

 <?php endwhile; endif; ?>


问:
How to schedule a job once every Thursday using Kue?
Using Kue, how do I schedule a job to be executed once every Thursday? The Kue readme mentions that I can delay a Job, but what about repeatedly executing the Job at a specific time?

I can do what I want with a cron job, but I like Kue's features.

What I want is to process a Job once anytime on Thursday, but only once.

答:
Take a look at kue-scheduler.  I'm pretty sure that you should be able to do something like this:

```<code>var kue = require('kue-scheduler');
var Queue = kue.createQueue();

//create a job instance
var job = Queue
            .createJob('every', data)
            .attempts(3)
            .backoff(backoff)
            .priority('normal');

//schedule it to run every Thursday at 00:00:00
var thursday = '0 0 0 * * 4';
Queue.every(thursday, job);

//somewhere process your scheduled jobs
Queue.process('every', function(job, done) {
    ...
    done();
});
</code>```

kue-scheduler docs: https://github.com/lykmapipo/kue-scheduler;
link in their docs to cron stuff: https://github.com/kelektiv/node-cron;

Body:
Take a look at kue-scheduler.  I'm pretty sure that you should be able to do something like this:

var kue = require('kue-scheduler');
var Queue = kue.createQueue();

//create a job instance
var job = Queue
            .createJob('every', data)
            .attempts(3)
            .backoff(backoff)
            .priority('normal');

//schedule it to run every Thursday at 00:00:00
var thursday = '0 0 0 * * 4';
Queue.every(thursday, job);

//somewhere process your scheduled jobs
Queue.process('every', function(job, done) {
    ...
    done();
});

kue-scheduler docs: https://github.com/lykmapipo/kue-scheduler;
link in their docs to cron stuff: https://github.com/kelektiv/node-cron;


问:
Powershell & Regex - How to find and delete uppercase characters from file names in directory
I need a Powershell script that will find and replace uppercase characters within all the filenames within a directory with nothing.

The script would do something like this:

Filename BEFORE: CAPITAL-letters.jpg

Filename AFTER: -letters.jpg

Edit: I tried running this script, but it didn't work

```<code>dir | rename-item -NewName {$_.name -replace [Regex]::Escape("[A-Z"),""}
</code>```

答:
```<code>$test = "CAPITAL-letters.jpg"
$test -creplace "[A-Z]"
</code>```

=> -letters.jpg

Body:
I need a Powershell script that will find and replace uppercase characters within all the filenames within a directory with nothing.

The script would do something like this:

Filename BEFORE: CAPITAL-letters.jpg

Filename AFTER: -letters.jpg

Edit: I tried running this script, but it didn't work

dir | rename-item -NewName {$_.name -replace [Regex]::Escape("[A-Z"),""}

Body:
$test = "CAPITAL-letters.jpg"
$test -creplace "[A-Z]"

=> -letters.jpg


问:
Foreign keys + table inheritance in PostgreSQL?
I have three tables: organization, organization_teams and org_users. Here organization_teams is inherited from organization. So suppose if a record is added in organizations_teams it will get the organization table id as value for id column in organization_teams.

org_users has foreign key on id column of organization. Now when I try to insert data in org_users it giving me error as below

```<code>insert or update on table "org_users" violates foreign key constraint "org_users_organizations"
DETAIL:  Key (org_id)=(12) is not present in table "organizations"
</code>```

Why?

答:
The only workaround i have found is:

create function returning trigger for checking existence of some id
in inherited table

create a constraint trigger instead of FK

Body:
I have three tables: organization, organization_teams and org_users. Here organization_teams is inherited from organization. So suppose if a record is added in organizations_teams it will get the organization table id as value for id column in organization_teams.

org_users has foreign key on id column of organization. Now when I try to insert data in org_users it giving me error as below

insert or update on table "org_users" violates foreign key constraint "org_users_organizations"
DETAIL:  Key (org_id)=(12) is not present in table "organizations"

Why?


问:
Python magicmock causes 'NoneType' object has no attribute 'unregister'
I'm trying to patch a function call with a custom mock I wrote

```<code>    subscriberMock = MagicMock(side_effect=subscriber)
    subscriberMock.return_value.unregister.return_value = True
    with patch('rospy.Subscriber', subscriberMock):
        data['op'] = "unsubscribe"
        data['topic'] = "/helo"
        self.rosbridge.incoming(data)
</code>```

The inner method has this piece of code

```<code>self.subscribers[topic] = rospy.Subscriber(topic, 'msg', outgoing_function)
self.subscribers[topic].unregister() # <-- AttributeError
</code>```

However when I run this it returns an attribute error

'NoneType' object has no attribute 'unregister'

I'm guessing the return_value is set to a NoneType but I thought this subscriberMock.return_value.unregister.return_value would override it

More Information:

if I print self.subscribers[topic] it returns None. It then runs the side effect. Why should self.subscribers[topic] = None given that I have a return value for a parameter in it.

答:
Instead of the above mock, you have to write a Mock calling the instantiation within the side effect

```<code>    def subscriber (topic, topic_type, outgoing_function):
        # convert to a ROS object
        output = ROSBridgeObject()
        output.foo = topic
        # pretend we got a message from what we subscribed to
        outgoing_function(output)
        mock = MagicMock()
        subscriberMock.unregister.return_value = True
        return mock
    subscriberMock = MagicMock(side_effect=subscriber)
</code>```

This is because MagicMock's either have return values or side effects

Body:
I'm trying to patch a function call with a custom mock I wrote

    subscriberMock = MagicMock(side_effect=subscriber)
    subscriberMock.return_value.unregister.return_value = True
    with patch('rospy.Subscriber', subscriberMock):
        data['op'] = "unsubscribe"
        data['topic'] = "/helo"
        self.rosbridge.incoming(data)

The inner method has this piece of code

self.subscribers[topic] = rospy.Subscriber(topic, 'msg', outgoing_function)
self.subscribers[topic].unregister() # <-- AttributeError

However when I run this it returns an attribute error

'NoneType' object has no attribute 'unregister'

I'm guessing the return_value is set to a NoneType but I thought this subscriberMock.return_value.unregister.return_value would override it

More Information:

if I print self.subscribers[topic] it returns None. It then runs the side effect. Why should self.subscribers[topic] = None given that I have a return value for a parameter in it.

Body:
Instead of the above mock, you have to write a Mock calling the instantiation within the side effect

    def subscriber (topic, topic_type, outgoing_function):
        # convert to a ROS object
        output = ROSBridgeObject()
        output.foo = topic
        # pretend we got a message from what we subscribed to
        outgoing_function(output)
        mock = MagicMock()
        subscriberMock.unregister.return_value = True
        return mock
    subscriberMock = MagicMock(side_effect=subscriber)

This is because MagicMock's either have return values or side effects


问:
Error GRPC Spanner Google Cloud With PHP
I'm using PHP to try using the Google Cloud Spanner. I already did the gCloud settings and everything, and that's right. Now I need to make the connection via PHP to do a CRUD with the database that is in Spanner, but the code below always returns the error:

PHP Fatal error:  Undefined constant 'Grpc\STATUS_UNKNOWN' in
  /xxx/xxxx/www/vendor/google/cloud-spanner/Connection/Grpc.php on line
  129

The code I have is:

```<code><?php
require 'vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;

/* Error start here */
$spanner = new SpannerClient([
    'projectId' => 'my-project-id'
]);

$db = $spanner->connect('instance', 'database');

$userQuery = $db->execute('SELECT * FROM usuario WHERE login = @login', [
    'parameters' => [
        'login' => 'devteam'
    ]
]);

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['login'];
</code>```

The requirements I use in the composer are:

```<code>"require": {
        "google/cloud": "^0.32.1",
        "google/cloud-spanner": "^0.2.2"
}
</code>```

I noticed that if I enter through the browser, the error presented above continues to appear. If I run the command php teste.php on the terminal, it runs the script correctly, ie, the terminal works and the browser does not.

答:
Google Cloud PHP's spanner client is gRPC only. This means to use it you will need to install the gRPC PHP extension:

```<code>pecl install grpc
</code>```

Once you have done that, add google/proto-client-php and google/gax to your composer.json and run composer update. After this is done, the error will be resolved.

Body:
I'm using PHP to try using the Google Cloud Spanner. I already did the gCloud settings and everything, and that's right. Now I need to make the connection via PHP to do a CRUD with the database that is in Spanner, but the code below always returns the error:

PHP Fatal error:  Undefined constant 'Grpc\STATUS_UNKNOWN' in
  /xxx/xxxx/www/vendor/google/cloud-spanner/Connection/Grpc.php on line
  129

The code I have is:

<?php
require 'vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;

/* Error start here */
$spanner = new SpannerClient([
    'projectId' => 'my-project-id'
]);

$db = $spanner->connect('instance', 'database');

$userQuery = $db->execute('SELECT * FROM usuario WHERE login = @login', [
    'parameters' => [
        'login' => 'devteam'
    ]
]);

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['login'];

The requirements I use in the composer are:

"require": {
        "google/cloud": "^0.32.1",
        "google/cloud-spanner": "^0.2.2"
}

I noticed that if I enter through the browser, the error presented above continues to appear. If I run the command php teste.php on the terminal, it runs the script correctly, ie, the terminal works and the browser does not.

Body:
Google Cloud PHP's spanner client is gRPC only. This means to use it you will need to install the gRPC PHP extension:

pecl install grpc

Once you have done that, add google/proto-client-php and google/gax to your composer.json and run composer update. After this is done, the error will be resolved.


问:
How to detect if ASP.NET is enabled in IIS 7
The challenge is to determine whether ASP.NET is enabled within IIS7 in a reliable and correct way.

Enabling/Disabling is done in this case by going into:

```<code>Server Manager ->
    Roles ->
        Web Server (IIS) ->
            Remove Role Services ->
                Remove ASP.NET
</code>```

The natural place to determine this should be within the applicationHost.config file. However, with ASP.NET enabled or disabled, we still have the "ManagedEngine" module available, and we still have the isapi filter record in the  tag.

The best I can find at the moment is to check if the <isapiCgiRestriction> tag includes the aspnet_isapi.dll, or that the ASPNET trace provider is available.

However these aren't detecting the presence of the ASP.NET config directly, just a side effect that could conceivably be reconfigured by the user.

I'd rather do this by examining the IIS configuration/setup rather than the OS itself, if possible, although enumerating the Roles & Services on the server might be acceptable if we can guarantee that this technique will always work whenever IIS7 is used.

Update

Thanks for the responses. Clarifying exactly what I want to do, I'm pulling settings from a variety of places in the server's configuration into a single (readonly) view to show what the user needs to have configured to allow the software to work.

One of the settings I need to bring in is this one:

The one highlighted in red.

I don't need to manipulate the setting, just reproduce it. I want to see whether the user checked the ASP.NET box when they added the IIS role to the server, as in this example they clearly didn't.

I'd like to do this by looking at something reliable in IIS rather than enumerating the role services because I don't want to add any platform specific dependencies on the check that I don't need. I don't know if it will ever be possible to install IIS7 on a server that doesn't have the Roles/Services infrastructure, but in preference, I'd rather not worry about it. I also have a load of libraries for scrubbing around IIS already.

However, I'm also having trouble finding out how to enumerate the Roles/Services at all, so if there's a solution that involves doing that, it would certainly be useful, and much better than checking the side effect of having the ASPNET trace provider lying around.

Unfortunately, if you don't check the ASP.NET button, you can still get the ManagedEngine module in the IIS applicationHost.config file, so it's not a reliable check. You can also have ASP.NET mapped as an isapi filter, so checking them isn't enough. These things are especially problematic in the case where ASP.NET was installed but has been removed.

It looks like the best solution would be to examine the Role Services. However, API information on this is looking pretty rare, hence the cry for help.

答:
Determining if asp.net is even an installed feature (prerequisite for enabling it) can be done through PowerShell, which implies there is .net api out there for it if you dig hard enough. The PowerShell methods:

```<code>Import-Module servermanager
Get-WindowsFeature web-asp-net
</code>```

Which will return an object of type Microsoft.Windows.ServerManager.Commands.Feature. The installed property is boolean and indicates whether or not the feature is installed.

Body:
The challenge is to determine whether ASP.NET is enabled within IIS7 in a reliable and correct way.

Enabling/Disabling is done in this case by going into:

Server Manager ->
    Roles ->
        Web Server (IIS) ->
            Remove Role Services ->
                Remove ASP.NET

The natural place to determine this should be within the applicationHost.config file. However, with ASP.NET enabled or disabled, we still have the "ManagedEngine" module available, and we still have the isapi filter record in the  tag.

The best I can find at the moment is to check if the <isapiCgiRestriction> tag includes the aspnet_isapi.dll, or that the ASPNET trace provider is available.

However these aren't detecting the presence of the ASP.NET config directly, just a side effect that could conceivably be reconfigured by the user.

I'd rather do this by examining the IIS configuration/setup rather than the OS itself, if possible, although enumerating the Roles & Services on the server might be acceptable if we can guarantee that this technique will always work whenever IIS7 is used.

Update

Thanks for the responses. Clarifying exactly what I want to do, I'm pulling settings from a variety of places in the server's configuration into a single (readonly) view to show what the user needs to have configured to allow the software to work.

One of the settings I need to bring in is this one:

The one highlighted in red.

I don't need to manipulate the setting, just reproduce it. I want to see whether the user checked the ASP.NET box when they added the IIS role to the server, as in this example they clearly didn't.

I'd like to do this by looking at something reliable in IIS rather than enumerating the role services because I don't want to add any platform specific dependencies on the check that I don't need. I don't know if it will ever be possible to install IIS7 on a server that doesn't have the Roles/Services infrastructure, but in preference, I'd rather not worry about it. I also have a load of libraries for scrubbing around IIS already.

However, I'm also having trouble finding out how to enumerate the Roles/Services at all, so if there's a solution that involves doing that, it would certainly be useful, and much better than checking the side effect of having the ASPNET trace provider lying around.

Unfortunately, if you don't check the ASP.NET button, you can still get the ManagedEngine module in the IIS applicationHost.config file, so it's not a reliable check. You can also have ASP.NET mapped as an isapi filter, so checking them isn't enough. These things are especially problematic in the case where ASP.NET was installed but has been removed.

It looks like the best solution would be to examine the Role Services. However, API information on this is looking pretty rare, hence the cry for help.

Body:
Determining if asp.net is even an installed feature (prerequisite for enabling it) can be done through PowerShell, which implies there is .net api out there for it if you dig hard enough. The PowerShell methods:

Import-Module servermanager
Get-WindowsFeature web-asp-net

Which will return an object of type Microsoft.Windows.ServerManager.Commands.Feature. The installed property is boolean and indicates whether or not the feature is installed.


问:
Google Cloud VPN error: peer didn't accept DH group MODP_1024, it requested MODP_1024
I have an issue with Google Cloud Platform, punctually with a VPN that we have mounted between our client and GCP, we have falls in a fixed period of approximately 5 hours. (5 hours up and 5 hours down.)

The issue is:

peer didn't accept DH group MODP_1024, it requested MODP_1024

The usually is 5 hours up and 5 hours down.
https : // i.stack.imgur.com/tWU66.png

Our client receives the following information
https : // i.stack.imgur.com/za5xo.png

The complete log is:

```<code>{
"textPayload": "peer didn't accept DH group MODP_1024, it requested MODP_1024"
"insertId": "1xygt3f4zil3t"
"resource": {
    "type": "vpn_gateway"
    "labels": {
        "gateway_id": "3128708644582367778"
        "project_id": "xxxxxxx-compensar"
        "region": "us-west1"
        }
    }
"timestamp": "2017-05-26T20:47:44.780876927Z"
"severity": "DEBUG"
"logName": "projects/xxxxxxx-compensar/logs/cloud.googleapis.com%2Fipsec_events"
"receiveTimestamp": "2017-05-26T20:47:44.825563989Z"
}
</code>```

The configuration on Client Services is:
https : // i.stack.imgur.com/eyMd4.png

The configuration on GCP is:

```<code>{
"creationTimestamp": "2017-02-20T08:43:58.085-08:00",
"description": "",
"forwardingRules": [
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp"
],
"id": "3128708644582367778",
"kind": "compute#targetVpnGateway",
"name": "cliente-chile-vpn",
"network": "projects/xxxxxxx/global/networks/cliente-chile",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn",
"status": "READY",
"tunnels": [
    "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1"
]
}

{
"creationTimestamp": "2017-05-24T12:46:01.059-07:00",
"description": "",
"detailedStatus": "Handshake with peer broken for unknown reason. Trying again soon.",
"id": "5377869613206363158",
"ikeVersion": 2,
"kind": "compute#vpnTunnel",
"localTrafficSelector": [
    "10.110.0.0/20",
    "10.100.0.0/20"
],
"name": "cliente-chile-vpn-tunnel-1",
"peerIp": "000.00.00.00",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1",
"sharedSecret": "*************",
"sharedSecretHash": "xxxxxxxxxxxxxxxxxxxxx",
"status": "FIRST_HANDSHAKE",
"targetVpnGateway": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:05.802-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "7352555096091566650",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp4500",
"portRange": "4500-4500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:04.428-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "8789138583346127419",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp500",
"portRange": "500-500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:03.043-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "ESP",
"id": "2497873112390345276",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-esp",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}
</code>```

答:
A couple of things, First looking at the client configuration it appears that the key renegotiation parameters are mismatched [1], fixing that may help with the timing disconnects.

The Rejection errors I believe are because cloud VPN is attempting to establish 2 Child SAs, one for each of your networks listed, one is established, the other seems to be rejected.

One option would be to change the Cloud VPN tunnel to have 0.0.0.0/0 on the remote side, and then set up 2 routes manually for your two remote networks inside GCP.

[1] https://cloud.google.com/compute/docs/vpn/advanced#supported_ike_ciphers

Body:
I have an issue with Google Cloud Platform, punctually with a VPN that we have mounted between our client and GCP, we have falls in a fixed period of approximately 5 hours. (5 hours up and 5 hours down.)

The issue is:

peer didn't accept DH group MODP_1024, it requested MODP_1024

The usually is 5 hours up and 5 hours down.
https : // i.stack.imgur.com/tWU66.png

Our client receives the following information
https : // i.stack.imgur.com/za5xo.png

The complete log is:

{
"textPayload": "peer didn't accept DH group MODP_1024, it requested MODP_1024"
"insertId": "1xygt3f4zil3t"
"resource": {
    "type": "vpn_gateway"
    "labels": {
        "gateway_id": "3128708644582367778"
        "project_id": "xxxxxxx-compensar"
        "region": "us-west1"
        }
    }
"timestamp": "2017-05-26T20:47:44.780876927Z"
"severity": "DEBUG"
"logName": "projects/xxxxxxx-compensar/logs/cloud.googleapis.com%2Fipsec_events"
"receiveTimestamp": "2017-05-26T20:47:44.825563989Z"
}

The configuration on Client Services is:
https : // i.stack.imgur.com/eyMd4.png

The configuration on GCP is:

{
"creationTimestamp": "2017-02-20T08:43:58.085-08:00",
"description": "",
"forwardingRules": [
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
    "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp"
],
"id": "3128708644582367778",
"kind": "compute#targetVpnGateway",
"name": "cliente-chile-vpn",
"network": "projects/xxxxxxx/global/networks/cliente-chile",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn",
"status": "READY",
"tunnels": [
    "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1"
]
}

{
"creationTimestamp": "2017-05-24T12:46:01.059-07:00",
"description": "",
"detailedStatus": "Handshake with peer broken for unknown reason. Trying again soon.",
"id": "5377869613206363158",
"ikeVersion": 2,
"kind": "compute#vpnTunnel",
"localTrafficSelector": [
    "10.110.0.0/20",
    "10.100.0.0/20"
],
"name": "cliente-chile-vpn-tunnel-1",
"peerIp": "000.00.00.00",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/vpnTunnels/cliente-chile-vpn-tunnel-1",
"sharedSecret": "*************",
"sharedSecretHash": "xxxxxxxxxxxxxxxxxxxxx",
"status": "FIRST_HANDSHAKE",
"targetVpnGateway": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:05.802-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "7352555096091566650",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp4500",
"portRange": "4500-4500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp4500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:04.428-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "UDP",
"id": "8789138583346127419",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-udp500",
"portRange": "500-500",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-udp500",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}

{
"creationTimestamp": "2017-02-20T08:44:03.043-08:00",
"description": "",
"IPAddress": "104.196.229.158",
"IPProtocol": "ESP",
"id": "2497873112390345276",
"kind": "compute#forwardingRule",
"loadBalancingScheme": "EXTERNAL",
"name": "cliente-chile-vpn-rule-esp",
"region": "projects/xxxxxxx/regions/us-west1",
"selfLink": "projects/xxxxxxx/regions/us-west1/forwardingRules/cliente-chile-vpn-rule-esp",
"target": "projects/xxxxxxx/regions/us-west1/targetVpnGateways/cliente-chile-vpn"
}


问:
How to write conditional select insert statement to fetch record from a table, and based on some particular column's values
for eg:

Table1:

```<code>c1,c2,c3 (1,10,'123')
</code>```

Table2

```<code>c1,c2,c3,c4
</code>```

Now I want to select record from table1 and if c3 column value starting two digit is 12 then I have to populate AA, and if 34 then BB in Table2 c4 column:

Table1 -- (1,10,'123')

Table2 -- (1,10,'123','AA')

Table1 -- (1,10,'3444')

Table2 -- (1,10,'3444','BB')

答:
OP has provided additional information in Comments under the original post. In particular, c3 is VARCHAR2 and always begins with either 12 or 34.

The following should work. If c3 does not begin with 12 or 34, then the value inserted in column c4 will be NULL. That is the default behavior of CASE expressions, so it doesn't need to be coded explicitly; if instead something like 'ZZ' is desired in that case, then we can add an else clause to CASE. (The OP said c3 always begins with either 12 or 34; if so, this is a moot point.)

```<code>insert into table2 ( c1, c2, c3, c4 )
  select c1, c2, c3,
         case when c3 like '12%' then 'AA'
              when c3 like '34%' then 'BB'
         end
  from   table1
;
</code>```

Demo:

```<code>SQL> create table table1 ( c1 number, c2 number, c3 varchar2(25) );
Table created.

SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '123' );
1 row created.

SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '3444' );
1 row created.

SQL> commit;
Commit complete.

SQL> select * from table1;

        C1         C2 C3
---------- ---------- -------------------------
         1         10 123
         1         10 3444

2 rows selected.
</code>```

Then:

```<code>SQL> create table table2 ( c1 number, c2 number, c3 varchar2(25), c4 varchar2(10) );
Table created.

SQL> select * from table2;
no rows selected

SQL> insert into table2 ( c1, c2, c3, c4 )
  2    select c1, c2, c3,
  3           case when c3 like '12%' then 'AA'
  4                when c3 like '34%' then 'BB'
  5           end
  6    from   table1
  7  ;

2 rows created.

SQL> select * from table2;

        C1         C2 C3                        C4
---------- ---------- ------------------------- ----------
         1         10 123                       AA
         1         10 3444                      BB

2 rows selected.
</code>```

Body:
for eg:

Table1:

c1,c2,c3 (1,10,'123')

Table2

c1,c2,c3,c4

Now I want to select record from table1 and if c3 column value starting two digit is 12 then I have to populate AA, and if 34 then BB in Table2 c4 column:

Table1 -- (1,10,'123')

Table2 -- (1,10,'123','AA')

Table1 -- (1,10,'3444')

Table2 -- (1,10,'3444','BB')

Body:
OP has provided additional information in Comments under the original post. In particular, c3 is VARCHAR2 and always begins with either 12 or 34.

The following should work. If c3 does not begin with 12 or 34, then the value inserted in column c4 will be NULL. That is the default behavior of CASE expressions, so it doesn't need to be coded explicitly; if instead something like 'ZZ' is desired in that case, then we can add an else clause to CASE. (The OP said c3 always begins with either 12 or 34; if so, this is a moot point.)

insert into table2 ( c1, c2, c3, c4 )
  select c1, c2, c3,
         case when c3 like '12%' then 'AA'
              when c3 like '34%' then 'BB'
         end
  from   table1
;

Demo:

SQL> create table table1 ( c1 number, c2 number, c3 varchar2(25) );
Table created.

SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '123' );
1 row created.

SQL> insert into table1 ( c1, c2, c3 ) values ( 1, 10, '3444' );
1 row created.

SQL> commit;
Commit complete.

SQL> select * from table1;

        C1         C2 C3
---------- ---------- -------------------------
         1         10 123
         1         10 3444

2 rows selected.

Then:

SQL> create table table2 ( c1 number, c2 number, c3 varchar2(25), c4 varchar2(10) );
Table created.

SQL> select * from table2;
no rows selected

SQL> insert into table2 ( c1, c2, c3, c4 )
  2    select c1, c2, c3,
  3           case when c3 like '12%' then 'AA'
  4                when c3 like '34%' then 'BB'
  5           end
  6    from   table1
  7  ;

2 rows created.

SQL> select * from table2;

        C1         C2 C3                        C4
---------- ---------- ------------------------- ----------
         1         10 123                       AA
         1         10 3444                      BB

2 rows selected.


问:
Stop knitr compilation button hidden in RStudio Compile PDF window
I just downloaded RStudio 1.0.143 for Windows 7 and am compiling a knitr document. However, in the "Compile PDF" tab the STOP button does not appear when compiling nor the "View Log", "Output", or "Issues" buttons that allow you to troubleshoot a .Rnw file that does not compile. Is there a setting to show these? I have attached an image, they are at the right hand side of the "Compile PDF" at the console.

Thanks!

答:
Right click on the Compile PDF tab during compilation and then click Reload in the menu that appears, and the Stop button should appear.

Right click on the Compile PDF tab after compilation and then click Reload as before, and the View Log, Output, and Issues buttons should appear.

(Found by trial and error.)