问:
How can I make an animation on page load to move re-arrange some elements to its original position?
I am having some troubles trying to make this animation:
What I need is that when the page loads, the icons must be a little bit up of its original position.
So:

On page load the icons are 5px higher than its original positions.

Trigger animation to re-arrange icons to its original positions(remove the 5px higher).

Here is the code I have so far:

var outerBox = $('.eight-box'),
    boxHeight = $(outerBox).height(),
    boxWidth = $(outerBox).width();
function changeNumbers() {
  var pos1 = $('.pos-1'),
      pos2 = $('.pos-2'),
      pos3 = $('.pos-3'),
      pos4 = $('.pos-4'),
      pos5 = $('.pos-5'),
      pos6 = $('.pos-6'),
      pos7 = $('.pos-7'),
      pos8 = $('.pos-8'),
      pos9 = $('.pos-9'),
      pos10 = $('.pos-10'),
      pos11 = $('.pos-11'),
      pos12 = $('.pos-12'),
      pos13 = $('.pos-13'),
      pos14 = $('.pos-14'),
      pos15 = $('.pos-15');
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.eight-box {
 position: relative;
 display: block;
 margin: 1em auto;
 width: 16em;
 height: 24em;
  font-family: sans-serif;
  font-size: 20px;
}
.fig-8 {
 display: block;
 position: absolute;
 color: #fff;
 width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}
.fig-8:before {
  display: block;
  content: '';
  background: rgba(0,0,0,.15);
/*  box-shadow: 0 0 .25em 0 rgba(0,0,0,.2), inset 0 0 2px rgba(0,0,0,.25);*/
  width: .65em;
  height: .65em;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.fig-8:after {
  content: '';
  width: 2em;
  height: 2em;
  background: #fff;
  transform: rotate(45deg);
  z-index: 20;
  position: absolute;
  top: -1.4em;
  left: -1.4em;
}
.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}
.col-5 {
 background: #e74c3c;
}
.col-6 {
 background: #f39c12;
}
.col-7 {
 background: #bdc3c7;
}
.col-8 {
 background: #2ecc71;
}
.col-9 {
 background: #34495e;
}
.col-10 {
 background: #2980b9;
}
.col-11 {
 background: #f1c40f;
}
.col-12 {
 background: #d35400;
}
.col-13 {
 background: #7f8c8d;
}
.col-14 {
 background: #3498db;
}
.col-15 {
 background: #16a085;
}
.pos-1 {
 top: 0;
 left: 43.75%;
}
.pos-2 {
 top: 6.25%;
 left: 68.75%;
}
.pos-3 {
 top: 22.92%;
 left: 78.125%;
}
.pos-4 {
 top: 39.58%;
 left: 68.75%;
}
.pos-5 {
 top: 45.83%;
 left: 43.75%;
}
.pos-6 {
 top: 52.08%;
 left: 18.75%;
}
.pos-7 {
 top: 68.75%;
 left: 9.375%;
}
.pos-8 {
 top: 85.417%;
 left: 18.75%;
}
.pos-9 {
 top: 91.67%;
 left: 43.75%;
}
.pos-10 {
 top: 85.417%;
 left: 68.75%;
}
.pos-11 {
 top: 68.75%;
 left: 78.125%;
}
.pos-12 {
 top: 52.08%;
 left: 68.75%;
}
.pos-13 {
 top: 39.58%;
 left: 18.75%;
}
.pos-14 {
 top: 22.92%;
 left: 9.375%;
}
.pos-15 {
 top: 6.25%;
 left: 18.75%;
}
.smile {
  position: absolute;
  width: 2em;
  height: 2em;
  line-height: 1.8;
  transform: rotate(90deg);
  text-align: center;
  border-radius: 50%;
/*  box-shadow: inset 0 0 0 2px #333;*/
  background: moccasin;
}
.smile-1 {
  top: 22.92%;
  left: 43.75%;
}
.smile-2 {
  top: 68.75%;
  left: 43.75%;
}

.eight-box {
 position: relative;
 display: block;
 margin: 1em auto;
 width: 16em;
 height: 24em;
  font-family: sans-serif;
  font-size: 20px;
}
.fig-8 {
 display: block;
 position: absolute;
 color: #fff;
 width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}
.fig-8:before {
  display: block;
  content: '';
  background: rgba(0,0,0,.15);
/*  box-shadow: 0 0 .25em 0 rgba(0,0,0,.2), inset 0 0 2px rgba(0,0,0,.25);*/
  width: .65em;
  height: .65em;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.fig-8:after {
  content: '';
  width: 2em;
  height: 2em;
  background: #fff;
  transform: rotate(45deg);
  z-index: 20;
  position: absolute;
  top: -1.4em;
  left: -1.4em;
}
.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}
.col-5 {
 background: #e74c3c;
}
.col-6 {
 background: #f39c12;
}
.col-7 {
 background: #bdc3c7;
}
.col-8 {
 background: #2ecc71;
}
.col-9 {
 background: #34495e;
}
.col-10 {
 background: #2980b9;
}
.col-11 {
 background: #f1c40f;
}
.col-12 {
 background: #d35400;
}
.col-13 {
 background: #7f8c8d;
}
.col-14 {
 background: #3498db;
}
.col-15 {
 background: #16a085;
}
.pos-1 {
 top: 0;
 left: 43.75%;
}
.pos-2 {
 top: 6.25%;
 left: 68.75%;
}
.pos-3 {
 top: 22.92%;
 left: 78.125%;
}
.pos-4 {
 top: 39.58%;
 left: 68.75%;
}
.pos-5 {
 top: 45.83%;
 left: 43.75%;
}
.pos-6 {
 top: 52.08%;
 left: 18.75%;
}
.pos-7 {
 top: 68.75%;
 left: 9.375%;
}
.pos-8 {
 top: 85.417%;
 left: 18.75%;
}
.pos-9 {
 top: 91.67%;
 left: 43.75%;
}
.pos-10 {
 top: 85.417%;
 left: 68.75%;
}
.pos-11 {
 top: 68.75%;
 left: 78.125%;
}
.pos-12 {
 top: 52.08%;
 left: 68.75%;
}
.pos-13 {
 top: 39.58%;
 left: 18.75%;
}
.pos-14 {
 top: 22.92%;
 left: 9.375%;
}
.pos-15 {
 top: 6.25%;
 left: 18.75%;
}
.smile {
  position: absolute;
  width: 2em;
  height: 2em;
  line-height: 1.8;
  transform: rotate(90deg);
  text-align: center;
  border-radius: 50%;
/*  box-shadow: inset 0 0 0 2px #333;*/
  background: moccasin;
}
.smile-1 {
  top: 22.92%;
  left: 43.75%;
}
.smile-2 {
  top: 68.75%;
  left: 43.75%;
}

.fig-8 {
    animation: pulse-special 1s 1s infinite alternate backwards;
    border-radius: 50%;
}
@-webkit-keyframes pulse-special {
    0% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -webkit-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}
@keyframes pulse-special {
    0% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -moz-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}</code>```

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

: )

: )

```

What do you suggest?

答:
I'm not sure if I understand, but you just need an animation that moves them down on all of the elements. Such as:

div {
  animation: moveDown 1s;
}

@keyframes moveDown {
  from {  margin-top: -5px  }
  to {  margin-top: 0  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Some text</div></code>```

Body:
I am having some troubles trying to make this animation:
What I need is that when the page loads, the icons must be a little bit up of its original position.
So:

On page load the icons are 5px higher than its original positions.

Trigger animation to re-arrange icons to its original positions(remove the 5px higher).

Here is the code I have so far:

var outerBox = $('.eight-box'),
    boxHeight = $(outerBox).height(),
    boxWidth = $(outerBox).width();
function changeNumbers() {
  var pos1 = $('.pos-1'),
      pos2 = $('.pos-2'),
      pos3 = $('.pos-3'),
      pos4 = $('.pos-4'),
      pos5 = $('.pos-5'),
      pos6 = $('.pos-6'),
      pos7 = $('.pos-7'),
      pos8 = $('.pos-8'),
      pos9 = $('.pos-9'),
      pos10 = $('.pos-10'),
      pos11 = $('.pos-11'),
      pos12 = $('.pos-12'),
      pos13 = $('.pos-13'),
      pos14 = $('.pos-14'),
      pos15 = $('.pos-15');
};

.eight-box {
 position: relative;
 display: block;
 margin: 1em auto;
 width: 16em;
 height: 24em;
  font-family: sans-serif;
  font-size: 20px;
}
.fig-8 {
 display: block;
 position: absolute;
 color: #fff;
 width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}
.fig-8:before {
  display: block;
  content: '';
  background: rgba(0,0,0,.15);
/*  box-shadow: 0 0 .25em 0 rgba(0,0,0,.2), inset 0 0 2px rgba(0,0,0,.25);*/
  width: .65em;
  height: .65em;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.fig-8:after {
  content: '';
  width: 2em;
  height: 2em;
  background: #fff;
  transform: rotate(45deg);
  z-index: 20;
  position: absolute;
  top: -1.4em;
  left: -1.4em;
}
.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}
.col-5 {
 background: #e74c3c;
}
.col-6 {
 background: #f39c12;
}
.col-7 {
 background: #bdc3c7;
}
.col-8 {
 background: #2ecc71;
}
.col-9 {
 background: #34495e;
}
.col-10 {
 background: #2980b9;
}
.col-11 {
 background: #f1c40f;
}
.col-12 {
 background: #d35400;
}
.col-13 {
 background: #7f8c8d;
}
.col-14 {
 background: #3498db;
}
.col-15 {
 background: #16a085;
}
.pos-1 {
 top: 0;
 left: 43.75%;
}
.pos-2 {
 top: 6.25%;
 left: 68.75%;
}
.pos-3 {
 top: 22.92%;
 left: 78.125%;
}
.pos-4 {
 top: 39.58%;
 left: 68.75%;
}
.pos-5 {
 top: 45.83%;
 left: 43.75%;
}
.pos-6 {
 top: 52.08%;
 left: 18.75%;
}
.pos-7 {
 top: 68.75%;
 left: 9.375%;
}
.pos-8 {
 top: 85.417%;
 left: 18.75%;
}
.pos-9 {
 top: 91.67%;
 left: 43.75%;
}
.pos-10 {
 top: 85.417%;
 left: 68.75%;
}
.pos-11 {
 top: 68.75%;
 left: 78.125%;
}
.pos-12 {
 top: 52.08%;
 left: 68.75%;
}
.pos-13 {
 top: 39.58%;
 left: 18.75%;
}
.pos-14 {
 top: 22.92%;
 left: 9.375%;
}
.pos-15 {
 top: 6.25%;
 left: 18.75%;
}
.smile {
  position: absolute;
  width: 2em;
  height: 2em;
  line-height: 1.8;
  transform: rotate(90deg);
  text-align: center;
  border-radius: 50%;
/*  box-shadow: inset 0 0 0 2px #333;*/
  background: moccasin;
}
.smile-1 {
  top: 22.92%;
  left: 43.75%;
}
.smile-2 {
  top: 68.75%;
  left: 43.75%;
}

.eight-box {
 position: relative;
 display: block;
 margin: 1em auto;
 width: 16em;
 height: 24em;
  font-family: sans-serif;
  font-size: 20px;
}
.fig-8 {
 display: block;
 position: absolute;
 color: #fff;
 width: 2em;
  height: 2em;
  line-height: 2;
  text-align: center;
  font-weight: bold;
  font-smoothing: antialiased;
 transition: all .5s linear;
  overflow: hidden;
  z-index: 5;
}
.fig-8:before {
  display: block;
  content: '';
  background: rgba(0,0,0,.15);
/*  box-shadow: 0 0 .25em 0 rgba(0,0,0,.2), inset 0 0 2px rgba(0,0,0,.25);*/
  width: .65em;
  height: .65em;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
}
.fig-8:after {
  content: '';
  width: 2em;
  height: 2em;
  background: #fff;
  transform: rotate(45deg);
  z-index: 20;
  position: absolute;
  top: -1.4em;
  left: -1.4em;
}
.col-1 {
 background: #1abc9c;
}
.col-2 {
 background: #9b59b6;
}
.col-3 {
 background: #27ae60;
}
.col-4 {
 background: #2c3e50;
}
.col-5 {
 background: #e74c3c;
}
.col-6 {
 background: #f39c12;
}
.col-7 {
 background: #bdc3c7;
}
.col-8 {
 background: #2ecc71;
}
.col-9 {
 background: #34495e;
}
.col-10 {
 background: #2980b9;
}
.col-11 {
 background: #f1c40f;
}
.col-12 {
 background: #d35400;
}
.col-13 {
 background: #7f8c8d;
}
.col-14 {
 background: #3498db;
}
.col-15 {
 background: #16a085;
}
.pos-1 {
 top: 0;
 left: 43.75%;
}
.pos-2 {
 top: 6.25%;
 left: 68.75%;
}
.pos-3 {
 top: 22.92%;
 left: 78.125%;
}
.pos-4 {
 top: 39.58%;
 left: 68.75%;
}
.pos-5 {
 top: 45.83%;
 left: 43.75%;
}
.pos-6 {
 top: 52.08%;
 left: 18.75%;
}
.pos-7 {
 top: 68.75%;
 left: 9.375%;
}
.pos-8 {
 top: 85.417%;
 left: 18.75%;
}
.pos-9 {
 top: 91.67%;
 left: 43.75%;
}
.pos-10 {
 top: 85.417%;
 left: 68.75%;
}
.pos-11 {
 top: 68.75%;
 left: 78.125%;
}
.pos-12 {
 top: 52.08%;
 left: 68.75%;
}
.pos-13 {
 top: 39.58%;
 left: 18.75%;
}
.pos-14 {
 top: 22.92%;
 left: 9.375%;
}
.pos-15 {
 top: 6.25%;
 left: 18.75%;
}
.smile {
  position: absolute;
  width: 2em;
  height: 2em;
  line-height: 1.8;
  transform: rotate(90deg);
  text-align: center;
  border-radius: 50%;
/*  box-shadow: inset 0 0 0 2px #333;*/
  background: moccasin;
}
.smile-1 {
  top: 22.92%;
  left: 43.75%;
}
.smile-2 {
  top: 68.75%;
  left: 43.75%;
}

.fig-8 {
    animation: pulse-special 1s 1s infinite alternate backwards;
    border-radius: 50%;
}
@-webkit-keyframes pulse-special {
    0% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -webkit-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -webkit-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}
@keyframes pulse-special {
    0% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, .9);
    }
    70% {
        -moz-box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 10px rgba(0, 115, 207, 0);
    }
    100% {
        -moz-box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
        box-shadow: 0 0 0 0 rgba(0, 115, 207, 0);
    }
}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

: )

: )

What do you suggest?

Body:
I'm not sure if I understand, but you just need an animation that moves them down on all of the elements. Such as:

div {
  animation: moveDown 1s;
}

@keyframes moveDown {
  from {  margin-top: -5px  }
  to {  margin-top: 0  }
}

<div>Some text</div>


来源: stackexchange

问:
How to hide the yellow console.logs in nodemon
Is it possible to hide the yellow logs that displays when you start en watch with nodemon?

below is displayed in yellow in the console.

```<code>[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /var/www/test/server/core/src/**/*
</code>```

答:
From the documentation returned by nodemon -h:

-q, --quiet .............. minimise nodemon messages to start/stop only.

So run:

```<code>nodemon --quiet your-file.js
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to hide the yellow logs that displays when you start en watch with nodemon?

below is displayed in yellow in the console.

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: /var/www/test/server/core/src/**/*

Body:
From the documentation returned by nodemon -h:

-q, --quiet .............. minimise nodemon messages to start/stop only.

So run:

nodemon --quiet your-file.js


问:
pip install module over proxy firewall
pip install with proxy firewall.

Someone referred me into looking at proxy and how I can put in arguments to get pass the proxy server and install the said python module. One of the link I found suggested I install CNTLM. >>
Using pip behind a proxy

This suggestion needs installation which the proxy prevents so is not going to work.

答:
It worked with me :</p>

```<code>pip --proxy http://[user]:[password]@proxy:[port] install module
</code>```

Title: pip install module over proxy firewall

Body:
It worked with me :

pip --proxy http://[user]:[password]@proxy:[port] install module


问:
ASP.NET Focus Scrolls Page to Input
I have a few textboxes/labels inside of an UpdatePanel. When I tab out of one of the textboxes, a label has to be updated with some text. This causes focus on the page to reset to the topmost element.

This is a data-entry form and the users expect to not have to use the mouse at all. I can set focus back on the correct textbox in code:

```<code>Page.SetFocus(tbxInput);
</code>```

or

```<code>tbxInput.Focus();
</code>```

In IE, the browser scroll position is maintained (woo hoo!). In Chrome and Firefox it is not; the scroll location is adjusted so that the focused textbox is the last element shown on the page. This is really disturbing to the user.

I am using the following rules in my web.config:

```<code><pages theme="Default" styleSheetTheme="Default" maintainScrollPositionOnPostBack="true" validateRequest="false">
</code>```

How can I achieve the behavior that IE has?

答: For this kind of thing I update the label text from javascript (possibly using an AJAX call to a web service or page method).  </p>

ContentLicense: CC BY-SA 2.5

Title: ASP.NET Focus Scrolls Page to Input

Body:
I have a few textboxes/labels inside of an UpdatePanel. When I tab out of one of the textboxes, a label has to be updated with some text. This causes focus on the page to reset to the topmost element.

This is a data-entry form and the users expect to not have to use the mouse at all. I can set focus back on the correct textbox in code:

Page.SetFocus(tbxInput);

or

tbxInput.Focus();

In IE, the browser scroll position is maintained (woo hoo!). In Chrome and Firefox it is not; the scroll location is adjusted so that the focused textbox is the last element shown on the page. This is really disturbing to the user.

I am using the following rules in my web.config:

<pages theme="Default" styleSheetTheme="Default" maintainScrollPositionOnPostBack="true" validateRequest="false">

How can I achieve the behavior that IE has?


问:
React-Native send multipart/form-data through HTTP
I have a react-native app that needs to send video/images to my server. I already know that normal posts work but when I attempt to send a formData object, it seems to never leave the phone. Here is my code.

```<code>// method = 'POST';
// body = new formData();
// body contains text data and image/video file
const post = (url, body, token, method) => {
  let xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader('Authorization', 'Bearer' + token);
  xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=---------------------------7692764ac82');
  xhr.send(body);
  console.log(xhr);
  return xhr.response;
}
</code>```

body is a formData object that contains an image/video.  In the object that xhr prints at the console log the _response contains "Binary FormData part needs a content-type header." But it seems I set it correctly right?

Please help, there are other similar questions but I have run out of ideas.  I have also tried using fetch with no success.

答:
The error message is not about the content-type header for the request (which you have set), it's about the content-type header for the part (which you did not show, so we have to assume it is missing).

When you add the parts to the FormData, don't forget to include a type. Example for an image:

```<code>const body = new FormData();
// ...
body.append('image', {
    uri: 'file:///...',
    type: 'image/jpeg',  // <-  Did you miss that one?
    name: 'someName',
});
</code>```

With the type properly set, the React Native runtime should add a content-type header for the part. This is done in FormData.js at line 79 in v0.46.0 (wherein value is the value for your type property):

```<code>if (typeof value.type === 'string') {
    headers['content-type'] = value.type;
}
</code>```

So, when type is missing, then content-type header for the part is missing, and then on Android you end up here, where you can see the origin of your error message.

This exact error and root cause is discussed in that GitHub issue.

Body:
I have a react-native app that needs to send video/images to my server. I already know that normal posts work but when I attempt to send a formData object, it seems to never leave the phone. Here is my code.

// method = 'POST';
// body = new formData();
// body contains text data and image/video file
const post = (url, body, token, method) => {
  let xhr = new XMLHttpRequest();
  xhr.open(method, url);
  xhr.setRequestHeader('Authorization', 'Bearer' + token);
  xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=---------------------------7692764ac82');
  xhr.send(body);
  console.log(xhr);
  return xhr.response;
}

body is a formData object that contains an image/video.  In the object that xhr prints at the console log the _response contains "Binary FormData part needs a content-type header." But it seems I set it correctly right?

Please help, there are other similar questions but I have run out of ideas.  I have also tried using fetch with no success.

Body:
The error message is not about the content-type header for the request (which you have set), it's about the content-type header for the part (which you did not show, so we have to assume it is missing).

When you add the parts to the FormData, don't forget to include a type. Example for an image:

const body = new FormData();
// ...
body.append('image', {
    uri: 'file:///...',
    type: 'image/jpeg',  // <-  Did you miss that one?
    name: 'someName',
});

With the type properly set, the React Native runtime should add a content-type header for the part. This is done in FormData.js at line 79 in v0.46.0 (wherein value is the value for your type property):

if (typeof value.type === 'string') {
    headers['content-type'] = value.type;
}

So, when type is missing, then content-type header for the part is missing, and then on Android you end up here, where you can see the origin of your error message.

This exact error and root cause is discussed in that GitHub issue.


问:
How to set an icon image for an application?
When I start my application, the icon on the desktop looks like this:

I want to know if there is a way I can change that image to an image of my choosing?

答:
Give this a try.

```<code>frame.setIconImage(new ImageIO.read(new File("res/game.png")));
</code>```

where res/game.png is the icon image you want to use

https://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html#ImageIcon(java.lang.String)

https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

Body:
Give this a try.

frame.setIconImage(new ImageIO.read(new File("res/game.png")));

where res/game.png is the icon image you want to use

https://docs.oracle.com/javase/7/docs/api/javax/swing/ImageIcon.html#ImageIcon(java.lang.String)

https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html


问:
Read sms shows only current month sms
I am trying to dump sms to text file but it only reads current month messages starting from date 1 upto current date. How can i possibly read all sms without setting app as default or anything like that?</p>

```<code>public List<Sms> getAllSms() {
    List<Sms> lstSms = new ArrayList<Sms>();
    Sms objSms = new Sms();
    Uri message = Uri.parse("content://sms/");
    ContentResolver cr = this.getContentResolver();

    Cursor c = cr.query(message, null, null, null, null);
    this.startManagingCursor(c);
    int totalSMS = c.getCount();

    if (c.moveToFirst()) {
        for (int i = 0; i < totalSMS; i++) {

            objSms = new Sms();
            objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
            objSms.setAddress(c.getString(c
                                          .getColumnIndexOrThrow("address")));
            objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
            objSms.setReadState(c.getString(c.getColumnIndex("read")));
            String date = c.getString(c.getColumnIndexOrThrow("date"));
            Long timestamp = Long.parseLong(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timestamp);
            Date finaldate = calendar.getTime();
            objSms.setTime(finaldate.toString());
            if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
                objSms.setFolderName("inbox");
            } else {
                objSms.setFolderName("sent");
            }

            lstSms.add(objSms);
            c.moveToNext();
        }
    }
    // else {
    // throw new RuntimeException("You have no SMS");
    // }
    c.close();

    return lstSms;
}
</code>```

答: Reading inbox and sent seperately solved my issue</p>

Title: Read sms shows only current month sms

Body:
I am trying to dump sms to text file but it only reads current month messages starting from date 1 upto current date. How can i possibly read all sms without setting app as default or anything like that?

public List<Sms> getAllSms() {
    List<Sms> lstSms = new ArrayList<Sms>();
    Sms objSms = new Sms();
    Uri message = Uri.parse("content://sms/");
    ContentResolver cr = this.getContentResolver();

    Cursor c = cr.query(message, null, null, null, null);
    this.startManagingCursor(c);
    int totalSMS = c.getCount();

    if (c.moveToFirst()) {
        for (int i = 0; i < totalSMS; i++) {

            objSms = new Sms();
            objSms.setId(c.getString(c.getColumnIndexOrThrow("_id")));
            objSms.setAddress(c.getString(c
                                          .getColumnIndexOrThrow("address")));
            objSms.setMsg(c.getString(c.getColumnIndexOrThrow("body")));
            objSms.setReadState(c.getString(c.getColumnIndex("read")));
            String date = c.getString(c.getColumnIndexOrThrow("date"));
            Long timestamp = Long.parseLong(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timestamp);
            Date finaldate = calendar.getTime();
            objSms.setTime(finaldate.toString());
            if (c.getString(c.getColumnIndexOrThrow("type")).contains("1")) {
                objSms.setFolderName("inbox");
            } else {
                objSms.setFolderName("sent");
            }

            lstSms.add(objSms);
            c.moveToNext();
        }
    }
    // else {
    // throw new RuntimeException("You have no SMS");
    // }
    c.close();

    return lstSms;
}


问:
How do I define an optional parameter in my Laravel routes?
I would like to define {id} an optional parameter in the following route:

```<code>Route::get('profile/edit/{id}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));
</code>```

How can I do this and also define a default parameter if one isn't provided?

答:
```<code>Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));
</code>```

you can pass {id?} for optional parameters in your route.

Laravel will take it as a optional. it is called as a wild card in laravel

Body:
I would like to define {id} an optional parameter in the following route:

Route::get('profile/edit/{id}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));

How can I do this and also define a default parameter if one isn't provided?

Body:
Route::get('profile/edit/{id?}', array('uses' => 'BusinessController@editProfile', 'as' => 'profile.edit'));

you can pass {id?} for optional parameters in your route.

Laravel will take it as a optional. it is called as a wild card in laravel


问:
AdControl not showing ads, even after uploading the app to the store
I Uploaded app an UWP app to the windows 10 store whil using AdControl to show ads in my app.

My Add Control doesn't show me ads, it just stay blank and throwing the next error:  "No ad available. No additional information""

In the dashbored - monetize I created ad unit name and got ad unit ID app ID and ad unit name as shown in here:

in the xaml file:

```<code><UI:AdControl ApplicationId="78eefbba-92ef-466f-bec3-81e17f9c36d4"
     AdUnitId="332861"
     Name="adControl"
     Height="60"
     Width="480"
     Grid.Row="5"
     HorizontalAlignment="Center"
     ErrorOccurred="OnAdError"
     Grid.ColumnSpan="6"
     Grid.Column="0"/>
</code>```

and wen i debug my app I'm getting:

e.ErrorCode:NoAdAvailable

and in OnAdError event I'm getting:

e.ErrorCode:NoAdAvailable
  ErrorMessage: no ad available. No additional information

what did i do worng? and how can i fix it?

Editted:
the problem was solved, as Romasz comment the ad wasn't in the right size.
another importent thing to notice is that in dev, even we the right size you may not see the ad until the app is published.

答:
It is not a size problem, phone sizes will also be displayed on desktop (proof).

It is only a matter of lack of ads.

edit : period of the year seems to be a very high factor : my personal ads fillrate was around 10% during july and august, it is now about 85% since september (on PC, date of edit is the 14th of october).

Body:
I Uploaded app an UWP app to the windows 10 store whil using AdControl to show ads in my app.

My Add Control doesn't show me ads, it just stay blank and throwing the next error:  "No ad available. No additional information""

In the dashbored - monetize I created ad unit name and got ad unit ID app ID and ad unit name as shown in here:

in the xaml file:

<UI:AdControl ApplicationId="78eefbba-92ef-466f-bec3-81e17f9c36d4"
     AdUnitId="332861"
     Name="adControl"
     Height="60"
     Width="480"
     Grid.Row="5"
     HorizontalAlignment="Center"
     ErrorOccurred="OnAdError"
     Grid.ColumnSpan="6"
     Grid.Column="0"/>

and wen i debug my app I'm getting:

e.ErrorCode:NoAdAvailable

and in OnAdError event I'm getting:

e.ErrorCode:NoAdAvailable
  ErrorMessage: no ad available. No additional information

what did i do worng? and how can i fix it?

Editted:
the problem was solved, as Romasz comment the ad wasn't in the right size.
another importent thing to notice is that in dev, even we the right size you may not see the ad until the app is published.


答:
Just put a question mark after it in the route, and give it a default in the function:

```<code>Route::get('profile/edit/{id?}', ...
public function editProfile ($id = 123) { ... }
</code>```

Documentation: https://laravel.com/docs/5.4/routing#parameters-optional-parameters

Title: How do I define an optional parameter in my Laravel routes?

Body:
Just put a question mark after it in the route, and give it a default in the function:

Route::get('profile/edit/{id?}', ...
public function editProfile ($id = 123) { ... }

Documentation: https://laravel.com/docs/5.4/routing#parameters-optional-parameters


问:
OpenCV C++ create reusable set of keypoints and descriptors for stitching multiple images
I have created a program that can stitch multiple images together and am now looking to improve the efficiency of it. Depending on the size of the stitched image, eventually it is to large and contains too many keypoints that the machine runs out of allocatable memory. To compensate for this my goal is to store all the keypoints and descriptors as they are found so that I don't need to find them again in the master stitched image and only need to find them in the new image being stitched. I had this process working in python but haven't had the same luck in C++.
In order to do this I need to perform a perspectiveTransform() on the keypoints and therefor convert them from vector<keypoint> to vector<point2f> and back to vector<keypoint>. I have been able to achieve this and can confirm it works (pick to follow). I am not sure if the same process needs to be done to the descriptors (currently I have don it but either its wrong or not effective).

Issue: When I run this the keypoints and descriptors don't appear to work and I throw an error I created being: "Not enough matches found" even though I know at least the keypoints are making its way to the function.

Here is the code for the keypoint and descriptor transforms. The code first calculates the warpPerspective to be applied to image one as homography will warp the second image only. The rest of the codd deals with keypoints and descriptors.

```<code>tuple<Mat, vector<KeyPoint>, Mat>  stitchMatches(Mat image1,Mat image2, Mat homography, vector<KeyPoint> kp1, vector<KeyPoint> kp2 , Mat desc1, Mat desc2){
    Mat result, destination, descriptors_updated;
    vector<Point2f> fourPoint;
    vector<KeyPoint> keypoints_updated;

    //-Get the four corners of the first image (master)
    fourPoint.push_back(Point2f (0,0));
    fourPoint.push_back(Point2f (image1.size().width,0));
    fourPoint.push_back(Point2f (0, image1.size().height));
    fourPoint.push_back(Point2f (image1.size().width, image1.size().height));
    //perspectiveTransform(Mat(fourPoint), destination, homography);

    //- Get points used to determine Htr
    double min_x, min_y, tam_x, tam_y;
    float min_x1, min_x2, min_y1, min_y2, max_x1, max_x2, max_y1, max_y2;
    min_x1 = min(fourPoint.at(0).x, fourPoint.at(1).x);
    min_x2 = min(fourPoint.at(2).x, fourPoint.at(3).x);
    min_y1 = min(fourPoint.at(0).y, fourPoint.at(1).y);
    min_y2 = min(fourPoint.at(2).y, fourPoint.at(3).y);
    max_x1 = max(fourPoint.at(0).x, fourPoint.at(1).x);
    max_x2 = max(fourPoint.at(2).x, fourPoint.at(3).x);
    max_y1 = max(fourPoint.at(0).y, fourPoint.at(1).y);
    max_y2 = max(fourPoint.at(2).y, fourPoint.at(3).y);
    min_x = min(min_x1, min_x2);
    min_y = min(min_y1, min_y2);
    tam_x = max(max_x1, max_x2);
    tam_y = max(max_y1, max_y2);

    //- Htr use to map image one to result in line with the alredy warped image 1
    Mat Htr = Mat::eye(3,3,CV_64F);
    if (min_x < 0){
        tam_x = image2.size().width - min_x;
        Htr.at<double>(0,2)= -min_x;
    }
    if (min_y < 0){
        tam_y = image2.size().height - min_y;
        Htr.at<double>(1,2)= -min_y;
    }

    result = Mat(Size(tam_x*2,tam_y*2), CV_8UC3,cv::Scalar(0,0,0));
    warpPerspective(image2, result, Htr, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   0);
    warpPerspective(image1, result, (Htr*homography), result.size(), INTER_LINEAR, BORDER_TRANSPARENT,0);

    //-- Variables to hold the keypoints at the respective stages
    vector<Point2f> kp1Local,kp2Local;
    vector<KeyPoint> kp1updated, kp2updated;

    //Localize the keypoints to allow for perspective change
    KeyPoint::convert(kp1, kp1Local);
    KeyPoint::convert(kp2, kp2Local);

    //perform persepctive transform on the keypoints of type vector<point2f>
    perspectiveTransform(kp1Local, kp1Local, (Htr));
    perspectiveTransform(kp2Local, kp2Local, (Htr*homography));

    //convert keypoints back to type vector<keypoint>
    for( size_t i = 0; i < kp1Local.size(); i++ ) {
        kp1updated.push_back(KeyPoint(kp1Local[i], 1.f));
    }
    for( size_t i = 0; i < kp2Local.size(); i++ ) {
        kp2updated.push_back(KeyPoint(kp2Local[i], 1.f));
    }

    //Add to master of list of keypoints to be passed along during next iteration of image
    keypoints_updated.reserve(kp1updated.size() + kp2updated.size());
    keypoints_updated.insert(keypoints_updated.end(),kp1updated.begin(),kp1updated.end());
    keypoints_updated.insert(keypoints_updated.end(),kp2updated.begin(),kp2updated.end());

    //WarpPerspective of decriptors to match that of the images and cooresponding keypoints
    Mat desc1New, desc2New;
    warpPerspective(desc2, desc2New, Htr, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   0);
    warpPerspective(desc1, desc1New, (Htr*homography), result.size(), INTER_LINEAR, BORDER_TRANSPARENT,0);

    //create a new Mat including the descriports from desc1 and desc2
    descriptors_updated.push_back(desc1New);
    descriptors_updated.push_back(desc2New);

    //------------TEST TO see if keypoints have moved

    Mat img_keypoints;
    drawKeypoints( result, keypoints_updated, img_keypoints, Scalar::all(-1), DrawMatchesFlags::DEFAULT );

    imshow("Keypoints 1", img_keypoints );
    waitKey();
    destroyAllWindows();

    return {result, keypoints_updated, descriptors_updated};
}
</code>```

The following code is my master stitching program that does the actual stitching.

```<code>tuple<Mat,vector<KeyPoint>,Mat> stitch(Mat img1,Mat img2 ,vector<KeyPoint> keypoints, Mat descriptors, String featureDetection,String featureExtractor,String keypointsMatcher,String showMatches){

    Mat desc, desc1, desc2, homography, result, croppedResult,descriptors_updated;
    std::vector<KeyPoint> keypoints_updated, kp1, kp2;
    std::vector<DMatch> matches;
    //-Base Case[2]
    if (keypoints.empty()){

        //-Detect Keypoints and their descriptors
        tie(kp1,desc1) = KeyPointDescriptor(img1, featureDetection,featureExtractor);
        tie(kp2,desc2) = KeyPointDescriptor(img2, featureDetection,featureExtractor);

        //Find matches and calculated homography based on keypoints and descriptors
        std::tie(matches,homography) = matchFeatures(kp1,  desc1,kp2, desc2, keypointsMatcher);
        //draw matches if requested
        if(showMatches == "true"){
            drawMatchedImages( img1, kp1, img2, kp2, matches);
        }
        //stitch the images and update the keypoint and descriptors
        std::tie(result,keypoints_updated,descriptors_updated) = stitchMatches(img1, img2, homography,kp1,kp2,desc1,desc2);
        //crop function using created cropping function
        croppedResult = crop(result);
        return {croppedResult,keypoints_updated,descriptors_updated};

    }

    //base case[3:n]
    else{

        //Get keypoints and descriptors of new image and add to respective lists
        tie(kp2,desc2) = KeyPointDescriptor(img2, featureDetection,featureExtractor);

        //find matches and determine homography
        std::tie(matches,homography) = matchFeatures(keypoints_updated,descriptors_updated,kp2,desc2, keypointsMatcher);
        //draw matches if requested
        if(showMatches == "true")
            drawMatchedImages( img1, keypoints, img2, kp2, matches);

        //stitch the images and update the keypoint and descriptors
        tie(result,keypoints_updated,descriptors_updated) = stitchMatches(img1, img2, homography,keypoints,kp2,descriptors,desc2);
        //crop function using created cropping function
        croppedResult = crop(result);
        return {croppedResult,keypoints_updated,descriptors_updated};
        }
}
</code>```

Lastly here is the image of the keypoints that are being transformed onto the stitched image. Any help is so greatly appreciated!

答: After combing through the I just happened to find I was using the wrong variable at one point!:)</p>

Body:
I have created a program that can stitch multiple images together and am now looking to improve the efficiency of it. Depending on the size of the stitched image, eventually it is to large and contains too many keypoints that the machine runs out of allocatable memory. To compensate for this my goal is to store all the keypoints and descriptors as they are found so that I don't need to find them again in the master stitched image and only need to find them in the new image being stitched. I had this process working in python but haven't had the same luck in C++.
In order to do this I need to perform a perspectiveTransform() on the keypoints and therefor convert them from vector<keypoint> to vector<point2f> and back to vector<keypoint>. I have been able to achieve this and can confirm it works (pick to follow). I am not sure if the same process needs to be done to the descriptors (currently I have don it but either its wrong or not effective).

Issue: When I run this the keypoints and descriptors don't appear to work and I throw an error I created being: "Not enough matches found" even though I know at least the keypoints are making its way to the function.

Here is the code for the keypoint and descriptor transforms. The code first calculates the warpPerspective to be applied to image one as homography will warp the second image only. The rest of the codd deals with keypoints and descriptors.

tuple<Mat, vector<KeyPoint>, Mat>  stitchMatches(Mat image1,Mat image2, Mat homography, vector<KeyPoint> kp1, vector<KeyPoint> kp2 , Mat desc1, Mat desc2){
    Mat result, destination, descriptors_updated;
    vector<Point2f> fourPoint;
    vector<KeyPoint> keypoints_updated;

    //-Get the four corners of the first image (master)
    fourPoint.push_back(Point2f (0,0));
    fourPoint.push_back(Point2f (image1.size().width,0));
    fourPoint.push_back(Point2f (0, image1.size().height));
    fourPoint.push_back(Point2f (image1.size().width, image1.size().height));
    //perspectiveTransform(Mat(fourPoint), destination, homography);

    //- Get points used to determine Htr
    double min_x, min_y, tam_x, tam_y;
    float min_x1, min_x2, min_y1, min_y2, max_x1, max_x2, max_y1, max_y2;
    min_x1 = min(fourPoint.at(0).x, fourPoint.at(1).x);
    min_x2 = min(fourPoint.at(2).x, fourPoint.at(3).x);
    min_y1 = min(fourPoint.at(0).y, fourPoint.at(1).y);
    min_y2 = min(fourPoint.at(2).y, fourPoint.at(3).y);
    max_x1 = max(fourPoint.at(0).x, fourPoint.at(1).x);
    max_x2 = max(fourPoint.at(2).x, fourPoint.at(3).x);
    max_y1 = max(fourPoint.at(0).y, fourPoint.at(1).y);
    max_y2 = max(fourPoint.at(2).y, fourPoint.at(3).y);
    min_x = min(min_x1, min_x2);
    min_y = min(min_y1, min_y2);
    tam_x = max(max_x1, max_x2);
    tam_y = max(max_y1, max_y2);

    //- Htr use to map image one to result in line with the alredy warped image 1
    Mat Htr = Mat::eye(3,3,CV_64F);
    if (min_x < 0){
        tam_x = image2.size().width - min_x;
        Htr.at<double>(0,2)= -min_x;
    }
    if (min_y < 0){
        tam_y = image2.size().height - min_y;
        Htr.at<double>(1,2)= -min_y;
    }

    result = Mat(Size(tam_x*2,tam_y*2), CV_8UC3,cv::Scalar(0,0,0));
    warpPerspective(image2, result, Htr, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   0);
    warpPerspective(image1, result, (Htr*homography), result.size(), INTER_LINEAR, BORDER_TRANSPARENT,0);

    //-- Variables to hold the keypoints at the respective stages
    vector<Point2f> kp1Local,kp2Local;
    vector<KeyPoint> kp1updated, kp2updated;

    //Localize the keypoints to allow for perspective change
    KeyPoint::convert(kp1, kp1Local);
    KeyPoint::convert(kp2, kp2Local);

    //perform persepctive transform on the keypoints of type vector<point2f>
    perspectiveTransform(kp1Local, kp1Local, (Htr));
    perspectiveTransform(kp2Local, kp2Local, (Htr*homography));

    //convert keypoints back to type vector<keypoint>
    for( size_t i = 0; i < kp1Local.size(); i++ ) {
        kp1updated.push_back(KeyPoint(kp1Local[i], 1.f));
    }
    for( size_t i = 0; i < kp2Local.size(); i++ ) {
        kp2updated.push_back(KeyPoint(kp2Local[i], 1.f));
    }

    //Add to master of list of keypoints to be passed along during next iteration of image
    keypoints_updated.reserve(kp1updated.size() + kp2updated.size());
    keypoints_updated.insert(keypoints_updated.end(),kp1updated.begin(),kp1updated.end());
    keypoints_updated.insert(keypoints_updated.end(),kp2updated.begin(),kp2updated.end());

    //WarpPerspective of decriptors to match that of the images and cooresponding keypoints
    Mat desc1New, desc2New;
    warpPerspective(desc2, desc2New, Htr, result.size(), INTER_LINEAR, BORDER_TRANSPARENT,   0);
    warpPerspective(desc1, desc1New, (Htr*homography), result.size(), INTER_LINEAR, BORDER_TRANSPARENT,0);

    //create a new Mat including the descriports from desc1 and desc2
    descriptors_updated.push_back(desc1New);
    descriptors_updated.push_back(desc2New);

    //------------TEST TO see if keypoints have moved

    Mat img_keypoints;
    drawKeypoints( result, keypoints_updated, img_keypoints, Scalar::all(-1), DrawMatchesFlags::DEFAULT );

    imshow("Keypoints 1", img_keypoints );
    waitKey();
    destroyAllWindows();

    return {result, keypoints_updated, descriptors_updated};
}

The following code is my master stitching program that does the actual stitching.

tuple<Mat,vector<KeyPoint>,Mat> stitch(Mat img1,Mat img2 ,vector<KeyPoint> keypoints, Mat descriptors, String featureDetection,String featureExtractor,String keypointsMatcher,String showMatches){

    Mat desc, desc1, desc2, homography, result, croppedResult,descriptors_updated;
    std::vector<KeyPoint> keypoints_updated, kp1, kp2;
    std::vector<DMatch> matches;
    //-Base Case[2]
    if (keypoints.empty()){

        //-Detect Keypoints and their descriptors
        tie(kp1,desc1) = KeyPointDescriptor(img1, featureDetection,featureExtractor);
        tie(kp2,desc2) = KeyPointDescriptor(img2, featureDetection,featureExtractor);

        //Find matches and calculated homography based on keypoints and descriptors
        std::tie(matches,homography) = matchFeatures(kp1,  desc1,kp2, desc2, keypointsMatcher);
        //draw matches if requested
        if(showMatches == "true"){
            drawMatchedImages( img1, kp1, img2, kp2, matches);
        }
        //stitch the images and update the keypoint and descriptors
        std::tie(result,keypoints_updated,descriptors_updated) = stitchMatches(img1, img2, homography,kp1,kp2,desc1,desc2);
        //crop function using created cropping function
        croppedResult = crop(result);
        return {croppedResult,keypoints_updated,descriptors_updated};

    }

    //base case[3:n]
    else{

        //Get keypoints and descriptors of new image and add to respective lists
        tie(kp2,desc2) = KeyPointDescriptor(img2, featureDetection,featureExtractor);

        //find matches and determine homography
        std::tie(matches,homography) = matchFeatures(keypoints_updated,descriptors_updated,kp2,desc2, keypointsMatcher);
        //draw matches if requested
        if(showMatches == "true")
            drawMatchedImages( img1, keypoints, img2, kp2, matches);

        //stitch the images and update the keypoint and descriptors
        tie(result,keypoints_updated,descriptors_updated) = stitchMatches(img1, img2, homography,keypoints,kp2,descriptors,desc2);
        //crop function using created cropping function
        croppedResult = crop(result);
        return {croppedResult,keypoints_updated,descriptors_updated};
        }
}

Lastly here is the image of the keypoints that are being transformed onto the stitched image. Any help is so greatly appreciated!


问:
Why is the top layout guide moving in my iMessage extension
I have an iMessage extension and I'm having some issues with the top layout guide. I have an MSMessagesAppViewController that handles changes between presentation styles. In my extension I have a button. When it is clicked I transition to expanded presentation style and then present a view controller modally. Here's the problem: my UI in the second VC is getting hidden behind the top navigation bar. I thought this was strange as I set my constraints to the top layout guide. So I dug through my code and started debugging the top layout guide. I noticed that after I transition to expanded presentation style, topLayoutGuide.length = 86. That's how it should be. But when I present the second view controller modally, the top layout guide is reset to 0. Why isn't it 86 as it should be? Here is my code:

In my main viewController:

```<code>@IBAction func addStickerButtonPressed(_ sender: AnyObject) {
    shouldPerformCreateSegue = true
    theSender = sender
    requestPresentationStyle(.expanded)

}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
    if presentationStyle == .expanded {
        if shouldPerformCreateSegue == true {
            shouldPerformCreateSegue = false
            performSegue(withIdentifier: "CreateStickerSegue", sender: theSender)//here is where I present the new viewController
        } else {
            searchBar.becomeFirstResponder()
            searchBar.placeholder = nil
            searchBar.showsCancelButton = true
            searchBar.tintColor = UIColor.white
        }
    } else {
        searchBar.showsCancelButton = false
    }
    print(topLayoutGuide.length) //This prints out 86
}
</code>```

In the other modally presented view controller:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.view.addConstraint(navBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor))
    print(topLayoutGuide.length) //This prints out 0
}
</code>```

答:
I used a slightly varied version of Andrey's

```<code>class MyViewController: MSMessagesAppViewController {
    private func presentModalViewController() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .savedPhotosAlbum
        imagePicker.modalPresentationStyle = .custom
        imagePicker.transitioningDelegate = self
        present(
            imagePicker,
            animated: true,
            completion: nil
        )
    }
}

extension MyViewController: UIViewControllerTransitioningDelegate {
    func presentationController(
         forPresented presented: UIViewController,
         presenting: UIViewController?,
         source: UIViewController
    ) -> UIPresentationController? {
         let vc = PresentationController(
             presentedViewController: presented,
             presenting: presenting
         )
         vc.framePresented = modalBoundaries.frame
         return vc
    }
}

class PresentationController: UIPresentationController {
     var framePresented = CGRect.zero
     override var frameOfPresentedViewInContainerView: CGRect {
         return framePresented
    }
}
</code>```

modalBoundaries being a dummy UIView constrained (via XIB in my case) to respect any TopLayoutGuide length.

Body:
I have an iMessage extension and I'm having some issues with the top layout guide. I have an MSMessagesAppViewController that handles changes between presentation styles. In my extension I have a button. When it is clicked I transition to expanded presentation style and then present a view controller modally. Here's the problem: my UI in the second VC is getting hidden behind the top navigation bar. I thought this was strange as I set my constraints to the top layout guide. So I dug through my code and started debugging the top layout guide. I noticed that after I transition to expanded presentation style, topLayoutGuide.length = 86. That's how it should be. But when I present the second view controller modally, the top layout guide is reset to 0. Why isn't it 86 as it should be? Here is my code:

In my main viewController:

@IBAction func addStickerButtonPressed(_ sender: AnyObject) {
    shouldPerformCreateSegue = true
    theSender = sender
    requestPresentationStyle(.expanded)

}
override func didTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
    if presentationStyle == .expanded {
        if shouldPerformCreateSegue == true {
            shouldPerformCreateSegue = false
            performSegue(withIdentifier: "CreateStickerSegue", sender: theSender)//here is where I present the new viewController
        } else {
            searchBar.becomeFirstResponder()
            searchBar.placeholder = nil
            searchBar.showsCancelButton = true
            searchBar.tintColor = UIColor.white
        }
    } else {
        searchBar.showsCancelButton = false
    }
    print(topLayoutGuide.length) //This prints out 86
}

In the other modally presented view controller:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.view.addConstraint(navBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor))
    print(topLayoutGuide.length) //This prints out 0
}

Body:
I used a slightly varied version of Andrey's

class MyViewController: MSMessagesAppViewController {
    private func presentModalViewController() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .savedPhotosAlbum
        imagePicker.modalPresentationStyle = .custom
        imagePicker.transitioningDelegate = self
        present(
            imagePicker,
            animated: true,
            completion: nil
        )
    }
}

extension MyViewController: UIViewControllerTransitioningDelegate {
    func presentationController(
         forPresented presented: UIViewController,
         presenting: UIViewController?,
         source: UIViewController
    ) -> UIPresentationController? {
         let vc = PresentationController(
             presentedViewController: presented,
             presenting: presenting
         )
         vc.framePresented = modalBoundaries.frame
         return vc
    }
}

class PresentationController: UIPresentationController {
     var framePresented = CGRect.zero
     override var frameOfPresentedViewInContainerView: CGRect {
         return framePresented
    }
}

modalBoundaries being a dummy UIView constrained (via XIB in my case) to respect any TopLayoutGuide length.


问:
Reshaping from wide to long data while collapsing variable values for same IDs in R
I am relatively new to R. I have a dataframe df that looks like this, where PMID is an ID:

```<code>PMID          Variable         Value
1             MH               Humans
1             MH               Male
1             MH               Middle Aged
1             RN               Aldosterone
1             RN               Renin
2             MH               Accidents, Traffic
2             MH               Male
2             RN               Antivenins
3             MH               Humans
3             MH               Crotulus
3             MH               Young Adult
</code>```

and so on. As you can see, some IDs have multiple MHs and/or RNs and some have none or one. I want to collapse all entries for each variable for each PMID. I also want to be able to separate each entry with a comma once collapsed, but first substitute the spaces present in the above dataframe into _ so that I can retain each value so that my final dataframe looks like this:

```<code>PMID         MH                                 RN
1            Humans, Male, Middle_Aged          Aldosterone, Renin
2            Accidents,_Traffic, Male           Antivenins
3            Humans, Crotulus, Young_Adult
</code>```

I have over 5 million rows, so please help in making the code computationally efficient. Thanks for your help.

答:
This is my solution :</p>

```<code>library(reshape2)
df=ddply(df,.(PMID,Variable), summarise,Pri = paste(Value,collapse=","))
acast(df, PMID ~ Variable)

  MH                           RN
1 "Humans,Male,MiddleAged"     "Aldosterone,Renin"
2 "Accidentstraffic,Male"      "Antivenins"
3 "Humans,Crotulus,YoungAdult" NA
</code>```

Body:
I am relatively new to R. I have a dataframe df that looks like this, where PMID is an ID:

PMID          Variable         Value
1             MH               Humans
1             MH               Male
1             MH               Middle Aged
1             RN               Aldosterone
1             RN               Renin
2             MH               Accidents, Traffic
2             MH               Male
2             RN               Antivenins
3             MH               Humans
3             MH               Crotulus
3             MH               Young Adult

and so on. As you can see, some IDs have multiple MHs and/or RNs and some have none or one. I want to collapse all entries for each variable for each PMID. I also want to be able to separate each entry with a comma once collapsed, but first substitute the spaces present in the above dataframe into _ so that I can retain each value so that my final dataframe looks like this:

PMID         MH                                 RN
1            Humans, Male, Middle_Aged          Aldosterone, Renin
2            Accidents,_Traffic, Male           Antivenins
3            Humans, Crotulus, Young_Adult

I have over 5 million rows, so please help in making the code computationally efficient. Thanks for your help.

Body:
This is my solution :

library(reshape2)
df=ddply(df,.(PMID,Variable), summarise,Pri = paste(Value,collapse=","))
acast(df, PMID ~ Variable)

  MH                           RN
1 "Humans,Male,MiddleAged"     "Aldosterone,Renin"
2 "Accidentstraffic,Male"      "Antivenins"
3 "Humans,Crotulus,YoungAdult" NA


问:
TSQL - update based on value between two ints in 2nd table.
Having an issue with doing a mass update with millions of rows.  Example of what I'm attempting to do below.  Trying to avoid case statements if possible as there are over 1000 ranks.

Table 1:

```<code>id, score, rank
1   4090   null
2   6400   null
3   8905   null
4   2551   null
</code>```

Table 2:

```<code>Rank,  Score
 1      0
 2      1000
 3      3500
 4      5000
 5      8000
 6      10000
</code>```

I'm attempting to update table 1 to display the correct rank.

EX: ID 2 having a score of 6400 would be above 5000 but below 8000 therefore be rank 4.  Is this possible without a case statement?

答:
Another Option is with a simple JOIN in concert with Lead()

Example

```<code>Update Table1 Set Rank=B.Rank
 From  Table1 A
 Join  (
            Select Rank
                  ,R1=Score
                  ,R2=Lead(Score,1,999999) over (Order By Score)
             From Table2
       ) B on A.score >= B.R1 and A.Score < B.R2
</code>```

Returns

```<code>id  score   rank
1   4090    3
2   6400    4
3   8905    5
4   2551    2
</code>```

Body:
Having an issue with doing a mass update with millions of rows.  Example of what I'm attempting to do below.  Trying to avoid case statements if possible as there are over 1000 ranks.

Table 1:

id, score, rank
1   4090   null
2   6400   null
3   8905   null
4   2551   null

Table 2:

Rank,  Score
 1      0
 2      1000
 3      3500
 4      5000
 5      8000
 6      10000

I'm attempting to update table 1 to display the correct rank.

EX: ID 2 having a score of 6400 would be above 5000 but below 8000 therefore be rank 4.  Is this possible without a case statement?

Body:
Another Option is with a simple JOIN in concert with Lead()

Example

Update Table1 Set Rank=B.Rank
 From  Table1 A
 Join  (
            Select Rank
                  ,R1=Score
                  ,R2=Lead(Score,1,999999) over (Order By Score)
             From Table2
       ) B on A.score >= B.R1 and A.Score < B.R2

Returns

id  score   rank
1   4090    3
2   6400    4
3   8905    5
4   2551    2


问:
update firebase data after doing calculations
I'm using Firebase as the db for my Ionic 2 app.

I wrote the following method to update all age fields in all child nodes to the value of 7 (for testing purposes):

```<code>  multiupdate(){
  var pc;

  this.memberProfileref.child('/members/').once('value',(snapshot)=> {

      snapshot.forEach(child=> {

          this.setAge(child.key);     // Will update all the age fields to 7 (works well)

          return false;
      });
   });
}

setAge(UserId){
    this.memberProfile.child(UserId).update({
       age:7
    });
}
</code>```

The above code is working well.

Insted of updating the age value, I now need to do a calculation and then an update.

I need to get duedate from Firebase, using the following method and calculate the duration based on today:

```<code>setduration(lastday){
   var today= moment().format('L');
      var durationd = moment(lastday).diff(moment(today));
      var dd=moment.duration(durationd).as('days');
     console.log(dd);
}
</code>```

But when I call the method [just as I did with the setAgemethod()], it can't get the result. How to change the code to solve this?

答:
I believe you want to emit the duration of each node by considering the already available duedate in the database. Check my code below and see how I called your method.   </p>

```<code> multiupdate(){
      var pc;

      this.memberProfileref.child('/members/').once('value',(snapshot)=> {

          snapshot.forEach(child=> {

              this.setAge(child.key); // Will update all the age fields to 7 (works well)
              this.setduration(child.val().duedate); //<-- call your method like this

              return false;
          });
       });
    }

    setAge(UserId){
        this.memberProfile.child(UserId).update({
           age:7
        });
    }

    setduration(lastday){
       var today= moment().format('L');
          var durationd = moment(lastday).diff(moment(today));
          var dd=moment.duration(durationd).as('days');
         console.log(dd);
    }
</code>```

Body:
I'm using Firebase as the db for my Ionic 2 app.

I wrote the following method to update all age fields in all child nodes to the value of 7 (for testing purposes):

  multiupdate(){
  var pc;

  this.memberProfileref.child('/members/').once('value',(snapshot)=> {

      snapshot.forEach(child=> {

          this.setAge(child.key);     // Will update all the age fields to 7 (works well)

          return false;
      });
   });
}

setAge(UserId){
    this.memberProfile.child(UserId).update({
       age:7
    });
}

The above code is working well.

Insted of updating the age value, I now need to do a calculation and then an update.

I need to get duedate from Firebase, using the following method and calculate the duration based on today:

setduration(lastday){
   var today= moment().format('L');
      var durationd = moment(lastday).diff(moment(today));
      var dd=moment.duration(durationd).as('days');
     console.log(dd);
}

But when I call the method [just as I did with the setAgemethod()], it can't get the result. How to change the code to solve this?

Body:
I believe you want to emit the duration of each node by considering the already available duedate in the database. Check my code below and see how I called your method.

 multiupdate(){
      var pc;

      this.memberProfileref.child('/members/').once('value',(snapshot)=> {

          snapshot.forEach(child=> {

              this.setAge(child.key); // Will update all the age fields to 7 (works well)
              this.setduration(child.val().duedate); //<-- call your method like this

              return false;
          });
       });
    }

    setAge(UserId){
        this.memberProfile.child(UserId).update({
           age:7
        });
    }

    setduration(lastday){
       var today= moment().format('L');
          var durationd = moment(lastday).diff(moment(today));
          var dd=moment.duration(durationd).as('days');
         console.log(dd);
    }


问:
Hosting a project on code.google with an Creative Commons licence
I have a project which was made under the Creative Commons licence (Attribution-NonCommercial)
Now I would like to upload my code to code.google.com since I have other project living there.

When I create a new project it asks me which opensource licence I want to choose. Choices available are:

apache license 2.0

artistic license/gpl

eclipse public license 1.0

GNU general public licence v2

GNU general public licence v3

GNU lesser general public license

MIT licence

mozilla public license 1.1

New BSD license

"other open source"

When I Select "other open source" there is a link to OSI-approved licenses which takes me to another list of licenses. (link text)

In all these lists the creative commons license is not mentioned while, interestingly enough, the content of the website itself (www.opensource.org) seems to be licensed by a creative commons license.

My question is this:

What license type should I choose in my code.google project in order to "select" creative commons license (Attribution-NonCommercial)?

答:
Creative Commons licences are not normally used for code. They're used for other works, like photos, music, documentation (hence its use on opensource.org), etc.

There are some Creative Commons licences that are very similar to open source licenses, but Attribution-NonCommercial would not be considered open source. In particular, NonComercial violates sections 1 and/or 6 of the The Open Source Definition:

Free Redistribution

The license shall not restrict any party from selling or giving away the software as a component of an aggregate software distribution containing programs from several different sources. The license shall not require a royalty or other fee for such sale.

No Discrimination Against Fields of Endeavor

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research.

(#2 is actually #6, but markdown keeps renumbering it.)


问:
Angular - Re-Populate form inputs from service
I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".

Component:

```<code>export class EditUserComponent implements OnInit {

    // Define our vars
    user: Users[];
    editUserForm: FormGroup;
    message: {};
    displayMessage = false;
    userID: number;
    errorMessage: any = '';

    constructor(
        private fb: FormBuilder,
        private _userService: UserService,
        private activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit(): void {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.userID = params['id'];
        });

        // Call our service and pass the UserID
        this._userService.getUser(this.userID)
            .then(res => {
                this.user = res;
                this.createForm();
            });

    }

    // Generate the form
    createForm() {
        this.editUserForm = this.fb.group({
            QID: ['', Validators.required],
            favoriteColor: [''],
            favoriteNumber: [''],
            favoriteActor: ['']
        });
    }

}
</code>```

Service:

```<code>// Fetch a single user
    getUser(userID: number) {
        return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(err => { this.handleError(err); });
    }
</code>```

Interface:

```<code>export interface Users {
    RecordID?: number;
    QID: string;
    favoriteColor?: string;
    favoriteNumber?: number;
    favoriteActor?: string;
}
</code>```

I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.

I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.

Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.

```<code>createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [''],
        favoriteNumber: [''],
        favoriteActor: ['']
    });
}
</code>```

答:
Bind a submit event to your form, then use this.editUserForm.value to access the data from the form.

In the component template:

```<code><form [formGroup]="editUserForm" (submit)="saveIt()">
</code>```

In the Component:

```<code>  saveIt() {
    if (this.editUserForm.dirty && this.editUserForm.valid) {
      alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`);
    }
  }
</code>```

Body:
I have a basic angular component that allows some one to edit the details of a user once they go to their profile and click on "edit".

Component:

export class EditUserComponent implements OnInit {

    // Define our vars
    user: Users[];
    editUserForm: FormGroup;
    message: {};
    displayMessage = false;
    userID: number;
    errorMessage: any = '';

    constructor(
        private fb: FormBuilder,
        private _userService: UserService,
        private activatedRoute: ActivatedRoute
    ) {
    }

    ngOnInit(): void {

        // Get the userID from the activated route
        this.activatedRoute.params.subscribe((params: Params) => {
            this.userID = params['id'];
        });

        // Call our service and pass the UserID
        this._userService.getUser(this.userID)
            .then(res => {
                this.user = res;
                this.createForm();
            });

    }

    // Generate the form
    createForm() {
        this.editUserForm = this.fb.group({
            QID: ['', Validators.required],
            favoriteColor: [''],
            favoriteNumber: [''],
            favoriteActor: ['']
        });
    }

}

Service:

// Fetch a single user
    getUser(userID: number) {
        return this._http.post(this.baseUrl + '/fetchUser', { "userID": userID }, { "headers": this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(err => { this.handleError(err); });
    }

Interface:

export interface Users {
    RecordID?: number;
    QID: string;
    favoriteColor?: string;
    favoriteNumber?: number;
    favoriteActor?: string;
}

I am trying to pass the values to my formGroup but I am having trouble figuring out how to access the values.

I assumed I could do something like this where I could access the user model and select a property from it but that is throwing an undefined error.

Would I pass the values here in the form group or bind them to the elements directly somehow? I am receiving the data back from the service just fine, just not sure how to get each of the values back to their respective fields.

createForm() {
    this.editUserForm = this.fb.group({
        QID: [this.user.QID, Validators.required],
        favoriteColor: [''],
        favoriteNumber: [''],
        favoriteActor: ['']
    });
}

Body:
Bind a submit event to your form, then use this.editUserForm.value to access the data from the form.

In the component template:

<form [formGroup]="editUserForm" (submit)="saveIt()">

In the Component:

  saveIt() {
    if (this.editUserForm.dirty && this.editUserForm.valid) {
      alert(`Number: ${this.editUserForm.value.favoriteNumber} Actor: ${this.editUserForm.value.favoriteActor}`);
    }
  }


问:
Endianess Related to processor or data type
I am working with little endian processor PIC 32 and am looking at a variable that is of type BOOL. One variable is initialized to TRUE and the other as false.

```<code>static BOOL A = TRUE;
BOOL static B = FALSE;
</code>```

In Memory when I look in memory for variable A, it shows

It looks like the processor just assigns a 32 bit number for true and false and not 8 bits so that means its processor dependent.
For an array of 6 elements of type BOOL, all set to TRUE. How would it be read? Is it going to show up as 6 elements of what is shown in the picture above?

答: BOOL is not a standard type. Depending on how it is defined in your environment, probably via a typedef in a header file, it may be any integer type, including unsigned char which would use 1 byte or int which may use 4 bytes on your system and other sizes for other architectures.

Body:
I am working with little endian processor PIC 32 and am looking at a variable that is of type BOOL. One variable is initialized to TRUE and the other as false.

static BOOL A = TRUE;
BOOL static B = FALSE;

In Memory when I look in memory for variable A, it shows

It looks like the processor just assigns a 32 bit number for true and false and not 8 bits so that means its processor dependent.
For an array of 6 elements of type BOOL, all set to TRUE. How would it be read? Is it going to show up as 6 elements of what is shown in the picture above?


问:
How to get DB connection in grails 3
What is proper way to get DB connection in Grails 3?

For grails 2 following code has works:

```<code>((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap
</code>```

But after migration to Grails 3 sometimes I see exceptions in the log:

java.sql.SQLException: Operation not allowed after ResultSet closed at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) at
  com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743) at
  com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1037) at
  com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2757) at
  com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:424)
  at java_sql_ResultSet$getLong$3.call(Unknown Source)

