问:
Error while installing chatterBot
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

```<code>Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot
</code>```

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7

答:
You are getting this error because you have not installed required package. I think you need download them and install them before trying to install the chatterBot directly.
You can install using 'pip' or you can download and us 'python'.

pip install path_where_you_have_downloaded_packages

or

python path_where_you_have_downloaded_packages\setup.py install

Try it.

Title: Error while installing chatterBot

Body:
Whenever I try to install ChatterBot using command pip install ChatterBot it gives this error:

Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'NewConnectionError('<pip._vendor.requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x0000000003687898>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)': /simple/chatterbot/
  Could not find a version that satisfies the requirement chatterbot (from versi
ons: )
No matching distribution found for chatterbot

I downgraded from Python 3.6 to 2.7, yet receiving the same error.

I am using windows 8, Anaconda 2.7


来源: stackexchange

问:
How do you print an error from a child thread in Haskell?
Given the following code:

```<code>module Main where

import Control.Concurrent

main :: IO ()
main = forkIO errorPrinter >> threadDelay 1000000 >> print "Finished"

errorPrinter = error "You can't see me!"
</code>```

I would expect, that upon running this code I would see this:

```<code>"You can't see me"
"Finished!"
</code>```

Printed to the console. However, "You can't see me" is never printed.

I realise that using error is not a good idea in production code, but I use it in development and I find that no errors are printed to the console - even those raised by dependencies.

I am sure this problem has an easy solution. I can't be the first person to have this issue, but I can't find an answer anywhere.

Any help would be much appreciated!

答:
I can't reproduce your problem; for me, it does print "You can't see me!":

```<code>% runhaskell test.hs
test.hs: You can't see me!
CallStack (from HasCallStack):
  error, called at test.hs:8:16 in main:Main
"Finished"
</code>```

I see similar behavior as far back as GHC 7.6 (the oldest GHC I have lying around); I would be mildly surprised to learn that this behavior has changed significantly in the last twenty years or so.

Anyway I would recommend switching over to printing the message you want printed:

```<code>import System.IO
errorPrinter = hPutStrLn stderr "You can't see me!"
</code>```

Say what you mean, and all that.

ContentLicense: CC BY-SA 3.0

Body:
Given the following code:

module Main where

import Control.Concurrent

main :: IO ()
main = forkIO errorPrinter >> threadDelay 1000000 >> print "Finished"

errorPrinter = error "You can't see me!"

I would expect, that upon running this code I would see this:

"You can't see me"
"Finished!"

Printed to the console. However, "You can't see me" is never printed.

I realise that using error is not a good idea in production code, but I use it in development and I find that no errors are printed to the console - even those raised by dependencies.

I am sure this problem has an easy solution. I can't be the first person to have this issue, but I can't find an answer anywhere.

Any help would be much appreciated!

Body:
I can't reproduce your problem; for me, it does print "You can't see me!":

% runhaskell test.hs
test.hs: You can't see me!
CallStack (from HasCallStack):
  error, called at test.hs:8:16 in main:Main
"Finished"

I see similar behavior as far back as GHC 7.6 (the oldest GHC I have lying around); I would be mildly surprised to learn that this behavior has changed significantly in the last twenty years or so.

Anyway I would recommend switching over to printing the message you want printed:

import System.IO
errorPrinter = hPutStrLn stderr "You can't see me!"

Say what you mean, and all that.


问:
SSIS script task fail version 15.0 script?
I have a 2012 SSIS project that runs on SQL Server 2016. I have SSDT 2015 on both my dev machine and server. Everything works fine except for script tasks - I made a change to an existing script task and rebuilt and redeployed the project and I receive the following error:

Script task uses version 15.0 script that is not supported in this release of integration services. To run the package, create a new script.

I've tried the following:

upgrading the project to 2016

creating a new script object

created script on the server

It runs fine through SSDT 2015, but once it is deployed it fails with the error above when executing the package via SSMS - this is the result from both my dev box and the server. I thought 14.0 was 2016? Any ideas how I can fix this?

Script tasks (in packages) cannot be executed via integration services catalog on server, but work fine in SSDT.

答: Here is what worked for me. If you use SSMS and try to add your DTSX (which contains a script) via Integration Services Catalog (Import and Deploy) it will fail.  However if you use the Project>Deploy option from within Visual Studio it will succeed. My target was SQL 2016 and SSDT is 2015. Note that under Project is a Upgrade All Packages option which I used.  I don't know if this is necessary, I don't think so, but just in case.</p>


问:
Python indentation in "empty lines"
Which is preferred ("." indicating whitespace)?

A)

```<code>def foo():
    x = 1
    y = 2
....
    if True:
        bar()
</code>```

B)

```<code>def foo():
    x = 1
    y = 2

    if True:
        bar()
</code>```

My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?

答:
vi implicitly discourages the behaviour in A because the {/} navigations no longer work as expected. git explicitly discourages it by highlighting it in red when you run git diff. I would also argue that if a line contains spaces it is not a blank line.

For that reason I strongly prefer B. There is nothing worse than expecting to skip six or so lines up with the { motion and ending up at the top of a class def.

ContentLicense: CC BY-SA 2.5

Title: Python indentation in "empty lines"

Body:
Which is preferred ("." indicating whitespace)?

A)

def foo():
    x = 1
    y = 2
....
    if True:
        bar()

B)

def foo():
    x = 1
    y = 2

    if True:
        bar()

My intuition would be B (that's also what vim does for me), but I see people using A) all the time. Is it just because most of the editors out there are broken?


问:
Intercepting call to the back button in my AJAX application
I have an AJAX app. A user clicks a button, and the page's display changes. They click the back button, expecting to go to the original state, but instead, they go to the previous page in their browser.

How can I intercept and re-assign the back button event? I've looked into libraries like RSH (which I couldn't get to work...), and I've heard that using the hash tag somehow helps, but I can't make sense of it.

