问:
Common.Logging.NLog not available for net core?
I'm currently using Common.Logging version 3.4.0-beta2 and NLog 5.0.0-beta07 on netcoreapp1.1. (its and ASP Net Core mvc project)
I cannot find Common.Logging.NLog specific version for that case.

In case it is not yet available, which log file option do I have as adapter for net core?

答:
I finally created two classes:

public class CommonLoggingNLogAdapter : ILoggerFactoryAdapter
{
    public ILog GetLogger(Type type)
    {
        return new NLogAdapter(type);
    }

    public ILog GetLogger(string key)
    {
        return new NLogAdapter(key);
    }
}
```

<p>and</p>

<pre class="lang-cs prettyprint-override"><code>public class NLogAdapter : ILog
{
    private Logger log;

    public bool IsTraceEnabled { get { return log.IsTraceEnabled; } }

    public bool IsDebugEnabled { get { return log.IsDebugEnabled; } }

    public bool IsErrorEnabled { get { return log.IsErrorEnabled; } }

    public bool IsFatalEnabled { get { return log.IsFatalEnabled; } }

    public bool IsInfoEnabled { get { return log.IsInfoEnabled; } }

    public bool IsWarnEnabled { get { return log.IsWarnEnabled; } }

    public IVariablesContext GlobalVariablesContext => throw new NotImplementedException();

    public IVariablesContext ThreadVariablesContext => throw new NotImplementedException();

    public INestedVariablesContext NestedThreadVariablesContext => throw new NotImplementedException();

    public NLogAdapter(Type type)
    {
        log = NLog.LogManager.GetLogger(type.ToString());
    }

    public NLogAdapter(string key)
    {
        log = NLog.LogManager.GetLogger(key);
    }

    public void Debug(object message)
    {
        log.Debug(message);
    }

    public void Debug(object message, Exception exception)
    {
        log.Debug(exception, message.ToString());
    }

    public void Debug(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Debug(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Debug(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Debug(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Error(object message)
    {
        log.Error(message);
    }

    public void Error(object message, Exception exception)
    {
        log.Error(exception, message.ToString());
    }

    public void Error(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Error(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Error(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Error(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Fatal(object message)
    {
        log.Fatal(message);
    }

    public void Fatal(object message, Exception exception)
    {
        log.Fatal(exception, message.ToString());
    }

    public void Fatal(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Fatal(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Fatal(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Fatal(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Info(object message)
    {
        log.Info(message);
    }

    public void Info(object message, Exception exception)
    {
        log.Info(exception, message.ToString());
    }

    public void Info(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Info(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Info(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Info(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Trace(object message)
    {
        log.Trace(message);
    }

    public void Trace(object message, Exception exception)
    {
        log.Trace(exception, message.ToString());
    }

    public void Trace(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Trace(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Trace(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Trace(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Warn(object message)
    {
        log.Warn(message);
    }

    public void Warn(object message, Exception exception)
    {
        log.Warn(exception, message.ToString());
    }

    public void Warn(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Warn(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Warn(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Warn(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }
}
</code>```

Then I can configure NLog as logger by doing:

Common.Logging.LogManager.Adapter = new CommonLoggingNLogAdapter();
```

This is a temporary solution I'm implementing until there is an official release.

Body:
I finally created two classes:

public class CommonLoggingNLogAdapter : ILoggerFactoryAdapter
{
    public ILog GetLogger(Type type)
    {
        return new NLogAdapter(type);
    }

    public ILog GetLogger(string key)
    {
        return new NLogAdapter(key);
    }
}

and

public class NLogAdapter : ILog
{
    private Logger log;

    public bool IsTraceEnabled { get { return log.IsTraceEnabled; } }

    public bool IsDebugEnabled { get { return log.IsDebugEnabled; } }

    public bool IsErrorEnabled { get { return log.IsErrorEnabled; } }

    public bool IsFatalEnabled { get { return log.IsFatalEnabled; } }

    public bool IsInfoEnabled { get { return log.IsInfoEnabled; } }

    public bool IsWarnEnabled { get { return log.IsWarnEnabled; } }

    public IVariablesContext GlobalVariablesContext => throw new NotImplementedException();

    public IVariablesContext ThreadVariablesContext => throw new NotImplementedException();

    public INestedVariablesContext NestedThreadVariablesContext => throw new NotImplementedException();

    public NLogAdapter(Type type)
    {
        log = NLog.LogManager.GetLogger(type.ToString());
    }

    public NLogAdapter(string key)
    {
        log = NLog.LogManager.GetLogger(key);
    }

    public void Debug(object message)
    {
        log.Debug(message);
    }

    public void Debug(object message, Exception exception)
    {
        log.Debug(exception, message.ToString());
    }

    public void Debug(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Debug(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Debug(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Debug(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void DebugFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Error(object message)
    {
        log.Error(message);
    }

    public void Error(object message, Exception exception)
    {
        log.Error(exception, message.ToString());
    }

    public void Error(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Error(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Error(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Error(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void ErrorFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Fatal(object message)
    {
        log.Fatal(message);
    }

    public void Fatal(object message, Exception exception)
    {
        log.Fatal(exception, message.ToString());
    }

    public void Fatal(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Fatal(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Fatal(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Fatal(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void FatalFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Info(object message)
    {
        log.Info(message);
    }

    public void Info(object message, Exception exception)
    {
        log.Info(exception, message.ToString());
    }

    public void Info(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Info(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Info(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Info(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void InfoFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Trace(object message)
    {
        log.Trace(message);
    }

    public void Trace(object message, Exception exception)
    {
        log.Trace(exception, message.ToString());
    }

    public void Trace(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Trace(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Trace(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Trace(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void TraceFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void Warn(object message)
    {
        log.Warn(message);
    }

    public void Warn(object message, Exception exception)
    {
        log.Warn(exception, message.ToString());
    }

    public void Warn(Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Warn(Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void Warn(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback)
    {
        throw new NotImplementedException();
    }

    public void Warn(IFormatProvider formatProvider, Action<FormatMessageHandler> formatMessageCallback, Exception exception)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(IFormatProvider formatProvider, string format, params object[] args)
    {
        throw new NotImplementedException();
    }

    public void WarnFormat(IFormatProvider formatProvider, string format, Exception exception, params object[] args)
    {
        throw new NotImplementedException();
    }
}

Then I can configure NLog as logger by doing:

Common.Logging.LogManager.Adapter = new CommonLoggingNLogAdapter();

This is a temporary solution I'm implementing until there is an official release.


来源: stackexchange

问:
PureScript "Could not match type" error for a Record
I'm following one of the exercises in the PureScript book where I have to define a function renderPath that takes an array of Points (x and y) and draws a path using them (using purescript-canvas), where a Point is defined as

```<code>type Point = { x :: Number, y :: Number }
</code>```

I've decided to split the function into two steps. The first step is to moveTo the first point in the array and then use lineTo over the remaining points.

Here is the function I've written so far which only has the first step. But I get this one error that I just can't figure out.

Here's the function

```<code>import Prelude
import Control.Monad.Eff (Eff)
import Data.Array.Partial (head, tail)
import Data.Maybe (Maybe(..))
import Graphics.Canvas (CANVAS, Context2D, arc, closePath, fillPath, getCanvasElementById, getContext2D, lineTo, moveTo, rect, setStrokeStyle, strokePath)
import Partial.Unsafe (unsafePartial)

renderPath :: forall eff
. Context2D
-> Array Point
-> Eff (canvas :: CANVAS | eff) Unit

renderPath ctx points = fillPath ctx $ do
  p0 <- unsafePartial head points
  moveTo ctx p0.x p0.y
</code>```

And I get this one error at p0 in the last line of the function (moveTo ctx p0.x p0.y)

The error is:

```<code>  Could not match type

    { x :: Number
    | t0
    }

  with type

    ( x :: Number
    , y :: Number
    )

while checking that type ( x :: Number
                         , y :: Number
                         )
  is at least as general as type { x :: Number
                                 | t0
                                 }
while checking that expression p0
  has type { x :: Number
           | t0
           }
while checking type of property accessor p0.x
in value declaration renderPath