It happens for 0,01% of requests

Grails 3.2.11

Gorm 6.0.12

答:
From grails docs, you can get the actual dataSource bean. From that you can access the connection or use it to query your db

```

    import groovy.sql.Sql

    def dataSource

    println "connection: ${dataSource.connection}"

    Sql sql = new Sql(dataSource)
    sql.eachRow("SELECT * FROM note") { row ->
       println "row: ${row}"
    }

```

Use 'dataSourceUnproxied' to avoid Hibernate transaction and session issues:

```

    def dataSourceUnproxied

```

Title: How to get DB connection in grails 3

Body:
What is proper way to get DB connection in Grails 3?

For grails 2 following code has works:

((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap

But after migration to Grails 3 sometimes I see exceptions in the log:

java.sql.SQLException: Operation not allowed after ResultSet closed at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) at
  com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743) at
  com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1037) at
  com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2757) at
  com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:424)
  at java_sql_ResultSet$getLong$3.call(Unknown Source)

It happens for 0,01% of requests

Grails 3.2.11

Gorm 6.0.12

Body:
From grails docs, you can get the actual dataSource bean. From that you can access the connection or use it to query your db

    import groovy.sql.Sql

    def dataSource

    println "connection: ${dataSource.connection}"

    Sql sql = new Sql(dataSource)
    sql.eachRow("SELECT * FROM note") { row ->
       println "row: ${row}"
    }