答:
I worked out a way to override normal history behavior and create distinct back and forward button events, using the HTML5 history API (it won't work in IE 9).  This is very hacky, but effective if you wanted to intercept the back and forward button events and handle them however you want.  This could be useful in a number of scenarios, e.g. if you were displaying a remote desktop window and needed to reproduce back and forward button clicks on the remote machine.

The following would override the back and forward button behavior:

```<code>var myHistoryOverride = new HistoryButtonOverride(function()
{
    console.log("Back Button Pressed");
    return true;
},
function()
{
    console.log("Forward Button Pressed");
    return true;
});
</code>```

If you returned false in either of those callback functions, you would be allowing the browser to proceed with a normal back/forward operation and leave your page.

Here is the full script required:

```<code>function addEvent(el, eventType, handler) {
    if (el.addEventListener) { // DOM Level 2 browsers
       el.addEventListener(eventType, handler, false);
    } else if (el.attachEvent) { // IE <= 8
        el.attachEvent('on' + eventType, handler);
    } else { // ancient browsers
        el['on' + eventType] = handler;
    }
}
function HistoryButtonOverride(BackButtonPressed, ForwardButtonPressed)
{
    var Reset = function ()
    {
        if (history.state == null)
            return;
        if (history.state.customHistoryStage == 1)
            history.forward();
        else if (history.state.customHistoryStage == 3)
            history.back();
    }
    var BuildURLWithHash = function ()
    {
        // The URLs of our 3 history states must have hash strings in them so that back and forward events never cause a page reload.
        return location.origin + location.pathname + location.search + (location.hash && location.hash.length > 1 ? location.hash : "#");
    }
    if (history.state == null)
    {
        // This is the first page load. Inject new history states to help identify back/forward button presses.
        var initialHistoryLength = history.length;
        history.replaceState({ customHistoryStage: 1, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.pushState({ customHistoryStage: 2, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.pushState({ customHistoryStage: 3, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.back();
    }
    else if (history.state.customHistoryStage == 1)
        history.forward();
    else if (history.state.customHistoryStage == 3)
        history.back();

    addEvent(window,"popstate",function ()
    {
        // Called when history navigation occurs.
        if (history.state == null)
            return;
        if (history.state.customHistoryStage == 1)
        {
            if (typeof BackButtonPressed == "function" && BackButtonPressed())
            {
                Reset();
                return;
            }
            if (history.state.initialHistoryLength > 1)
                history.back(); // There is back-history to go to.
            else
                history.forward(); // No back-history to go to, so undo the back operation.
        }
        else if (history.state.customHistoryStage == 3)
        {
            if (typeof ForwardButtonPressed == "function" && ForwardButtonPressed())
            {
                Reset();
                return;
            }
            if (history.length > history.state.initialHistoryLength + 2)
                history.forward(); // There is forward-history to go to.
            else
                history.back(); // No forward-history to go to, so undo the forward operation.
        }
    });
};
</code>```

This works by a simple concept.  When our page loads, we create 3 distinct history states (numbered 1, 2, and 3) and navigate the browser to state number 2.  Because state 2 is in the middle, the next history navigation event will put us in either state 1 or 3, and from this we can determine which direction the user pressed.  And just like that, we've intercepted a back or forward button event.  We then handle it however we want and return to state number 2 so we can capture the next history navigation event.

Obviously, you would need to refrain from using history.replaceState and history.pushState methods while using the HistoryButtonOverride script, or else you'd break it.

ContentLicense: CC BY-SA 4.0

Body:
I worked out a way to override normal history behavior and create distinct back and forward button events, using the HTML5 history API (it won't work in IE 9).  This is very hacky, but effective if you wanted to intercept the back and forward button events and handle them however you want.  This could be useful in a number of scenarios, e.g. if you were displaying a remote desktop window and needed to reproduce back and forward button clicks on the remote machine.

The following would override the back and forward button behavior:

var myHistoryOverride = new HistoryButtonOverride(function()
{
    console.log("Back Button Pressed");
    return true;
},
function()
{
    console.log("Forward Button Pressed");
    return true;
});

If you returned false in either of those callback functions, you would be allowing the browser to proceed with a normal back/forward operation and leave your page.

Here is the full script required:

function addEvent(el, eventType, handler) {
    if (el.addEventListener) { // DOM Level 2 browsers
       el.addEventListener(eventType, handler, false);
    } else if (el.attachEvent) { // IE <= 8
        el.attachEvent('on' + eventType, handler);
    } else { // ancient browsers
        el['on' + eventType] = handler;
    }
}
function HistoryButtonOverride(BackButtonPressed, ForwardButtonPressed)
{
    var Reset = function ()
    {
        if (history.state == null)
            return;
        if (history.state.customHistoryStage == 1)
            history.forward();
        else if (history.state.customHistoryStage == 3)
            history.back();
    }
    var BuildURLWithHash = function ()
    {
        // The URLs of our 3 history states must have hash strings in them so that back and forward events never cause a page reload.
        return location.origin + location.pathname + location.search + (location.hash && location.hash.length > 1 ? location.hash : "#");
    }
    if (history.state == null)
    {
        // This is the first page load. Inject new history states to help identify back/forward button presses.
        var initialHistoryLength = history.length;
        history.replaceState({ customHistoryStage: 1, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.pushState({ customHistoryStage: 2, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.pushState({ customHistoryStage: 3, initialHistoryLength: initialHistoryLength }, "", BuildURLWithHash());
        history.back();
    }
    else if (history.state.customHistoryStage == 1)
        history.forward();
    else if (history.state.customHistoryStage == 3)
        history.back();

    addEvent(window,"popstate",function ()
    {
        // Called when history navigation occurs.
        if (history.state == null)
            return;
        if (history.state.customHistoryStage == 1)
        {
            if (typeof BackButtonPressed == "function" && BackButtonPressed())
            {
                Reset();
                return;
            }
            if (history.state.initialHistoryLength > 1)
                history.back(); // There is back-history to go to.
            else
                history.forward(); // No back-history to go to, so undo the back operation.
        }
        else if (history.state.customHistoryStage == 3)
        {
            if (typeof ForwardButtonPressed == "function" && ForwardButtonPressed())
            {
                Reset();
                return;
            }
            if (history.length > history.state.initialHistoryLength + 2)
                history.forward(); // There is forward-history to go to.
            else
                history.back(); // No forward-history to go to, so undo the forward operation.
        }
    });
};

This works by a simple concept.  When our page loads, we create 3 distinct history states (numbered 1, 2, and 3) and navigate the browser to state number 2.  Because state 2 is in the middle, the next history navigation event will put us in either state 1 or 3, and from this we can determine which direction the user pressed.  And just like that, we've intercepted a back or forward button event.  We then handle it however we want and return to state number 2 so we can capture the next history navigation event.

Obviously, you would need to refrain from using history.replaceState and history.pushState methods while using the HistoryButtonOverride script, or else you'd break it.


问:
Converting frame.time to epoch
Using the following command what modifications need to be made to get frame.time as epoch in tshark?</p>

```<code>tshark -T fields -n -r btle.pcap -E separator=, -e frame.time -e btle_rf.access_address_offenses -e btle_rf.channel -e btle_rf.flags -e btle_rf.flags.access_address_offenses_valid -e btle_rf.flags.channel_aliased -e btle_rf.flags.crc_checked -e btle_rf.flags.crc_valid -e btle_rf.flags.decrypted -e btle_rf.flags.dewhitened -e btle_rf.flags.mic_checked -e btle_rf.flags.mic_valid -e btle_rf.flags.noise_dbm_valid -e btle_rf.flags.reference_access_address_valid -e btle_rf.flags.rfu.1 -e btle_rf.flags.rfu.2 -e btle_rf.flags.signal_dbm_valid -e btle_rf.noise_dbm -e btle_rf.reference_access_address -e btle_rf.signal_dbm -e btle_rf.signed_byte_unused -e btle_rf.unsigned_byte_unused -e btle_rf.word_unused>btle.csv
</code>```

答:
As long as you are running Wireshark 1.4.0 or later, you can try changing -e frame.time to -e frame.time_epoch.  If you're running an older version of Wireshark, then I might suggest upgrading to a newer version.

With the latest stable version of Wireshark (2.2.7 as of this writing), all frame filters are documented in View -> Internals -> Supported Protocols -> Frame -> ... and you can always reference the online Display Filter Reference page as well.

Title: Converting frame.time to epoch

Body:
Using the following command what modifications need to be made to get frame.time as epoch in tshark?

tshark -T fields -n -r btle.pcap -E separator=, -e frame.time -e btle_rf.access_address_offenses -e btle_rf.channel -e btle_rf.flags -e btle_rf.flags.access_address_offenses_valid -e btle_rf.flags.channel_aliased -e btle_rf.flags.crc_checked -e btle_rf.flags.crc_valid -e btle_rf.flags.decrypted -e btle_rf.flags.dewhitened -e btle_rf.flags.mic_checked -e btle_rf.flags.mic_valid -e btle_rf.flags.noise_dbm_valid -e btle_rf.flags.reference_access_address_valid -e btle_rf.flags.rfu.1 -e btle_rf.flags.rfu.2 -e btle_rf.flags.signal_dbm_valid -e btle_rf.noise_dbm -e btle_rf.reference_access_address -e btle_rf.signal_dbm -e btle_rf.signed_byte_unused -e btle_rf.unsigned_byte_unused -e btle_rf.word_unused>btle.csv


问:
How can I clear rows in DataGridView with C#?
Following Error in this line.

```<code>datagridview1.Rows.Clear()
</code>```

but this line gives error:

Cannot clear this list.

答:
If you load your DataGridView with a parameter, you can send an empty parameter to it. This will clear your DataGridView without having to set its DataSet to null.

For example, I load my DataGridView with a Code, when I fill a TextBox.

```<code>this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, TextBox1.Text);
</code>```

If I want to clear its content, then

```<code>this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, "");
</code>```

Body:
Following Error in this line.

datagridview1.Rows.Clear()

but this line gives error:

Cannot clear this list.

Body:
If you load your DataGridView with a parameter, you can send an empty parameter to it. This will clear your DataGridView without having to set its DataSet to null.

For example, I load my DataGridView with a Code, when I fill a TextBox.

this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, TextBox1.Text);

If I want to clear its content, then

this.dataTable1TableAdapter.Fill(this.ds_MyDataSet.DataTable1, "");


问:
Finding the bootstrap affix plugin js only file
Where can i get the affix plugin JS, without having to load the whole bootstrap JS?

http://getbootstrap.com/javascript/#affix

答: You can actually customize what you want your bootstrap package to contain using http://getbootstrap.com/customize/ or you can just find the code for #affix within bootstrap and extract it to a separate JS file your self. Just beware some JS libraries are dependent on others.</p>


问:
Common custom server side validation function for multiple aspx pages
I have multiple aspx pages which have same form controls taking user inputs like firstname, lastname, address.

These fields already have required, regex and length based client side validations. Now what I need to do is add a custom validator to these pages which will perform a common validation. But I dont want to go about editing all the pages as they are in hundreds. I am only looking at adding a custom validation tag to the aspx pages and a common server side validation function which can be assigned to the custom validator tag on the aspx pages, which will save my efforts.

These pages are very old so I cannot change the form to a user control. Also because each page has different css.

Is it possible to write a common server side validator function which can be accessed by multiple aspx pages?

答:
You can create your own Validator by extending the CustomValidator class like this

```<code>namespace CustomValidation
{
    public class MyValidator : CustomValidator
    {
        protected override bool OnServerValidate(string value)
        {
            bool baseresult = base.OnServerValidate(value);
            if (baseresult && value == "TestValue")
                return true;

            return false;
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
        }

        protected override bool ControlPropertiesValid()
        {
            return base.ControlPropertiesValid();
        }

        protected override bool EvaluateIsValid()
        {
            return base.EvaluateIsValid();
        }
    }
}
</code>```

And in your aspx pages just add the control -

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<%@ Register TagPrefix="mytag" Namespace="CustomValidation" Assembly="WebApplication1"%>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <mytag:MyValidator ErrorMessage="Testing" ControlToValidate="txtBox" runat="server" />
            <asp:TextBox runat="server" ID="txtBox"></asp:TextBox>
            <asp:Button Text="Test Button" runat="server" ID="btnTest" OnClick="btnTest_Click" />
        </div>
    </form>
</body>
</html>
</code>```

And your OnServerValidate will be called on Page.IsValid

```<code>namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnTest_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

            }
        }
    }
}
</code>```

Body:
You can create your own Validator by extending the CustomValidator class like this

namespace CustomValidation
{
    public class MyValidator : CustomValidator
    {
        protected override bool OnServerValidate(string value)
        {
            bool baseresult = base.OnServerValidate(value);
            if (baseresult && value == "TestValue")
                return true;

            return false;
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
        }

        protected override bool ControlPropertiesValid()
        {
            return base.ControlPropertiesValid();
        }

        protected override bool EvaluateIsValid()
        {
            return base.EvaluateIsValid();
        }
    }
}

And in your aspx pages just add the control -

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<%@ Register TagPrefix="mytag" Namespace="CustomValidation" Assembly="WebApplication1"%>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <mytag:MyValidator ErrorMessage="Testing" ControlToValidate="txtBox" runat="server" />
            <asp:TextBox runat="server" ID="txtBox"></asp:TextBox>
            <asp:Button Text="Test Button" runat="server" ID="btnTest" OnClick="btnTest_Click" />
        </div>
    </form>
</body>
</html>

And your OnServerValidate will be called on Page.IsValid

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnTest_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {

            }
        }
    }
}


问:
How can a static method get instance details or do instance specific actions
The below code obviously will not compile.

```<code>public class Machine {
  public int id;
  static Machine staticMethod() { return this; } //compilation error - "Cannot use this in a static context"
  maskId() {   }
}
</code>```

And so it is not possible from staticMethod() to

(1) get information specific to any instance of Machine Object

(2) perform an action specific to any instance of Machine object

Unless I am missed something really simple.

How does the static methods of Thread Class deal with actions/information of specific thread.

Below are signatures of such methods from java docs Thread

static Thread  currentThread()   //Returns a reference to the currently executing thread object.

  static void    dumpStack() //Prints a stack trace of the current thread to the standard error stream.

Did I miss something. Or  are these methods (or Thread Class) different. Like Native implementations etc or what so ever but are able to determine the calling instance.

答:
I think it is done by scheduler,
Here i am mentioning class structure (it is my perception, how it works)</p>

```<code>class Thread{
static currentThread();

}

Class Scheduler{
//it has queue of all threads and also has track on current running thread
//queue = {Thread1,Thread2,Thread3,Thread4,Thread5}
// let thread3 is running, whenever a call to Thread3.currentThread come up
//some how jvm get instance of Thread3 from this queue and returns.

}
</code>```

Body:
The below code obviously will not compile.

public class Machine {
  public int id;
  static Machine staticMethod() { return this; } //compilation error - "Cannot use this in a static context"
  maskId() {   }
}

And so it is not possible from staticMethod() to

(1) get information specific to any instance of Machine Object

(2) perform an action specific to any instance of Machine object

Unless I am missed something really simple.

How does the static methods of Thread Class deal with actions/information of specific thread.

Below are signatures of such methods from java docs Thread

static Thread  currentThread()   //Returns a reference to the currently executing thread object.

  static void    dumpStack() //Prints a stack trace of the current thread to the standard error stream.

Did I miss something. Or  are these methods (or Thread Class) different. Like Native implementations etc or what so ever but are able to determine the calling instance.

Body:
I think it is done by scheduler,
Here i am mentioning class structure (it is my perception, how it works)

class Thread{
static currentThread();

}

Class Scheduler{
//it has queue of all threads and also has track on current running thread
//queue = {Thread1,Thread2,Thread3,Thread4,Thread5}
// let thread3 is running, whenever a call to Thread3.currentThread come up
//some how jvm get instance of Thread3 from this queue and returns.

}


问:
IO and Future[Option] monad transformers
I'm trying to figure out how to write this piece of code in an elegant pure-functional style using scalaz7 IO and monad transformers but just can't get my head around it.

Just imagine I have this simple API:

```<code>def findUuid(request: Request): Option[String] = ???
def findProfile(uuid: String): Future[Option[Profile]] = redisClient.get[Profile](uuid)
</code>```

Using this API I can easily write impure function with OptionT transformer like this:

```<code>val profileT = for {
  uuid <- OptionT(Future.successful(findUuid(request)))
  profile <- OptionT(findProfile(uuid))
} yield profile
val profile: Future[Option[Profile]] = profileT.run
</code>```

As you have noticed - this function contains findProfile() with a side-effect. I want to isolate this effect inside of the IO monad and interpret outside of the pure function but don't know how to combine it all together.

```<code>def findProfileIO(uuid: String): IO[Future[Option[Profile]]] = IO(findProfile(uuid))

val profileT = for {
  uuid <- OptionT(Future.successful(findUuid(request)))
  profile <- OptionT(findProfileIO(uuid)) //??? how to put Option inside of the IO[Future[Option]]
} yield profile
val profile = profileT.run //how to run transformer and interpret IO with the unsafePerformIO()???
</code>```

Any peaces of advice on how it might be done?

答:
End up with this piece of code, thought it might be useful for someone (Play 2.6).

Controller's method is a pure function since Task evaluation takes place outside of the controller inside of PureAction ActionBuilder. Thanks to Luka's answer!

Still struggling with new paradigm of Action composition in Play 2.6 though, but this is another story.

FrontendController.scala:

```<code>def index = PureAction.pure { request =>
  val profileOpt = (for {
    uuid <- OptionT(Task.now(request.cookies.get("uuid").map(t => uuidKey(t.value))))
    profile <- OptionT(redis.get[Profile](uuid).asTask)
  } yield profile).run
  profileOpt.map { profileOpt =>
    Logger.info(profileOpt.map(p => s"User logged in - $p").getOrElse("New user, suggesting login"))
    Ok(views.html.index(profileOpt))
  }
}
</code>```

Actions.scala

Convenient action with Task resolution at the end

```<code>class PureAction @Inject()(parser: BodyParsers.Default)(implicit ec: ExecutionContext) extends ActionBuilderImpl(parser) {
  self =>
  def pure(block: Request[AnyContent] => Task[Result]): Action[AnyContent] = composeAction(new Action[AnyContent] {
    override def parser: BodyParser[AnyContent] = self.parser
    override def executionContext: ExecutionContext = self.ec
    override def apply(request: Request[AnyContent]): Future[Result] = {
      val taskResult = block(request)
      taskResult.asFuture //End of the world lives here
    }
  })
}
</code>```

Converters.scala

Task->Future and Future->Task implicit converters

```<code>implicit class FuturePimped[+T](root: => Future[T]) {
  import scalaz.Scalaz._
  def asTask(implicit ec: ExecutionContext): Task[T] = {
    Task.async { register =>
      root.onComplete {
        case Success(v) => register(v.right)
        case Failure(ex) => register(ex.left)
      }
    }
  }
}

implicit class TaskPimped[T](root: => Task[T]) {
  import scalaz._
  val p: Promise[T] = Promise()
  def asFuture: Future[T] = {
    root.unsafePerformAsync {
      case -\/(ex) => p.failure(ex); ()
      case \/-(r) => p.success(r); ()
    }
    p.future
  }
}
</code>```

Body:
I'm trying to figure out how to write this piece of code in an elegant pure-functional style using scalaz7 IO and monad transformers but just can't get my head around it.

Just imagine I have this simple API:

def findUuid(request: Request): Option[String] = ???
def findProfile(uuid: String): Future[Option[Profile]] = redisClient.get[Profile](uuid)

Using this API I can easily write impure function with OptionT transformer like this:

val profileT = for {
  uuid <- OptionT(Future.successful(findUuid(request)))
  profile <- OptionT(findProfile(uuid))
} yield profile
val profile: Future[Option[Profile]] = profileT.run

As you have noticed - this function contains findProfile() with a side-effect. I want to isolate this effect inside of the IO monad and interpret outside of the pure function but don't know how to combine it all together.

def findProfileIO(uuid: String): IO[Future[Option[Profile]]] = IO(findProfile(uuid))

val profileT = for {
  uuid <- OptionT(Future.successful(findUuid(request)))
  profile <- OptionT(findProfileIO(uuid)) //??? how to put Option inside of the IO[Future[Option]]
} yield profile
val profile = profileT.run //how to run transformer and interpret IO with the unsafePerformIO()???

Any peaces of advice on how it might be done?

Body:
End up with this piece of code, thought it might be useful for someone (Play 2.6).

Controller's method is a pure function since Task evaluation takes place outside of the controller inside of PureAction ActionBuilder. Thanks to Luka's answer!

Still struggling with new paradigm of Action composition in Play 2.6 though, but this is another story.

FrontendController.scala:

def index = PureAction.pure { request =>
  val profileOpt = (for {
    uuid <- OptionT(Task.now(request.cookies.get("uuid").map(t => uuidKey(t.value))))
    profile <- OptionT(redis.get[Profile](uuid).asTask)
  } yield profile).run
  profileOpt.map { profileOpt =>
    Logger.info(profileOpt.map(p => s"User logged in - $p").getOrElse("New user, suggesting login"))
    Ok(views.html.index(profileOpt))
  }
}

Actions.scala

Convenient action with Task resolution at the end

class PureAction @Inject()(parser: BodyParsers.Default)(implicit ec: ExecutionContext) extends ActionBuilderImpl(parser) {
  self =>
  def pure(block: Request[AnyContent] => Task[Result]): Action[AnyContent] = composeAction(new Action[AnyContent] {
    override def parser: BodyParser[AnyContent] = self.parser
    override def executionContext: ExecutionContext = self.ec
    override def apply(request: Request[AnyContent]): Future[Result] = {
      val taskResult = block(request)
      taskResult.asFuture //End of the world lives here
    }
  })
}

Converters.scala

Task->Future and Future->Task implicit converters

implicit class FuturePimped[+T](root: => Future[T]) {
  import scalaz.Scalaz._
  def asTask(implicit ec: ExecutionContext): Task[T] = {
    Task.async { register =>
      root.onComplete {
        case Success(v) => register(v.right)
        case Failure(ex) => register(ex.left)
      }
    }
  }
}

implicit class TaskPimped[T](root: => Task[T]) {
  import scalaz._
  val p: Promise[T] = Promise()
  def asFuture: Future[T] = {
    root.unsafePerformAsync {
      case -\/(ex) => p.failure(ex); ()
      case \/-(r) => p.success(r); ()
    }
    p.future
  }
}


问:
Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed
I've added some pictures with the format *.png to my drawable-directory and linked it with the layouts. But every time when I tried to build it, there appears an error

"...Crunching Crunsher ...png failed"

Following is the output of the console:

```<code>app:mergeDebugResources
AAPT out(1561599) : No Delegate set : lost message:Done
AAPT out(12956469) : No Delegate set : lost message:Done
AAPT out(20612543) : No Delegate set : lost message:Crunching             C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\bt_meeting_focused.png
AAPT out(11030156) : No Delegate set : lost message:Crunching     C:\Dev\StudioProjects\test\android\app\src\main\res\mipmap-mdpi\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:Crunching single PNG file: C:\Dev\StudioProjects\test\android\app\src\main\res\mipmap-    mdpi\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:    Output file:     C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\mipmap-mdpi-v4\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:Done
AAPT err(11030156): libpng error: Not a PNG file
AAPT out(20612543) : No Delegate set : lost message:Crunching single PNG     file:     C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\bt_meeting_focused.png
AAPT out(20612543) : No Delegate set : lost message:    Output file:     C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\drawable\b    t_meeting_focused.png
AAPT out(20612543) : No Delegate set : lost message:Done
AAPT err(20612543): libpng error: Not a PNG file
AAPT err(1561599): libpng error: Not a PNG file
AAPT err(12956469): libpng error: Not a PNG file

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Crunching Cruncher uhr.png failed, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --    debug option to get more log output.

BUILD FAILED

Total time: 14.598 secs
Executing tasks: [clean, :app:generateDebugSources,     :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
:app:clean
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportSupportV42220Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
AAPT out(14080484) : No Delegate set : lost message:Done
AAPT out(9206750) : No Delegate set : lost message:Done
AAPT out(25360025) : No Delegate set : lost message:Done
AAPT err(25360025): libpng error: Not a PNG file
AAPT err(14080484): libpng error: Not a PNG file
AAPT out(6423170) : No Delegate set : lost message:Crunching C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\anfrage_senden_.png
AAPT err(6423170): libpng error: Not a PNG file
AAPT out(6423170) : No Delegate set : lost message:Crunching single PNG file:     C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\anfrage_senden_.png
AAPT out(6423170) : No Delegate set : lost message: Output file: C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\drawable\a    nfrage_senden_.png
AAPT out(6423170) : No Delegate set : lost message:Done
AAPT err(9206750): libpng error: Not a PNG file

Process list not empty
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Crunching Cruncher uhr.png failed, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --    debug option to get more log output.

BUILD FAILED

Total time: 4.325 secs
</code>```

I tried to clean the project, rebuild it, refresh the dependencies via "gradlew clean build --refresh-dependencies", nothing worked. I've checked the dependencies in the build.gradle file but nothing seems creating the error.

```<code>   apply plugin: 'com.android.application'
   android {
   compileSdkVersion 22
   buildToolsVersion "22.0.1"
   compileOptions.encoding = 'windows-1251'

   defaultConfig {
       applicationId "com.example.benutzer.test"
       minSdkVersion 16
       targetSdkVersion 22
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
    release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'),    'proguard-rules.pro'
       }
   }
   }

   dependencies {
   compile 'com.android.support:support-v4:22.2.0'
  }
</code>```

Do you've got an idea, what's the source of the error? The filepath is also not too long and everytime unter 256 signs, that also not the problem :/

Thank you in advance :)

答:
If you're running Linux, try this:

```<code>sudo apt-get install lib32stdc++6 lib32z1
</code>```

It is from here.

Body:
I've added some pictures with the format *.png to my drawable-directory and linked it with the layouts. But every time when I tried to build it, there appears an error

"...Crunching Crunsher ...png failed"

Following is the output of the console:

app:mergeDebugResources
AAPT out(1561599) : No Delegate set : lost message:Done
AAPT out(12956469) : No Delegate set : lost message:Done
AAPT out(20612543) : No Delegate set : lost message:Crunching             C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\bt_meeting_focused.png
AAPT out(11030156) : No Delegate set : lost message:Crunching     C:\Dev\StudioProjects\test\android\app\src\main\res\mipmap-mdpi\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:Crunching single PNG file: C:\Dev\StudioProjects\test\android\app\src\main\res\mipmap-    mdpi\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:    Output file:     C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\mipmap-mdpi-v4\ic_launcher.png
AAPT out(11030156) : No Delegate set : lost message:Done
AAPT err(11030156): libpng error: Not a PNG file
AAPT out(20612543) : No Delegate set : lost message:Crunching single PNG     file:     C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\bt_meeting_focused.png
AAPT out(20612543) : No Delegate set : lost message:    Output file:     C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\drawable\b    t_meeting_focused.png
AAPT out(20612543) : No Delegate set : lost message:Done
AAPT err(20612543): libpng error: Not a PNG file
AAPT err(1561599): libpng error: Not a PNG file
AAPT err(12956469): libpng error: Not a PNG file

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Crunching Cruncher uhr.png failed, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --    debug option to get more log output.

BUILD FAILED

Total time: 14.598 secs
Executing tasks: [clean, :app:generateDebugSources,     :app:generateDebugAndroidTestSources]

Configuration on demand is an incubating feature.
:app:clean
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportSupportV42220Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
AAPT out(14080484) : No Delegate set : lost message:Done
AAPT out(9206750) : No Delegate set : lost message:Done
AAPT out(25360025) : No Delegate set : lost message:Done
AAPT err(25360025): libpng error: Not a PNG file
AAPT err(14080484): libpng error: Not a PNG file
AAPT out(6423170) : No Delegate set : lost message:Crunching C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\anfrage_senden_.png
AAPT err(6423170): libpng error: Not a PNG file
AAPT out(6423170) : No Delegate set : lost message:Crunching single PNG file:     C:\Dev\StudioProjects\test\android\app\src\main\res\drawable\anfrage_senden_.png
AAPT out(6423170) : No Delegate set : lost message: Output file: C:\Dev\StudioProjects\test\android\app\build\intermediates\res\debug\drawable\a    nfrage_senden_.png
AAPT out(6423170) : No Delegate set : lost message:Done
AAPT err(9206750): libpng error: Not a PNG file

Process list not empty
:app:mergeDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:mergeDebugResources'.
> Crunching Cruncher uhr.png failed, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --    debug option to get more log output.

BUILD FAILED

Total time: 4.325 secs

I tried to clean the project, rebuild it, refresh the dependencies via "gradlew clean build --refresh-dependencies", nothing worked. I've checked the dependencies in the build.gradle file but nothing seems creating the error.

   apply plugin: 'com.android.application'
   android {
   compileSdkVersion 22
   buildToolsVersion "22.0.1"
   compileOptions.encoding = 'windows-1251'

   defaultConfig {
       applicationId "com.example.benutzer.test"
       minSdkVersion 16
       targetSdkVersion 22
       versionCode 1
       versionName "1.0"
   }
   buildTypes {
    release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile('proguard-android.txt'),    'proguard-rules.pro'
       }
   }
   }

   dependencies {
   compile 'com.android.support:support-v4:22.2.0'
  }

Do you've got an idea, what's the source of the error? The filepath is also not too long and everytime unter 256 signs, that also not the problem :/

Thank you in advance :)

Body:
If you're running Linux, try this:

sudo apt-get install lib32stdc++6 lib32z1

It is from here.


问:
Installing Kentico 10 at the top level alongside a preexisting site for dev until live
I want to use Kentico 10 on a live server that already has a website full of files located at the top level. I want to develop a new site with Kentico alongside this current site. I hope this Kentico site I am building can be unknown to visitors and I can build all the new pages in Kentico and, when I am ready, flip the default home page to go to the Kentico based home page and all the links will work from the top level of the domain like this:

```<code>www.example.com [home page]
www.example.com/contact
www.example.com/news
</code>```

I installed a test version on a local computer and observed this default setup:

```<code>http:/localhost/Kentico10
C:\inetpub\wwwroot\Kentico10
</code>```

With the default file being here: Kentico10/CMS/Default.aspx

I am concerned that this doesn't appear to be at the top level. Should I be or does Kentico allow me to set up my top level link structure even if the CMS is contained in those default folders?

Also, if I created a page in Kentico with the address www.example.com/news and I already had a folder in my web directory called "news" with a default or index file in it how does Kentico handle this?

答:
A few things:

Never install a site you intend to do development on in a production environment.

Set up a new website on your server in IIS and point it to your new directory holding your new Kentico install

Setup a binding for a specific URL on that website, you will have to have that DNS record pointing to your IP of your production server.

Ensure your current website already has a URL binding setup for it's current URL otherwise if it is simply bound to * then any requests will be sent to that IIS instance and your new website won't be requested.

Check out this article also on specific step by step instructions on how to setup a site in IIS:

https://technet.microsoft.com/en-us/library/cc772350(v=ws.10).aspx

Body:
I want to use Kentico 10 on a live server that already has a website full of files located at the top level. I want to develop a new site with Kentico alongside this current site. I hope this Kentico site I am building can be unknown to visitors and I can build all the new pages in Kentico and, when I am ready, flip the default home page to go to the Kentico based home page and all the links will work from the top level of the domain like this:

www.example.com [home page]
www.example.com/contact
www.example.com/news

I installed a test version on a local computer and observed this default setup:

http:/localhost/Kentico10
C:\inetpub\wwwroot\Kentico10

With the default file being here: Kentico10/CMS/Default.aspx

I am concerned that this doesn't appear to be at the top level. Should I be or does Kentico allow me to set up my top level link structure even if the CMS is contained in those default folders?

Also, if I created a page in Kentico with the address www.example.com/news and I already had a folder in my web directory called "news" with a default or index file in it how does Kentico handle this?


问:
Photo as website home page background dimensions?
hope this question is ok on stackoverflow. I want to use a photo as the background for the homepage of a website. The photo will be take up the entire page. However i don't know what resolution i should make the photo. I was thinking 1920 x 1200px so that people with 24 inch screen don't see the 'ends' of the photo. However is that big enough? I'm worried about the site looking ok on screens larger than 24 inches.

Also anyone know how i should optimize the photo so it loads as fast as possible? Thanks.

答:
For a solution that will work on most modern browsers, you will need to place the image in a div with a z-index less than the rest of your page (see: Stretch and scale CSS background)

As far as creating a 1920x1200 photo that will compress to a small size, I would recommend trying a smaller size (e.g. 960x600) and see if it looks okay on your 24-inch screen. There are many programs that will let you specify file size for your compression (e.g. FastStone Resizer) so you can experiment and see what is acceptable. In general, photos with less detail and/or color-depth will compress better.

Another problem you are going to run into is aspect ratio. Even assuming that your web-site is always opened in a full screen browser and not a window, sometimes that screen is going to be 16:9 ratio and sometimes 4:3. You could try to create an photo that has a nice 4:3 ratio "sweet-spot" in the center and adjust your div using some Javascript based on the current window aspect-ratio.


问:
Extra space at the end of UITextView
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

```<code>- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }
</code>```

setTextViewHeight

```<code>- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }
</code>```

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

答:
Use

```<code> [_descriptionTextView setTextContainerInset:UIEdgeInsetsMake(0, 0, 0, 0)];
</code>```

as can be readed in UITextView Class reference

textContainerInset  Property The inset of the text container's layout
  area within the text view's content area.

Declaration

OBJECTIVE-C
  @property(nonatomic, assign) UIEdgeInsets
  textContainerInset

Discussion

This property provides text margins for
  text laid out in the text view. By default the value of this property
  is (8, 0, 8, 0).

Hope this helps

Title: Extra space at the end of UITextView

Body:
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }

setTextViewHeight

- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

Body:
Use

 [_descriptionTextView setTextContainerInset:UIEdgeInsetsMake(0, 0, 0, 0)];

as can be readed in UITextView Class reference

textContainerInset  Property The inset of the text container's layout
  area within the text view's content area.

Declaration

OBJECTIVE-C
  @property(nonatomic, assign) UIEdgeInsets
  textContainerInset

Discussion

This property provides text margins for
  text laid out in the text view. By default the value of this property
  is (8, 0, 8, 0).

Hope this helps


问:
Set all bits in unsigned to 1 if equal, 0 if not
How can I achieve the following with the minimum number of Intel instructions and without a branch or conditional move:

```<code>unsigned compare(unsigned x
  ,unsigned y) {
    return (x == y)? ~0 : 0;
}
</code>```

This is on hot code path and I need to squeeze out the most.

答:
GCC solves this nicely, and it knows the negation trick when compiling with -O2 and up:

```<code>unsigned compare(unsigned x, unsigned y) {
    return (x == y)? ~0 : 0;
}