where t0 is an unknown type
</code>```

I'm assuming that p0 should be of the type { x :: Number, y :: Number }

This error shows one as { x :: Number | t0 } and the other as ( x :: Number, y :: Number). I don't understand this at all. Why is one using {} and the other (). What's the difference between them? Where am I going wrong?

I'd also request an explanation along with any correction as I'm new to PureScript and functional programming as a whole so I'm having trouble trying to understand a lot of concepts.

答:
I'm not entirely sure why you get that particular error message, but one issue with your code is this line:

```<code>p0 <- unsafePartial head points
</code>```

this is supposed to be

```<code>let p0 = unsafePartial (head points)
</code>```

<- in a do block means something like "get the value out of the context of Eff". But since unsafePartial (head points) is not an Eff, the types don't match and you get an error message.

this code compiles:

http://try.purescript.org/?backend=flare&gist=6baa84215d33bf6f11c808e24b95c72f

ContentLicense: CC BY-SA 3.0

Body:
I'm following one of the exercises in the PureScript book where I have to define a function renderPath that takes an array of Points (x and y) and draws a path using them (using purescript-canvas), where a Point is defined as

type Point = { x :: Number, y :: Number }

I've decided to split the function into two steps. The first step is to moveTo the first point in the array and then use lineTo over the remaining points.

Here is the function I've written so far which only has the first step. But I get this one error that I just can't figure out.

Here's the function

import Prelude
import Control.Monad.Eff (Eff)
import Data.Array.Partial (head, tail)
import Data.Maybe (Maybe(..))
import Graphics.Canvas (CANVAS, Context2D, arc, closePath, fillPath, getCanvasElementById, getContext2D, lineTo, moveTo, rect, setStrokeStyle, strokePath)
import Partial.Unsafe (unsafePartial)

renderPath :: forall eff
. Context2D
-> Array Point
-> Eff (canvas :: CANVAS | eff) Unit

renderPath ctx points = fillPath ctx $ do
  p0 <- unsafePartial head points
  moveTo ctx p0.x p0.y

And I get this one error at p0 in the last line of the function (moveTo ctx p0.x p0.y)

The error is:

  Could not match type

    { x :: Number
    | t0
    }

  with type

    ( x :: Number
    , y :: Number
    )

while checking that type ( x :: Number
                         , y :: Number
                         )
  is at least as general as type { x :: Number
                                 | t0
                                 }
while checking that expression p0
  has type { x :: Number
           | t0
           }
while checking type of property accessor p0.x
in value declaration renderPath

where t0 is an unknown type

I'm assuming that p0 should be of the type { x :: Number, y :: Number }

This error shows one as { x :: Number | t0 } and the other as ( x :: Number, y :: Number). I don't understand this at all. Why is one using {} and the other (). What's the difference between them? Where am I going wrong?

I'd also request an explanation along with any correction as I'm new to PureScript and functional programming as a whole so I'm having trouble trying to understand a lot of concepts.

Body:
I'm not entirely sure why you get that particular error message, but one issue with your code is this line:

p0 <- unsafePartial head points

this is supposed to be

let p0 = unsafePartial (head points)

<- in a do block means something like "get the value out of the context of Eff". But since unsafePartial (head points) is not an Eff, the types don't match and you get an error message.

this code compiles:

http://try.purescript.org/?backend=flare&gist=6baa84215d33bf6f11c808e24b95c72f


问:
No compiler found in your classpath! (you may need to add 'tools.jar') Axis 1.4 + Tomcat 9.0
I already did everything to correct this error, since the modified environment variables , already put the tools.jar within the tomcat9.0 / bin and / lib in addition to the axis / WEB -INF / lib.

<?xml version="1.0" encoding="UTF-8"?>

-<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">

-<soapenv:Body>

-<soapenv:Fault>

<faultcode>soapenv:Server.userException</faultcode>

<faultstring>java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')</faultstring>

-<detail>

<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">DESKTOP-MRKMOSG</ns1:hostname>

</detail>

</soapenv:Fault>

</soapenv:Body>

</soapenv:Envelope>```

AMBIENTE:

CATALINA_HOME=C:\Program Files\Apache Software Foundation\Tomcat 9.0

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_77

PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

CLASSPATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%;%JAVA_HOME%\bin;

答: I think the ToolProvider class (which is what is used to get your hands on the Java compiler inside Java program) assumes the tools.jar is either on the boot classpath or in $JAVA_HOME/lib or $JAVA_HOME/../lib in case Java home is pointing to a JRE instead of the full JDK.</p>

Body:
I already did everything to correct this error, since the modified environment variables , already put the tools.jar within the tomcat9.0 / bin and / lib in addition to the axis / WEB -INF / lib.

<?xml version="1.0" encoding="UTF-8"?>

-<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">

-<soapenv:Body>

-<soapenv:Fault>

<faultcode>soapenv:Server.userException</faultcode>

<faultstring>java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')</faultstring>

-<detail>

<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">DESKTOP-MRKMOSG</ns1:hostname>

</detail>

</soapenv:Fault>

</soapenv:Body>

</soapenv:Envelope>

AMBIENTE:

CATALINA_HOME=C:\Program Files\Apache Software Foundation\Tomcat 9.0

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_77

PATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin

CLASSPATH=%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%;%JAVA_HOME%\bin;


问:
OData returns array instead of JSON - How to convert?
I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.

My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?

Here is the code that I am using:

```<code>$.ajax({
                type: "GET",
                url: requestUri,
                dataType: "script",
                accept: "application/json",
                success: function(data, request) {
                    var jsonData = JSON.parse(data);
                },
                error: function(msg) {
                    alert(msg);
                }})
</code>```

Here is an example response of logging the variable data with console.log:

{"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}

答:
You can add it to a variable and access it just like that.

```<code>var v={"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]};
//v.value[0] is a json object
console.log(v.value[0]);
</code>```

or skip the assignment altogether and access this way:

```<code>data.value[0]
data.value[0].Genre
data.value[0].RunTime
etc....
</code>```

Body:
I've been trying to figure how to properly receive an OData response in Javascript for a couple of days. The problem is the response is formatted as an array instead of JSON, so the function JSON.parse(mydata) does not work with the data I am receiving.

My question is two-fold: What is the proper way to request OData to send a response as JSON and/or how do I format my current response to be JSON?

Here is the code that I am using:

$.ajax({
                type: "GET",
                url: requestUri,
                dataType: "script",
                accept: "application/json",
                success: function(data, request) {
                    var jsonData = JSON.parse(data);
                },
                error: function(msg) {
                    alert(msg);
                }})

Here is an example response of logging the variable data with console.log:

{"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]}

Body:
You can add it to a variable and access it just like that.

var v={"@odata.context":"http://localhost:5001/odata/$metadata#Movies","value":[{"Title":"Pulp Fiction","Genre":"Action","RunTime":0,"Sales":0,"Key":2}]};
//v.value[0] is a json object
console.log(v.value[0]);

or skip the assignment altogether and access this way:

data.value[0]
data.value[0].Genre
data.value[0].RunTime
etc....


问:
GRAILS + Spring Security Plugin --- password is not encrypted when adding users
Clean installation of Grails 3.2.9 + Spring Security Plugin 3.1.0.

Default User/Role/UserRole domains created by s2-quickstart com.raf.app User Role.

BootStrap init code:

```<code>...
def init = { servletContext ->
    def adminRole = Role.findOrSaveWhere(authority: 'ROLE_ADMIN')
    def user = User.findOrSaveWhere(username: 'raf',
            password: 'password')
    if (!user.authorities.contains(adminRole)){
        UserRole.create(user, adminRole)
    }
...
</code>```

I saw in a tutorial that the password for this user should appear encoded in the db (using dbconsole to check this out), but in my case it does not (it's just 'password' like in here).

So I went to the User domain and made these horrible changes:

```<code>def beforeUpdate() {
        encodePassword()
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : springSecurityService.encodePassword(password)
    }
</code>```

And this on the other hand throws NullPointer exception. Why?

```<code> Cannot invoke method encodePassword() on null object
</code>```

So what do I do to have my passwords encrypted, like I like 'em?

答:
So to explain what is going on in the hope it makes more sense

You have simply told the code to repeat the encrypt function if it cant find encode.

Above code by default is here

```<code> password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
</code>```

This says :

```<code>if (springSecurityService?.passwordEncoder) {
springSecurityService.encodePassword(password)
} else {
password
}
</code>```

So you see you have told it to do what it can't

I am  on grails 3.2.8 and using:

```<code>compile 'org.grails.plugins:spring-security-core:3.1.2'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Clean installation of Grails 3.2.9 + Spring Security Plugin 3.1.0.

Default User/Role/UserRole domains created by s2-quickstart com.raf.app User Role.

BootStrap init code:

...
def init = { servletContext ->
    def adminRole = Role.findOrSaveWhere(authority: 'ROLE_ADMIN')
    def user = User.findOrSaveWhere(username: 'raf',
            password: 'password')
    if (!user.authorities.contains(adminRole)){
        UserRole.create(user, adminRole)
    }
...

I saw in a tutorial that the password for this user should appear encoded in the db (using dbconsole to check this out), but in my case it does not (it's just 'password' like in here).

So I went to the User domain and made these horrible changes:

def beforeUpdate() {
        encodePassword()
    }

    protected void encodePassword() {
        password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : springSecurityService.encodePassword(password)
    }

And this on the other hand throws NullPointer exception. Why?

 Cannot invoke method encodePassword() on null object

So what do I do to have my passwords encrypted, like I like 'em?

Body:
So to explain what is going on in the hope it makes more sense

You have simply told the code to repeat the encrypt function if it cant find encode.

Above code by default is here

 password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password

This says :

if (springSecurityService?.passwordEncoder) {
springSecurityService.encodePassword(password)
} else {
password
}

So you see you have told it to do what it can't

I am  on grails 3.2.8 and using:

compile 'org.grails.plugins:spring-security-core:3.1.2'


问:
Simulate Values that follow a Distribution Curve in R

I want to simulate demand values that follows different distributions (ex above: starts of linear> exponential>invlog>etc) I'm a bit confused by the notion of probability distributions but thought I could use rnorm, rexp, rlogis, etc. Is there any way I could do so?

I think it may be this but in R: Generating smoothed randoms that follow a distribution

答:
Simulating random values from commonly-used probability distributions in R is fairly trivial using rnorm(), rexp(), etc, if you know what distribution you want to use, as well as its parameters.  For example, rnorm(10, mean=5, sd=2) returns 10 draws from a normal distribution with mean 5 and sd 2.

```<code>rnorm(10, mean = 5, sd = 2)
##  [1] 5.373151 7.970897 6.933788 5.455081 6.346129 5.767204 3.847219 7.477896 5.860069 6.154341

## or here's a histogram of 10000 draws...
hist(rnorm(10000, 5, 2))
</code>```

You might be interested in an exponential distribution - check out hist(rexp(10000, rate=1)) to get the idea.

The easiest solution will be to investigate what probability distribution(s) you're interested in and their implementation in R.

It is still possible to return random draws from some custom function, and there are a few techniques out there for doing it - but it might get messy.  Here's a VERY rough implementation of drawing randomly from probabilities defined by the region of x^3 - 3x^2 + 4 between zero and 3.

```<code>## first a vector of random uniform draws from the region
unifdraws <- runif(10000, 0, 3)

## assign a probability of "keeping" draws based on scaled probability
pkeep <- (unifdraws^3 - 3*unifdraws^2 + 4)/4

## randomly keep observations based on this probability
keep <- rbinom(10000, size=1, p=pkeep)
draws <- unifdraws[keep==1]

## and there it is!
hist(draws)

## of course, it's less than 10000 now, because we rejected some
length(draws)
## [1] 4364
</code>```

Body:
Simulating random values from commonly-used probability distributions in R is fairly trivial using rnorm(), rexp(), etc, if you know what distribution you want to use, as well as its parameters.  For example, rnorm(10, mean=5, sd=2) returns 10 draws from a normal distribution with mean 5 and sd 2.

rnorm(10, mean = 5, sd = 2)
##  [1] 5.373151 7.970897 6.933788 5.455081 6.346129 5.767204 3.847219 7.477896 5.860069 6.154341

## or here's a histogram of 10000 draws...
hist(rnorm(10000, 5, 2))

You might be interested in an exponential distribution - check out hist(rexp(10000, rate=1)) to get the idea.

The easiest solution will be to investigate what probability distribution(s) you're interested in and their implementation in R.

It is still possible to return random draws from some custom function, and there are a few techniques out there for doing it - but it might get messy.  Here's a VERY rough implementation of drawing randomly from probabilities defined by the region of x^3 - 3x^2 + 4 between zero and 3.

## first a vector of random uniform draws from the region
unifdraws <- runif(10000, 0, 3)

## assign a probability of "keeping" draws based on scaled probability
pkeep <- (unifdraws^3 - 3*unifdraws^2 + 4)/4

## randomly keep observations based on this probability
keep <- rbinom(10000, size=1, p=pkeep)
draws <- unifdraws[keep==1]

## and there it is!
hist(draws)

## of course, it's less than 10000 now, because we rejected some
length(draws)
## [1] 4364


问:
Salt Stack: Function: pkg.installed. Yum does not update installed package
My code is:

```<code>others:
  pkg.installed:
    - sources:
      - epel-release: https://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/epel-release-6-5.noarch.rpm
      - salt-latest: https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm
</code>```

and I'm getting error:

```<code>errors:
    - Loaded plugins: fastestmirror, replace
      Setting up Install Process
      Examining     /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: salt-repo-latest-2.el6.noarch
      /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: does not update installed package.
      Error: Nothing to do
</code>```

I thinkt that may be a problem with salt-repo-latest-2.el6.noarch.rpm. When I manually run yum install for this RPM's I'm getting the same error but running in Salt Stack only getting this error.

It should end with:

```<code>      ID: others
Function: pkg.installed
  Result: True
 Comment: All specified packages are already installed
 Started: 10:45:33.171971
Duration: 595.672 ms
 Changes:
</code>```

but I'm getting:

```<code>      ID: others
Function: pkg.installed
  Result: False
 Comment: Error occurred installing package(s). Additional info follows:

          errors:
              - Loaded plugins: fastestmirror, replace
                Setting up Install Process
                Examining /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: salt-repo-latest-2.el6.noarch
                /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: does not update installed package.
                Error: Nothing to do
 Started: 10:46:13.906581
Duration: 8988.515 ms
 Changes:
</code>```

答:
The package name is salt-repo not salt-latest.

Code should be:

```<code>others:
  pkg.installed:
    - sources:
      - epel-release: https://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/epel-release-6-5.noarch.rpm
      - salt-repo: https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm
</code>```

Body:
My code is:

others:
  pkg.installed:
    - sources:
      - epel-release: https://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/epel-release-6-5.noarch.rpm
      - salt-latest: https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm

and I'm getting error:

errors:
    - Loaded plugins: fastestmirror, replace
      Setting up Install Process
      Examining     /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: salt-repo-latest-2.el6.noarch
      /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: does not update installed package.
      Error: Nothing to do

I thinkt that may be a problem with salt-repo-latest-2.el6.noarch.rpm. When I manually run yum install for this RPM's I'm getting the same error but running in Salt Stack only getting this error.

It should end with:

      ID: others
Function: pkg.installed
  Result: True
 Comment: All specified packages are already installed
 Started: 10:45:33.171971
Duration: 595.672 ms
 Changes:

but I'm getting:

      ID: others
Function: pkg.installed
  Result: False
 Comment: Error occurred installing package(s). Additional info follows:

          errors:
              - Loaded plugins: fastestmirror, replace
                Setting up Install Process
                Examining /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: salt-repo-latest-2.el6.noarch
                /var/cache/salt/minion/extrn_files/base/repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm: does not update installed package.
                Error: Nothing to do
 Started: 10:46:13.906581
Duration: 8988.515 ms
 Changes:

Body:
The package name is salt-repo not salt-latest.

Code should be:

others:
  pkg.installed:
    - sources:
      - epel-release: https://dl.iuscommunity.org/pub/ius/stable/CentOS/6/x86_64/epel-release-6-5.noarch.rpm
      - salt-repo: https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el6.noarch.rpm


问:
How can i add a button box to scene view ? (Not ui)
```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class Menu : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown("m"))
            Debug.Log("menu");
    }
}
</code>```

First the Update function is not calling in scene view.
And second how can i add in the Start or in other event a box menu like ? For example:

```<code>GUILayout.Window(0, new Rect(10, 10, 100, 100), (id)=> {
            GUILayout.Button("A Button");
        },
</code>```

答:
Solution:</p>

```<code>using UnityEditor;
using UnityEngine;

public class SceneGUI : EditorWindow
{
    [MenuItem("Window/Scene GUI/Enable")]
    public static void Enable()
    {
        SceneView.onSceneGUIDelegate += OnScene;
        Debug.Log("Scene GUI : Enabled");
    }

    [MenuItem("Window/Scene GUI/Disable")]
    public static void Disable()
    {
        SceneView.onSceneGUIDelegate -= OnScene;
        Debug.Log("Scene GUI : Disabled");
    }

    private static void OnScene(SceneView sceneview)
    {
        Handles.BeginGUI();
        if (GUILayout.Button("Destroy Objects", GUILayout.Width(100), GUILayout.Height(100)))
        {

        }

        Handles.EndGUI();
    }
}
</code>```

Body:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class Menu : MonoBehaviour {

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown("m"))
            Debug.Log("menu");
    }
}

First the Update function is not calling in scene view.
And second how can i add in the Start or in other event a box menu like ? For example:

GUILayout.Window(0, new Rect(10, 10, 100, 100), (id)=> {
            GUILayout.Button("A Button");
        },

Body:
Solution:

using UnityEditor;
using UnityEngine;

public class SceneGUI : EditorWindow
{
    [MenuItem("Window/Scene GUI/Enable")]
    public static void Enable()
    {
        SceneView.onSceneGUIDelegate += OnScene;
        Debug.Log("Scene GUI : Enabled");
    }

    [MenuItem("Window/Scene GUI/Disable")]
    public static void Disable()
    {
        SceneView.onSceneGUIDelegate -= OnScene;
        Debug.Log("Scene GUI : Disabled");
    }

    private static void OnScene(SceneView sceneview)
    {
        Handles.BeginGUI();
        if (GUILayout.Button("Destroy Objects", GUILayout.Width(100), GUILayout.Height(100)))
        {

        }

        Handles.EndGUI();
    }
}


问:
Int stream and collect
So I am having trouble understanding the principle of this supplier ,accumulator  and combiner in the collect from IntStream. I found an example.

```<code>IntStream.range(6,11)
         .collect(StringBuilder::new,
                  StringBuilder::appendCodePoint,
                  StringBuilder::append);
</code>```

Anyone mind explaining the StringBuilder::appendCodePoint part?

答:
What if we write it like this:

```<code>IntStream.range(6, 11)
          .collect(StringBuilder::new,
             (StringBuilder sb, int x) -> sb.appendCodePoint(x),
             StringBuilder::append);
</code>```

The accumulator is a Consumer, that takes an Integer as argument and returns nothing.

StringBuilder::appendCodePoint is a method reference that does the same thing as the lambda expression.

Title: Int stream and collect

Body:
So I am having trouble understanding the principle of this supplier ,accumulator  and combiner in the collect from IntStream. I found an example.

IntStream.range(6,11)
         .collect(StringBuilder::new,
                  StringBuilder::appendCodePoint,
                  StringBuilder::append);

Anyone mind explaining the StringBuilder::appendCodePoint part?

Body:
What if we write it like this:

IntStream.range(6, 11)
          .collect(StringBuilder::new,
             (StringBuilder sb, int x) -> sb.appendCodePoint(x),
             StringBuilder::append);

The accumulator is a Consumer, that takes an Integer as argument and returns nothing.

StringBuilder::appendCodePoint is a method reference that does the same thing as the lambda expression.


问:
Java how to put a dot after a period
I have a piece of text. What i want to do is that in the entire text i want to put a whitespace after all the periods if its not already present. If its already present i dont want two spaces.

Also if the text contains multiple consecutive periods i want to put a whitespace only after the last period and that too only if whitespace is not already present.

I tried using this:

```<code>.replaceAll("[.!?;]", "$0 ").replaceAll("\\s+", " ")
</code>```

But this fails for multiple dots

Thanks.

答:
The part about unless a whitespace is already present is a moot point.

Generally, for the quickest solution, suck up all the data with a pattern,

blindly then replace it.

https://regex101.com/r/aPa0Bk/1

Globally,

Find (?:\s+|(\.+))\s*

Replace '$1 '

This is designed to trim whitespace as it goes.

Title: Java how to put a dot after a period

Body:
I have a piece of text. What i want to do is that in the entire text i want to put a whitespace after all the periods if its not already present. If its already present i dont want two spaces.

Also if the text contains multiple consecutive periods i want to put a whitespace only after the last period and that too only if whitespace is not already present.

I tried using this:

.replaceAll("[.!?;]", "$0 ").replaceAll("\\s+", " ")

But this fails for multiple dots

Thanks.


问:
Encryption or Hashing of Date Value
I have an old program that has been discontinued which communicates with an SQL database.  When I enter certain information in the defunct software, it is encrypted, encoded, or hashed before being entered into the database.

I am creating another application to interact with the same data, and I need to figure out how the end result is being produced.

Here's an example:

```<code>I enter 6/18/2017,  I get y/7w/iXIE

I enter 6/18/2099,  I get y/7w/iXBM

I enter 6/12/2017,  I get y/7c/iXIE

I enter 12/11/2018, I get SN/u0/ZmWk
</code>```

The last one throws me for a loop... what method is being used and how can I replicate this?

答:
It might be format preserving encryption or just substatutions. In all cases the number of characgters in each section delimited by / are the same number of characters. With enough samples, all 12 months, 31 days and years you should be able to match the method.</p>

```<code>6/18/2017
y/7w/iXIE

6/18/2099
y/7w/iXBM

6/12/2017
y/7c/iXIE

12/11/2018
SN/u0/ZmWk
</code>```

```
months:    6 -> y,      12 -> SN
days:     11 -> u0,     12 -> 7c,     18 -> 7w
years:  2017 -> iXIE, 2018 -> ZmWk, 2099 -> iXBM
```

Title: Encryption or Hashing of Date Value

Body:
I have an old program that has been discontinued which communicates with an SQL database.  When I enter certain information in the defunct software, it is encrypted, encoded, or hashed before being entered into the database.

I am creating another application to interact with the same data, and I need to figure out how the end result is being produced.

Here's an example:

I enter 6/18/2017,  I get y/7w/iXIE

I enter 6/18/2099,  I get y/7w/iXBM

I enter 6/12/2017,  I get y/7c/iXIE

I enter 12/11/2018, I get SN/u0/ZmWk

The last one throws me for a loop... what method is being used and how can I replicate this?

Body:
It might be format preserving encryption or just substatutions. In all cases the number of characgters in each section delimited by / are the same number of characters. With enough samples, all 12 months, 31 days and years you should be able to match the method.

6/18/2017
y/7w/iXIE

6/18/2099
y/7w/iXBM

6/12/2017
y/7c/iXIE

12/11/2018
SN/u0/ZmWk

months:    6 -> y,      12 -> SN
days:     11 -> u0,     12 -> 7c,     18 -> 7w
years:  2017 -> iXIE, 2018 -> ZmWk, 2099 -> iXBM


问:
poly() in lm(): difference between raw vs. orthogonal
I have

```<code>library(ISLR)
attach(Wage)

# Polynomial Regression and Step Functions

fit=lm(wage~poly(age,4),data=Wage)
coef(summary(fit))

fit2=lm(wage~poly(age,4,raw=T),data=Wage)
coef(summary(fit2))

plot(age, wage)
lines(20:350, predict(fit, newdata = data.frame(age=20:350)), lwd=3, col="darkred")
lines(20:350, predict(fit2, newdata = data.frame(age=20:350)), lwd=3, col="darkred")
</code>```

The prediction lines seem to be the same, however why are the coefficients so different? How do you intepret them in raw=T and raw=F.

I see that the coefficients produced with poly(...,raw=T) match the ones with ~age+I(age^2)+I(age^3)+I(age^4).

If I want to use the coefficients to get the prediction "manually" (without using the predict() function) is there something I should pay attention to? How should I interpret the coefficients of the orthogonal polynomials in poly().

答:
I believe the way the polynomial regression would be run based on raw=T, is that one would look at the highest power term and assess its significance based on the pvalue for that coefficient.

If found not significant (large pvalue) then the regression would be re-run without that particular non-significant power (ie. the next lower degree) and this would be carried out one step at a time reducing if not significant.

If at any time the higher degree is significant then the process would stop and assert that, that degree is the appropriate one.

Body:
I have

library(ISLR)
attach(Wage)

# Polynomial Regression and Step Functions

fit=lm(wage~poly(age,4),data=Wage)
coef(summary(fit))

fit2=lm(wage~poly(age,4,raw=T),data=Wage)
coef(summary(fit2))

plot(age, wage)
lines(20:350, predict(fit, newdata = data.frame(age=20:350)), lwd=3, col="darkred")
lines(20:350, predict(fit2, newdata = data.frame(age=20:350)), lwd=3, col="darkred")

The prediction lines seem to be the same, however why are the coefficients so different? How do you intepret them in raw=T and raw=F.

I see that the coefficients produced with poly(...,raw=T) match the ones with ~age+I(age^2)+I(age^3)+I(age^4).

If I want to use the coefficients to get the prediction "manually" (without using the predict() function) is there something I should pay attention to? How should I interpret the coefficients of the orthogonal polynomials in poly().


问:
Prevent a user from closing a browser window using "X"?
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

```<code>window.onunload = function() { alert("unloading"); }
</code>```

答:
Why do you want to do this?  We can probably help you come up with a different design that doesn't require this if you tell us what you're trying to do.

However, to answer your question: it's not possible to catch that event in all cases.  You cannot prevent the user from closing the browser or guarantee that your code will execute when they do.  You can make it slightly annoying for them, but they can disable javascript, or kill the process, or reboot the computer.  Using the unload function is the closest you can come to having some code that runs when the window closes (it will run in cases of normal shutdown or when the user navigates away).

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

Body:
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

window.onunload = function() { alert("unloading"); }

OwnerDisplayName: rmeador


问:
Where can I download Coldfusion MX 7 for Mac?
It seems like it is no longer downloadable from Adobe, so I was wondering if anyone out there knows where I can download it from. </p>

答:
You can download it from Adobe here:

http://www.adobe.com/cfusion/tdrc/index.cfm?product=coldfusion7


问:
Unable to parse required data from nested arrays in json using python
When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:

```<code>import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)
</code>```

And the partial response is like:

```<code>[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo@zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david@sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception@century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer@century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer@century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather@century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall@century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}
</code>```

答:
Write before the print(j)

```<code>import pdb; pdb.set_trace()
</code>```

Run your script and then the console will wait for commands, there you can write commands, start playing with your json, remember that a Json are tuples with dictionaries, that can have more tupels or more dictionaries inside, so you will end with something like

print (j[1]['EmailAddress'])

Body:
When I tried with my script, I do get response but can't parse the Name and Email from this response as I never worked with json arrays. Hope there is somebody to give me an idea. I tried with:

import requests
from urllib.parse import urlencode
url = 'https://oresapp.asicanada.net/ores.imis.services/api/member/?'
address = '&callback=angular.callbacks._0&city=&companyName=&personName='
xhr = url + urlencode({'address':address})
j = requests.get(xhr).json()
print(j)

And the partial response is like:

[{'EmailAddress': '', 'Zip': '', 'Members': [{'Fax': '', 'FirstLastName': 'Ryley Reat', 'Id': 46648, 'FirstName': 'Ryley', 'FullName': 'Ryley Reat', 'Email': 'zolo@zolo.ca', 'LastName': 'Reat', 'LocationId': 46647, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': '', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': 'CANADA', 'GeoCode': {'latitude': 56.130366, 'longitude': -106.346771}, 'City': '', 'FullAddress': 'CANADA', 'Id': 46647, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Zolo Realty Inc.', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': '', 'Zip': 'T3H 4W2', 'Members': [{'Fax': '', 'FirstLastName': 'David SandBrand', 'Id': 46646, 'FirstName': 'David', 'FullName': 'David SandBrand', 'Email': 'david@sandbrand.com', 'LastName': 'SandBrand', 'LocationId': 46645, 'Phone': '', 'WebSite': ''}], 'ProvinceCode': 'AB', 'CityRanking': 1.0, 'WorkPhone': '', 'Website': '', 'GeoCodeAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'GeoCode': {'latitude': 51.0626195, 'longitude': -114.1907432}, 'City': 'Calgary', 'FullAddress': '146 West Springs Pl SW Calgary, AB  T3H 4W2 CANADA', 'Id': 46645, 'Fax': '', 'CompanyNameRanking': 1.0, 'Company': 'Damecca Holdings Ltd', 'Country': 'Canada', 'BrokerName': ' '}, {'EmailAddress': 'c.reception@century21.ca', 'Zip': 'S9V 0N7', 'Members': [{'Fax': '', 'FirstLastName': 'Alex Palmer', 'Id': 45347, 'FirstName': 'Alex', 'FullName': 'Alex Palmer', 'Email': 'alex.palmer@century21.ca', 'LastName': 'Palmer', 'LocationId': 37526, 'Phone': '(306) 821-0138', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Becky Hofer', 'Id': 45379, 'FirstName': 'Becky', 'FullName': 'Becky Hofer', 'Email': 'becky.hofer@century21.ca', 'LastName': 'Hofer', 'LocationId': 37526, 'Phone': '(306) 830-9740', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Cheryl Fairweather', 'Id': 45346, 'FirstName': 'Cheryl', 'FullName': 'Cheryl Fairweather', 'Email': 'cheryl.fariweather@century21.ca', 'LastName': 'Fairweather', 'LocationId': 37526, 'Phone': '(780) 808-9406', 'WebSite': ''}, {'Fax': '', 'FirstLastName': 'Chris Hassall', 'Id': 45334, 'FirstName': 'Chris', 'FullName': 'Chris Hassall', 'Email': 'chris.hassall@century21.ca', 'LastName': 'Hassall', 'LocationId': 37526, 'Phone': '(780) 871-3838', 'WebSite': ''}

Body:
Write before the print(j)

import pdb; pdb.set_trace()

Run your script and then the console will wait for commands, there you can write commands, start playing with your json, remember that a Json are tuples with dictionaries, that can have more tupels or more dictionaries inside, so you will end with something like

print (j[1]['EmailAddress'])


问:
Is there an easy way to run,use & display desktop programs on web browser from my own computer without uploading on other server or using online app?
For example there is a calculator app inside my computer so can i run ,use and display calculator app on web browser from my computer but only by using server like xammp or other offline software without uploading on others server or using online app ? please provide easy solution.</p>

答:
You can try OnlineVNC? http://www.onlinevnc.com/
I'm not sure if it fits your criteria though. It's a server part that you install on your PC so that you can remote it from a browser.</p>


问:
Finding parent documents based on a child ID
Suppose I have the following schemas

```<code>let TutorialQuizSchema = new mongoose.Schema({
    groups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Group' }]
});