Use 'dataSourceUnproxied' to avoid Hibernate transaction and session issues:

    def dataSourceUnproxied


问:
how to make height responsive screens in ionic 2?
I know we can make horizontally responsive content in ionic 2. What i want to know is how to make pages height responsive for all type of screens for example if a screen cover whole area on iphone 5 then it should cover whole height wisie area in iphone 7 also ? whats the best approach to achieve this ?</p>

答:
I hope you will get good idea to make the responsive properly from the follow parameters.

vw: 1/100th viewport width

vh: 1/100th viewport height

vmin: 1/100th of the smallest side

vmax: 1/100th of the largest side

Actually vh is a perfect solution to make the responsive based on viewporot. The viewport is the area where the browser renders the site. This is your screen minus the reserved space of the browser chrome. Sometimes you want to size an element based on that viewport, like a sidebar. This can be done using a unit we’re all familiar with: percentages.


问:
Core Data Property Validation in Swift 3
I'm trying to set up custom property validation for a property belonging to an NSManagedObject subclass. According to the docs the general signature for such a method in Swift 3 is as follows:

```<code>func validate<Key>(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws
</code>```

My property is called amount, so I've got:

```<code>class Transaction: NSManagedObject {

    @NSManaged var amount: Float

    func validateAmount(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
        // custom validation logic...
    }
}
</code>```