unsigned compare2(unsigned x, unsigned y) {
    return -static_cast<unsigned>(x == y);
}

compare(unsigned int, unsigned int):
        xor     eax, eax
        cmp     edi, esi
        sete    al
        neg     eax
        ret
compare2(unsigned int, unsigned int):
        xor     eax, eax
        cmp     edi, esi
        sete    al
        neg     eax
        ret
</code>```

Visual Studio generates the following code:

```<code>compare2, COMDAT PROC
        xor      eax, eax
        or       r8d, -1                    ; ffffffffH
        cmp      ecx, edx
        cmove    eax, r8d
        ret      0
compare2 ENDP
compare, COMDAT PROC
        xor      eax, eax
        cmp      ecx, edx
        setne    al
        dec      eax
        ret      0
compare ENDP
</code>```

Here it seems the first version avoids the conditional move (note that the order of the funtions was changed).

To view other compiler's solution try pasting the code to
https://gcc.godbolt.org/ (add optimization flags).

Interestingly the first version produces shorter code on icc. Basically you have to measure actual performance with your compiler for each version and choose the best.

Also I would not be so sure a conditional register move is slower than other operations.

I assume you wrote the function just to show us the relevant part of the code, but a function like this would be an ideal candidate for inlining, potentially allowing the compiler to perform much more useful optimizations that involve the code where this is actually used. This may allow the compiler/CPU to parallelize this computation with other code, or merge some operations.

So, assuming this is indeed a function in your code, write it with the inline keyword and put it in a header.

Body:
How can I achieve the following with the minimum number of Intel instructions and without a branch or conditional move:

unsigned compare(unsigned x
  ,unsigned y) {
    return (x == y)? ~0 : 0;
}

This is on hot code path and I need to squeeze out the most.

Body:
GCC solves this nicely, and it knows the negation trick when compiling with -O2 and up:

unsigned compare(unsigned x, unsigned y) {
    return (x == y)? ~0 : 0;
}

unsigned compare2(unsigned x, unsigned y) {
    return -static_cast<unsigned>(x == y);
}

compare(unsigned int, unsigned int):
        xor     eax, eax
        cmp     edi, esi
        sete    al
        neg     eax
        ret
compare2(unsigned int, unsigned int):
        xor     eax, eax
        cmp     edi, esi
        sete    al
        neg     eax
        ret

Visual Studio generates the following code:

compare2, COMDAT PROC
        xor      eax, eax
        or       r8d, -1                    ; ffffffffH
        cmp      ecx, edx
        cmove    eax, r8d
        ret      0
compare2 ENDP
compare, COMDAT PROC
        xor      eax, eax
        cmp      ecx, edx
        setne    al
        dec      eax
        ret      0
compare ENDP

Here it seems the first version avoids the conditional move (note that the order of the funtions was changed).

To view other compiler's solution try pasting the code to
https://gcc.godbolt.org/ (add optimization flags).

Interestingly the first version produces shorter code on icc. Basically you have to measure actual performance with your compiler for each version and choose the best.

Also I would not be so sure a conditional register move is slower than other operations.

I assume you wrote the function just to show us the relevant part of the code, but a function like this would be an ideal candidate for inlining, potentially allowing the compiler to perform much more useful optimizations that involve the code where this is actually used. This may allow the compiler/CPU to parallelize this computation with other code, or merge some operations.

So, assuming this is indeed a function in your code, write it with the inline keyword and put it in a header.


问:
javascript counting duplicates in array
Please consider this JS function

I have seen this similar question but couldn't understand.

```<code>function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)
</code>```

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.

答: The array value hasn't been set yet, so you can't increment undefined. The first time it hits a value, the "|| 1" portion sets the initial value to 1. If it hits that same index again (which is no longer undefined and now set to 1), it executes the left side instead and increments the pre-existing value by 1. </p>

Title: javascript counting duplicates in array

Body:
Please consider this JS function

I have seen this similar question but couldn't understand.

function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.


问:
How do I access an API URL in Java (rather than python)?
How do I do this in Java?

```<code>import requests

