问:
CSS animation shorthand property syntax order

If the order of values for the CSS animation shorthand property are as such : animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction] [fill-mode] [play-state]; , how does the below CSS make sense?

 animation: coffee-labels-active 0.5s 0.5s cubic-bezier(0.645, 0.045, 0.355, 1) both;

It appears that [delay] is coming before [timing-function] and that the fill mode is both.
Are we able to play around with the order of these values?

答:
Actually, it seems that the animation shorthand property doesn't follow a strict order as many of the other CSS syntaxes do. Here's an example:

For the class element we have got the timing function, followed by delay.

For the class element2 we have got delay followed by timing function.

For the class element3, I randomized all of the animation properties and still the output is same.

Hence, we can conclude what we assumed.

.element {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch 1.5s ease-out 0s alternate infinite none running;
}

.element2 {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch 1.5s 0s ease-out alternate infinite none running;
}

.element3 {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch ease-out 1.5s  none running 0s  alternate infinite ;
}

@keyframes stretch {
  0% {
    transform: scale(.3);
    background-color: red;
    border-radius: 100%;
  }
  50% {
    background-color: orange;
  }
  100% {
    transform: scale(1);
    background-color: yellow;
  }
}

body,
html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="element"></div>

<div class="element2"></div>

<div class="element3"></div></code>```

Body:
Actually, it seems that the animation shorthand property doesn't follow a strict order as many of the other CSS syntaxes do. Here's an example:

For the class element we have got the timing function, followed by delay.

For the class element2 we have got delay followed by timing function.

For the class element3, I randomized all of the animation properties and still the output is same.

Hence, we can conclude what we assumed.

.element {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch 1.5s ease-out 0s alternate infinite none running;
}

.element2 {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch 1.5s 0s ease-out alternate infinite none running;
}

.element3 {
  height: 250px;
  width: 250px;
  margin: 0 auto;
  background-color: red;
  animation: stretch ease-out 1.5s  none running 0s  alternate infinite ;
}

@keyframes stretch {
  0% {
    transform: scale(.3);
    background-color: red;
    border-radius: 100%;
  }
  50% {
    background-color: orange;
  }
  100% {
    transform: scale(1);
    background-color: yellow;
  }
}

body,
html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

<div class="element"></div>

<div class="element2"></div>

<div class="element3"></div>


来源: stackexchange

问:
Twitter: direct message with quick reply is missing buttons
I am building a Twitter chatbot and I need quick reply buttons on direct messages.

After my failed hacking on the excellent Tweetinvi library (does not support the quick reply yet) I tried to go back to the roots and used Twurl to simplify the problem.

I tried with the sample provided by Twitter with minor editing:

changed user id;

replaced CR LF with nothing

removed the ' in what's

Finally the message is sent but I can see only the text without the quick reply buttons.

Here is my twurl command line

```<code>twurl authorize (the 4 tokens)
twurl account
</code>```

(the account is authorized)

```<code>twurl -t -A 'Content-type: application/json' /1.1/direct_messages/events/new.json -d '{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"999999999"},"message_data":{"text":"What syourfavoritetypeofbird?","quick_reply":{"type":"options","options":[{"label":"RedBird","description":"Adescriptionabouttheredbird.","metadata":"external_id_1"},{"label":"BlueBird","description":"Adescriptionaboutthebluebird.","metadata":"external_id_2"},{"label":"BlackBird","description":"Adescriptionabouttheblackbird.","metadata":"external_id_3"},{"label":"WhiteBird","description":"Adescriptionaboutthewhitebird.","metadata":"external_id_4"}]}}}}}'
</code>```

That's Twitter response:

```<code>-> "status: 200 OK\r\n"
-> "strict-transport-security: max-age=631138519\r\n"
-> "x-access-level: read-write-directmessages\r\n"
-> "x-connection-hash: b85f0c59aeb2f9b8b4c439fb448e541a\r\n"
-> "x-content-type-options: nosniff\r\n"
-> "x-frame-options: SAMEORIGIN\r\n"
-> "x-response-time: 225\r\n"
-> "x-transaction: 006a0b630064b6c7\r\n"
-> "x-tsa-request-body-time: 0\r\n"
-> "x-twitter-response-tags: BouncerCompliant\r\n"
-> "x-xss-protection: 1; mode=block\r\n"
-> "\r\n"
</code>```

The message format seems ok (I got errors when I used the ' in text) but I do not see the buttons, so I ask for advice.

Note: to install twurl on Windows I followed this excellent tutorial

答:
The problem was malformed Json.

with this

```<code>{"event": {"type": "message_create","message_create": {"target": {"recipient_id": "12345"},"sender_id": "6789","message_data": {"text": "Choose your destiny","quick_reply": {"type": "options","options": [{"label": "one","metadata": "1","description": "One descr"},{"label": "Two","metadata": "2","description": "Descr 2}]}}}}}
</code>```

it works.

ContentLicense: CC BY-SA 3.0

Body:
I am building a Twitter chatbot and I need quick reply buttons on direct messages.

After my failed hacking on the excellent Tweetinvi library (does not support the quick reply yet) I tried to go back to the roots and used Twurl to simplify the problem.

I tried with the sample provided by Twitter with minor editing:

changed user id;

replaced CR LF with nothing

removed the ' in what's

Finally the message is sent but I can see only the text without the quick reply buttons.

Here is my twurl command line

twurl authorize (the 4 tokens)
twurl account

(the account is authorized)

twurl -t -A 'Content-type: application/json' /1.1/direct_messages/events/new.json -d '{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"999999999"},"message_data":{"text":"What syourfavoritetypeofbird?","quick_reply":{"type":"options","options":[{"label":"RedBird","description":"Adescriptionabouttheredbird.","metadata":"external_id_1"},{"label":"BlueBird","description":"Adescriptionaboutthebluebird.","metadata":"external_id_2"},{"label":"BlackBird","description":"Adescriptionabouttheblackbird.","metadata":"external_id_3"},{"label":"WhiteBird","description":"Adescriptionaboutthewhitebird.","metadata":"external_id_4"}]}}}}}'

That's Twitter response:

-> "status: 200 OK\r\n"
-> "strict-transport-security: max-age=631138519\r\n"
-> "x-access-level: read-write-directmessages\r\n"
-> "x-connection-hash: b85f0c59aeb2f9b8b4c439fb448e541a\r\n"
-> "x-content-type-options: nosniff\r\n"
-> "x-frame-options: SAMEORIGIN\r\n"
-> "x-response-time: 225\r\n"
-> "x-transaction: 006a0b630064b6c7\r\n"
-> "x-tsa-request-body-time: 0\r\n"
-> "x-twitter-response-tags: BouncerCompliant\r\n"
-> "x-xss-protection: 1; mode=block\r\n"
-> "\r\n"

The message format seems ok (I got errors when I used the ' in text) but I do not see the buttons, so I ask for advice.

Note: to install twurl on Windows I followed this excellent tutorial

Body:
The problem was malformed Json.

with this

{"event": {"type": "message_create","message_create": {"target": {"recipient_id": "12345"},"sender_id": "6789","message_data": {"text": "Choose your destiny","quick_reply": {"type": "options","options": [{"label": "one","metadata": "1","description": "One descr"},{"label": "Two","metadata": "2","description": "Descr 2}]}}}}}

it works.


问:
Reload iFrame (same-domain) without changing `src=`
I am dynamically creating iframe , which just contains content (no src attribute).

```<code>var iframe = document.createElement('iframe');
iframe.contentWindow.document.body.innerHTML=  my_page_content;
....
</code>```

however, JS scripts (<script src="....." inside my_page_content) are not being loaded and I have to re-load scripts.

these methods wont help me to reload frame:

```<code>//this one emptyfies the iframe at all
iframeElement.src = iframeElement.src
//this one is not possible, because the `<script>` links are embedded in the content already.
var script = doc.createElement('script');  script.src = "jquery.min.js";
framebody.appendChild(script);
</code>```

what are the solutions to force the iframe to load the included scripts in its html content? maybe I am attaching the content in a wrong way?

答:
The only way I've solved this was to write the body inside iframe using write() command:

```<code>var ifr = iframeElement.contentWindow.document;
ifr.open(); ifr.write("<body>"+ my_page_content +"</body>");    ifr.close();
</code>```

neither appendChild() nor .innerHTML helped me.

Body:
I am dynamically creating iframe , which just contains content (no src attribute).

var iframe = document.createElement('iframe');
iframe.contentWindow.document.body.innerHTML=  my_page_content;
....

however, JS scripts (<script src="....." inside my_page_content) are not being loaded and I have to re-load scripts.

these methods wont help me to reload frame:

//this one emptyfies the iframe at all
iframeElement.src = iframeElement.src
//this one is not possible, because the `<script>` links are embedded in the content already.
var script = doc.createElement('script');  script.src = "jquery.min.js";
framebody.appendChild(script);

what are the solutions to force the iframe to load the included scripts in its html content? maybe I am attaching the content in a wrong way?

Body:
The only way I've solved this was to write the body inside iframe using write() command:

var ifr = iframeElement.contentWindow.document;
ifr.open(); ifr.write("<body>"+ my_page_content +"</body>");    ifr.close();

neither appendChild() nor .innerHTML helped me.


问:
SQL Server 2012: Login failed for user 'NT Service\MSSQLServerOLAPService'.; 28000
I am using Analysis services in Microsoft SQL Server 2012 on Windows 7.

I tried to create Mining models and process it. I am getting the following error while processing it.

OLE DB error: OLE DB or ODBC error:

  Login failed for user 'NT Service\MSSQLServerOLAPService'.; 28000.

How to correct this and process the model successfully?

答:
I just had the same issue, but other people's answers does not help.

In my case I fixed like this:

Open SQL Server configuration manager

In SQL Services > Double click on SQL Server and copy the full user (in my case NT Service\MSSQLSERVER)

Double click on SQL Server Analysis Services

Paste the user with no password

You will probably need to set "Use the service account" in your Data Source, in your project of Visual Studio


问:
Assign CGPoint in UIPanGestureRecognizer from .began to .changed

Inside my view I have a cardContainerView with a UIPanGestureRecognizer attached to it. Depending on whether the user grabbed the card at the top or bottom half I want to add different rotation angles to my card, which works fine now.

My problem is that the way I implemented it, the user can grab the card at the top (which results in a positive rotation) and slide the card below the location.y threshold I am using, which then results in the card using a negative rotation angle. That causes a jarring jump of the card.

I tried grabbing the location.y in the .began part and assign it to the .changed but apparently I can't do that. It results in a nil value. Anyone have any idea how else I could solve this?

Much appreciated!

```<code>    //When animation begins
    if sender.state == UIGestureRecognizerState.began {
        print("PAN BEGAN")
        cardContainerViewInitialCenter = cardContainerView.center
        addNewTempCard()
        initialPoint = location
        print("InitialPoint PAN BEGAN \(initialPoint)")
        print("InitialPoint.y PAN BEGAN \(initialPoint.y)")
    }

    //While panning
    else if sender.state == UIGestureRecognizerState.changed {
        print("PAN CHANGED")

        //User grabbed card at top half
        if location.y < view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }

        //User grabbed card at bottom half
        else if location.y > view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }
    }
</code>```

答:
Try this:</p>

```<code>class Foo {
  private var initialPoint: CGPoint?

  @objc func panGestureHandler(_ gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .began: self.initialPoint = gesture.location(in: self.view)
    case .changed:
       if let initial = self.initialPoint {
          // your code from above that deals with .changed goes here, using `initial` as the starting point
       }
    case .ended: self.initialPoint = nil
  }

}
</code>```

Body:
Inside my view I have a cardContainerView with a UIPanGestureRecognizer attached to it. Depending on whether the user grabbed the card at the top or bottom half I want to add different rotation angles to my card, which works fine now.

My problem is that the way I implemented it, the user can grab the card at the top (which results in a positive rotation) and slide the card below the location.y threshold I am using, which then results in the card using a negative rotation angle. That causes a jarring jump of the card.

I tried grabbing the location.y in the .began part and assign it to the .changed but apparently I can't do that. It results in a nil value. Anyone have any idea how else I could solve this?

Much appreciated!

    //When animation begins
    if sender.state == UIGestureRecognizerState.began {
        print("PAN BEGAN")
        cardContainerViewInitialCenter = cardContainerView.center
        addNewTempCard()
        initialPoint = location
        print("InitialPoint PAN BEGAN \(initialPoint)")
        print("InitialPoint.y PAN BEGAN \(initialPoint.y)")
    }

    //While panning
    else if sender.state == UIGestureRecognizerState.changed {
        print("PAN CHANGED")

        //User grabbed card at top half
        if location.y < view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationTopNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }

        //User grabbed card at bottom half
        else if location.y > view.frame.height/2 {
            print("TOP HALF")

            if translation.x >= 0 && translation.x <= 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x > 50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomPos)
                tempCardView.alpha = convertedNewCardAlphaPos
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXPos, y: convertedNewCardScaleYPos)
            }

            else if translation.x < 0 && translation.x >= -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }

            else if translation.x < -50 {
                cardContainerView.center = CGPoint(x: cardContainerViewInitialCenter.x + translation.x, y: cardContainerViewInitialCenter.y)
                cardContainerView.transform = CGAffineTransform.init(rotationAngle: convertedRotationBottomNeg)
                tempCardView.alpha = convertedNewCardAlphaNeg
                tempCardView.transform = view.transform.scaledBy(x: convertedNewCardScaleXNeg, y: convertedNewCardScaleYNeg)
            }
        }
    }

Body:
Try this:

class Foo {
  private var initialPoint: CGPoint?

  @objc func panGestureHandler(_ gesture: UIPanGestureRecognizer) {
    switch gesture.state {
    case .began: self.initialPoint = gesture.location(in: self.view)
    case .changed:
       if let initial = self.initialPoint {
          // your code from above that deals with .changed goes here, using `initial` as the starting point
       }
    case .ended: self.initialPoint = nil
  }

}


问:
Uploading image in ASP.NET Boilerplate
When posting an image, HttpContext.Current.Request is null.

Is there any simple way to achieve this? I am using dropzone.js on client side.

Project is Angular with Web API (ASP.NET Core 2.0) template.

```<code>[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
    HttpResponseMessage response = new HttpResponseMessage();
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
    }
    return response;
}
</code>```

答:
This is the code which i had done it is working fine.</p>

```<code>public void PostFile(IFormFile file)
{
    var uploads = Path.Combine("ROOT PATH FOR THE FILES", "uploads");

    if (file.Length > 0)
    {
        var filePath = Path.Combine(uploads, file.FileName);

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
}
</code>```

Title: Uploading image in ASP.NET Boilerplate

Body:
When posting an image, HttpContext.Current.Request is null.

Is there any simple way to achieve this? I am using dropzone.js on client side.

Project is Angular with Web API (ASP.NET Core 2.0) template.

[HttpPost]
public HttpResponseMessage UploadJsonFile()
{
    HttpResponseMessage response = new HttpResponseMessage();
    var httpRequest = HttpContext.Current.Request;
    if (httpRequest.Files.Count > 0)
    {
        foreach (string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/UploadFile/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
    }
    return response;
}

Body:
This is the code which i had done it is working fine.

public void PostFile(IFormFile file)
{
    var uploads = Path.Combine("ROOT PATH FOR THE FILES", "uploads");

    if (file.Length > 0)
    {
        var filePath = Path.Combine(uploads, file.FileName);

        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Android - Store inputstream in file
I am retrieveing an XML feed from a url and then parsing it. What I need to do is also store that internally to the phone so that when there is no internet connection it can parse the saved option rather than the live one.

The problem I am facing is that I can create the url object, use getInputStream to get the contents, but it will not let me save it.

```<code>URL url = null;
InputStream inputStreamReader = null;
XmlPullParser xpp = null;

url = new URL("http://*********");
inputStreamReader = getInputStream(url);

ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFileAppeal.srl"));

//--------------------------------------------------------
//This line is where it is erroring.
//--------------------------------------------------------
out.writeObject( inputStreamReader );
//--------------------------------------------------------
out.close();
</code>```

Any ideas how I can go about saving the input stream so I can load it later.

Cheers

答:
There's the way of IOUtils:

```<code>copy(InputStream input, OutputStream output)
</code>```

The code of it is similar to this :

```<code>public static long copyStream(InputStream input, OutputStream output) throws IOException {
    long count = 0L;
    byte[] buffer = new byte[4096];
    for (int n; -1 != (n = input.read(buffer)); count += (long) n)
        output.write(buffer, 0, n);
    return count;
}
</code>```

Title: Android - Store inputstream in file

Body:
I am retrieveing an XML feed from a url and then parsing it. What I need to do is also store that internally to the phone so that when there is no internet connection it can parse the saved option rather than the live one.

The problem I am facing is that I can create the url object, use getInputStream to get the contents, but it will not let me save it.

URL url = null;
InputStream inputStreamReader = null;
XmlPullParser xpp = null;

url = new URL("http://*********");
inputStreamReader = getInputStream(url);

ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(getCacheDir(),"")+"cacheFileAppeal.srl"));

//--------------------------------------------------------
//This line is where it is erroring.
//--------------------------------------------------------
out.writeObject( inputStreamReader );
//--------------------------------------------------------
out.close();

Any ideas how I can go about saving the input stream so I can load it later.

Cheers

Body:
There's the way of IOUtils:

copy(InputStream input, OutputStream output)

The code of it is similar to this :

public static long copyStream(InputStream input, OutputStream output) throws IOException {
    long count = 0L;
    byte[] buffer = new byte[4096];
    for (int n; -1 != (n = input.read(buffer)); count += (long) n)
        output.write(buffer, 0, n);
    return count;
}


问:
Writing all Camera2 CaptureResults into a file
I am trying to export into a texte file all the parameters from an acquisition using Camera2 API on Android. I figured out that they are all contained in the CaptureCallback but I just don't know how to parse them all and write them into a file.

```<code>private CameraCaptureSession.CaptureCallback mCaptureCallback  = new CameraCaptureSession.CaptureCallback()
{

    private void process(CaptureResult result)
    {
        //parse and write as txt all available result keys and values
    }
}
</code>```

It is probably an easy thing to do.

答:
Here is a piece of code that do the job. I open a file, parse all the keys and write the values into it : </p>

```<code>File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES), "MyApp");
File outputfile = new File(mediaStorageDir, "Camera_parameters.txt");
if (! mediaStorageDir.exists()){
    if (! mediaStorageDir.mkdirs()){
        return;
    }
}
try {
    FileOutputStream m_outputstream = new FileOutputStream(outputfile);
    OutputStreamWriter m_stream = new OutputStreamWriter(m_outputstream);
    List<CaptureResult.Key<?>> keys = result.getKeys();
    for (CaptureResult.Key<?> key : keys) {
        Log.d(TAG, key + " has value " + result.get(key));
        m_stream.write(key + "\t" + result.get(key) + "\n");
    }
    m_stream.close();
}
catch (IOException e)
{
    Log.e("Exception", "File write failed: " + e.toString());
}
</code>```

Body:
I am trying to export into a texte file all the parameters from an acquisition using Camera2 API on Android. I figured out that they are all contained in the CaptureCallback but I just don't know how to parse them all and write them into a file.

private CameraCaptureSession.CaptureCallback mCaptureCallback  = new CameraCaptureSession.CaptureCallback()
{

    private void process(CaptureResult result)
    {
        //parse and write as txt all available result keys and values
    }
}

It is probably an easy thing to do.

Body:
Here is a piece of code that do the job. I open a file, parse all the keys and write the values into it :

File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES), "MyApp");
File outputfile = new File(mediaStorageDir, "Camera_parameters.txt");
if (! mediaStorageDir.exists()){
    if (! mediaStorageDir.mkdirs()){
        return;
    }
}
try {
    FileOutputStream m_outputstream = new FileOutputStream(outputfile);
    OutputStreamWriter m_stream = new OutputStreamWriter(m_outputstream);
    List<CaptureResult.Key<?>> keys = result.getKeys();
    for (CaptureResult.Key<?> key : keys) {
        Log.d(TAG, key + " has value " + result.get(key));
        m_stream.write(key + "\t" + result.get(key) + "\n");
    }
    m_stream.close();
}
catch (IOException e)
{
    Log.e("Exception", "File write failed: " + e.toString());
}


问:
How do I change the headers that PHP sends when using file_get_contents on an external URL?
I need to change the headers that PHP sends when it requests a file using file_get_contents(). Is that possible or would I have to use CURL?</p>

答: You will need to use CURL. It's also more reliable. See curl_setopt and CURLOPT_HTTPHEADER.</p>

ContentLicense: CC BY-SA 2.5


问:
If date between two dates in second table return value
I am trying to determine if a datetime is between a beginning datetime and ending datetime and if it is return a value(s) that match this. It is working in data.table but want to get it working in DPLYR.

So if you have datetimes:

```<code>2017-07-01 02:15:00
2017-07-01 02:30:00
</code>```

look these up in a second table

```<code>begin,      end,                           value1,  value2
2017-07-01 00:01:00,  2017-07-01 01:00:00,  1,       2
2017-07-01 01:01:00,  2017-07-01 02:00:00,  3,       4
2017-07-01 02:01:00,  2017-07-01 03:00:00,  5,       6
</code>```

return

```<code>date                value1   value2
2017-07-01 02:15:00    5        6
2017-07-01 02:30:00    5        6
</code>```

There are many of the lookup values so it would be a few hundred lookup date times.

I have this working with data.table but want to use DPLYR to reduce dependence on many packages.  This is what I have so far:

```<code>library(tidyverse)
library(lubridate)
library(data.table)

dates <- read_csv("date1.csv") %>%
  mutate(date = as_datetime(date))

lookup <- read_csv("lookup.csv") %>%
  mutate(begin = as_datetime(begin),
         end = as_datetime(end))

dates <- data.table(dates)
lookup <- data.table(lookup)
setkey(lookup, begin, end)
dates[, c("begin", "end") := date]
test.df <- foverlaps(dates, lookup)[, c("date", "value1", "value2"),
                                        with = FALSE]
</code>```

I was thinking of using something like:

```<code>test <- dates %>% rowwise() %>%
  mutate(value1 = ifelse( lookup$begin >= date & date <= lookup$end, lookup$value1, ""))
</code>```

Here is the dates to look up:

```<code>    dates <- structure(list(date = structure(c(1498867200, 1498868100, 1498869000,
1498869900, 1498870800, 1498871700, 1498872600, 1498873500, 1498874400,
1498875300, 1498876200, 1498877100, 1498878000, 1498878900, 1498879800,
1498880700, 1498881600, 1498882500), tzone = "UTC", class = c("POSIXct",
"POSIXt"))), .Names = "date", class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L))
</code>```

The lookup table:

```<code>    lookup <- structure(list(begin = structure(c(1498867260, 1498870860, 1498874460,
1498878060, 1498881660, 1498885260, 1498888860, 1498892460, 1498896060
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), end = structure(c(1498870800,
1498874400, 1498878000, 1498881600, 1498885200, 1498888800, 1498892400,
1498896000, 1498899600), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    value1 = c(1L, 3L, 5L, 7L, 9L, 11L, 13L, 15L, 17L), value2 = c(2L,
    4L, 6L, 8L, 10L, 12L, 14L, 16L, 18L)), .Names = c("begin",
"end", "value1", "value2"), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L))
</code>```

答:
You can try the following:

```<code>library(tidyverse)
library(lubridate)

dates <- dates %>%
  mutate(match_date = format(date, "%Y-%m-%d"),
         match_hour = hour(date - minutes(1)))

lookup <- lookup %>%
  mutate(match_date = format(begin, "%Y-%m-%d"),
         match_hour = hour(begin))

left_join(dates, lookup, by = c("match_date", "match_hour")) %>%
  filter(date >= begin & date <= end) %>%
  select(- match_date, - match_hour) %>%
  head()

# A tibble: 6 x 5
#                  date               begin                 end value1 value2
#                <dttm>              <dttm>              <dttm>  <int>  <int>
# 1 2017-07-01 00:15:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 2 2017-07-01 00:30:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 3 2017-07-01 00:45:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 4 2017-07-01 01:00:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 5 2017-07-01 01:15:00 2017-07-01 01:01:00 2017-07-01 02:00:00      3      4
# 6 2017-07-01 01:30:00 2017-07-01 01:01:00 2017-07-01 02:00:00      3      4
</code>```

First I extract the dates and hour of the day to match on. I substract one minute from the date in the dates-table as your end times in your lookup-table contain the times sharp (I mean e.g. 01:00:00). As I want to join on the begin-dates to get the right matching hour (e.g. 0 in this case), I substract the minute.

Then I do a left_join of dates and lookup and filter on your desired criteria.

Body:
I am trying to determine if a datetime is between a beginning datetime and ending datetime and if it is return a value(s) that match this. It is working in data.table but want to get it working in DPLYR.

So if you have datetimes:

2017-07-01 02:15:00
2017-07-01 02:30:00

look these up in a second table

begin,      end,                           value1,  value2
2017-07-01 00:01:00,  2017-07-01 01:00:00,  1,       2
2017-07-01 01:01:00,  2017-07-01 02:00:00,  3,       4
2017-07-01 02:01:00,  2017-07-01 03:00:00,  5,       6

return

date                value1   value2
2017-07-01 02:15:00    5        6
2017-07-01 02:30:00    5        6

There are many of the lookup values so it would be a few hundred lookup date times.

I have this working with data.table but want to use DPLYR to reduce dependence on many packages.  This is what I have so far:

library(tidyverse)
library(lubridate)
library(data.table)

dates <- read_csv("date1.csv") %>%
  mutate(date = as_datetime(date))

lookup <- read_csv("lookup.csv") %>%
  mutate(begin = as_datetime(begin),
         end = as_datetime(end))

dates <- data.table(dates)
lookup <- data.table(lookup)
setkey(lookup, begin, end)
dates[, c("begin", "end") := date]
test.df <- foverlaps(dates, lookup)[, c("date", "value1", "value2"),
                                        with = FALSE]

I was thinking of using something like:

test <- dates %>% rowwise() %>%
  mutate(value1 = ifelse( lookup$begin >= date & date <= lookup$end, lookup$value1, ""))

Here is the dates to look up:

    dates <- structure(list(date = structure(c(1498867200, 1498868100, 1498869000,
1498869900, 1498870800, 1498871700, 1498872600, 1498873500, 1498874400,
1498875300, 1498876200, 1498877100, 1498878000, 1498878900, 1498879800,
1498880700, 1498881600, 1498882500), tzone = "UTC", class = c("POSIXct",
"POSIXt"))), .Names = "date", class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -18L))

The lookup table:

    lookup <- structure(list(begin = structure(c(1498867260, 1498870860, 1498874460,
1498878060, 1498881660, 1498885260, 1498888860, 1498892460, 1498896060
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), end = structure(c(1498870800,
1498874400, 1498878000, 1498881600, 1498885200, 1498888800, 1498892400,
1498896000, 1498899600), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    value1 = c(1L, 3L, 5L, 7L, 9L, 11L, 13L, 15L, 17L), value2 = c(2L,
    4L, 6L, 8L, 10L, 12L, 14L, 16L, 18L)), .Names = c("begin",
"end", "value1", "value2"), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -9L))

Body:
You can try the following:

library(tidyverse)
library(lubridate)

dates <- dates %>%
  mutate(match_date = format(date, "%Y-%m-%d"),
         match_hour = hour(date - minutes(1)))

lookup <- lookup %>%
  mutate(match_date = format(begin, "%Y-%m-%d"),
         match_hour = hour(begin))

left_join(dates, lookup, by = c("match_date", "match_hour")) %>%
  filter(date >= begin & date <= end) %>%
  select(- match_date, - match_hour) %>%
  head()

# A tibble: 6 x 5
#                  date               begin                 end value1 value2
#                <dttm>              <dttm>              <dttm>  <int>  <int>
# 1 2017-07-01 00:15:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 2 2017-07-01 00:30:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 3 2017-07-01 00:45:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 4 2017-07-01 01:00:00 2017-07-01 00:01:00 2017-07-01 01:00:00      1      2
# 5 2017-07-01 01:15:00 2017-07-01 01:01:00 2017-07-01 02:00:00      3      4
# 6 2017-07-01 01:30:00 2017-07-01 01:01:00 2017-07-01 02:00:00      3      4

First I extract the dates and hour of the day to match on. I substract one minute from the date in the dates-table as your end times in your lookup-table contain the times sharp (I mean e.g. 01:00:00). As I want to join on the begin-dates to get the right matching hour (e.g. 0 in this case), I substract the minute.

Then I do a left_join of dates and lookup and filter on your desired criteria.


问:
Python: Having trouble replacing lines from file
I'm trying to build a translator using deepl for subtitles but it isn't running perfectly. I managed to translate the subtitles and most of the part I'm having problems replacing the lines. I can see that the lines are translated because it prints them but it doesn't replace them. Whenever I run the program it is the same as the original file.

This is the code responsible for:

```<code>def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output,'r+')
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            for line in fileresp.readlines():
                newline = fileresp.write(line.replace(linefromsub,translationSentence))
        except IndexError:
            print("Error parsing data from deepl")
</code>```

This is the how the file looks:

```<code>1
00:00:02,470 --> 00:00:04,570
        - Yes, I do.
        - (laughs)

2
00:00:04,605 --> 00:00:07,906
      My mom doesn't want
      to babysit everyday

3
00:00:07,942 --> 00:00:09,274
        or any day.

4
00:00:09,310 --> 00:00:11,977
        But I need
    my mom's help sometimes.

5
00:00:12,013 --> 00:00:14,046
        She's just gonna
    have to be grandma today.
</code>```

Help will be appreaciated :)
Thanks.

答:
You are opening fileresp with r+ mode. When you call readlines(), the file's position will be set to the end of the file. Subsequent calls to write() will then append to the file. If you want to overwrite the original contents as opposed to append, you should try this instead:

```<code>allLines = fileresp.readlines()
fileresp.seek(0)    # Set position to the beginning
fileresp.truncate() # Delete the contents
for line in allLines:
    fileresp.write(...)
</code>```

Update

It's difficult to see what you're trying to accomplish with r+ mode here but it seems you have two separate input and output files. If that's the case consider:

```<code>def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output, 'w') # Use w mode instead
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            fileresp.write(translationSentence) # Write the translated sentence
        except IndexError:
            print("Error parsing data from deepl")
</code>```

Body:
I'm trying to build a translator using deepl for subtitles but it isn't running perfectly. I managed to translate the subtitles and most of the part I'm having problems replacing the lines. I can see that the lines are translated because it prints them but it doesn't replace them. Whenever I run the program it is the same as the original file.

This is the code responsible for:

def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output,'r+')
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            for line in fileresp.readlines():
                newline = fileresp.write(line.replace(linefromsub,translationSentence))
        except IndexError:
            print("Error parsing data from deepl")

This is the how the file looks:

1
00:00:02,470 --> 00:00:04,570
        - Yes, I do.
        - (laughs)

2
00:00:04,605 --> 00:00:07,906
      My mom doesn't want
      to babysit everyday

3
00:00:07,942 --> 00:00:09,274
        or any day.

4
00:00:09,310 --> 00:00:11,977
        But I need
    my mom's help sometimes.

5
00:00:12,013 --> 00:00:14,046
        She's just gonna
    have to be grandma today.

Help will be appreaciated :)
Thanks.

Body:
You are opening fileresp with r+ mode. When you call readlines(), the file's position will be set to the end of the file. Subsequent calls to write() will then append to the file. If you want to overwrite the original contents as opposed to append, you should try this instead:

allLines = fileresp.readlines()
fileresp.seek(0)    # Set position to the beginning
fileresp.truncate() # Delete the contents
for line in allLines:
    fileresp.write(...)

Update

It's difficult to see what you're trying to accomplish with r+ mode here but it seems you have two separate input and output files. If that's the case consider:

def translate(input, output, languagef, languaget):
    file = open(input, 'r').read()
    fileresp = open(output, 'w') # Use w mode instead
    subs = list(srt.parse(file))
    for sub in subs:
        try:
            linefromsub = sub.content
            translationSentence = pydeepl.translate(linefromsub, languaget.upper(), languagef.upper())
            print(str(sub.index) + ' ' + translationSentence)
            fileresp.write(translationSentence) # Write the translated sentence
        except IndexError:
            print("Error parsing data from deepl")


问:
The deferred antipattern, how to handle rejects?
I understand what is The deferred antipattern, also mentioned as "The Forgotten Promise" HERE.

I also read: what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it.

Anyways I should try to get rid of using $q.defer().

But I don't understand how to handle case where I got response and I need to reject it because it doesn't have proper key.

This is my method in Service that returns promise to controller.

```<code>self.findTime = function(data){

  var deferred = $q.defer();

   apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            deferred.reject(response);
         }

        deferred.resolve(response);
      }
      , function (error) {
      deferred.reject(error);
        console.error(error);
      });

      return deferred.promise;
};
</code>```

So I tried to change it to:

```<code>self.findTime = function(data){

   return apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            // return WHAT ??? <-------------
         }
        return response;
      }
      , function (error) {
      // return WHAT ??? <-------------
        console.error(error);
   });
};
</code>```

How to handle reject?

In controller, on reject  I show some morning message.

```<code> Service.findTime(data).then(function (response) {
   // do something
    }, function (error) {
      // show warn dialog
 });