As I understand it, when I create a new Transaction instance, set its amount property, and then try to save the managed object context, validateValue:forKey: should be called on the relevant instance, which should in turn locate and call my custom validation method. Unfortunately this isn't happening: validateValue:forKey: is called, but my method is ignored.

You can see all this for yourself in this sample project (written in Xcode 8.3.3), and I'd be grateful if someone can tell me where I'm going wrong.

答: func validateAmount(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws is called. Add a _ like in validateValue(_ value.

Body:
I'm trying to set up custom property validation for a property belonging to an NSManagedObject subclass. According to the docs the general signature for such a method in Swift 3 is as follows:

func validate<Key>(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws

My property is called amount, so I've got:

class Transaction: NSManagedObject {

    @NSManaged var amount: Float

    func validateAmount(value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
        // custom validation logic...
    }
}

As I understand it, when I create a new Transaction instance, set its amount property, and then try to save the managed object context, validateValue:forKey: should be called on the relevant instance, which should in turn locate and call my custom validation method. Unfortunately this isn't happening: validateValue:forKey: is called, but my method is ignored.

You can see all this for yourself in this sample project (written in Xcode 8.3.3), and I'd be grateful if someone can tell me where I'm going wrong.


问:
Typescript - Error while compiling a .ts file in visual studio code
I'm getting the below error, while I try to compile a .ts file from the Visual Studio Code IDE. (Using Ctrl+Shift+B)

Problem matcher {0} can't be resolved. The matcher will be ignoredThe filename, directory name, or volume label syntax is incorrect.

Here is my tasks.json,

```<code>{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "always"
}
</code>```

Can someone help me what could be the issue here?.

答:
It looks like you have not configured a task runner for transpiling Typescript.

On VS Code, Ctrl+Shift+P and type "Configure Task Runner", press Enter to select it. Select "Typescript.json" from the options.

Save all and it should work.

The complete reference on configuring Typescript can be found here:
https://code.visualstudio.com/docs/languages/typescript

Body:
I'm getting the below error, while I try to compile a .ts file from the Visual Studio Code IDE. (Using Ctrl+Shift+B)

Problem matcher {0} can't be resolved. The matcher will be ignoredThe filename, directory name, or volume label syntax is incorrect.

Here is my tasks.json,

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "always"
}

Can someone help me what could be the issue here?.


问:
How can I find download links for vimeo videos?
I saw that today vimeo changed the way they are streaming the videos and I can't stream their videos anymore. I saw that when I generate the link to the video, which was for example:

```<code>http://vimeo.com/moogaloop/play/clip:6649390/1eab2a25f30f1aadaf5e306d0f40fd6c/1292498602/?q=hd
</code>```

It's redirecting me to a page saying "Permission denied". I tried using curl, but without any success. I sniffed the traffic and I saw that it's streaming from something like:

```<code>http://av.vimeo.com/02047/623/34209065.mp4?token=1292496582_34de09a6d13212cf26af08357d311c30
</code>```

Does anybody know how to get the working URL to the video file?

The way I'm getting the videos at the moment is:

Choose link http://vimeo.com/video_id.

Get only the video_id.

Get the XML for the video http://vimeo.com/moogaloop/load/clip:video_id;.

parse the XML and find the necessary information:

request_signature

request_signature_expires

isHD

Generate the link:

```<code>$video_link = "http://vimeo.com/moogaloop/play/clip:".$video_id."/".$request_signature."/".$request_signature_expires."/?q=".$quality."";
</code>```

If I do this manually through the browser it works, but if I do it through the script it doesn't.

答:
After spending a few hours on finding out how I can get the direct link to vimeo I found a good solution. So here are the steps for the users who want to download and stream video src directly from vimeo. Keep in mind that they block all IP addresses and probably hosts which are downloading the videos in this way, so I just stopped using their services and I will never use them again :).

Steps to get the video sources:

choose link http://vimeo.com/video_id

get only the video_id

get the xml for the video http://vimeo.com/moogaloop/load/clip:video_id;

parse the xml and I find the necessary information I need:

request_signature

request_signature_expires

isHD

Then I generate the link:

```<code>$video_link = "http://vimeo.com/moogaloop/play/clip:".$video_id."/".$request_signature."/".$request_signature_expires."/?q=".$quality."";
</code>```

Then if you are php dev, you call wget command through exec in this way

exec("wget -b '$video_link' -a 'wget.log' -O -");

Then you read the log and find out the link you are looking for. You can simply parse the log file. The direct link is between "Location: " and "[following]"

You return the direct link and clean the log file :)