params = {
  "api_key": "asdfg_54321",
  "format": "json"
}
r = requests.get('https://www.parsehub.com/api/v2/projects/qwertyuiop/last_ready_run/data', params=params)
print(r.text)
</code>```

I need to access an online API in the form of a JSON file, and I can do so in Python, but I need the data for an android studio app, so I have to figure out how to access a URL with API key as a permission in Java instead.

答:
Make sure to resolve ${PROJECT_TOKEN}, ${API_KEY} and ${FORMAT} variables</p>

```<code>public static void getResultOfLastReadyRun() throws IOException {
    URL url = new URL("https://www.parsehub.com/api/v2/projects/${PROJECT_TOKEN}/last_ready_run/data?api_key=${API_KEY}&format=${FORMAT}");

    try(Scanner sc = new Scanner(new GZIPInputStream(url.openStream()))) {
        while (sc.hasNext()) {
            System.out.println(sc.nextLine());
        }
    }
}
</code>```

Body:
How do I do this in Java?

import requests

params = {
  "api_key": "asdfg_54321",
  "format": "json"
}
r = requests.get('https://www.parsehub.com/api/v2/projects/qwertyuiop/last_ready_run/data', params=params)
print(r.text)

I need to access an online API in the form of a JSON file, and I can do so in Python, but I need the data for an android studio app, so I have to figure out how to access a URL with API key as a permission in Java instead.

Body:
Make sure to resolve ${PROJECT_TOKEN}, ${API_KEY} and ${FORMAT} variables

public static void getResultOfLastReadyRun() throws IOException {
    URL url = new URL("https://www.parsehub.com/api/v2/projects/${PROJECT_TOKEN}/last_ready_run/data?api_key=${API_KEY}&format=${FORMAT}");

    try(Scanner sc = new Scanner(new GZIPInputStream(url.openStream()))) {
        while (sc.hasNext()) {
            System.out.println(sc.nextLine());
        }
    }
}


问:
log probability plot in R?
Does anyone know how to create log probability plot like this one in R where the x-axis is probability and y-axis is in log-scale. I read and downloaded the package heR.Misc package but I don't know how to use it.
!

答:
Here is an example using base R, simplified a bit from this post: (https://stat.ethz.ch/pipermail/r-help/2004-February/045370.html).

```<code>## Make some data
y <- rnorm(n=175, mean=100, sd=75)
y <- sort(y)
pct <- 1:length(y)/(length(y)+1)