let GroupSchema = new mongoose.Schema({
    members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    responses: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Response' }]
});

let UserSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});
</code>```

Given a user ID, is it possible to query all the tutorial quizzes with all the groups that have the user as one of its members?

I'm new to aggregation, but I think it would be something like this

```<code>TutorialQuiz.aggreggate([
    {
        $unwind: '$groups'
    },
    {
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
        $unwind: '$group'
    },
    {
        $match: {
            'group.members': { $in: [req.user._id] }
        }
    }
]).exec((err, data) => {
    // etc
})
</code>```

If I am correct, my only problem with this is that the data comes out flattened. Is it possible to unflatten it to maintain the hierarchical structure (like if we were just doing a find + populate query) ?

Note: if there is better/easier way to do this, I am open to suggestions also.

答:
You can $lookup objectIds directly without $unwinding  and use $filter instead of second $unwind inside the $addFields stage to filter the group on presence of user_id value in the members array in 3.4 version.

Something like

```<code>TutorialQuiz.aggreggate([
    {
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
      $addFields: {
         group: {
            $filter: {
               input: "$group",
               as: "group",
               cond: { $in: [ req.user._id, "$$group.members" ] }
            }
         }
      }
   }
])
</code>```

Body:
Suppose I have the following schemas

let TutorialQuizSchema = new mongoose.Schema({
    groups: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Group' }]
});

let GroupSchema = new mongoose.Schema({
    members: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
    responses: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Response' }]
});

let UserSchema = new mongoose.Schema({
    name: {
        first: String,
        last: String
    }
});

Given a user ID, is it possible to query all the tutorial quizzes with all the groups that have the user as one of its members?

I'm new to aggregation, but I think it would be something like this

TutorialQuiz.aggreggate([
    {
        $unwind: '$groups'
    },
    {
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
        $unwind: '$group'
    },
    {
        $match: {
            'group.members': { $in: [req.user._id] }
        }
    }
]).exec((err, data) => {
    // etc
})

If I am correct, my only problem with this is that the data comes out flattened. Is it possible to unflatten it to maintain the hierarchical structure (like if we were just doing a find + populate query) ?

Note: if there is better/easier way to do this, I am open to suggestions also.

Body:
You can $lookup objectIds directly without $unwinding  and use $filter instead of second $unwind inside the $addFields stage to filter the group on presence of user_id value in the members array in 3.4 version.

Something like

TutorialQuiz.aggreggate([
    {
        $lookup: {
            from: 'groups',
            localField: 'groups',
            foreignField: '_id',
            as: 'group'
        }
    },
    {
      $addFields: {
         group: {
            $filter: {
               input: "$group",
               as: "group",
               cond: { $in: [ req.user._id, "$$group.members" ] }
            }
         }
      }
   }
])


问:
How do i pass named parameters (not all string values) to another job in Jenkins Pipeline?
I want to pass a bunch of parameters that are named, some of which are also Maps of named parameters into another job. The below does not work:

```<code>node
{
    stage ('Deploying')
    {
        build job: 'job-runner',
        serverSetup: [test: 'test'],
        jobs: [
            myJob: "true"
        ],
        runType: [test: "test"]
    }
}
</code>```

I want the called job to be able to do all of the following:

```<code>parameters.serverSetup.test
if ( parameters.jobs.MyJob == true )
parameters.runtype.test
</code>```

How would I do that?

答: With the build job function, you can pass parameters. Ex : build job: 'job-runner', parameters: [[$class: 'StringParameterValue', name: 'string1', value: param1], [$class: 'BooleanParameterValue', name: 'myJob', value: params.myJob]]

Body:
I want to pass a bunch of parameters that are named, some of which are also Maps of named parameters into another job. The below does not work:

node
{
    stage ('Deploying')
    {
        build job: 'job-runner',
        serverSetup: [test: 'test'],
        jobs: [
            myJob: "true"
        ],
        runType: [test: "test"]
    }
}

I want the called job to be able to do all of the following:

parameters.serverSetup.test
if ( parameters.jobs.MyJob == true )
parameters.runtype.test

How would I do that?


问:
How to submit data to SQL Server database using infopath without code
Can someone tell me how do I update/modify SQL Server database from using info path form with code?

Currently I'm using InfoPath to receive data from SQL database.

Thank you

Detailed help will be highly appreciated.

答: Did you create a new form using the Database template or are you connecting to the DB after the fact from a list you wanted to add the SQL db connection to? The easiest route is just to Create a new IP form using the Database template under the Advanced templates as it creates the fields and controls to enter and edit the SQL data you want to work with. If not then you need to run a SQL CREATE statement.</p>


问:
Excel VBA: copy and divide rows based on date/time criteria
I am trying to transform a file with a log of operations in a three-shift production environment to be able to group them by shifts (const 7-15, 15-23, 23-7), i.e. if both the start date/time and the end date/time of the record are not within the same shift then duplicate the row below and change the original end date/time and duplicated end date/time to the corresponding shift end.

```<code>Event   Start date/time    End date/time      Shift Start    Shift End
A       18/05/2017 4:30    18/05/2017 11:45   Mid (23-7)     Day (7-15)
</code>```

transforming to:

```<code>Event   Start date/time    End date/time      Shift Start    Shift End
A       18/05/2017 4:30    18/05/2017 7:00    Mid (23-7)     Mid (23-7)
A       18/05/2017 7:00    18/05/2017 11:45   Day (7-15)     Day (7-15)
</code>```

Unfortunately I am not good enough with VBA, so at the beginning I was trying to solve that using solely excel formulas, and added a column that shows how many shifts the event lasted (what is equal to the X number of rows that have to be doubled), that may be helpful with iterations.

```<code>Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 23:30  Mid (23-7)     Mid (23-7)   3
</code>```

Logic behind:

```<code>Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 7:00   Mid (23-7)     Mid (23-7)   ""
A        18/05/2017 7:00    18/05/2017 23:30  Day (7-15)     Mid (23-7)   2
</code>```

expected result:

```<code>Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 7:00   Mid (23-7)     Mid (23-7)   ""
A        18/05/2017 7:00    18/05/2017 15:00  Day (7-15)     Day (7-15)   ""
A        18/05/2017 15:00   18/05/2017 23:00  Aft (15-23)    Aft (15-23)  ""
A        18/05/2017 23:00   18/05/2017 23:30  Mid (23-7)     Mid (23-7)   ""
</code>```

I’ve been trying to solve that for hours sourcing the internet, and eventually I have only been able to duplicate the row X-number of times below leaving column F blank, but I feel like it’s a dead end. Any assistance would be appreciated!

Thanks!

EDIT

```<code>Sub duplicate()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicate
        copyRows = Range("F" & lngRow).Value
        Range("F" & lngRow + 1 & ":F" & lngRow + copyRows).EntireRow.Insert
        Range("A" & lngRow & ":F" & (lngRow + copyRows)).FillDown 'was just testing the code. here I think I should work on cells and defined const. do I need an array to solve that problem?
        Range("F" & lngRow & ":F" & (lngRow + copyRows)).Value = ""
        lngRow = lngRow + copyRows
    End If
    lngRow = lngRow + 1