NOTE: keep in mind again that this won't work forever. Sooner or later they will block your ip :).

Body:
I saw that today vimeo changed the way they are streaming the videos and I can't stream their videos anymore. I saw that when I generate the link to the video, which was for example:

http://vimeo.com/moogaloop/play/clip:6649390/1eab2a25f30f1aadaf5e306d0f40fd6c/1292498602/?q=hd

It's redirecting me to a page saying "Permission denied". I tried using curl, but without any success. I sniffed the traffic and I saw that it's streaming from something like:

http://av.vimeo.com/02047/623/34209065.mp4?token=1292496582_34de09a6d13212cf26af08357d311c30

Does anybody know how to get the working URL to the video file?

The way I'm getting the videos at the moment is:

Choose link http://vimeo.com/video_id.

Get only the video_id.

Get the XML for the video http://vimeo.com/moogaloop/load/clip:video_id;.

parse the XML and find the necessary information:

request_signature

request_signature_expires

isHD

Generate the link:

$video_link = "http://vimeo.com/moogaloop/play/clip:".$video_id."/".$request_signature."/".$request_signature_expires."/?q=".$quality."";

If I do this manually through the browser it works, but if I do it through the script it doesn't.

Body:
After spending a few hours on finding out how I can get the direct link to vimeo I found a good solution. So here are the steps for the users who want to download and stream video src directly from vimeo. Keep in mind that they block all IP addresses and probably hosts which are downloading the videos in this way, so I just stopped using their services and I will never use them again :).