## For x ticks
probs <- c(0.0001, 0.001, 0.01, 0.1, 0.3, 0.5, 0.7,
           0.9, 0.99, 0.999, 0.9999)
x.vals <- qnorm(probs)

## Plotting area
xs <- c(-4, 4)
ys <- seq(-2,4)
par(xaxs="i", yaxs="i")
plot(NA, NA, xlim=c(xs[1], xs[2]), ylim=c(min(ys), max(ys)),
     axes=FALSE, xlab=NA, ylab=NA)

## X Axis
axis(side=1, at=x.vals, labels=FALSE, tck=-0.01)

text(x=x.vals, y=rep(min(ys)-0.35, length(x.vals)),
     labels=probs*100, xpd=TRUE, srt=325, font=2)

## Y Axis
axis(side=2, at=ys, labels=FALSE)
text(y=ys, x=rep(xs[1]-.08, length(ys)),
     labels= as.character(10^ys), xpd = NA, font=2,
     pos=2)

for (i in ys){
    axis(side=2, at=log10(seq(2,9))+ i,
         labels=NA, tck = -0.01)
}

## Grid lines and box
abline(h=ys, col="grey80", lty=2)
abline(v=qnorm(probs), col="grey80", lty=2)
box()

## Plot Data
lines(x=qnorm(pct), y=log10(y), col="blue")
</code>```

Title: log probability plot in R?

Body:
Here is an example using base R, simplified a bit from this post: (https://stat.ethz.ch/pipermail/r-help/2004-February/045370.html).

## Make some data
y <- rnorm(n=175, mean=100, sd=75)
y <- sort(y)
pct <- 1:length(y)/(length(y)+1)

## For x ticks
probs <- c(0.0001, 0.001, 0.01, 0.1, 0.3, 0.5, 0.7,
           0.9, 0.99, 0.999, 0.9999)
x.vals <- qnorm(probs)

## Plotting area
xs <- c(-4, 4)
ys <- seq(-2,4)
par(xaxs="i", yaxs="i")
plot(NA, NA, xlim=c(xs[1], xs[2]), ylim=c(min(ys), max(ys)),
     axes=FALSE, xlab=NA, ylab=NA)

## X Axis
axis(side=1, at=x.vals, labels=FALSE, tck=-0.01)

text(x=x.vals, y=rep(min(ys)-0.35, length(x.vals)),
     labels=probs*100, xpd=TRUE, srt=325, font=2)

## Y Axis
axis(side=2, at=ys, labels=FALSE)
text(y=ys, x=rep(xs[1]-.08, length(ys)),
     labels= as.character(10^ys), xpd = NA, font=2,
     pos=2)

for (i in ys){
    axis(side=2, at=log10(seq(2,9))+ i,
         labels=NA, tck = -0.01)
}

## Grid lines and box
abline(h=ys, col="grey80", lty=2)
abline(v=qnorm(probs), col="grey80", lty=2)
box()

## Plot Data
lines(x=qnorm(pct), y=log10(y), col="blue")


问:
Cell appears blank in the UITableView
I am making a view controller with tableView for presenting individual news cards.  I want to load cells once and for all (without reusing it as usual). So I do this:

```<code>    tableView.register(UINib(nibName: "RatingNewsCell", bundle: nil), forCellReuseIdentifier: "RatingNewsCell")
    tableView.register(UINib(nibName: "PromoNewsCell", bundle: nil), forCellReuseIdentifier: "PromoNewsCell")

    var cells = [UITableViewCell]()

    let rating = RatingNewsCell()
    rating.delegate = self
    cells.append(rating)

    etc...

    self.items = cells