</code>```

答:
You have two options.

You can return a rejection promise from within your resolve:

```<code>return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            return $q.reject('reason'); // Convert to rejection
        }
        return response;
    }, function (error) {
        console.error(error);
        return $q.reject('reason');  // Chain rejection
    });
</code>```

or you can throw an exception:

```<code>return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            throw new Error('reason');
        }
        return response;
    }, function (error) {
        console.error(error);
        throw new Error(error);
    });
</code>```

Body:
I understand what is The deferred antipattern, also mentioned as "The Forgotten Promise" HERE.

I also read: what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it.

Anyways I should try to get rid of using $q.defer().

But I don't understand how to handle case where I got response and I need to reject it because it doesn't have proper key.

This is my method in Service that returns promise to controller.

self.findTime = function(data){

  var deferred = $q.defer();

   apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            deferred.reject(response);
         }

        deferred.resolve(response);
      }
      , function (error) {
      deferred.reject(error);
        console.error(error);
      });

      return deferred.promise;
};

So I tried to change it to:

self.findTime = function(data){

   return apiClient.findTime(data)
      .then(function (response) {

         if (response.result !== "success") {
            // return WHAT ??? <-------------
         }
        return response;
      }
      , function (error) {
      // return WHAT ??? <-------------
        console.error(error);
   });
};

How to handle reject?

In controller, on reject  I show some morning message.

 Service.findTime(data).then(function (response) {
   // do something
    }, function (error) {
      // show warn dialog
 });

Body:
You have two options.

You can return a rejection promise from within your resolve:

return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            return $q.reject('reason'); // Convert to rejection
        }
        return response;
    }, function (error) {
        console.error(error);
        return $q.reject('reason');  // Chain rejection
    });

or you can throw an exception:

return apiClient.findTime(data)
    .then(function (response) {
        if (response.result !== "success") {
            throw new Error('reason');
        }
        return response;
    }, function (error) {
        console.error(error);
        throw new Error(error);
    });


问:
Passing parameter between ViewModels using MVVMLight
I'm having a problem to pass parameters betweeen my ViewModels using the Messenger class in the MVVMLight Framework.

This is the code I'm using :

ViewModelLocator

```<code>public ViewModelLocator ()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<INavigationService, NavigationService>();

    SimpleIoc.Default.Register(() => new MainViewModel(NavigationService));
    SimpleIoc.Default.Register(() => new SecondViewModel(NavigationService));
}