Steps to get the video sources:

choose link http://vimeo.com/video_id

get only the video_id

get the xml for the video http://vimeo.com/moogaloop/load/clip:video_id;

parse the xml and I find the necessary information I need:

request_signature

request_signature_expires

isHD

Then I generate the link:

$video_link = "http://vimeo.com/moogaloop/play/clip:".$video_id."/".$request_signature."/".$request_signature_expires."/?q=".$quality."";

Then if you are php dev, you call wget command through exec in this way

exec("wget -b '$video_link' -a 'wget.log' -O -");

Then you read the log and find out the link you are looking for. You can simply parse the log file. The direct link is between "Location: " and "[following]"

You return the direct link and clean the log file :)

NOTE: keep in mind again that this won't work forever. Sooner or later they will block your ip :).


问:
Visual Studio 2017 Xamarin Android API Level 25: Enable the default proguard
I cannot build my android application with the default visual studio 2017 proguard enabled.

I enable the proguard from

Project > Android.Properties > Android Options > Check "Enable ProGuard"

Then I cannot build my application.

It says:

C:\Program Files (Access is denied)

How do I fix this?

答: it's a common Linux/Windows command-line compatibility issue. you might have to set ANDROID_HOME (the path to the Android SDK, without spaces) under "System Properties" > "Advanced System Settings" > "Environment Variables" > "System Variables". Visual Studio should pick up these values - also check permissions on proguard.exe, eg. if the current user can run it from the command line. here it's also explained: "How to Fix Error “C:\Program Files (Access is Denied)” When Proguard has Enabled while Build a Android app" (linking the SDK is the other option). Moving the whole SDK to C:\Android\SDK might be suggested. Visual Studio may even install the SDK twice, when installing it beside an existing IDE, unless one has JAVA_HOME, ANDROID_HOME and ANDROID_AVD_HOME (the emulator images) defined. Having the SDK within the user profile (or within "Program Files") is rather problematic. At least, these variables can be used to change the individual install locations (in order to fix PATH issues alike this - or to delete eventual duplicate SDK installs).