Loop
End Sub
</code>```

EDIT 2 this is my first code I have ever written, sorry for any mistakes. I know it's not the cleanest code, but I try my best.

```<code>Sub duplicate2()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicated
        copyRows = Range("F" & lngRow).Value 'ok
        Range("F" & lngRow + 1 & ":F" & lngRow + 1).EntireRow.Insert 'insert a row below
        Range("F" & lngRow + 1 & ":F" & lngRow + 1).Value = copyRows - 1 'decrease X by 1
        Range("F" & lngRow & ":F" & lngRow).Value = "" 'clean original X
        Range("A" & lngRow + 1 & ":E" & lngRow + 1).FillDown 'duplicate row

        'here I should work on cells and defined const. do I need an array to solve that problem?

    End If
    lngRow = lngRow + 1
Loop
End Sub
</code>```

```<code>Sub duplicate()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicate
        copyRows = Range("F" & lngRow).Value
        Range("F" & lngRow + 1 & ":F" & lngRow + copyRows).EntireRow.Insert
        Range("A" & lngRow & ":F" & (lngRow + copyRows)).FillDown 'was just testing the code. here I think I should work on cells and defined const. do I need an array to solve that problem?
        Range("F" & lngRow & ":F" & (lngRow + copyRows)).Value = ""
        lngRow = lngRow + copyRows
    End If
    lngRow = lngRow + 1