public MainViewModel MainViewModel
{
    get { return SimpleIoc.Default.GetInstance<MainViewModel>(); }
}

public SecondViewModel SecondViewModel
{
    get { return SimpleIoc.Default.GetInstance<SecondViewModel>(); }
}

public INavigationService NavigationService
{
    get { return SimpleIoc.Default.GetInstance<INavigationService>(); }
}
</code>```

MainViewModel

```<code>private void ShowPersonDetailsCommand(object obj)
{
    Messenger.Default.Send((Person)obj);
    _navigationService.NavigateTo(new Uri("/SecondPage.xaml", UriKind.Relative))
}
</code>```

SecondViewModel

```<code>public SecondViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;

    Messenger.Default.Register<Person>(
        this,
        person =>
        {
            Person = person;
        });
}
</code>```

In my MainViewModel (ShowPersonDetailsCommand), I'm navigating to a SecondPage and sending a person as parameter in the Messenger class. At this point, the person is well constructed and sent as a message.

But in the SecondViewModel constructor, the person is null :(

Is there something I'm missing ?

I thinks I did something wrong ...

For your information :

Windows Phone 8.1 (Silverlight)

MVVMLight 5.0.2

Visual Studio 2013 Update 4

答:
Instead of sending a message, you could pass a parameter in the NavigationServicesEx.Navigate method call.

This blog by Marco Minerva advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.

Create the INavigable interface described in the blog:

```<code>public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}
</code>```

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

```<code>NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);
</code>```

In the OnNavigatedToAsync method that you implement in your ViewModel:

```<code>public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}
</code>```

Body:
I'm having a problem to pass parameters betweeen my ViewModels using the Messenger class in the MVVMLight Framework.

This is the code I'm using :

ViewModelLocator

public ViewModelLocator ()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<INavigationService, NavigationService>();

    SimpleIoc.Default.Register(() => new MainViewModel(NavigationService));
    SimpleIoc.Default.Register(() => new SecondViewModel(NavigationService));
}

public MainViewModel MainViewModel
{
    get { return SimpleIoc.Default.GetInstance<MainViewModel>(); }
}

public SecondViewModel SecondViewModel
{
    get { return SimpleIoc.Default.GetInstance<SecondViewModel>(); }
}

public INavigationService NavigationService
{
    get { return SimpleIoc.Default.GetInstance<INavigationService>(); }
}

MainViewModel

private void ShowPersonDetailsCommand(object obj)
{
    Messenger.Default.Send((Person)obj);
    _navigationService.NavigateTo(new Uri("/SecondPage.xaml", UriKind.Relative))
}

SecondViewModel

public SecondViewModel(INavigationService navigationService)
{
    _navigationService = navigationService;

    Messenger.Default.Register<Person>(
        this,
        person =>
        {
            Person = person;
        });
}

In my MainViewModel (ShowPersonDetailsCommand), I'm navigating to a SecondPage and sending a person as parameter in the Messenger class. At this point, the person is well constructed and sent as a message.

But in the SecondViewModel constructor, the person is null :(

Is there something I'm missing ?

I thinks I did something wrong ...

For your information :

Windows Phone 8.1 (Silverlight)

MVVMLight 5.0.2

Visual Studio 2013 Update 4

Body:
Instead of sending a message, you could pass a parameter in the NavigationServicesEx.Navigate method call.

This blog by Marco Minerva advises how to hook in to the Frame_Navigating event (that it missing from the vanilla NavigationServiceEx class) to access the argument when the destination page is navigated to.

Create the INavigable interface described in the blog:

public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:

public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}


问:
config-map kubernetes multiple environments
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

```<code>    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}
</code>```

Specified the name of the config map in my application.yml

```<code>spring:
  application:
    name: echo-configmap