问:
FLASK Restful API not able to add using PUT
I am using this documentation: from FLASK Restful

```<code>from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)
</code>```

In order to add
the new todo, they call the following command on python:

```<code>from requests import put, get
put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()
</code>```

The data comes from the json object  {'data': '.....}
and it retrieved here: request.form['data']

I want to replace 'Remember the milk' with my data2 object:

```<code>data2 = {'ALTNUM':'noalt', 'CUSTTYPE': 'O',
'LASTNAME':'lnamedata2', 'FIRSTNAME':'fndata2', 'ADDR':'1254 data 2 address',
'ADDR2':'apt 3', 'CITY':'los angeles',
'COUNTY':'011', 'STATE':'CA',
'ZIPCODE':'90293', 'COUNTRY':'001',
'ADDR_TYPE':'O','PHONE':'4254658029',
'PHONE2':'3442567777',
'EMAIL':'test2@test2.com'}
</code>```

and call: print put('http://localhost:5000/newcustomer', data={'data':data2}).json()

MY API resource:

```<code>class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.form['data']
        print(data)
        return data
</code>```

I get the following errors when calling these:

```<code>print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data={'data':data2}).json()
print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data=data2)

{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
CUSTTYPE
{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
<Response [400]>
</code>```

What am I doing wrong?
@foslock should it be data = request.json['data'] ? since it is an object and not form data?

答:
Returning JSON, not str

It looks like your API routes are returning raw string casted versions of the resource objects. You instead want to return them as JSON, which flask can do for you with the jsonify method.

```<code>import flask

class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.get_json()
        new_cust = q.create_cust(data)
        return flask.jsonify(new_cust)
</code>```

Notice how in Python, the string representation of a native dictionary is not exactly equivalent to the JSON version:

```<code>>>> dct = {'Hey': 'some value'}
>>> print(dct)
{'Hey': 'some value'}
>>> print(json.dumps(dct))
{"Hey": "some value"}
</code>```

Sending JSON with PUT/POST

When using the requests library to send a PUT/POST request, you are by default sending the body of the request in a form-encoded (application/x-www-form-urlencoded to be specific) format, which is explained here. This format is not great for nested structured data like what you are attempting to send. Instead, you can send the data JSON encoded (application/json) using the json keyword argument.

```<code>requests.put(url, json=data2)
</code>```

Side note: If you are attempting to create a new customer, you may want to use POST instead as it may be considered more RESTful, as PUTs are generally for updating an existing resource, but this is up to you.

Pulling values from PUT/POST Data

Since we are sending the body of the request as JSON now, we need to deserialize it as such in the API server. You can see this happening above in the following line:

```<code>data = request.get_json()
</code>```

You can refer to this answer for more information about properly pulling data out of a HTTP request in Flask.

Body:
I am using this documentation: from FLASK Restful

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)