Loop
End Sub
</code>```

答:
You can try this macro to split the rows by shift. Uses only columns A-C without using your additional helper columns. It can handles durations that can span many days, because it handles the dates and calculates the shifts precisely using a dedicated function (see the utility function shifEnd below).

```<code>Sub SplitShifts()
  Application.ScreenUpdating = False: Application.EnableEvents = False
  On Error GoTo Cleanup

  Dim r As Range: Set r = Sheet1.Range("A2:F2")
  Do Until Len(Trim(r(1))) = 0 ' loop until row is empty
    If shiftEnd(r(2)) >= r(3) Then
      Set r = r.Offset(1) ' no split needed, next row
    Else ' insert new row and split shifts
      r.Copy: r.Insert Shift:=xlDown
      r(2) = shiftEnd(r(2))
      r(0, 3) = r(2)
    End If
  Loop

Cleanup:
  Application.ScreenUpdating = True: Application.EnableEvents = True: Application.CutCopyMode = False
End Sub

Function shiftEnd(ByVal d As Date) As Date
  Select Case Hour(d)
    Case 0 To 6: shiftEnd = Int(d) + TimeSerial(7, 0, 0)
    Case 7 To 14: shiftEnd = Int(d) + TimeSerial(15, 0, 0)
    Case 15 To 22: shiftEnd = Int(d) + TimeSerial(23, 0, 0)
    Case 23: shiftEnd = Int(d) + 1 + TimeSerial(7, 0, 0) ' Next day 7:00
  End Select