</code>```

echo-configmap

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap
</code>```

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?

答:
This sounds like a good use case for Helm. You could deploy your application as a Helm Chart, which would basically allow you to generate your Kubernetes resources (like ConfigMaps, Deployments, and whatever else you need) from templates.

You can use the documentation on Helm Charts to get started with Helm. After having created a Chart with helm create, you will get a templates/ directory, in which you might place the following YAML template for your ConfigMap:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ printf "%s-%s" .Release.Name .Chart.Name }}
  labels:
    app: {{ .Chart.Name | trunc 63 | trimSuffix "-" }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  application.properties: |-
    message={{ .Values.properties.message }}
</code>```

You can add a second YAML template for your Deployment object (actually, helm create will already create a sensible default deployment). Simply add your ConfigMap as volume, there:

```<code>containers:
  - name: {{ .Chart.Name }}
    # [...]
    volumes:
      - name: property-volume
        mountPath: /etc/your-app/properties
volumes:
  - name: property-volume
    configMap:
      name: {{ printf "%s-%s" .Release.Name .Chart.Name }}
</code>```

Each Helm chart has a values.yaml file, in which you can define default values that are then used to fill in your templates. This default file might look like this (remember that the ConfigMap template above contained a {{ .Values.properties.message }} expression):

```<code>replicaCount: 1
image:
  repository: your-docker-image
  tag: your-docker-tag
properties:
  message: Hello!
</code>```

Next, use this Helm chart and the helm install command to deploy your application as many times as you want with different configurations. You can supply different YAML files in which you override specific values from your values.yaml file, or override individual values using --set:

```<code>$ helm install --name dev --set image.tag=latest --set replicaCount=1 path/to/chart
$ helm install --name prod --set image.tag=stable --set replicaCount=3 --set properties.message="Hello from prod" path/to/chart
</code>```

As to your second question: Of course you should put your Helm Chart into version control. You can then use the helm upgrade command to apply changes to an already deployed application.

Body:
I am trying to deploy a Spring Boot application using configuration data from Kubernetes cluster. I have a simple RestController that prints a message by reading from a Kubernetes cluster.

    private String message = "Message not coming from Kubernetes config map";

@RequestMapping(value="/echo", method=GET)
public String printKubeConfig() {
    return message;
}

Specified the name of the config map in my application.yml

spring:
  application:
    name: echo-configmap

echo-configmap

apiVersion: v1
kind: ConfigMap
metadata:
  name: echo-configmap
data:
  application.properties: |-
    message=Hello from dev Kubernetes Configmap
  application_qa.properties: |-
    message=Hello from qa Kubernetes Configmap

I have several environments like qa, int, test etc

What's the best way to specify environment specific properties in the config map? And how to access them in Spring boot application?

Ex: if the application is deployed in qa, my service should return the message "Hello from qa Kubernetes Configmap"

We also have plans to read these configuration files from GIT in future. How to handle that usecase?

Body:
This sounds like a good use case for Helm. You could deploy your application as a Helm Chart, which would basically allow you to generate your Kubernetes resources (like ConfigMaps, Deployments, and whatever else you need) from templates.

You can use the documentation on Helm Charts to get started with Helm. After having created a Chart with helm create, you will get a templates/ directory, in which you might place the following YAML template for your ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ printf "%s-%s" .Release.Name .Chart.Name }}
  labels:
    app: {{ .Chart.Name | trunc 63 | trimSuffix "-" }}
    chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
data:
  application.properties: |-
    message={{ .Values.properties.message }}

You can add a second YAML template for your Deployment object (actually, helm create will already create a sensible default deployment). Simply add your ConfigMap as volume, there:

containers:
  - name: {{ .Chart.Name }}
    # [...]
    volumes:
      - name: property-volume
        mountPath: /etc/your-app/properties
volumes:
  - name: property-volume
    configMap:
      name: {{ printf "%s-%s" .Release.Name .Chart.Name }}

Each Helm chart has a values.yaml file, in which you can define default values that are then used to fill in your templates. This default file might look like this (remember that the ConfigMap template above contained a {{ .Values.properties.message }} expression):

replicaCount: 1
image:
  repository: your-docker-image
  tag: your-docker-tag
properties:
  message: Hello!

Next, use this Helm chart and the helm install command to deploy your application as many times as you want with different configurations. You can supply different YAML files in which you override specific values from your values.yaml file, or override individual values using --set:

$ helm install --name dev --set image.tag=latest --set replicaCount=1 path/to/chart
$ helm install --name prod --set image.tag=stable --set replicaCount=3 --set properties.message="Hello from prod" path/to/chart

As to your second question: Of course you should put your Helm Chart into version control. You can then use the helm upgrade command to apply changes to an already deployed application.


问:
c#, Microsoft Interop Excel , change font style for s selected range
I need to change the font style (font type ) of some cells in Excel sheet.
Excel sheet is generated by Microsoft.Office.Interop.Excel

I want to change B3 to B100 range to be in Arial font type.
here is my code

```<code>Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
worksheet.get_Range("B3", "B100").Cells.Font.FontStyle = "Arial";

for (int i = 1; i < records_datagridview.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = records_datagridview.Columns[i - 1].HeaderText;
}

for (int i = 0; i < records_datagridview.Rows.Count; i++)
{
   for (int j = 0; j < records_datagridview.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = records_datagridview.Rows[i].Cells[j].Value.ToString();
   }
}

String file_path = fbd.SelectedPath + "/records_sheet_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_.xlsx";

workbook.SaveAs(file_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

app.Quit();
</code>```

I used

```<code>worksheet.get_Range("B3", "B4").Cells.Font.FontStyle = "Arial";
</code>```

But it's not working
Can any one help me on this

答:
hange your code to this:

```<code>worksheet.get_Range("B3", "B4").Cells.Font.Name = "Arial";
</code>```

Tip: In many cases, you can answer questions like these yourself: simply record an Excel macro and look at the generated code. Even though it is VBA, not C#, you will often see what you need.

Body:
I need to change the font style (font type ) of some cells in Excel sheet.
Excel sheet is generated by Microsoft.Office.Interop.Excel

I want to change B3 to B100 range to be in Arial font type.
here is my code

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
worksheet.get_Range("B3", "B100").Cells.Font.FontStyle = "Arial";

for (int i = 1; i < records_datagridview.Columns.Count + 1; i++)
{
   worksheet.Cells[1, i] = records_datagridview.Columns[i - 1].HeaderText;
}

for (int i = 0; i < records_datagridview.Rows.Count; i++)
{
   for (int j = 0; j < records_datagridview.Columns.Count; j++)
   {
      worksheet.Cells[i + 2, j + 1] = records_datagridview.Rows[i].Cells[j].Value.ToString();
   }
}

String file_path = fbd.SelectedPath + "/records_sheet_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_.xlsx";

workbook.SaveAs(file_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

app.Quit();

I used

worksheet.get_Range("B3", "B4").Cells.Font.FontStyle = "Arial";

But it's not working
Can any one help me on this

Body:
hange your code to this:

worksheet.get_Range("B3", "B4").Cells.Font.Name = "Arial";

Tip: In many cases, you can answer questions like these yourself: simply record an Excel macro and look at the generated code. Even though it is VBA, not C#, you will often see what you need.


问:
How To Insert Arrays with objects values into mysql using for or foreach in javascript (nodejs)?
This is my cron job api:

```<code>var job = new cronJob('* * * * * *', function () {
    Draft.find().then(data => {
        var finalData = data;
            Profsms.create({
                phoneno: draftData.contacts.gsm,
                sender: senderName,
                message: message
            }).then(function (data) {
                if (data) {
                    console.log("successfully moved in profsms mysql");
                } else {
                    console.log("failed");
                }
            })
    });
}, function () {
    console.log('DelCron Job finished.');
}, true, 'Asia/Calcutta');
</code>```

In finalData variable i am getting this type of json object:

```<code>{
    "draftType" : "contactdraft",
    "scheduledTime" : null,
    "senderdata" : "",
    "draftData" : {
        "contacts" : [
            {
                "updatedAt" : "2017-12-07T12:09:10.000Z",
                "createdAt" : "2017-12-07T12:09:10.000Z",
                "data3" : "",
                "data2" : "",
                "data1" : "",
                "country" : "",
                "url" : "",
                "company" : "",
                "email" : "sameer@ech.com",
                "dob" : null,
                "postcode" : "",
                "region" : "",
                "city" : "",
                "street" : "",
                "lastName" : "Sameer",
                "firstName" : "Mohamed",
                "gsm" : "123344",
                "id" : 12
            },
            {
                "updatedAt" : "2017-12-07T12:09:58.000Z",
                "createdAt" : "2017-12-07T12:09:58.000Z",
                "data3" : "",
                "data2" : "",
                "data1" : "",
                "country" : "",
                "url" : "",
                "company" : "",
                "email" : "ganesh@ich.com",
                "dob" : null,
                "postcode" : "",
                "region" : "",
                "city" : "",
                "street" : "",
                "lastName" : "Pandiyan",
                "firstName" : "Ganesh",
                "gsm" : "1233",
                "id" : 13
            }
        ]
    },
    "senderName" : "ifelse",
    "message" : "hey...",
    "draftName" : "December 9",
}
</code>```

I want to insert  the gsm number from draftData and senderName and message values into db

Want to store

```<code>                    phoneno: draftData.contacts.gsm,
                    sender: senderName,
                    message: message
</code>```

How to do this?

I am using sequelize ORM with mysql.

Can you help me to solve this using for or foreach or any other function in javascript?

答:
I finally write my own code and got answer:

```<code>var job = new cronJob('* * * * * *', function () {
    Draft.find().then(data => {
        var finalData = data;
        var array = [];
        for (var i = 0; i < finalData.length; i++) {
            for (var j = 0; j < finalData[i].draftData.contacts.length; j++) {
               array.push({
                  phoneno: finalData[i].draftData.contacts[j].gsm,
                  sender: finalData[i].senderName,
                  message: finalData[i].message
               })
            }
        }
        Profsms.bulkCreate(array).then(function (data) {
            if (data) {
                console.log("successfully moved in profsms mysql");
            } else {
                console.log("failed");
            }
        })
    });
}, function () {
    console.log('DelCron Job finished.');
}, true, 'Asia/Calcutta');
</code>```

Is this good approach?

Body:
This is my cron job api:

var job = new cronJob('* * * * * *', function () {
    Draft.find().then(data => {
        var finalData = data;
            Profsms.create({
                phoneno: draftData.contacts.gsm,
                sender: senderName,
                message: message
            }).then(function (data) {
                if (data) {
                    console.log("successfully moved in profsms mysql");
                } else {
                    console.log("failed");
                }
            })
    });
}, function () {
    console.log('DelCron Job finished.');
}, true, 'Asia/Calcutta');

In finalData variable i am getting this type of json object:

{
    "draftType" : "contactdraft",
    "scheduledTime" : null,
    "senderdata" : "",
    "draftData" : {
        "contacts" : [
            {
                "updatedAt" : "2017-12-07T12:09:10.000Z",
                "createdAt" : "2017-12-07T12:09:10.000Z",
                "data3" : "",
                "data2" : "",
                "data1" : "",
                "country" : "",
                "url" : "",
                "company" : "",
                "email" : "sameer@ech.com",
                "dob" : null,
                "postcode" : "",
                "region" : "",
                "city" : "",
                "street" : "",
                "lastName" : "Sameer",
                "firstName" : "Mohamed",
                "gsm" : "123344",
                "id" : 12
            },
            {
                "updatedAt" : "2017-12-07T12:09:58.000Z",
                "createdAt" : "2017-12-07T12:09:58.000Z",
                "data3" : "",
                "data2" : "",
                "data1" : "",
                "country" : "",
                "url" : "",
                "company" : "",
                "email" : "ganesh@ich.com",
                "dob" : null,
                "postcode" : "",
                "region" : "",
                "city" : "",
                "street" : "",
                "lastName" : "Pandiyan",
                "firstName" : "Ganesh",
                "gsm" : "1233",
                "id" : 13
            }
        ]
    },
    "senderName" : "ifelse",
    "message" : "hey...",
    "draftName" : "December 9",
}

I want to insert  the gsm number from draftData and senderName and message values into db

Want to store

                    phoneno: draftData.contacts.gsm,
                    sender: senderName,
                    message: message

How to do this?

I am using sequelize ORM with mysql.

Can you help me to solve this using for or foreach or any other function in javascript?

Body:
I finally write my own code and got answer:

var job = new cronJob('* * * * * *', function () {
    Draft.find().then(data => {
        var finalData = data;
        var array = [];
        for (var i = 0; i < finalData.length; i++) {
            for (var j = 0; j < finalData[i].draftData.contacts.length; j++) {
               array.push({
                  phoneno: finalData[i].draftData.contacts[j].gsm,
                  sender: finalData[i].senderName,
                  message: finalData[i].message
               })
            }
        }
        Profsms.bulkCreate(array).then(function (data) {
            if (data) {
                console.log("successfully moved in profsms mysql");
            } else {
                console.log("failed");
            }
        })
    });
}, function () {
    console.log('DelCron Job finished.');
}, true, 'Asia/Calcutta');

Is this good approach?


问:
ImportError: No module named enum on python 2.7
I'm running a code with Python 2.7. And I get "ImportError: No module named enum". I installed enum with "pip install enum" but the error keeps coming. What shall I do??</p>

答:
The enum module is part of Python 3.4 (and later) stdlib but not part of Python 2.7 stdlib.

Fortunately, there's an available backport suitable to Python 2.7. Install it and play with it.

https://pypi.python.org/pypi/enum34


问:
MDI in WPF .Net Project
I have downloaded the MDI Library from the following link

https://wpfmdi.codeplex.com/ and then it placed it in bin folder of WPF project and write the

```<code>xmlns:mdi="clr-namespace:WPF.MDI;assembly=WPF.MDI"
</code>```

in xaml.cs
but when i write

```<code><mdi:MdiContainer></mdi:MdiContainer>
</code>```

I faced the error

the mdiContainer doesnot exists in current namespace
  xmlns:mdi="clr-namespace:WPF.MDI;assembly=WPF.MDI

Can anyone tell me what is the exact problem?

答: First download the solution for the WPF Multiple Document Interface (MDI) from CodePlex then build that solution and copy the output WPF.MDI.dll from the Debug folder which is inside the bin folder then reference it in your project instead of the library you downloaded first from CodePlex and it will work out. At least it worked for me :)</p>

Title: MDI in WPF .Net Project

Body:
I have downloaded the MDI Library from the following link

https://wpfmdi.codeplex.com/ and then it placed it in bin folder of WPF project and write the

xmlns:mdi="clr-namespace:WPF.MDI;assembly=WPF.MDI"

in xaml.cs
but when i write

<mdi:MdiContainer></mdi:MdiContainer>

I faced the error

the mdiContainer doesnot exists in current namespace
  xmlns:mdi="clr-namespace:WPF.MDI;assembly=WPF.MDI

Can anyone tell me what is the exact problem?


问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答:
Dependency injection is your friend. As already stated, expose the dependency via the constructor (which seems to be the typical way) or you could do it via Property injection. At any rate, when you register your dependency at application startup, you can tell the container to make it a singleton so when you ask for a reference, you get the same effect as a static reference.

For Ninject, the syntax is:

```<code>var kernel = new Ninject.StandardKernel(settings);
kernel.Bind<ISomeInterface>().To<MyConcreteObject>().InSingletonScope();
</code>```

For Unity, the syntax is:

```<code>UnityContainer container = new UnityContainer();
container.RegisterType<ISomeInterface, MyConcreteObject>(new ContainerControlledLifetimeManager());
</code>```

So your classes can be something like:

```<code>public class MyThing
{
    ISomeInterface _mySingletonObject;

    public MyThing(ISomeInterface mySingletonObject)
    {
        _mySingletonObject = mySingletonObject;
    }
}
</code>```

This class will always get the same instance of the object injected into it, provided you use the container to resolve an instance of that class.

Again, for Ninject:

```<code>var singletopnObject = kernel.Get<ISomeInterface>();
</code>```

And unity (I think from memory)

```<code>var singletopnObject = container.Resolve<ISomeInterface>();
</code>```

And all other IoC containers offer the same features in different ways.

P.S. Statics are not evil. They are fast and very useful when used properly.

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

Body:
Dependency injection is your friend. As already stated, expose the dependency via the constructor (which seems to be the typical way) or you could do it via Property injection. At any rate, when you register your dependency at application startup, you can tell the container to make it a singleton so when you ask for a reference, you get the same effect as a static reference.

For Ninject, the syntax is:

var kernel = new Ninject.StandardKernel(settings);
kernel.Bind<ISomeInterface>().To<MyConcreteObject>().InSingletonScope();

For Unity, the syntax is:

UnityContainer container = new UnityContainer();
container.RegisterType<ISomeInterface, MyConcreteObject>(new ContainerControlledLifetimeManager());

So your classes can be something like:

public class MyThing
{
    ISomeInterface _mySingletonObject;

    public MyThing(ISomeInterface mySingletonObject)
    {
        _mySingletonObject = mySingletonObject;
    }
}

This class will always get the same instance of the object injected into it, provided you use the container to resolve an instance of that class.

Again, for Ninject:

var singletopnObject = kernel.Get<ISomeInterface>();

And unity (I think from memory)

var singletopnObject = container.Resolve<ISomeInterface>();

And all other IoC containers offer the same features in different ways.

P.S. Statics are not evil. They are fast and very useful when used properly.


问:
How to make a Thread wait until an Array contains elements
I have two Threads Robot which both have an AssemblyLine lineIn and lineOut. The AssemblyLines are Arrays which contain elements. The lineOut from Robot 1 is the lineIn from Robot2, so they are "connected" via that AssemblyLine.

The Robots is picking up an element from the AssemblyLine lineIn, waiting a give amount of time and then putting the element down on the AssemblyLine lineOut.

How can I let the second robot wait or interrupt until the first robot put down the first element on the array?

That's my solution, the problem is I heard Thread.sleep() + while() generates massive overhead:

```<code>public void run() {
    PrintedBoard printedBoard = null;
    while (lineIn.size() == 0) {
        try {
            Thread.sleep(1);
        } catch(InterruptedException ie) {}
    }

    while (printedBoard != PrintedBoard.STOPPER) {
        printedBoard = lineIn.pickUp();
        try {
            Thread.sleep(time);
        } catch (InterruptedException ie) {}
        lineOut.putDown(printedBoard);
    }
}
</code>```

答:
```<code>public class AssemblyLine{

    public static void main(String[] args) throws Exception {
        BlockingQueue queue = new ArrayBlockingQueue(n); //provide queue size n

        RobotLineIn robotIn = new RobotLineIn(queue);
        RobotLineOut robotOut = new RobotLineOut(queue);

        new Thread(robotIn).start();
        new Thread(robotOut).start();
    }
}

public class RobotLineIn implements Runnable{

    private BlockingQueue queue = null;

    public RobotLineIn(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
          //read your data here from assembly line and put in queue.
        } catch (Exception e) {
        }
    }
}

public class RobotLineOut implements Runnable{

    private BlockingQueue queue = null;

    public RobotLineOut(BlockingQueue queue) {
        this.queue = queue;
    }

    public void run() {
        try {
          //read data from queue.
        } catch (Exception e) {
        }
    }
}
</code>```

Body:
I have two Threads Robot which both have an AssemblyLine lineIn and lineOut. The AssemblyLines are Arrays which contain elements. The lineOut from Robot 1 is the lineIn from Robot2, so they are "connected" via that AssemblyLine.

The Robots is picking up an element from the AssemblyLine lineIn, waiting a give amount of time and then putting the element down on the AssemblyLine lineOut.

How can I let the second robot wait or interrupt until the first robot put down the first element on the array?

That's my solution, the problem is I heard Thread.sleep() + while() generates massive overhead:

public void run() {
    PrintedBoard printedBoard = null;
    while (lineIn.size() == 0) {
        try {
            Thread.sleep(1);
        } catch(InterruptedException ie) {}
    }

    while (printedBoard != PrintedBoard.STOPPER) {
        printedBoard = lineIn.pickUp();
        try {
            Thread.sleep(time);
        } catch (InterruptedException ie) {}
        lineOut.putDown(printedBoard);
    }
}


问:
K fold cross validation using keras
It seems that k-fold cross validation in convn net is not taken seriously due to huge running time of the neural network. I have a small data-set and I am interested in doing k-fold cross validation using the example given here. Is it possible? Thanks.</p>

答:
If you are using images with data generators, here's one way to do 10-fold cross-validation with Keras and scikit-learn. The strategy is to copy the files to training, validation, and test subfolders according to each fold.

import numpy as np
import os
import pandas as pd
import shutil
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# used to copy files according to each fold
def copy_images(df, directory):
    destination_directory = "{path to your data directory}/" + directory
    print("copying {} files to {}...".format(directory, destination_directory))

    # remove all files from previous fold
    if os.path.exists(destination_directory):
        shutil.rmtree(destination_directory)

    # create folder for files from this fold
    if not os.path.exists(destination_directory):
        os.makedirs(destination_directory)

    # create subfolders for each class
    for c in set(list(df['class'])):
        if not os.path.exists(destination_directory + '/' + c):
            os.makedirs(destination_directory + '/' + c)

    # copy files for this fold from a directory holding all the files
    for i, row in df.iterrows():
        try:
            # this is the path to all of your images kept together in a separate folder
            path_from = "{path to all of your images}"
            path_from = path_from + "{}.jpg"
            path_to = "{}/{}".format(destination_directory, row['class'])

            # move from folder keeping all files to training, test, or validation folder (the "directory" argument)
            shutil.copy(path_from.format(row['filename']), path_to)
        except Exception, e:
            print("Error when copying {}: {}".format(row['filename'], str(e)))

# dataframe containing the filenames of the images (e.g., GUID filenames) and the classes
df = pd.read_csv('{path to your data}.csv')
df_y = df['class']
df_x = df
del df_x['class']

skf = StratifiedKFold(n_splits = 10)
total_actual = []
total_predicted = []
total_val_accuracy = []
total_val_loss = []
total_test_accuracy = []

for i, (train_index, test_index) in enumerate(skf.split(df_x, df_y)):
    x_train, x_test = df_x.iloc[train_index], df_x.iloc[test_index]
    y_train, y_test = df_y.iloc[train_index], df_y.iloc[test_index]

    train = pd.concat([x_train, y_train], axis=1)
    test = pd.concat([x_test, y_test], axis = 1)

    # take 20% of the training data from this fold for validation during training
    validation = train.sample(frac = 0.2)

    # make sure validation data does not include training data
    train = train[~train['filename'].isin(list(validation['filename']))]

    # copy the images according to the fold
    copy_images(train, 'training')
    copy_images(validation, 'validation')
    copy_images(test, 'test')

    print('**** Running fold '+ str(i))

    # here you call a function to create and train your model, returning validation accuracy and validation loss
    val_accuracy, val_loss = create_train_model();

    # append validation accuracy and loss for average calculation later on
    total_val_accuracy.append(val_accuracy)
    total_val_loss.append(val_loss)

    # here you will call a predict() method that will predict the images on the "test" subfolder
    # this function returns the actual classes and the predicted classes in the same order
    actual, predicted = predict()

    # append accuracy from the predictions on the test data
    total_test_accuracy.append(accuracy_score(actual, predicted))

    # append all of the actual and predicted classes for your final evaluation
    total_actual = total_actual + actual
    total_predicted = total_predicted + predicted

    # this is optional, but you can also see the performance on each fold as the process goes on
    print(classification_report(total_actual, total_predicted))
    print(confusion_matrix(total_actual, total_predicted))

print(classification_report(total_actual, total_predicted))
print(confusion_matrix(total_actual, total_predicted))
print("Validation accuracy on each fold:")
print(total_val_accuracy)
print("Mean validation accuracy: {}%".format(np.mean(total_val_accuracy) * 100))

print("Validation loss on each fold:")
print(total_val_loss)
print("Mean validation loss: {}".format(np.mean(total_val_loss)))

print("Test accuracy on each fold:")
print(total_test_accuracy)
print("Mean test accuracy: {}%".format(np.mean(total_test_accuracy) * 100))
```

<p>In your predict() function, if you are using a data generator, the only way I could find to keep the predictions in the same order when testing was to use a <code>batch_size</code> of <code>1</code>:</p>

<pre class="lang-python prettyprint-override"><code>generator = ImageDataGenerator().flow_from_directory(
        '{path to your data directory}/test',
        target_size = (img_width, img_height),
        batch_size = 1,
        color_mode = 'rgb',
        # categorical for a multiclass problem
        class_mode = 'categorical',
        # this will also ensure the same order
        shuffle = False)
</code>```

With this code, I was able to do 10-fold cross-validation using data generators (so I did not have to keep all files in memory). This can be a lot of work if you have millions of images and the batch_size = 1 could be a bottleneck if your test set is large, but for my project this worked well.

Title: K fold cross validation using keras

Body:
If you are using images with data generators, here's one way to do 10-fold cross-validation with Keras and scikit-learn. The strategy is to copy the files to training, validation, and test subfolders according to each fold.

import numpy as np
import os
import pandas as pd
import shutil
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# used to copy files according to each fold
def copy_images(df, directory):
    destination_directory = "{path to your data directory}/" + directory
    print("copying {} files to {}...".format(directory, destination_directory))

    # remove all files from previous fold
    if os.path.exists(destination_directory):
        shutil.rmtree(destination_directory)

    # create folder for files from this fold
    if not os.path.exists(destination_directory):
        os.makedirs(destination_directory)

    # create subfolders for each class
    for c in set(list(df['class'])):
        if not os.path.exists(destination_directory + '/' + c):
            os.makedirs(destination_directory + '/' + c)

    # copy files for this fold from a directory holding all the files
    for i, row in df.iterrows():
        try:
            # this is the path to all of your images kept together in a separate folder
            path_from = "{path to all of your images}"
            path_from = path_from + "{}.jpg"
            path_to = "{}/{}".format(destination_directory, row['class'])

            # move from folder keeping all files to training, test, or validation folder (the "directory" argument)
            shutil.copy(path_from.format(row['filename']), path_to)
        except Exception, e:
            print("Error when copying {}: {}".format(row['filename'], str(e)))

# dataframe containing the filenames of the images (e.g., GUID filenames) and the classes
df = pd.read_csv('{path to your data}.csv')
df_y = df['class']
df_x = df
del df_x['class']

skf = StratifiedKFold(n_splits = 10)
total_actual = []
total_predicted = []
total_val_accuracy = []
total_val_loss = []
total_test_accuracy = []

for i, (train_index, test_index) in enumerate(skf.split(df_x, df_y)):
    x_train, x_test = df_x.iloc[train_index], df_x.iloc[test_index]
    y_train, y_test = df_y.iloc[train_index], df_y.iloc[test_index]

    train = pd.concat([x_train, y_train], axis=1)
    test = pd.concat([x_test, y_test], axis = 1)

    # take 20% of the training data from this fold for validation during training
    validation = train.sample(frac = 0.2)

    # make sure validation data does not include training data
    train = train[~train['filename'].isin(list(validation['filename']))]

    # copy the images according to the fold
    copy_images(train, 'training')
    copy_images(validation, 'validation')
    copy_images(test, 'test')

    print('**** Running fold '+ str(i))

    # here you call a function to create and train your model, returning validation accuracy and validation loss
    val_accuracy, val_loss = create_train_model();

    # append validation accuracy and loss for average calculation later on
    total_val_accuracy.append(val_accuracy)
    total_val_loss.append(val_loss)

    # here you will call a predict() method that will predict the images on the "test" subfolder
    # this function returns the actual classes and the predicted classes in the same order
    actual, predicted = predict()

    # append accuracy from the predictions on the test data
    total_test_accuracy.append(accuracy_score(actual, predicted))

    # append all of the actual and predicted classes for your final evaluation
    total_actual = total_actual + actual
    total_predicted = total_predicted + predicted

    # this is optional, but you can also see the performance on each fold as the process goes on
    print(classification_report(total_actual, total_predicted))
    print(confusion_matrix(total_actual, total_predicted))

print(classification_report(total_actual, total_predicted))
print(confusion_matrix(total_actual, total_predicted))
print("Validation accuracy on each fold:")
print(total_val_accuracy)
print("Mean validation accuracy: {}%".format(np.mean(total_val_accuracy) * 100))

print("Validation loss on each fold:")
print(total_val_loss)
print("Mean validation loss: {}".format(np.mean(total_val_loss)))

print("Test accuracy on each fold:")
print(total_test_accuracy)
print("Mean test accuracy: {}%".format(np.mean(total_test_accuracy) * 100))

In your predict() function, if you are using a data generator, the only way I could find to keep the predictions in the same order when testing was to use a batch_size of 1:

generator = ImageDataGenerator().flow_from_directory(
        '{path to your data directory}/test',
        target_size = (img_width, img_height),
        batch_size = 1,
        color_mode = 'rgb',
        # categorical for a multiclass problem
        class_mode = 'categorical',
        # this will also ensure the same order
        shuffle = False)

With this code, I was able to do 10-fold cross-validation using data generators (so I did not have to keep all files in memory). This can be a lot of work if you have millions of images and the batch_size = 1 could be a bottleneck if your test set is large, but for my project this worked well.


问:
How could the test_and_set() instruction still work on a multiprocessor?
Dear stack overflow community,

I'm reading Operating System Concepts (2012) by Silberschatz, Galvin and Gagne, it says "if two test_and_set() instructions are executed simultaneously (each on a different CPU), they will be executed sequentially in some arbitrary order." on page 210, I cannot understand why two such institutions will be executed sequentially even on a multiprocessor. What if each instruction is executed on a different processor? To the best of my knowledge, these two institutions be executed simultaneously.

My understanding of the atomicity of instructions and the multiprocessor stays at a quite superficial level, so I may take the problem for granted. Could anyone help me out here?

答:
The outcome depends upon the machine instruction. Let me use the VAX as an example as it is an easy to understand processor:

http://www.ece.lsu.edu/ee4720/doc/vax.pdf

The VAX has a BBSS (Branch on Bit Set and Set) instruction and a BBSSI (Branch on Bit Set and Set Interlocked) instruction.

If you have 2 processors doing a BBSS on the same clear bit you could get:

```<code>P1 Tests Bit (Clear)
P2 Tests Bit (Clear)
P1 Sets Bit and does not branch
P2 Sets Bit and dot not branch
</code>```

If you do a BBSSI on the same bit, the processor locks the memory. You get

```<code>p1 locks the memory
p1 Tests Bit (Clear)
P2 Tests Bit and is Blocked
P1 Sets Bit and does not branch
p1 unlocks the memory
P2 Tests Bit (SET)
P2 Branches
</code>```

Instructions do not execute in a single step for the most part and the processors can operate independently of each other.

Body:
The outcome depends upon the machine instruction. Let me use the VAX as an example as it is an easy to understand processor:

http://www.ece.lsu.edu/ee4720/doc/vax.pdf

The VAX has a BBSS (Branch on Bit Set and Set) instruction and a BBSSI (Branch on Bit Set and Set Interlocked) instruction.

If you have 2 processors doing a BBSS on the same clear bit you could get:

P1 Tests Bit (Clear)
P2 Tests Bit (Clear)
P1 Sets Bit and does not branch
P2 Sets Bit and dot not branch

If you do a BBSSI on the same bit, the processor locks the memory. You get

p1 locks the memory
p1 Tests Bit (Clear)
P2 Tests Bit and is Blocked
P1 Sets Bit and does not branch
p1 unlocks the memory
P2 Tests Bit (SET)
P2 Branches

Instructions do not execute in a single step for the most part and the processors can operate independently of each other.