</code>```

Cells are loaded like this:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    return items[indexPath.section]
}
</code>```

Cell code looks like this:

```<code>class RatingNewsCell: UITableViewCell
{
    var delegate: RatingNewsCellDelegate?

    @IBOutlet weak var shopNameLabel: UILabel!
    @IBOutlet weak var bouquetImageView: RoundImageView!
    @IBOutlet weak var floristImageView: RoundImageView!
    @IBOutlet weak var ratingControl: RatingPicker!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: "RatingNewsCell")
    }

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()

        ratingControl.setSelected(newIndex: 0)
    }
}
</code>```

In the result I've got a table view, but cell just appears blank:

Any ideas?

答:
I suggest to refactor your code to use tableView's datasource method though you are only using static cells. </p>

```<code>enum Section: Int {
    case RatingNews
    case PromoNews
    static var count: Int { return Section.PromoNews.rawValue + 1 }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return Section.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let section = Section(rawValue: indexPath.section)!
    switch section {
    case .PromoNews:
        let cell = tableView.dequeueReusableCell(withIdentifier: "RatingNewsCell", for: indexPath) as! RatingNewsCell
        return cell
    case .RatingNews:
        let cell = tableView.dequeueReusableCell(withIdentifier: "PromoNewsCell", for: indexPath) as! PromoNewsCell
        return cell
    }
}
</code>```

Title: Cell appears blank in the UITableView

Body:
I am making a view controller with tableView for presenting individual news cards.  I want to load cells once and for all (without reusing it as usual). So I do this:

    tableView.register(UINib(nibName: "RatingNewsCell", bundle: nil), forCellReuseIdentifier: "RatingNewsCell")
    tableView.register(UINib(nibName: "PromoNewsCell", bundle: nil), forCellReuseIdentifier: "PromoNewsCell")

    var cells = [UITableViewCell]()

    let rating = RatingNewsCell()
    rating.delegate = self
    cells.append(rating)

    etc...

    self.items = cells

Cells are loaded like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    return items[indexPath.section]
}

Cell code looks like this:

class RatingNewsCell: UITableViewCell
{
    var delegate: RatingNewsCellDelegate?

    @IBOutlet weak var shopNameLabel: UILabel!
    @IBOutlet weak var bouquetImageView: RoundImageView!
    @IBOutlet weak var floristImageView: RoundImageView!
    @IBOutlet weak var ratingControl: RatingPicker!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: "RatingNewsCell")
    }

    required init?(coder decoder: NSCoder)
    {
        super.init(coder: decoder)
    }

    override func awakeFromNib()
    {
        super.awakeFromNib()

        ratingControl.setSelected(newIndex: 0)
    }
}

In the result I've got a table view, but cell just appears blank:

Any ideas?

Body:
I suggest to refactor your code to use tableView's datasource method though you are only using static cells.

enum Section: Int {
    case RatingNews
    case PromoNews
    static var count: Int { return Section.PromoNews.rawValue + 1 }
}

func numberOfSections(in tableView: UITableView) -> Int {
    return Section.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let section = Section(rawValue: indexPath.section)!
    switch section {
    case .PromoNews:
        let cell = tableView.dequeueReusableCell(withIdentifier: "RatingNewsCell", for: indexPath) as! RatingNewsCell
        return cell
    case .RatingNews:
        let cell = tableView.dequeueReusableCell(withIdentifier: "PromoNewsCell", for: indexPath) as! PromoNewsCell
        return cell
    }
}


问:
what regular expression can extract data I need?
I have a string

```<code>url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'
</code>```

I like to extract the number 528341191030 between the first two \u. I tried this,

```<code>m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)
</code>```

But it doesn't work. What is wrong with my solution?

答:
Better way is to parseurl and get the query string values

```<code>url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'
import urllib.parse as urlparse
print ( urlparse.parse_qs(urlparse.urlparse(url).query) )
print ( urlparse.parse_qs(urlparse.urlparse(url).query)['id'] )
</code>```

Output:

```<code>{'id': ['528341191030'], 'ns': ['1'], 'abbucket': ['0']}
['528341191030']
</code>```

Body:
I have a string

url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'

I like to extract the number 528341191030 between the first two \u. I tried this,

m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)

But it doesn't work. What is wrong with my solution?

Body:
Better way is to parseurl and get the query string values

url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'
import urllib.parse as urlparse
print ( urlparse.parse_qs(urlparse.urlparse(url).query) )
print ( urlparse.parse_qs(urlparse.urlparse(url).query)['id'] )

Output:

{'id': ['528341191030'], 'ns': ['1'], 'abbucket': ['0']}
['528341191030']


Title: transform a matrix inserting zero row

Body:
I have got a matrix, called crash.data. I would like to create a matrix which is exactly the same but with rows with zeros in between, as in the code below

> head(crash.data)
            [,1]       [,2]       [,3]
[1,]  0.14449657 -0.2289661 -0.9065017
[2,]  0.06079472 -0.1801571 -0.9796568
[3,] -0.04159815 -0.2442845 -0.9071650
[4,] -0.01820570 -0.1778194 -0.9765629
[5,] -0.06200437 -0.2801673 -0.9325789
[6,]  0.09424269 -0.2143995 -0.9233422
> graph<-matrix(0,ncol=3,nrow = 4000)
> for (i in seq(2,4000,2)){graph[i,]<-as.matrix(crash.data)[i/2,]}
> head(graph)
            [,1]       [,2]       [,3]
[1,]  0.00000000  0.0000000  0.0000000
[2,]  0.14449657 -0.2289661 -0.9065017
[3,]  0.00000000  0.0000000  0.0000000
[4,]  0.06079472 -0.1801571 -0.9796568
[5,]  0.00000000  0.0000000  0.0000000
[6,] -0.04159815 -0.2442845 -0.9071650

In order to do so, I am using a for cycle. Is there a nicer and faster way, ideally without using a for cycle?

Thanks

Body:
Another alternative is to construct a matrix of 0s with the correct dimension and then fill it in.

# matrix of 0s, double the number of rows
m2 <- matrix(0, nrow=2*nrow(m1), ncol=ncol(m1))
# fill in every other row using seq to index the rows
m2[seq(2, nrow(m2), 2),] <- m1

with db's dataset, this returns

m2
            [,1]        [,2]       [,3]
 [1,]  0.0000000  0.00000000  0.0000000
 [2,]  1.3709584  1.51152200 -1.3888607
 [3,]  0.0000000  0.00000000  0.0000000
 [4,] -0.5646982 -0.09465904 -0.2787888
 [5,]  0.0000000  0.00000000  0.0000000
 [6,]  0.3631284  2.01842371 -0.1333213
 [7,]  0.0000000  0.00000000  0.0000000
 [8,]  0.6328626 -0.06271410  0.6359504
 [9,]  0.0000000  0.00000000  0.0000000
[10,]  0.4042683  1.30486965 -0.2842529
[11,]  0.0000000  0.00000000  0.0000000
[12,] -0.1061245  2.28664539 -2.6564554


问:
adding some jquery script to Magento page
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

```<code>$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
</code>```

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

答:
expanding on Alan's excellent summary. If you just want to add the file to one specific page you can use the following snippet in the Layout Update XML field:

```<code><reference name="head">
    <action method="addJs"><script>path/to/my/file.js</script></action>
</reference>
</code>```

and place the file into
http://example.com/js/path/to/my/file.js

or if you want it residing in your skin folder use

```<code><reference name="head">
    <action method="addItem"><type>skin_js</type><name>js/file.js</name><params/></action>
</reference>
</code>```

with the expected location
http://example.com/skin/frontend/base/default/js/file.js
change base and default according to the package and theme you are using

You can also use the above snippet in any other layout/?.xml file just place it within the layout handle you want to address. For example to place it in all cms pages in cms.xml you'll find

```<code><cms_page>
 ....
</cms_page>
</code>```

and change it to

```<code><cms_page>
    ...
    <reference name="head">
        <action method="addJs"><script>path/to/my/file.js</script></action>
    </reference>
</cms_page>
</code>```

and another easy one for adding a snippet of javascript to all pages
go to System > Configuration > Design > Footer > Miscellaneous HTML

Further reading:

Using local.xml for theme customisations

Demystifying Magento’s Layout XML

Body:
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

Body:
expanding on Alan's excellent summary. If you just want to add the file to one specific page you can use the following snippet in the Layout Update XML field:

<reference name="head">
    <action method="addJs"><script>path/to/my/file.js</script></action>
</reference>

and place the file into
http://example.com/js/path/to/my/file.js

or if you want it residing in your skin folder use

<reference name="head">
    <action method="addItem"><type>skin_js</type><name>js/file.js</name><params/></action>
</reference>

with the expected location
http://example.com/skin/frontend/base/default/js/file.js
change base and default according to the package and theme you are using

You can also use the above snippet in any other layout/?.xml file just place it within the layout handle you want to address. For example to place it in all cms pages in cms.xml you'll find

<cms_page>
 ....
</cms_page>

and change it to

<cms_page>
    ...
    <reference name="head">
        <action method="addJs"><script>path/to/my/file.js</script></action>
    </reference>
</cms_page>

and another easy one for adding a snippet of javascript to all pages
go to System > Configuration > Design > Footer > Miscellaneous HTML

Further reading:

Using local.xml for theme customisations

Demystifying Magento’s Layout XML


答:
@Oleksiy's answer is great, but didn't fully work for my requirements. Within a session, if multiple nulls are observed, all are filled with the first non-null for the session. I needed the last non-null value to propagate forward.

The following tweak worked for my use case:

```<code>def fill_forward(df, id_column, key_column, fill_column):

    # Fill null's with last *non null* value in the window
    ff = df.withColumn(
        'fill_fwd',
        func.last(fill_column, True) # True: fill with last non-null
        .over(
            Window.partitionBy(id_column)
            .orderBy(key_column)
            .rowsBetween(-sys.maxsize, 0))
        )

    # Drop the old column and rename the new column
    ff_out = ff.drop(fill_column).withColumnRenamed('fill_fwd', fill_column)

    return ff_out
</code>```

Title: Fill in null with previously known good value with pyspark

Body:
Is there a way to replace null values in pyspark dataframe with the last valid value? There is addtional timestamp and session columns if you think you need them for windows partitioning and ordering. More specifically, I'd like to achieve the following conversion:

+---------+-----------+-----------+      +---------+-----------+-----------+
| session | timestamp |         id|      | session | timestamp |         id|
+---------+-----------+-----------+      +---------+-----------+-----------+
|        1|          1|       null|      |        1|          1|       null|
|        1|          2|        109|      |        1|          2|        109|
|        1|          3|       null|      |        1|          3|        109|
|        1|          4|       null|      |        1|          4|        109|
|        1|          5|        109| =>   |        1|          5|        109|
|        1|          6|       null|      |        1|          6|        109|
|        1|          7|        110|      |        1|          7|        110|
|        1|          8|       null|      |        1|          8|        110|
|        1|          9|       null|      |        1|          9|        110|
|        1|         10|       null|      |        1|         10|        110|
+---------+-----------+-----------+      +---------+-----------+-----------+

Body:
@Oleksiy's answer is great, but didn't fully work for my requirements. Within a session, if multiple nulls are observed, all are filled with the first non-null for the session. I needed the last non-null value to propagate forward.

The following tweak worked for my use case:

def fill_forward(df, id_column, key_column, fill_column):

    # Fill null's with last *non null* value in the window
    ff = df.withColumn(
        'fill_fwd',
        func.last(fill_column, True) # True: fill with last non-null
        .over(
            Window.partitionBy(id_column)
            .orderBy(key_column)
            .rowsBetween(-sys.maxsize, 0))
        )

    # Drop the old column and rename the new column
    ff_out = ff.drop(fill_column).withColumnRenamed('fill_fwd', fill_column)

    return ff_out


问:
Unique Index on Array in MongoDB
Say we have a collection of documents similar to this:

```<code>{
  foo: "Bar",
  foos: [1, 2, 3]
}
</code>```

I would like to define a unique index such that no document identical to this one can be inserted into the database.

```<code>db.stuffs.ensureIndex({ foos: 1 }, { unique: true })
</code>```

Seems to block any document containing a foos array with any intersection, eg. if the document above was already in the database, then

```<code>{
    foo: "Bar",
    foos: [ 1 ]
}
</code>```

Would also be blocked.

```<code>> db.stuffs.ensureIndex({ foos: 1 }, { unique: true })
> db.stuffs.insert({ foo: "Bar", foos: [ 1, 2, 3 ]})
> db.stuffs.insert({ foo: "Bar", foos: [ 1 ]})
E11000 duplicate key error index: test.stuffs.$foos_1  dup key: { : 1.0 }
</code>```

I would like to be able to make insertions of [ 1, 2 ], [ 2, 1 ], [ 1, 3 ], etc. but not two [ 1, 2 ]

答:
Please refer to this question. Explains why Unique Index won't work in this case.

Unique index in MongoDB

To index a field that holds an array value, MongoDB creates an index
  key for each element in the array.

Title: Unique Index on Array in MongoDB

Body:
Say we have a collection of documents similar to this:

{
  foo: "Bar",
  foos: [1, 2, 3]
}

I would like to define a unique index such that no document identical to this one can be inserted into the database.

db.stuffs.ensureIndex({ foos: 1 }, { unique: true })

Seems to block any document containing a foos array with any intersection, eg. if the document above was already in the database, then

{
    foo: "Bar",
    foos: [ 1 ]
}

Would also be blocked.

> db.stuffs.ensureIndex({ foos: 1 }, { unique: true })
> db.stuffs.insert({ foo: "Bar", foos: [ 1, 2, 3 ]})
> db.stuffs.insert({ foo: "Bar", foos: [ 1 ]})
E11000 duplicate key error index: test.stuffs.$foos_1  dup key: { : 1.0 }

I would like to be able to make insertions of [ 1, 2 ], [ 2, 1 ], [ 1, 3 ], etc. but not two [ 1, 2 ]


问:
UWP UserControl + ContentControl
I'm trying to understand how content controls work and how I can place one inside a user control I'm constructing. From what I understand, my user control should have an object dependency property and then I should be able to add a content control to my user control and bind it to the dependency property.

I've tried variations of the User Control XAML, including bypassing the ScrollViewer element and placing the ContentControl inside the base grid of the User Control XAML.

How do I place this image inside this control? And more broadly how do I place any XAML inside a User Control?

User Control CS

```<code>namespace CoreProject.UserControls
{
public sealed partial class ZoomControl : UserControl
{
    public ZoomControl()
    {
        this.InitializeComponent();
    }

    #region Properties
    public static readonly DependencyProperty ZoomContentProperty =
    DependencyProperty.Register("ZoomContent", typeof(object), typeof(ZoomControl), new PropertyMetadata(null));
    public object ZoomContent
    {
        get { return (object)GetValue(ZoomContentProperty); }
        set { SetValue(ZoomContentProperty, value); }
    }
    #endregion

    public void UnZoom()
    {
        // unzoom
        ImageScrollViewer.Visibility = Visibility.Visible;
        var period = TimeSpan.FromMilliseconds(10);
        Windows.System.Threading.ThreadPoolTimer.CreateTimer(async (source) =>
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ImageScrollViewer.ChangeView(0.0, 0.0, 0.8F, true);
                ImageScrollViewer.Visibility = Visibility.Collapsed;
            });
        }, period);
    }

    public void ZoomToPosition(double zoomOriginX, double zoomOriginY, float zoomFactor, bool disableAnimations)
    {
        ImageScrollViewer.Visibility = Visibility.Visible;
        var period = TimeSpan.FromMilliseconds(10);
        Windows.System.Threading.ThreadPoolTimer.CreateTimer(async (source) =>
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ImageScrollViewer.ChangeView(zoomOriginX, zoomOriginY, 1.2F, disableAnimations);
            });
        }, period);
    }
}
</code>```

}

User Control Xaml

```<code><Grid>
    <ScrollViewer x:Name="ImageScrollViewer"
                  ZoomMode="Enabled"
                  Visibility="Collapsed"
                  HorizontalContentAlignment="Center"
                  VerticalContentAlignment="Center"
                  Background="Transparent"
                  HorizontalScrollMode="Enabled"
                  VerticalScrollMode="Enabled"
                  HorizontalScrollBarVisibility="Hidden"
                  VerticalScrollBarVisibility="Hidden">
        <Grid>
            <!-- HERE IS WHERE I WANT TO PLACE MY CONTENT -->
            <ContentControl Content="{Binding ZoomContent, ElementName=zoomContent}" />
        </Grid>
    </ScrollViewer>
</Grid>
</code>```

User Control Usage

```<code><usercontrols:ZoomControl x:Name="ZoomControl">
    <usercontrols:ZoomControl.ZoomContent>
        <!-- THIS IS HOW I WANT TO ADD MY CONTENT, SIMPLY PLACE XAML ELEMENT -->
        <Image Source="/Assets/colocationDataCenterData.jpg" />
    </usercontrols:ZoomControl.ZoomContent>
</usercontrols:ZoomControl>
</code>```

答:
```<code> <Grid>
     <!-- HERE IS WHERE I WANT TO PLACE MY CONTENT -->
     <ContentControl Content="{x:Bind ZoomContent, Mode=OneWay}" />
 </Grid>
</code>```

You can also use x:Bind instead - it takes the Binding context as the class itself (your UserControl), so you can straight bind.