End Function
</code>```

Testing

```<code>Event   Start date      End date
A       5/18/17 4:30    5/18/17 21:18
B       5/20/17 18:54   5/22/17 2:06
C       5/22/17 11:42   5/23/17 6:54
D       5/25/17 16:30   5/26/17 6:54
E       5/26/17 4:30    5/26/17 18:54
F       5/27/17 4:30    5/28/17 14:06
G       5/30/17 16:30   5/31/17 23:42
</code>```

Body:
I am trying to transform a file with a log of operations in a three-shift production environment to be able to group them by shifts (const 7-15, 15-23, 23-7), i.e. if both the start date/time and the end date/time of the record are not within the same shift then duplicate the row below and change the original end date/time and duplicated end date/time to the corresponding shift end.

Event   Start date/time    End date/time      Shift Start    Shift End
A       18/05/2017 4:30    18/05/2017 11:45   Mid (23-7)     Day (7-15)

transforming to:

Event   Start date/time    End date/time      Shift Start    Shift End
A       18/05/2017 4:30    18/05/2017 7:00    Mid (23-7)     Mid (23-7)
A       18/05/2017 7:00    18/05/2017 11:45   Day (7-15)     Day (7-15)

Unfortunately I am not good enough with VBA, so at the beginning I was trying to solve that using solely excel formulas, and added a column that shows how many shifts the event lasted (what is equal to the X number of rows that have to be doubled), that may be helpful with iterations.

Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 23:30  Mid (23-7)     Mid (23-7)   3

Logic behind:

Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 7:00   Mid (23-7)     Mid (23-7)   ""
A        18/05/2017 7:00    18/05/2017 23:30  Day (7-15)     Mid (23-7)   2

expected result:

Event    Start date/time    End date/time     Shift Start    Shift End    X
A        18/05/2017 4:30    18/05/2017 7:00   Mid (23-7)     Mid (23-7)   ""
A        18/05/2017 7:00    18/05/2017 15:00  Day (7-15)     Day (7-15)   ""
A        18/05/2017 15:00   18/05/2017 23:00  Aft (15-23)    Aft (15-23)  ""
A        18/05/2017 23:00   18/05/2017 23:30  Mid (23-7)     Mid (23-7)   ""

I’ve been trying to solve that for hours sourcing the internet, and eventually I have only been able to duplicate the row X-number of times below leaving column F blank, but I feel like it’s a dead end. Any assistance would be appreciated!

Thanks!

EDIT

Sub duplicate()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicate
        copyRows = Range("F" & lngRow).Value
        Range("F" & lngRow + 1 & ":F" & lngRow + copyRows).EntireRow.Insert
        Range("A" & lngRow & ":F" & (lngRow + copyRows)).FillDown 'was just testing the code. here I think I should work on cells and defined const. do I need an array to solve that problem?
        Range("F" & lngRow & ":F" & (lngRow + copyRows)).Value = ""
        lngRow = lngRow + copyRows
    End If
    lngRow = lngRow + 1
Loop
End Sub

EDIT 2 this is my first code I have ever written, sorry for any mistakes. I know it's not the cleanest code, but I try my best.

Sub duplicate2()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicated
        copyRows = Range("F" & lngRow).Value 'ok
        Range("F" & lngRow + 1 & ":F" & lngRow + 1).EntireRow.Insert 'insert a row below
        Range("F" & lngRow + 1 & ":F" & lngRow + 1).Value = copyRows - 1 'decrease X by 1
        Range("F" & lngRow & ":F" & lngRow).Value = "" 'clean original X
        Range("A" & lngRow + 1 & ":E" & lngRow + 1).FillDown 'duplicate row

        'here I should work on cells and defined const. do I need an array to solve that problem?

    End If
    lngRow = lngRow + 1
Loop
End Sub

Sub duplicate()
Dim lngRow As Long, copyRows As Integer

Application.ScreenUpdating = False
lngRow = 2 '1. header
Do Until IsEmpty(Range("A" & lngRow))
    If Range("F" & lngRow).Value >= 1 Then 'check if the row should be duplicate
        copyRows = Range("F" & lngRow).Value
        Range("F" & lngRow + 1 & ":F" & lngRow + copyRows).EntireRow.Insert
        Range("A" & lngRow & ":F" & (lngRow + copyRows)).FillDown 'was just testing the code. here I think I should work on cells and defined const. do I need an array to solve that problem?
        Range("F" & lngRow & ":F" & (lngRow + copyRows)).Value = ""
        lngRow = lngRow + copyRows
    End If
    lngRow = lngRow + 1
Loop
End Sub

Body:
You can try this macro to split the rows by shift. Uses only columns A-C without using your additional helper columns. It can handles durations that can span many days, because it handles the dates and calculates the shifts precisely using a dedicated function (see the utility function shifEnd below).

Sub SplitShifts()
  Application.ScreenUpdating = False: Application.EnableEvents = False
  On Error GoTo Cleanup

  Dim r As Range: Set r = Sheet1.Range("A2:F2")
  Do Until Len(Trim(r(1))) = 0 ' loop until row is empty
    If shiftEnd(r(2)) >= r(3) Then
      Set r = r.Offset(1) ' no split needed, next row
    Else ' insert new row and split shifts
      r.Copy: r.Insert Shift:=xlDown
      r(2) = shiftEnd(r(2))
      r(0, 3) = r(2)
    End If
  Loop

Cleanup:
  Application.ScreenUpdating = True: Application.EnableEvents = True: Application.CutCopyMode = False
End Sub

Function shiftEnd(ByVal d As Date) As Date
  Select Case Hour(d)
    Case 0 To 6: shiftEnd = Int(d) + TimeSerial(7, 0, 0)
    Case 7 To 14: shiftEnd = Int(d) + TimeSerial(15, 0, 0)
    Case 15 To 22: shiftEnd = Int(d) + TimeSerial(23, 0, 0)
    Case 23: shiftEnd = Int(d) + 1 + TimeSerial(7, 0, 0) ' Next day 7:00
  End Select
End Function

Testing

Event   Start date      End date
A       5/18/17 4:30    5/18/17 21:18
B       5/20/17 18:54   5/22/17 2:06
C       5/22/17 11:42   5/23/17 6:54
D       5/25/17 16:30   5/26/17 6:54
E       5/26/17 4:30    5/26/17 18:54
F       5/27/17 4:30    5/28/17 14:06
G       5/30/17 16:30   5/31/17 23:42


问:
How to determine count of a value in a column based on constraints?
I have a large dataset and I was wondering how to calculate the most common occurrences of a certain attribute's value.

For instance, let's say I have a hypothetical table called Cats. I insert the following values into it:

```<code>Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int)

INSERT INTO CATS (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);
</code>```

What if I want to determine the most common city for female cats in the year 1980? How would I do so? I can't seem to wrap my head around it.

答:
```<code>create table #Cats (Cat_ID int, Cat_name varchar(max), cat_hometown varchar(max), Gender varchar(max), Birth_Year int)

INSERT Into #CATS (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);

;with cat_count as (
select count(1) NumberofCats, Cat_Hometown from #Cats
where Gender = 'F'
and Birth_year = 1980
group by cat_hometown
)

select Cat_Hometown from cat_count
where NumberofCats = (select max(numberofcats) from cat_count)
</code>```

Body:
I have a large dataset and I was wondering how to calculate the most common occurrences of a certain attribute's value.

For instance, let's say I have a hypothetical table called Cats. I insert the following values into it:

Create table Cats (Cat_ID int, Cat_name varchar(max), Cat_Hometown varchar(max), Gender varchar(max), Birth_Year int)

INSERT INTO CATS (Cat_ID, Cat_Name, Cat_Hometown, Gender, Birth_year)
VALUES (1, 'Blue','Boston','M', 1980),
(2, 'Steamer','Plymouth','F', 1999),
(3, 'Stack','Newton','F', 1980),
(4, 'Overflow','Boston','M', 1978),
(5, 'CatorDog','Allston','F', 1999);

What if I want to determine the most common city for female cats in the year 1980? How would I do so? I can't seem to wrap my head around it.


问:
Adding Spring (Boot?) to existing RESTEasy JAX-RS application
I have an existing Maven project based on JAX-RS using RESTEasy. It works great! It creates a WAR that I deploy to Tomcat running on Ubuntu. It's clean and follows the latest standards. The POM is simple:

```<code>...
<packaging>war</packaging>
...
<dependencies>
...
  <dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0.1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
...
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.5.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>3.0.0</version>
    </plugin>
  </plugins>