In order to add
the new todo, they call the following command on python:

from requests import put, get
put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()

The data comes from the json object  {'data': '.....}
and it retrieved here: request.form['data']

I want to replace 'Remember the milk' with my data2 object:

data2 = {'ALTNUM':'noalt', 'CUSTTYPE': 'O',
'LASTNAME':'lnamedata2', 'FIRSTNAME':'fndata2', 'ADDR':'1254 data 2 address',
'ADDR2':'apt 3', 'CITY':'los angeles',
'COUNTY':'011', 'STATE':'CA',
'ZIPCODE':'90293', 'COUNTRY':'001',
'ADDR_TYPE':'O','PHONE':'4254658029',
'PHONE2':'3442567777',
'EMAIL':'test2@test2.com'}

and call: print put('http://localhost:5000/newcustomer', data={'data':data2}).json()

MY API resource:

class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.form['data']
        print(data)
        return data

I get the following errors when calling these:

print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data={'data':data2}).json()
print put('http://localhost:5000/newcustomer', data=data2).json()
print put('http://localhost:5000/newcustomer', data=data2)

{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
CUSTTYPE
{u'message': u'The browser (or proxy) sent a request that this server could not understand.'}
<Response [400]>

What am I doing wrong?
@foslock should it be data = request.json['data'] ? since it is an object and not form data?

Body:
Returning JSON, not str

It looks like your API routes are returning raw string casted versions of the resource objects. You instead want to return them as JSON, which flask can do for you with the jsonify method.

import flask

class New_Customer(Resource):
    def put(self):
        q = PHQuery()
        data = request.get_json()
        new_cust = q.create_cust(data)
        return flask.jsonify(new_cust)

Notice how in Python, the string representation of a native dictionary is not exactly equivalent to the JSON version:

>>> dct = {'Hey': 'some value'}
>>> print(dct)
{'Hey': 'some value'}
>>> print(json.dumps(dct))
{"Hey": "some value"}

Sending JSON with PUT/POST

When using the requests library to send a PUT/POST request, you are by default sending the body of the request in a form-encoded (application/x-www-form-urlencoded to be specific) format, which is explained here. This format is not great for nested structured data like what you are attempting to send. Instead, you can send the data JSON encoded (application/json) using the json keyword argument.

requests.put(url, json=data2)

Side note: If you are attempting to create a new customer, you may want to use POST instead as it may be considered more RESTful, as PUTs are generally for updating an existing resource, but this is up to you.

Pulling values from PUT/POST Data

Since we are sending the body of the request as JSON now, we need to deserialize it as such in the API server. You can see this happening above in the following line:

data = request.get_json()

You can refer to this answer for more information about properly pulling data out of a HTTP request in Flask.


问:
Is there a shorter way to do exactly this?
I'm trying to find away to do this in a shorter way I don't like not using else in the end because it looks weird without it. This works for me for some reason. If I add the, " else: return True" it will only look at the first true from the list and then return True but won't check the rest... and will end the function</p>

```<code>b = [[True, True, True], [True, True, True], [True, True, False]]

for i in range(3):
    for j in range(3):
        if b[i][j] == False:
             return False
return True
</code>```

答:
I guess a pretty short way to accomplish this would be:</p>

```<code>return all(i for l in b for i in l)
</code>```

Body:
I'm trying to find away to do this in a shorter way I don't like not using else in the end because it looks weird without it. This works for me for some reason. If I add the, " else: return True" it will only look at the first true from the list and then return True but won't check the rest... and will end the function

b = [[True, True, True], [True, True, True], [True, True, False]]

for i in range(3):
    for j in range(3):
        if b[i][j] == False:
             return False
return True

Body:
I guess a pretty short way to accomplish this would be:

return all(i for l in b for i in l)