If you want classical binding to work you need to name and userControl INSIDE the usercontrol itself. (BTW, typically you'd do this as a TEMPLATED control instead and use templatebindings)

```<code><UserControl x:Name="zoomContent">
    <Grid>
         <ScrollViewer x:Name="ImageScrollViewer"
              ZoomMode="Enabled"
              Visibility="Collapsed"
              HorizontalContentAlignment="Center"
              VerticalContentAlignment="Center"
              Background="Transparent"
              HorizontalScrollMode="Enabled"
              VerticalScrollMode="Enabled"
              HorizontalScrollBarVisibility="Hidden"
              VerticalScrollBarVisibility="Hidden">
         <Grid>
             <!-- HERE IS WHERE I WANT TO PLACE MY CONTENT -->
             <ContentControl Content="{Binding ZoomContent, ElementName=zoomContent}" />
         </Grid>
     </ScrollViewer>
  </Grid>
</UserControl>
</code>```

Title: UWP UserControl + ContentControl

Body:
I'm trying to understand how content controls work and how I can place one inside a user control I'm constructing. From what I understand, my user control should have an object dependency property and then I should be able to add a content control to my user control and bind it to the dependency property.

I've tried variations of the User Control XAML, including bypassing the ScrollViewer element and placing the ContentControl inside the base grid of the User Control XAML.

How do I place this image inside this control? And more broadly how do I place any XAML inside a User Control?

User Control CS

namespace CoreProject.UserControls
{
public sealed partial class ZoomControl : UserControl
{
    public ZoomControl()
    {
        this.InitializeComponent();
    }

    #region Properties
    public static readonly DependencyProperty ZoomContentProperty =
    DependencyProperty.Register("ZoomContent", typeof(object), typeof(ZoomControl), new PropertyMetadata(null));
    public object ZoomContent
    {
        get { return (object)GetValue(ZoomContentProperty); }
        set { SetValue(ZoomContentProperty, value); }
    }
    #endregion

    public void UnZoom()
    {
        // unzoom
        ImageScrollViewer.Visibility = Visibility.Visible;
        var period = TimeSpan.FromMilliseconds(10);
        Windows.System.Threading.ThreadPoolTimer.CreateTimer(async (source) =>
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ImageScrollViewer.ChangeView(0.0, 0.0, 0.8F, true);
                ImageScrollViewer.Visibility = Visibility.Collapsed;
            });
        }, period);
    }

    public void ZoomToPosition(double zoomOriginX, double zoomOriginY, float zoomFactor, bool disableAnimations)
    {
        ImageScrollViewer.Visibility = Visibility.Visible;
        var period = TimeSpan.FromMilliseconds(10);
        Windows.System.Threading.ThreadPoolTimer.CreateTimer(async (source) =>
        {
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ImageScrollViewer.ChangeView(zoomOriginX, zoomOriginY, 1.2F, disableAnimations);
            });
        }, period);
    }
}

}

User Control Xaml

<Grid>
    <ScrollViewer x:Name="ImageScrollViewer"
                  ZoomMode="Enabled"
                  Visibility="Collapsed"
                  HorizontalContentAlignment="Center"
                  VerticalContentAlignment="Center"
                  Background="Transparent"
                  HorizontalScrollMode="Enabled"
                  VerticalScrollMode="Enabled"
                  HorizontalScrollBarVisibility="Hidden"
                  VerticalScrollBarVisibility="Hidden">
        <Grid>

            <ContentControl Content="{Binding ZoomContent, ElementName=zoomContent}" />
        </Grid>
    </ScrollViewer>
</Grid>

User Control Usage

<usercontrols:ZoomControl x:Name="ZoomControl">
    <usercontrols:ZoomControl.ZoomContent>

        <Image Source="/Assets/colocationDataCenterData.jpg" />
    </usercontrols:ZoomControl.ZoomContent>
</usercontrols:ZoomControl>

Body:
 <Grid>
     <!-- HERE IS WHERE I WANT TO PLACE MY CONTENT -->
     <ContentControl Content="{x:Bind ZoomContent, Mode=OneWay}" />
 </Grid>

You can also use x:Bind instead - it takes the Binding context as the class itself (your UserControl), so you can straight bind.

If you want classical binding to work you need to name and userControl INSIDE the usercontrol itself. (BTW, typically you'd do this as a TEMPLATED control instead and use templatebindings)

<UserControl x:Name="zoomContent">
    <Grid>
         <ScrollViewer x:Name="ImageScrollViewer"
              ZoomMode="Enabled"
              Visibility="Collapsed"
              HorizontalContentAlignment="Center"
              VerticalContentAlignment="Center"
              Background="Transparent"
              HorizontalScrollMode="Enabled"
              VerticalScrollMode="Enabled"
              HorizontalScrollBarVisibility="Hidden"
              VerticalScrollBarVisibility="Hidden">
         <Grid>
             <!-- HERE IS WHERE I WANT TO PLACE MY CONTENT -->
             <ContentControl Content="{Binding ZoomContent, ElementName=zoomContent}" />
         </Grid>
     </ScrollViewer>
  </Grid>
</UserControl>


问:
Tibco Businessworks Date Format
I'm trying to format a date in Tibco Businessworks 6.2.2 in the following format:

```<code>06-AUG-2015 12:11 AM
</code>```

I've found the picture string on several websites for xpath that, according to those who use them, will format the date like this. I've not been able to figure out how to only get the AUG instead of AUGUST without JUNE and JULY showing up as JUN and JUL.

Here is the xpath I'm using:

```<code>format-dateTime(current-dateTime(), '[D01]-[MNn, *-3]-[Y0001] [h01]:[m01] [PN]')
</code>```

Here is the output I'm getting:

```<code>06-August-2015 12:11 AM
</code>```

Any and all information is greatly appreciated.

答:
I used this function. (BW 5.12)

```<code>tib:format-dateTime('dd-MMM-yyyy hh:mm a', current-dateTime())
</code>```

Out

06-Jul-2017 11:34 AM

Title: Tibco Businessworks Date Format

Body:
I'm trying to format a date in Tibco Businessworks 6.2.2 in the following format:

06-AUG-2015 12:11 AM

I've found the picture string on several websites for xpath that, according to those who use them, will format the date like this. I've not been able to figure out how to only get the AUG instead of AUGUST without JUNE and JULY showing up as JUN and JUL.

Here is the xpath I'm using:

format-dateTime(current-dateTime(), '[D01]-[MNn, *-3]-[Y0001] [h01]:[m01] [PN]')

Here is the output I'm getting:

06-August-2015 12:11 AM

Any and all information is greatly appreciated.

Body:
I used this function. (BW 5.12)

tib:format-dateTime('dd-MMM-yyyy hh:mm a', current-dateTime())

Out

06-Jul-2017 11:34 AM


问:
Cron compress files
I would like to introduce a Cron tak that will 'gzip' files with the following rule:

Locate files in a folder name '/log' (can be located anywhere in the filesystem) and

gzip files, older than 2 days, that have './log' in the file name handle

I have written a the script below - which does not work - am I close? What is required to make it work? Thanks.

/usr/bin/find ./logs -mtime +2 -name "*.log*"|xargs gzip

答: The -name argument takes a glob.  Your command would only match files literally named .log.  Try -name "*.log".

Title: Cron compress files


问:
How do I disambiguate traits in Rust?
I want to use the write_fmt method on two different types of object:

```<code>use std::fmt::Write;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}
</code>```

I get an error when using Write because they are both named the same:

error[E0252]: a trait named `Write` has already been imported in this module
 --> src/main.rs:8:5
  |
7 | use std::fmt::Write;
  |     --------------- previous import of `Write` here
8 | use std::io::Write;
  |     ^^^^^^^^^^^^^^ `Write` already imported
      a.write_fmt(format_args!("hello"));
      b.write_fmt(format_args!("hello"));
```

<p>Or I get an error saying the trait is not available:</p>

<pre class="lang-none prettyprint-override"><code>error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
  --> src/main.rs:76:4
   |
76 |    b.write_fmt(format_args!("hello"));
   |      ^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use std::io::Write;`
</code>```

答:
You can call the trait method directly:

```<code>fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    std::fmt::Write::write_fmt(&mut a, format_args!("hello"));
    std::io::Write::write_fmt(&mut b, format_args!("hello"));
}
</code>```

You can also choose to only import the trait in a smaller scope:

```<code>fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    {
        use std::fmt::Write;
        a.write_fmt(format_args!("hello"));
    }

    {
        use std::io::Write;
        b.write_fmt(format_args!("hello"));
    }
}
</code>```

Note that if you choose to use a smaller scope, you can also use the write! macro directly:

```<code>fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    {
        use std::fmt::Write;
        write!(a, "hello");
    }

    {
        use std::io::Write;
        write!(b, "hello");
    }
}
</code>```

In either case, you should handle the Result return value.

See also:

How to call a method when a trait and struct use the same name?

Title: How do I disambiguate traits in Rust?

Body:
I want to use the write_fmt method on two different types of object:

use std::fmt::Write;
use std::io::Write;

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    a.write_fmt(format_args!("hello"));
    b.write_fmt(format_args!("hello"));
}

I get an error when using Write because they are both named the same:

error[E0252]: a trait named `Write` has already been imported in this module
 --> src/main.rs:8:5
  |
7 | use std::fmt::Write;
  |     --------------- previous import of `Write` here
8 | use std::io::Write;
  |     ^^^^^^^^^^^^^^ `Write` already imported
      a.write_fmt(format_args!("hello"));
      b.write_fmt(format_args!("hello"));

Or I get an error saying the trait is not available:

error[E0599]: no method named `write_fmt` found for type `std::fs::File` in the current scope
  --> src/main.rs:76:4
   |
76 |    b.write_fmt(format_args!("hello"));
   |      ^^^^^^^^^
   |
   = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
   = help: candidate #1: `use std::io::Write;`

Body:
You can call the trait method directly:

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    std::fmt::Write::write_fmt(&mut a, format_args!("hello"));
    std::io::Write::write_fmt(&mut b, format_args!("hello"));
}

You can also choose to only import the trait in a smaller scope:

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    {
        use std::fmt::Write;
        a.write_fmt(format_args!("hello"));
    }

    {
        use std::io::Write;
        b.write_fmt(format_args!("hello"));
    }
}

Note that if you choose to use a smaller scope, you can also use the write! macro directly:

fn main() {
    let mut a = String::new();
    let mut b = std::fs::File::create("test").unwrap();

    {
        use std::fmt::Write;
        write!(a, "hello");
    }

    {
        use std::io::Write;
        write!(b, "hello");
    }
}

In either case, you should handle the Result return value.

See also:

How to call a method when a trait and struct use the same name?