...
</code>```

I don't need any web.xml because I'm using the latest Java EE annotations:

```<code>import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class MyRESTApplication extends Application {

  final FooResource fooResource = new FooResourceService();

...

  @Override
  public Set<Object> getSingletons() {
    return ImmutableSet.of(fooResource);
  }
}
</code>```

This is all simple and it's working so great! Now I just want a way to easily change FooResource implementations based on the profile --- in other words, wire my singletons. That's where Spring comes in, right? And I've been told that Spring Boot makes Spring even more awesome, and you can use it with anything, and it gives you an actuator that allows you to gain real-time inside on the health of your system.

Unfortunately all the Spring Boot books and tutorials seem to think I'm starting with one of their quick-start applications. But I already have a great, simple application. I just want to:

Get my application wiring, based on profiles, from an external configuration file (not annotations) via Spring.

Get whatever other goodness comes from Spring Boot, because apparently it is awesome and will completely transform my application.

How do I add Spring (or Spring Boot) to this simple little JAX-RS application?

答:
we solved it that way, that we created a singleton spring bean, let's call it ServiceStartupClass, where we register all JAX-RS services.

Here some code snippet how we start our services:

```<code>import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;

@Component
@ApplicationPath("/")
public class ServiceStartupClass extends ResourceConfig {

    @PostConstruct
    public void startup() {
        register(FooResource.class);
        ...
    }
}
</code>```

If you need any further help, let me know

Body:
I have an existing Maven project based on JAX-RS using RESTEasy. It works great! It creates a WAR that I deploy to Tomcat running on Ubuntu. It's clean and follows the latest standards. The POM is simple:

...
<packaging>war</packaging>
...
<dependencies>
...
  <dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0.1</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-servlet-initializer</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
  <dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.1.0.Final</version>
  </dependency>
...
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <version>3.5.1</version>
      <configuration>
        <source>1.8</source>
        <target>1.8</target>
      </configuration>
    </plugin>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>3.0.0</version>
    </plugin>
  </plugins>
...

I don't need any web.xml because I'm using the latest Java EE annotations:

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/")
public class MyRESTApplication extends Application {

  final FooResource fooResource = new FooResourceService();

...

  @Override
  public Set<Object> getSingletons() {
    return ImmutableSet.of(fooResource);
  }
}

This is all simple and it's working so great! Now I just want a way to easily change FooResource implementations based on the profile --- in other words, wire my singletons. That's where Spring comes in, right? And I've been told that Spring Boot makes Spring even more awesome, and you can use it with anything, and it gives you an actuator that allows you to gain real-time inside on the health of your system.

Unfortunately all the Spring Boot books and tutorials seem to think I'm starting with one of their quick-start applications. But I already have a great, simple application. I just want to:

Get my application wiring, based on profiles, from an external configuration file (not annotations) via Spring.

Get whatever other goodness comes from Spring Boot, because apparently it is awesome and will completely transform my application.

How do I add Spring (or Spring Boot) to this simple little JAX-RS application?

Body:
we solved it that way, that we created a singleton spring bean, let's call it ServiceStartupClass, where we register all JAX-RS services.

Here some code snippet how we start our services:

import javax.ws.rs.ApplicationPath;

import org.glassfish.jersey.server.ResourceConfig;

@Component
@ApplicationPath("/")
public class ServiceStartupClass extends ResourceConfig {

    @PostConstruct
    public void startup() {
        register(FooResource.class);
        ...
    }
}

If you need any further help, let me know


问:
Multi-WIndow Support block activity regeneration
When my app goes to multi-Window mode, my activity gets killed and regenerated. IS this the expected behavior.

I was trying to block this using this behavior?

答:
Found code to handle Multi Window from Link: https://medium.com/google-developers/5-tips-for-preparing-for-multi-window-in-android-n-7bed803dda64</p>

```<code><activity
  android:name=".MyActivity"
  android:configChanges="screenSize|smallestScreenSize
      |screenLayout|orientation"
/>
</code>```

Body:
Found code to handle Multi Window from Link: https://medium.com/google-developers/5-tips-for-preparing-for-multi-window-in-android-n-7bed803dda64

<activity
  android:name=".MyActivity"
  android:configChanges="screenSize|smallestScreenSize
      |screenLayout|orientation"
/>


问:
Nested Set SQL problem
http://dev.mysql.com/tech-resources/articles/hierarchical-data.html

```<code>LOCK TABLE nested_category WRITE;

SELECT @myLeft := lft FROM nested_category

WHERE name = '2 WAY RADIOS';

UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myLeft;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myLeft;

INSERT INTO nested_category(name, lft, rgt) VALUES('FRS', @myLeft + 1, @myLeft + 2);

UNLOCK TABLES;
</code>```

I tried running this sample code in codeigniter via $this->db->query() but I get this error

```<code>A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOCK TABLE nested_category WRITE; SELECT @myLeft := lft FROM nested_category WHERE name = '2 WAY RADIOS';' at line 3

LOCK TABLE nested_category WRITE; SELECT @myLeft := lft FROM nested_category WHERE name = '2 WAY RADIOS'; UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myLeft; UPDATE nested_category SET lft = lft + 2 WHERE lft > @myLeft; INSERT INTO nested_category(name, lft, rgt) VALUES('FRS', @myLeft + 1, @myLeft + 2); UNLOCK TABLES;
</code>```

I am sure the database is not the problem since I ran this SQL in phpmyadmin and it worked. But when I run at via code, I get an error. Could this be a codeigniter problem? A file encoding problem? Does the query() function support multiple queries at once? I am stumped.

答:
In fact it does not. Most user front-ends for MySQL will split multiple up SQL queries you input and send them one by one, so you might not have noticed that.

You need to split each query into its own query() call, and it will work as expected assuming each query() is called on the same MySQL connection/session.

On another note, if you're using MySQL 5.0 or above, you can use a transaction instead of having to manually lock/unlock your tables. Just replace LOCK TABLE nested_category WRITE with BEGIN and UNLOCK TABLES with COMMIT.

Title: Nested Set SQL problem

Body:
http://dev.mysql.com/tech-resources/articles/hierarchical-data.html

LOCK TABLE nested_category WRITE;

SELECT @myLeft := lft FROM nested_category

WHERE name = '2 WAY RADIOS';

UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myLeft;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myLeft;

INSERT INTO nested_category(name, lft, rgt) VALUES('FRS', @myLeft + 1, @myLeft + 2);

UNLOCK TABLES;

I tried running this sample code in codeigniter via $this->db->query() but I get this error

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOCK TABLE nested_category WRITE; SELECT @myLeft := lft FROM nested_category WHERE name = '2 WAY RADIOS';' at line 3

LOCK TABLE nested_category WRITE; SELECT @myLeft := lft FROM nested_category WHERE name = '2 WAY RADIOS'; UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myLeft; UPDATE nested_category SET lft = lft + 2 WHERE lft > @myLeft; INSERT INTO nested_category(name, lft, rgt) VALUES('FRS', @myLeft + 1, @myLeft + 2); UNLOCK TABLES;

I am sure the database is not the problem since I ran this SQL in phpmyadmin and it worked. But when I run at via code, I get an error. Could this be a codeigniter problem? A file encoding problem? Does the query() function support multiple queries at once? I am stumped.


问:
SSRS hidden columns expression consuming time while rednering
I am converting one crystal report to SSRS In which There are multiple group header having expression like

IIF(Fields!MainGroupOrder.Value = 2 And Fields!DaysOrHours.Value =
  "Hours",IIF(Sum(Fields!Count_01.Value) = 0, 0,
  Sum(Fields!Jan_CountTurnTime.Value)/Sum(Fields!Count_01.Value)/60),IIF(Sum(Fields!Count_01.Value)
  = 0, 0, Sum(Fields!Jan_CountTurnTime.Value)/Sum(Fields!Count_01.Value))/60/9)

There are 12 such statements in each row with 5 rows

This row with 12 columns has visibility condition at row level

When I am viewing report after removing these expression, Report is taking 37 seconds to render
With same parameter when I am rendering report with these expression It is taking 1 minutes and 20 seconds (these expressions are not visible with given parameters)

I read somewhere that SSRS after 2005 does not calculate hidden column till its not used in any other visible condition
Then why time is increasing on inclusion of these expression even though these are not visible and also not used in any visible condition

Can you explain why and it would be great if you can help me in decreasing the time this report is taking due to these expression which are not visible

Thanks

答:
In SSRS, every expression takes time to evaluate. Even invisible objects complete all their calculations. You can easily test this by making everything invisible, it doesn't save any time.

Here are some general tips to make SSRS reports faster:

Optimize the original query.

Cache the report beforehand.

Do more of the calculations in the SQL as opposed to in the report.

Use a stored procedure instead of plain SQL.

Use parameters to filter the query to just the data you need as opposed to filtering it in the report afterwards.

Use a calculated field to consolidate logic that is used in multiple places in the report. This way, the calculation is only done once per row.