问:
Yield after if within nested for loop
I'm having trouble with a nested for loop and using yield properly.

The problem is if I have two lists of the form List[(Int,Int)]

```<code>val ls = (1,5)::(3,2)::(5,3)::Nil
val ls_two = (1,9)::(5,9)::(6,7)::Nil
</code>```

and now I want to create a third list only combining the key and both second int of all the lists so the result would be

```<code>val result = (1,5,9)::(5,3,9)::Nil
</code>```

I've tried a few variations of something like this which none seem to work

```<code>val result = for(i <- ls) {
               for(j <- ls_two) {
                 if(i._1 == j._1) yield (i._1,i._2,j._2)
               }
             }
</code>```

I've tried placing the yield at the end of the for loop, it seems to work if i replace yield with println but i'm not sure how to do it with yield.

Also if you have a more functional approach to how to solve this it would be greatly appreciated, thanks!

答:
The recommended approach here is not to "nest" the "loops" at all - but to create a single for-comprehension which uses a "guard":</p>

```<code>val result = for {
  i <- ls
  j <- ls_two if i._1 == j._1
} yield (i._1,i._2,j._2)
</code>```

Title: Yield after if within nested for loop

Body:
I'm having trouble with a nested for loop and using yield properly.

The problem is if I have two lists of the form List[(Int,Int)]

val ls = (1,5)::(3,2)::(5,3)::Nil
val ls_two = (1,9)::(5,9)::(6,7)::Nil

and now I want to create a third list only combining the key and both second int of all the lists so the result would be

val result = (1,5,9)::(5,3,9)::Nil

I've tried a few variations of something like this which none seem to work

val result = for(i <- ls) {
               for(j <- ls_two) {
                 if(i._1 == j._1) yield (i._1,i._2,j._2)
               }
             }

I've tried placing the yield at the end of the for loop, it seems to work if i replace yield with println but i'm not sure how to do it with yield.

Also if you have a more functional approach to how to solve this it would be greatly appreciated, thanks!

Body:
The recommended approach here is not to "nest" the "loops" at all - but to create a single for-comprehension which uses a "guard":

val result = for {
  i <- ls
  j <- ls_two if i._1 == j._1
} yield (i._1,i._2,j._2)


来源: stackexchange

问:
UnsafePointer<Int8> not working
The following unit test always fails as some UnsafePointer equal some other. This behavior I observe for at least 3 strings.
I'm using Xcode Version 9.1 (9B55) on High Sierra Version 10.13.1 (17B48).

```<code>func testUnsafePointer() {
    let a = "aaa"
    let b = "bbb"
    let c = "ccc"

    let ua = UnsafePointer<Int8>(a)
    let ub = UnsafePointer<Int8>(b)
    let uc = UnsafePointer<Int8>(c)

    print("a: '\(a)', ua: '\(ua)'")
    print("b: '\(b)', ub: '\(ub)'")
    print("c: '\(c)', uc: '\(uc)'")

    XCTAssertTrue(ua != ub)
    XCTAssertTrue(ub != uc)
    XCTAssertTrue(uc != ua)
}
</code>```

The printout looks similar to this

```<code>a: 'aaa', ua: '0x000060c000056a30'
b: 'bbb', ub: '0x00006080000530d0'
c: 'ccc', uc: '0x00006080000530d0'
</code>```

NB. in the swift playground everything looks ok.

答:
In

```<code>let ua = UnsafePointer<Int8>(a)
</code>```

the

```<code>init(_ other: UnsafePointer<Pointee>)
</code>```

initializer of UnsafePointer is called. I.e. you are passing
a Swift String to a function taking a UnsafePointer<Int8>
argument. In that case a temporary C string representation is created and passed to the function,
compare String value to UnsafePointer<UInt8> function parameter behavior.

That temporary C string is only valid for the duration of the function
call, and on return, it is not guaranteed that the memory pointed
to by ua still contains that C string (or any valid data). In addition,

```<code>let ua = UnsafePointer<Int8>(a)
let ub = UnsafePointer<Int8>(b)
let uc = UnsafePointer<Int8>(c)
</code>```

can use the same storage for the temporary C string, in that case
the pointers would be equal, as you observed.

If your intention is to call a C function taking const char * arguments, then you can simply pass the Swift strings. The compiler
will insert the necessary code to create C string representations
(which are again valid for the duration of the function call),
as explained in String value to UnsafePointer<UInt8> function parameter behavior:

```<code>let a = "aaa"
let b = "bbb"
let c = "ccc"

cfunc(a, b, c)
</code>```

ContentLicense: CC BY-SA 3.0

Title: UnsafePointer<Int8> not working

Body:
The following unit test always fails as some UnsafePointer equal some other. This behavior I observe for at least 3 strings.
I'm using Xcode Version 9.1 (9B55) on High Sierra Version 10.13.1 (17B48).

func testUnsafePointer() {
    let a = "aaa"
    let b = "bbb"
    let c = "ccc"

    let ua = UnsafePointer<Int8>(a)
    let ub = UnsafePointer<Int8>(b)
    let uc = UnsafePointer<Int8>(c)

    print("a: '\(a)', ua: '\(ua)'")
    print("b: '\(b)', ub: '\(ub)'")
    print("c: '\(c)', uc: '\(uc)'")

    XCTAssertTrue(ua != ub)
    XCTAssertTrue(ub != uc)
    XCTAssertTrue(uc != ua)
}

The printout looks similar to this

a: 'aaa', ua: '0x000060c000056a30'
b: 'bbb', ub: '0x00006080000530d0'
c: 'ccc', uc: '0x00006080000530d0'

NB. in the swift playground everything looks ok.

Body:
In

let ua = UnsafePointer<Int8>(a)

the

init(_ other: UnsafePointer<Pointee>)

initializer of UnsafePointer is called. I.e. you are passing
a Swift String to a function taking a UnsafePointer<Int8>
argument. In that case a temporary C string representation is created and passed to the function,
compare String value to UnsafePointer<UInt8> function parameter behavior.

That temporary C string is only valid for the duration of the function
call, and on return, it is not guaranteed that the memory pointed
to by ua still contains that C string (or any valid data). In addition,

let ua = UnsafePointer<Int8>(a)
let ub = UnsafePointer<Int8>(b)
let uc = UnsafePointer<Int8>(c)

can use the same storage for the temporary C string, in that case
the pointers would be equal, as you observed.

If your intention is to call a C function taking const char * arguments, then you can simply pass the Swift strings. The compiler
will insert the necessary code to create C string representations
(which are again valid for the duration of the function call),
as explained in String value to UnsafePointer<UInt8> function parameter behavior:

let a = "aaa"
let b = "bbb"
let c = "ccc"

cfunc(a, b, c)


问:
Linked Stylesheet Error - Resource interpreted as Stylesheet but transferred with MIME type text/plain
Following a basic React tutorial (https://www.fullstackreact.com) but I'm not able to get the given stylesheets to work properly due this error in console.

Here is the complete source of what I have so far -

```<code>    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Timeline</title>
  <link href="https://gist.githubusercontent.com/auser/2bc34b9abf07f34f602dccd6ca855df1/raw/40c5e7c8cad4c6920fed940fc31cbb63abd94c29/timeline.css" rel="stylesheet" type="text/css" />
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

  <!-- Script tags including React -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</head>
<body>
  <div class="demo">
    <div id="app"></div>
  </div>
  <script type="text/babel">
    class App extends React.Component {
        render() {
            return (
            <div className="notificationsFrame">
                <div className="panel">
                    <Header />
                </div>
            </div>
            )
        }
    }

    class Header extends React.Component {
        render() {
            return (
            <div className="header">
                <div className="fa fa-more"></div>

                <span className="title">Timeline</span>

                <input
                type="text"
                className="searchInput"
                placeholder="Search ..." />

                <div className="fa fa-search searchIcon"></div>
            </div>
            )
        }
    }

        var mount = document.querySelector('#app');
        ReactDOM.render(<App />, mount);
  </script>
</body>
</html>
</code>```

I've checked in dev tools and for timeline.css I have "Accept:text/css" in the request headers which I believe is right. I don't know why it is then being transferred with a different type? This question has been asked before but the answers all seem to be saying that something to do with the type of the request is incorrect, but I can't see where.

答:
the webmasters of site block all script and stylesheet.
this is a security feature that avoids MIME type confusion attacks.

for more info go: mozilla developer

Solution:

change your stylesheet timeline.css in other CDN or enter it in your host or in html page
example: your code

or this:

```<code><html>
<head>
  <meta charset="utf-8">
  <title>Timeline</title>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

  <!-- Script tags including React -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</head>
  <style>
    .demo {
  position: relative;
}
.demo .notificationsFrame {
  z-index: 2;
  width: 100%;
  top: 20px;
  background: #fff;
  border-radius: 3px;
  overflow: hidden;
  font-family: 'Open Sans', Helvetica, sans-serif;
  margin-bottom: 40px;
}
.demo .notificationsFrame.show-menu {
  transform: translate3d(150px, 0, 0);
}
.demo .notificationsFrame .searchInput {
  border: 10px solid red;
  box-sizing: border-box;
  position: absolute;
  top: 13px;
  right: 55px;
  width: 200px;
  height: 34px;
  border-radius: 17px;
  border: none;
  background: #fff;
  padding: 0 17px;
  font-size: 13px;
  color: #666;
  transition: all 0.3s ease-in-out;
  transform: translateX(15px);
  opacity: 0;
  pointer-events: none;
}
.demo .notificationsFrame .searchInput:focus {
  outline: none;
}
.demo .notificationsFrame .searchInput.active {
  -webkit-transform: translateX(0);
  transform: translateX(0);
  opacity: 1;
  pointer-events: all;
}
.demo .notificationsFrame .header {
  position: relative;
  height: 60px;
  background: #5f98cd;
  padding-top: 0;
}
.demo .notificationsFrame .header .menuIcon {
  position: absolute;
  width: 29px;
  height: 15px;
  top: 23px;
  left: 20px;
  cursor: pointer;
}
.demo .notificationsFrame .header .menuIcon:hover .dashTop, .demo .notificationsFrame .header .menuIcon:hover .dashBottom, .demo .notificationsFrame .header .menuIcon:hover .circle {
  background: #fff;
}
.demo .notificationsFrame .header .menuIcon .dashTop {
  position: absolute;
  width: 20px;
  height: 3px;
  top: 0;
  left: 0;
  background: #b2daff;
  border-radius: 3px;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}
.demo .notificationsFrame .header .menuIcon .dashBottom {
  position: absolute;
  width: 20px;
  height: 3px;
  top: 0;
  left: 0;
  background: #b2daff;
  border-radius: 3px;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
  width: 29px;
  top: auto;
  bottom: 0;
}
.demo .notificationsFrame .header .menuIcon .circle {
  position: absolute;
  height: 7px;
  width: 7px;
  border-radius: 4px;
  top: -2px;
  right: 0;
  background: #b2daff;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}
.demo .notificationsFrame .header .title {
  display: block;
  text-align: center;
  color: #fff;
  font-weight: 600;
  font-size: 15px;
}
.demo .notificationsFrame .header .searchIcon {
  position: absolute;
  z-index: 3;
  font-size: 21px;
  color: #fff;
  top: 18px;
  right: 20px;
  -webkit-transition: all 0.3s ease;
  transition: all 0.3s ease;
  cursor: pointer;
}
.demo .notificationsFrame .header .searchIcon:hover {
  color: #fff;
}
.demo .notificationsFrame .content {
  position: relative;
  height: 100%;
  overflow: hidden;
}
.demo .notificationsFrame .content .line {
  position: absolute;
  top: 0;
  left: 40px;
  bottom: 0;
  width: 3px;
  background: #ebebeb;
}
.demo .notificationsFrame .content .item {
  position: relative;
  z-index: 2;
  margin: 20px 30px 30px 70px;
  display: block;
  /*border-radius: 50%;
   border: 5px solid #ecf0f1;
   box-sizing: border-box;
   position: absolute;
   height: 20px;
   width: 20px;
   background: #fff;
   border: 2px solid #5F98CD;
   box-shadow: 0 0 0 3px #fff;*/
}
.demo .notificationsFrame .content .item:hover {
  color: #5f98cd;
  cursor: pointer;
}
.demo .notificationsFrame .content .item .circle {
  box-sizing: border-box;
  position: absolute;
  height: 11px;
  width: 11px;
  background: #fff;
  border: 2px solid #5f98cd;
  box-shadow: 0 0 0 3px #fff;
  border-radius: 6px;
  top: 0;
  left: -20px;
}
.demo .notificationsFrame .content .item .avatar {
  position: absolute;
  height: 40px;
  width: 40px;
  display: inline-block;
  vertical-align: top;
  overflow: hidden;
  left: -49px;
}
.demo .notificationsFrame .content .item .avatar img {
  width: 100%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  -ms-border-radius: 50%;
  -o-border-radius: 50%;
  border-radius: 50%;
  position: absolute;
  left: 0;
  top: 0;
}
.demo .notificationsFrame .content .item .time {
  display: block;
  font-size: 11px;
  line-height: 11px;
  margin-bottom: 2px;
}
.demo .notificationsFrame .content .item p {
  font-size: 15px;
  line-height: 20px;
  margin: 0px 40px 0px 0px;
  font-family: 'Open Sans', Lora, Times, no-serif;
}
.demo .notificationsFrame .content .item p b {
  font-weight: 600;
}
.demo .notificationsFrame .content .item .right {
  position: absolute;
  right: 5px;
  font-size: 11px;
  top: 11px;
}
.demo .notificationsFrame .content .item .commentCount {
  position: absolute;
  right: 15px;
  font-size: 12px;
  top: 11px;
}
.demo .notificationsFrame .content .item .commentCount:after {
  content: "\f075";
  font-family: FontAwesome;
  position: absolute;
  font-size: 20px;
  color: #ebebeb;
  top: -50%;
  left: 100%;
  margin-left: 10px;
  z-index: 3;
}
.demo .notificationsFrame .content .item .commentCount:hover:after {
  color: lightblue;
}
.demo .notificationsFrame .footer {
  position: relative;
  background: #fff;
  margin: auto;
  height: 30px;
  border-top: 1px solid #eee;
  width: 100%;
  border-radius: 10px;
}
.demo .notificationsFrame .footer button {
  background: #eee;
  position: absolute;
  width: 100%;
  right: 0px;
  left: 0px;
  top: 0px;
  bottom: 0px;
  border: 0;
}
.demo .notificationsFrame .footer button i {
  margin: 0 10px;
}

  </style>
<body>
  <div class="demo">
    <div id="app"></div>
  </div>
  <script type="text/babel">
    class App extends React.Component {
        render() {
            return (
            <div className="notificationsFrame">
                <div className="panel">
                    <Header />
                </div>
            </div>
            )
        }
    }

    class Header extends React.Component {
        render() {
            return (
            <div className="header">
                <div className="fa fa-more"></div>

                <span className="title">Timeline</span>

                <input
                type="text"
                className="searchInput"
                placeholder="Search ..." />

                <div className="fa fa-search searchIcon"></div>
            </div>
            )
        }
    }

        var mount = document.querySelector('#app');
        ReactDOM.render(<App />, mount);
  </script>
</body>
</html>
</code>```

Body:
Following a basic React tutorial (https://www.fullstackreact.com) but I'm not able to get the given stylesheets to work properly due this error in console.

Here is the complete source of what I have so far -

    <!DOCTYPE html>

  <meta charset="utf-8">
  <title>Timeline</title>
  <link href="https://gist.githubusercontent.com/auser/2bc34b9abf07f34f602dccd6ca855df1/raw/40c5e7c8cad4c6920fed940fc31cbb63abd94c29/timeline.css" rel="stylesheet" type="text/css" />
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

I've checked in dev tools and for timeline.css I have "Accept:text/css" in the request headers which I believe is right. I don't know why it is then being transferred with a different type? This question has been asked before but the answers all seem to be saying that something to do with the type of the request is incorrect, but I can't see where.

Body:
the webmasters of site block all script and stylesheet.
this is a security feature that avoids MIME type confusion attacks.

for more info go: mozilla developer

Solution:

change your stylesheet timeline.css in other CDN or enter it in your host or in html page
example: your code

or this:

<html>
<head>
  <meta charset="utf-8">
  <title>Timeline</title>
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

  <!-- Script tags including React -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

</head>
  <style>
    .demo {
  position: relative;
}
.demo .notificationsFrame {
  z-index: 2;
  width: 100%;
  top: 20px;
  background: #fff;
  border-radius: 3px;
  overflow: hidden;
  font-family: 'Open Sans', Helvetica, sans-serif;
  margin-bottom: 40px;
}
.demo .notificationsFrame.show-menu {
  transform: translate3d(150px, 0, 0);
}
.demo .notificationsFrame .searchInput {
  border: 10px solid red;
  box-sizing: border-box;
  position: absolute;
  top: 13px;
  right: 55px;
  width: 200px;
  height: 34px;
  border-radius: 17px;
  border: none;
  background: #fff;
  padding: 0 17px;
  font-size: 13px;
  color: #666;
  transition: all 0.3s ease-in-out;
  transform: translateX(15px);
  opacity: 0;
  pointer-events: none;
}
.demo .notificationsFrame .searchInput:focus {
  outline: none;
}
.demo .notificationsFrame .searchInput.active {
  -webkit-transform: translateX(0);
  transform: translateX(0);
  opacity: 1;
  pointer-events: all;
}
.demo .notificationsFrame .header {
  position: relative;
  height: 60px;
  background: #5f98cd;
  padding-top: 0;
}
.demo .notificationsFrame .header .menuIcon {
  position: absolute;
  width: 29px;
  height: 15px;
  top: 23px;
  left: 20px;
  cursor: pointer;
}
.demo .notificationsFrame .header .menuIcon:hover .dashTop, .demo .notificationsFrame .header .menuIcon:hover .dashBottom, .demo .notificationsFrame .header .menuIcon:hover .circle {
  background: #fff;
}
.demo .notificationsFrame .header .menuIcon .dashTop {
  position: absolute;
  width: 20px;
  height: 3px;
  top: 0;
  left: 0;
  background: #b2daff;
  border-radius: 3px;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}
.demo .notificationsFrame .header .menuIcon .dashBottom {
  position: absolute;
  width: 20px;
  height: 3px;
  top: 0;
  left: 0;
  background: #b2daff;
  border-radius: 3px;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
  width: 29px;
  top: auto;
  bottom: 0;
}
.demo .notificationsFrame .header .menuIcon .circle {
  position: absolute;
  height: 7px;
  width: 7px;
  border-radius: 4px;
  top: -2px;
  right: 0;
  background: #b2daff;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;
}
.demo .notificationsFrame .header .title {
  display: block;
  text-align: center;
  color: #fff;
  font-weight: 600;
  font-size: 15px;
}
.demo .notificationsFrame .header .searchIcon {
  position: absolute;
  z-index: 3;
  font-size: 21px;
  color: #fff;
  top: 18px;
  right: 20px;
  -webkit-transition: all 0.3s ease;
  transition: all 0.3s ease;
  cursor: pointer;
}
.demo .notificationsFrame .header .searchIcon:hover {
  color: #fff;
}
.demo .notificationsFrame .content {
  position: relative;
  height: 100%;
  overflow: hidden;
}
.demo .notificationsFrame .content .line {
  position: absolute;
  top: 0;
  left: 40px;
  bottom: 0;
  width: 3px;
  background: #ebebeb;
}
.demo .notificationsFrame .content .item {
  position: relative;
  z-index: 2;
  margin: 20px 30px 30px 70px;
  display: block;
  /*border-radius: 50%;
   border: 5px solid #ecf0f1;
   box-sizing: border-box;
   position: absolute;
   height: 20px;
   width: 20px;
   background: #fff;
   border: 2px solid #5F98CD;
   box-shadow: 0 0 0 3px #fff;*/
}
.demo .notificationsFrame .content .item:hover {
  color: #5f98cd;
  cursor: pointer;
}
.demo .notificationsFrame .content .item .circle {
  box-sizing: border-box;
  position: absolute;
  height: 11px;
  width: 11px;
  background: #fff;
  border: 2px solid #5f98cd;
  box-shadow: 0 0 0 3px #fff;
  border-radius: 6px;
  top: 0;
  left: -20px;
}
.demo .notificationsFrame .content .item .avatar {
  position: absolute;
  height: 40px;
  width: 40px;
  display: inline-block;
  vertical-align: top;
  overflow: hidden;
  left: -49px;
}
.demo .notificationsFrame .content .item .avatar img {
  width: 100%;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  -ms-border-radius: 50%;
  -o-border-radius: 50%;
  border-radius: 50%;
  position: absolute;
  left: 0;
  top: 0;
}
.demo .notificationsFrame .content .item .time {
  display: block;
  font-size: 11px;
  line-height: 11px;
  margin-bottom: 2px;
}
.demo .notificationsFrame .content .item p {
  font-size: 15px;
  line-height: 20px;
  margin: 0px 40px 0px 0px;
  font-family: 'Open Sans', Lora, Times, no-serif;
}
.demo .notificationsFrame .content .item p b {
  font-weight: 600;
}
.demo .notificationsFrame .content .item .right {
  position: absolute;
  right: 5px;
  font-size: 11px;
  top: 11px;
}
.demo .notificationsFrame .content .item .commentCount {
  position: absolute;
  right: 15px;
  font-size: 12px;
  top: 11px;
}
.demo .notificationsFrame .content .item .commentCount:after {
  content: "\f075";
  font-family: FontAwesome;
  position: absolute;
  font-size: 20px;
  color: #ebebeb;
  top: -50%;
  left: 100%;
  margin-left: 10px;
  z-index: 3;
}
.demo .notificationsFrame .content .item .commentCount:hover:after {
  color: lightblue;
}
.demo .notificationsFrame .footer {
  position: relative;
  background: #fff;
  margin: auto;
  height: 30px;
  border-top: 1px solid #eee;
  width: 100%;
  border-radius: 10px;
}
.demo .notificationsFrame .footer button {
  background: #eee;
  position: absolute;
  width: 100%;
  right: 0px;
  left: 0px;
  top: 0px;
  bottom: 0px;
  border: 0;
}
.demo .notificationsFrame .footer button i {
  margin: 0 10px;
}

  </style>
<body>
  <div class="demo">
    <div id="app"></div>
  </div>
  <script type="text/babel">
    class App extends React.Component {
        render() {
            return (
            <div className="notificationsFrame">
                <div className="panel">
                    <Header />
                </div>
            </div>
            )
        }
    }

    class Header extends React.Component {
        render() {
            return (
            <div className="header">
                <div className="fa fa-more"></div>

                <span className="title">Timeline</span>

                <input
                type="text"
                className="searchInput"
                placeholder="Search ..." />

                <div className="fa fa-search searchIcon"></div>
            </div>
            )
        }
    }

        var mount = document.querySelector('#app');
        ReactDOM.render(<App />, mount);
  </script>
</body>
</html>


问:
Python animation with multiple lines
I am trying to display a Python 2.7 Matplotlib figure, animated to show 2 lines, looping through 11 files each containing different month data

The line data is held in dataframes called CoinMarketData[i] for frames 1 through 11, in the columns 'Log MC' and 'Log EMC'.

The code I have so far:

```<code>fig = plt.figure()
ax = plt.axes(xlim=(0,100), ylim=(0,30))
N=11
lines = [plt.plot([], [])[0] for _ in range(N)]

def init():
    for line in lines:
        line.set_data([],[])
    return lines

def animate(i):
    for j,line in enumerate(lines):
        # I think i need to put lists of the X and Y data in here
        lines.set_data(x, y) # set_data only takes 2 arguments...how do I set both y and y2 to the lines?
    return lines

anim = animation.FuncAnimation(fig, animate, init_func=init,
           frames=100, interval=20, blit=True)

plt.show()
</code>```

答:
If you want to have 2 lines, don't create 11 of them. Since each line belongs to one column, you can set the data seperately.</p>

```<code>import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import numpy as np

N=11

dataframes = [pd.DataFrame({"x":np.sort(np.random.rand(10)*100),
                            "y1":np.random.rand(10)*30,
                            "y2":np.random.rand(10)*30}) for _ in range(N)]

fig = plt.figure()
ax = plt.axes(xlim=(0,100), ylim=(0,30))

lines = [plt.plot([], [])[0] for _ in range(2)]

def animate(i):
    lines[0].set_data(dataframes[i]["x"], dataframes[i]["y1"])
    lines[1].set_data(dataframes[i]["x"], dataframes[i]["y2"])
    return lines

anim = animation.FuncAnimation(fig, animate,
           frames=N, interval=20, blit=True)

plt.show()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python animation with multiple lines

Body:
I am trying to display a Python 2.7 Matplotlib figure, animated to show 2 lines, looping through 11 files each containing different month data

The line data is held in dataframes called CoinMarketData[i] for frames 1 through 11, in the columns 'Log MC' and 'Log EMC'.

The code I have so far:

fig = plt.figure()
ax = plt.axes(xlim=(0,100), ylim=(0,30))
N=11
lines = [plt.plot([], [])[0] for _ in range(N)]

def init():
    for line in lines:
        line.set_data([],[])
    return lines

def animate(i):
    for j,line in enumerate(lines):
        # I think i need to put lists of the X and Y data in here
        lines.set_data(x, y) # set_data only takes 2 arguments...how do I set both y and y2 to the lines?
    return lines

anim = animation.FuncAnimation(fig, animate, init_func=init,
           frames=100, interval=20, blit=True)

plt.show()

Body:
If you want to have 2 lines, don't create 11 of them. Since each line belongs to one column, you can set the data seperately.

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import numpy as np

N=11

dataframes = [pd.DataFrame({"x":np.sort(np.random.rand(10)*100),
                            "y1":np.random.rand(10)*30,
                            "y2":np.random.rand(10)*30}) for _ in range(N)]

fig = plt.figure()
ax = plt.axes(xlim=(0,100), ylim=(0,30))

lines = [plt.plot([], [])[0] for _ in range(2)]

def animate(i):
    lines[0].set_data(dataframes[i]["x"], dataframes[i]["y1"])
    lines[1].set_data(dataframes[i]["x"], dataframes[i]["y2"])
    return lines

anim = animation.FuncAnimation(fig, animate,
           frames=N, interval=20, blit=True)

plt.show()


问:
Assign to a null pointer an area inside a function and preserve the value outside
I have a function that reads from a socket, it returns a char** where packets are stored and my intention is to use a NULL unsigned int pointer where I store the length of single packet.

```<code>char** readPackets(int numToRead,unsigned int  **lens,int socket){

    char** packets=(char**)malloc(numToRead);
    int *len=(int*)malloc(sizeof(int)*numToRead);

    *(lens)=len;

    for(int i=0;i<numToRead;i++){
        //read
        packets[i]=(char*)malloc(MAX_ETH_LEN);
        register int pack_len=read(socket,packets[i],MAX_ETH_LEN);

        //TODO handler error in  case of freezing

        if(pack_len<=0){
            i--;
            continue;
        }
        len[i]=pack_len;
    }

    return packets;

}
</code>```

I use it in this way:

```<code>unsigned int *lens_out=NULL;
char **packets=readPackets(N_PACK,&lens,sniff_sock[handler]);
</code>```

where N_PACK is a constant defined previously.

Now the problem is that when I am inside the function everything works, in fact *(lens) points to the same memory area of len and outside the function lens_out points to the same area too. Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

The problem is that outside the function even if lens_out points to the same area of len elements with same index are different for example

```<code>len[0]=46
lens_out[0]=4026546640
</code>```

Can anyone explain where I made the mistake?

答:
Firstly, I want to put it out there that you should write clear code for the sake of future maintenance, and not for what you think is optimal (yet). This entire function should merely be replaced with read. That's the crux of my post.

Now the problem is that when I am inside the function everything works

I disagree. On a slightly broader topic, the biggest problem here is that you've posted a question containing code which doesn't compile when copied and pasted unmodified, and the question isn't about the error messages, so we can't answer the question without guessing.

My guess is that you haven't noticed these error messages; you're running a stale binary which we don't have the source code for, we can't reproduce the issue and we can't see the old source code, so we can't help you. It is as valid as any other guess. For example, there's another answer which speculates:

Your statement char** packets=(char**)malloc(numToRead) for sure does not reserve enough memory.

The malloc manual doesn't guarantee that precisely numToRead bytes will be allocated; in fact, allocations to processes tend to be performed in pages and just as the sleep manual doesn't guarantee a precise number of milliseconds/microseconds, it may allocate more or it may allocate less; in the latter case, malloc must return NULL which your code needs to check.

It's extremely common for implementations to seem to behave correctly when a buffer is overflowed anyway. Nonetheless, it'd be best if you fixed that buffer overflow. malloc doesn't know about the type you're allocating; you need to tell it everything about the size, not just the number of elements.

P.S. You probably want select or sleep within your loop, you know, to "handle error in case of freezing" or whatever. Generally, OSes will switch context to another program when you call one of those, and only switch back when there's data ready to process. By calling sleep after sending or receiving, you give the OS a heads up that it needs to perform some I/O. The ability to choose that timing can be beneficial, when you're optimising. Not at the moment, though.

Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

I'm fairly sure you've misunderstood that. Perhaps gdb is implicitly dereferencing your pointers, for you; that's really irrelevant to C (so don't confuse anything you learn from gdb with anything C-related).

In fact, I strongly recommend learning a little bit less about gdb and a lot more about assert, because the former won't help you document your code for future maintenance from other people, including us, those who you ask questions to, where-as the latter will. If you include assert in your code, you're almost certainly strengthening your question (and code) much more than including gdb into your question would.

The types of len[i] and *(len[i]) are different, and their values are affected by the way types are interpreted. These values can only be considered equal When they're converted to the same type. We can see this through C11/3.19p1 (the definition of "value", where the standard establishes it is dependant upon type). len[i] is an int * value, where-as *(len[i]) is an int value. The two categories of values might have different alignment, representation and... well, they have different semantics entirely. One is for integral data, and the other is a reference to an object or array. You shouldn't be comparing them, no matter how equal they may seem; the information you obtain from such a comparison is virtually useless.

You can't use len[i] in a multiplication expression, for example. They're certainly not equal in that respect. They might compare equal (as a side-effect of comparison introducing implicit conversions), which is useless information for you to have, and that is a different story.

memcmp((int[]){0}, (unsigned char[]){ [sizeof int] = 42 }, sizeof int) may return 0 indicating that they're equal, but you know that array of characters contains an extra byte, right? Yeh... they're equal...

You must check the return value of malloc (and don't cast the return value), if you're using it, though I really think you should reconsider your options with that regard.

The fact that you use malloc means everyone who uses your function must then use free; it's locking down-stream programmers into an anti-pattern that can tear the architecture of software apart. You should separate categories of allocation logic and user interface logic from processing logic.

For example, you use read which gives you the opportunity to choose whatever storage duration you like. This means you have an immense number of optimisation opportunities. It gives you, the downstream programmer, the opportunity to write flexible code which assigns whatever storage duration you like to the memory used. Imagine if, on the other hand, you had to free every return value from every function... That's the mess you're encouraging.

This is especially a poor, inefficient design when constants are involved (i.e. your usecase), because you could just use an automatic array and get rid of the calls to malloc and free altogether... Your downstream programmers code could be:

```<code>char packet[size][count];
int n_read = read(fd, packet, size * count);
</code>```

Perhaps you think using malloc to allocate (and later read) n spaces for packets is faster than using something else to allocate n spaces. You should test that theory, because from my experience computers tend to be optimised for simpler, shorter, more concise logic.

In anticipation:

But I can't return packet; like that!

True. You can't return packet; to your downstream programmer, so you modify an object pointed at by an argument. That doesn't mean you should use malloc, though.

Unfortunately, too many programs are adopting this "use malloc everywhere" mentality. It's reminiscent of the "don't use goto" crap that we've been fed. Rather than listening to cargo cult propaganda, I recommend thinking critically about what you hear, because your peers are in the same position as you; they don't necessarily know what they're talking about.

Body:
I have a function that reads from a socket, it returns a char** where packets are stored and my intention is to use a NULL unsigned int pointer where I store the length of single packet.

char** readPackets(int numToRead,unsigned int  **lens,int socket){

    char** packets=(char**)malloc(numToRead);
    int *len=(int*)malloc(sizeof(int)*numToRead);

    *(lens)=len;

    for(int i=0;i<numToRead;i++){
        //read
        packets[i]=(char*)malloc(MAX_ETH_LEN);
        register int pack_len=read(socket,packets[i],MAX_ETH_LEN);

        //TODO handler error in  case of freezing

        if(pack_len<=0){
            i--;
            continue;
        }
        len[i]=pack_len;
    }

    return packets;

}

I use it in this way:

unsigned int *lens_out=NULL;
char **packets=readPackets(N_PACK,&lens,sniff_sock[handler]);

where N_PACK is a constant defined previously.

Now the problem is that when I am inside the function everything works, in fact *(lens) points to the same memory area of len and outside the function lens_out points to the same area too. Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

The problem is that outside the function even if lens_out points to the same area of len elements with same index are different for example

len[0]=46
lens_out[0]=4026546640

Can anyone explain where I made the mistake?

Body:
Firstly, I want to put it out there that you should write clear code for the sake of future maintenance, and not for what you think is optimal (yet). This entire function should merely be replaced with read. That's the crux of my post.

Now the problem is that when I am inside the function everything works

I disagree. On a slightly broader topic, the biggest problem here is that you've posted a question containing code which doesn't compile when copied and pasted unmodified, and the question isn't about the error messages, so we can't answer the question without guessing.

My guess is that you haven't noticed these error messages; you're running a stale binary which we don't have the source code for, we can't reproduce the issue and we can't see the old source code, so we can't help you. It is as valid as any other guess. For example, there's another answer which speculates:

Your statement char** packets=(char**)malloc(numToRead) for sure does not reserve enough memory.

The malloc manual doesn't guarantee that precisely numToRead bytes will be allocated; in fact, allocations to processes tend to be performed in pages and just as the sleep manual doesn't guarantee a precise number of milliseconds/microseconds, it may allocate more or it may allocate less; in the latter case, malloc must return NULL which your code needs to check.

It's extremely common for implementations to seem to behave correctly when a buffer is overflowed anyway. Nonetheless, it'd be best if you fixed that buffer overflow. malloc doesn't know about the type you're allocating; you need to tell it everything about the size, not just the number of elements.

P.S. You probably want select or sleep within your loop, you know, to "handle error in case of freezing" or whatever. Generally, OSes will switch context to another program when you call one of those, and only switch back when there's data ready to process. By calling sleep after sending or receiving, you give the OS a heads up that it needs to perform some I/O. The ability to choose that timing can be beneficial, when you're optimising. Not at the moment, though.

Inside the function len[i] equals to *(lens[i]) (I checked it with gdb).

I'm fairly sure you've misunderstood that. Perhaps gdb is implicitly dereferencing your pointers, for you; that's really irrelevant to C (so don't confuse anything you learn from gdb with anything C-related).

In fact, I strongly recommend learning a little bit less about gdb and a lot more about assert, because the former won't help you document your code for future maintenance from other people, including us, those who you ask questions to, where-as the latter will. If you include assert in your code, you're almost certainly strengthening your question (and code) much more than including gdb into your question would.

The types of len[i] and *(len[i]) are different, and their values are affected by the way types are interpreted. These values can only be considered equal When they're converted to the same type. We can see this through C11/3.19p1 (the definition of "value", where the standard establishes it is dependant upon type). len[i] is an int * value, where-as *(len[i]) is an int value. The two categories of values might have different alignment, representation and... well, they have different semantics entirely. One is for integral data, and the other is a reference to an object or array. You shouldn't be comparing them, no matter how equal they may seem; the information you obtain from such a comparison is virtually useless.

You can't use len[i] in a multiplication expression, for example. They're certainly not equal in that respect. They might compare equal (as a side-effect of comparison introducing implicit conversions), which is useless information for you to have, and that is a different story.

memcmp((int[]){0}, (unsigned char[]){ [sizeof int] = 42 }, sizeof int) may return 0 indicating that they're equal, but you know that array of characters contains an extra byte, right? Yeh... they're equal...

You must check the return value of malloc (and don't cast the return value), if you're using it, though I really think you should reconsider your options with that regard.

The fact that you use malloc means everyone who uses your function must then use free; it's locking down-stream programmers into an anti-pattern that can tear the architecture of software apart. You should separate categories of allocation logic and user interface logic from processing logic.

For example, you use read which gives you the opportunity to choose whatever storage duration you like. This means you have an immense number of optimisation opportunities. It gives you, the downstream programmer, the opportunity to write flexible code which assigns whatever storage duration you like to the memory used. Imagine if, on the other hand, you had to free every return value from every function... That's the mess you're encouraging.

This is especially a poor, inefficient design when constants are involved (i.e. your usecase), because you could just use an automatic array and get rid of the calls to malloc and free altogether... Your downstream programmers code could be:

char packet[size][count];
int n_read = read(fd, packet, size * count);

Perhaps you think using malloc to allocate (and later read) n spaces for packets is faster than using something else to allocate n spaces. You should test that theory, because from my experience computers tend to be optimised for simpler, shorter, more concise logic.

In anticipation:

But I can't return packet; like that!

True. You can't return packet; to your downstream programmer, so you modify an object pointed at by an argument. That doesn't mean you should use malloc, though.

Unfortunately, too many programs are adopting this "use malloc everywhere" mentality. It's reminiscent of the "don't use goto" crap that we've been fed. Rather than listening to cargo cult propaganda, I recommend thinking critically about what you hear, because your peers are in the same position as you; they don't necessarily know what they're talking about.


问:
How to add params before hash in Ionic 3
I need my server to receive params to be able to do some better sharing for social platforms like facebook.

So for example when a user goes to a page at mysite.com for item 1001, I want it to prepend a param before the # mysite.com?item=1001/#/.

This is so that if a user copies that url and shares it, the facebook bot's request for the page will include ?item=1001 in its request so I can redirect the page to our server to serve the meta page with the relevant information.

Any information after the # doesn't get sent to the server because the browser understands that it is only for the client to use.

Is it possible in Ionic to prepend query params to the url while doing normal ionic page navigation? mysite.com?item=1001/#/

答:
I ended up just using window to do this instead of making use of the ionic routing libraries.

```<code>window.history.replaceState(
   {} ,
   "Title",
   `${window.location.origin}?item=${this.item_id}/${window.location.hash}`
);
</code>```

Which changes the url to mysite.com?item=1001/#/nav/n4/other_stuff as desired.  This link can then be copied and shared and the backend will be aware of the content that it needs to generate if it is a bot

Body:
I ended up just using window to do this instead of making use of the ionic routing libraries.

window.history.replaceState(
   {} ,
   "Title",
   `${window.location.origin}?item=${this.item_id}/${window.location.hash}`
);

Which changes the url to mysite.com?item=1001/#/nav/n4/other_stuff as desired.  This link can then be copied and shared and the backend will be aware of the content that it needs to generate if it is a bot


问:
application loader inapp purchase import disappeared
Until last week, we could import text files with several in-app purchases in application loader on MacOS. Now, we can only submit application binaries.
I try to find another solution to import several in-app at one time but with no success.
How to import in-app at one time now?</p>

答:
I stumbled upon the same issue, and the new way of doing this is through XML Delivery using a command-line app called Transporter.

Data should be prepared in a specific format specified here:

http://help.apple.com/itc/appsspec/#/itc5b4d94692

Transporter tool user guide:

https://help.apple.com/itc/transporteruserguide/#/itc0d5b535bf


问:
JavaScript: How Can I Make A Var "Array" Work?
Is there a way to name a var using a sort of "Array?" My code is this:

```<code>for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    var Square[i] = document.createElement("div");
    Square[i].style.position = "relative";
    Square[i].style.float = "left";
    Square[i].style.width = "50px";
    Square[i].style.height = "50px";
    Square[i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square[i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square[i]);
}
</code>```

I know my code doesn't work, but I want to implement the same idea so I can get a result of this:

```<code>var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc
</code>```

I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?

答:
var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    Square['Square'+i] = document.createElement("div");
    Square['Square'+i].style.position = "relative";
    Square['Square'+i].style.float = "left";
    Square['Square'+i].style.width = "50px";
    Square['Square'+i].style.height = "50px";
    Square['Square'+i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square['Square'+i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square['Square'+i]);
    getTestColor = '';

}
console.log(Square);```

This example does what you want using an object instead of an array, but meets your desire to dynamically create accessible Square1, Square2, etc... They are all contained in Square. In the console with this snippet, you will see that 100 squares are created and added to the Square object. They will be accessible by Square.SquareX (where X is some number), or Square['SquareX'], or Square['Square'+X] where X is some number again.

Body:
Is there a way to name a var using a sort of "Array?" My code is this:

for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    var Square[i] = document.createElement("div");
    Square[i].style.position = "relative";
    Square[i].style.float = "left";
    Square[i].style.width = "50px";
    Square[i].style.height = "50px";
    Square[i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square[i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square[i]);
}

I know my code doesn't work, but I want to implement the same idea so I can get a result of this:

var Square1...
var Square2...
var Square3...
var Square4...
var Square5...
etc

I also tried doing a "Concentration" var, but it didn't work. How do I do this so the document doesn't append the same square multiple times?

Body:
var Square = {};
var SquareCont = document.createElement('div');
var getHorizontalSquares = 10;
var getVerticalSquares = 10;
var TestColorArray = ['a','b','c','f','e','0','1','2','3','3','4','5'];
var getTestColor = '';
for(var i = 0; i < (getHorizontalSquares * getVerticalSquares); i++){
    Square['Square'+i] = document.createElement("div");
    Square['Square'+i].style.position = "relative";
    Square['Square'+i].style.float = "left";
    Square['Square'+i].style.width = "50px";
    Square['Square'+i].style.height = "50px";
    Square['Square'+i].id = "square" + (i + 1);
    for(var ii = 0; ii < 6; ii++){
        var TestColor = TestColorArray[Math.round(Math.random()*(TestColorArray.length - 1))];
        getTestColor += TestColor;
    }
    Square['Square'+i].style.backgroundColor = "#" + getTestColor;
    SquareCont.appendChild(Square['Square'+i]);
    getTestColor = '';

}
console.log(Square);

This example does what you want using an object instead of an array, but meets your desire to dynamically create accessible Square1, Square2, etc... They are all contained in Square. In the console with this snippet, you will see that 100 squares are created and added to the Square object. They will be accessible by Square.SquareX (where X is some number), or Square['SquareX'], or Square['Square'+X] where X is some number again.


问:
Using recode and case_when together
Table1$subject contains the variables "Biology", "Chemistry", and "Physics".
For Table 2, I want to recode this, to replace all instances of Biology/Chemistry with 1 and all instances of Physics with 0.

I tried the following code, since I believe this is achievable using the recode and case_when commands:

```<code>    Table2 <- recode(Table1, case_when(
    .$subject <= "biology" ~ 1,
    .$subject <= "chemistry" ~ 1,
    .$subject <= "physics" ~ 0))
</code>```

Currently, I get an error message saying "case_when must be a two-sided formula, not a logical". I'm new to R so I'm not quite sure what I'm doing wrong. Really grateful if anyone has any ideas!

答:
This reminded me of when I first started working with R, too, and I walked over and asked the data scientists this very same question.

They shared with me a different approach that is generally preferable in these situations. I have looked back many times and appreciated learning it early on.

The database normalization approach (unless someone out there can help us with a better name) involves mapping your code values into a separate dataframe. Then you take that collection of mapped values and join them to the dataframe you are wanting to encode.

This helps keep the code more strictly responsible for manipulations, and the dataframes responsible for holding values/data. This not only can speed up much of your work, saving you from hand-coding in hard-coded lookup tables, but in the longer term it will make it much easier when someone is debugging or performing modifications and re-developments.

The normalized data management approach then would look like:

```<code># your code mapping
df_map <- tribble(~subject,    ~subj_cd,
                  "chemistry", 1,
                  "biology",   1,
                  "physics",   0)

# a dummy raw dataframe that you might be wanting to encode
df_raw <- tibble(stud_id = 2678:2877,
                 subject = sample(c("chemistry",
                                    "biology",
                                    "physics",
                                    "astronomy"), 200, replace = TRUE))

# encoding the data
df_coded <-
    df_raw %>%
    left_join(df_map)
df_code
</code>```

```<code>> df_coded
# A tibble: 200 x 3
   stud_id   subject subj_cd
     <int>     <chr>   <dbl>
 1    2678   physics       2
 2    2679   physics       2
 3    2680   biology       1
 4    2681 astronomy      NA
 5    2682 chemistry       1
 6    2683 chemistry       1
 7    2684   physics       2
 8    2685 chemistry       1
 9    2686 chemistry       1
10    2687 astronomy      NA
# ... with 190 more rows
</code>```

If you find yourself needing a quick and easy way to build longer code maps (or, especially, share them with other folks), then you will probably find Jenny Brian's googlesheets package very helpful (she's a member of team tidyverse) A really helpful vignette for it can be found here

Title: Using recode and case_when together

Body:
Table1$subject contains the variables "Biology", "Chemistry", and "Physics".
For Table 2, I want to recode this, to replace all instances of Biology/Chemistry with 1 and all instances of Physics with 0.

I tried the following code, since I believe this is achievable using the recode and case_when commands:

    Table2 <- recode(Table1, case_when(
    .$subject <= "biology" ~ 1,
    .$subject <= "chemistry" ~ 1,
    .$subject <= "physics" ~ 0))

Currently, I get an error message saying "case_when must be a two-sided formula, not a logical". I'm new to R so I'm not quite sure what I'm doing wrong. Really grateful if anyone has any ideas!

Body:
This reminded me of when I first started working with R, too, and I walked over and asked the data scientists this very same question.

They shared with me a different approach that is generally preferable in these situations. I have looked back many times and appreciated learning it early on.

The database normalization approach (unless someone out there can help us with a better name) involves mapping your code values into a separate dataframe. Then you take that collection of mapped values and join them to the dataframe you are wanting to encode.

This helps keep the code more strictly responsible for manipulations, and the dataframes responsible for holding values/data. This not only can speed up much of your work, saving you from hand-coding in hard-coded lookup tables, but in the longer term it will make it much easier when someone is debugging or performing modifications and re-developments.

The normalized data management approach then would look like:

# your code mapping
df_map <- tribble(~subject,    ~subj_cd,
                  "chemistry", 1,
                  "biology",   1,
                  "physics",   0)

# a dummy raw dataframe that you might be wanting to encode
df_raw <- tibble(stud_id = 2678:2877,
                 subject = sample(c("chemistry",
                                    "biology",
                                    "physics",
                                    "astronomy"), 200, replace = TRUE))

# encoding the data
df_coded <-
    df_raw %>%
    left_join(df_map)
df_code

> df_coded
# A tibble: 200 x 3
   stud_id   subject subj_cd
     <int>     <chr>   <dbl>
 1    2678   physics       2
 2    2679   physics       2
 3    2680   biology       1
 4    2681 astronomy      NA
 5    2682 chemistry       1
 6    2683 chemistry       1
 7    2684   physics       2
 8    2685 chemistry       1
 9    2686 chemistry       1
10    2687 astronomy      NA
# ... with 190 more rows

If you find yourself needing a quick and easy way to build longer code maps (or, especially, share them with other folks), then you will probably find Jenny Brian's googlesheets package very helpful (she's a member of team tidyverse) A really helpful vignette for it can be found here


问:
Is it possible to budle Unity application, transfer it to the device and run it in some kind of player?
It may be a silly question, but I dont know what to google.

Consider this, we are building unity AR application that run on IOS. Every client has custom need, so there is custom application for every one of them. Because of that whole application lifecycle managment is nigthmare.

We would like to build just one appliaction as player and download all content (unity app) from server and just run it.

Is something like that possible? How can we achieve that?

答: AssetBundle recommended by @Everts seems like good fit, it does not solve everything but for sure helps a lot.</p>


问:
How can I convert a string into a variable name in C#?
I have four pre-defined input keywords. (e.g num1, num2, etc) Based on these keywords the user will define a formula in a textbox.
Example:
num1 + num2 * num3 * (num3-num1)

Since this input will be taken from a textbox it will be a string.
How can convert these keywords from string to the variable name and execute the formula in my code?

I didn't find any suitable answer for this in other threads.

Any help is appreciated. Thanks

答:
Try out the DynamicExpresso nuget package - https://www.nuget.org/packages/DynamicExpresso.Core/

Then you can do something like:

```<code>var s = "num1 + num2 * num3 * (num3-num1)";
var interpreter = new Interpreter();

int num1 = 11;
int num2 = 12;
int num3 = 13;

var parameters = new[]
{
    new Parameter("num1", num1),
    new Parameter("num2", num2),
    new Parameter("num3", num3)
};
var result = interpreter.Eval(s, parameters);

Console.WriteLine(result); // 323
</code>```

Body:
Try out the DynamicExpresso nuget package - https://www.nuget.org/packages/DynamicExpresso.Core/

Then you can do something like:

var s = "num1 + num2 * num3 * (num3-num1)";
var interpreter = new Interpreter();

int num1 = 11;
int num2 = 12;
int num3 = 13;

var parameters = new[]
{
    new Parameter("num1", num1),
    new Parameter("num2", num2),
    new Parameter("num3", num3)
};
var result = interpreter.Eval(s, parameters);

Console.WriteLine(result); // 323


问:
Continued - Vehicle License Plate Detection
Continuing from this thread:

What are good algorithms for vehicle license plate detection?

I've developed my image manipulation techniques to emphasise the license plate as much as possible, and overall I'm happy with it, here are two samples.

Now comes the most difficult part, actually detecting the license plate. I know there are a few edge detection methods, but my maths is quite poor so I'm unable to translate some of the complex formulas into code.

My idea so far is to loop through every pixel within the image (for loop based on img width & height) From this compare each pixel against a list of colours, from this an algorithm is checked to see if the colors keep differentiating between the license plate white, and the black of the text. If this happens to be true these pixels are built into a new bitmap within memory, then an OCR scan is performed once this pattern has stopped being detected.

I'd appreciate some input on this as it might be a flawed idea, too slow or intensive.

Thanks

答:
Your method of "see if the colors keep differentiating between the license plate white, and the black of the text" is basically searching for areas where the pixel intensity changes from black to white and vice-versa many times. Edge detection can accomplish essentially the same thing. However, implementing your own methods is still a good idea because you will learn a lot in the process. Heck, why not do both and compare the output of your method with that of some ready-made edge detection algorithm?

At some point you will want to have a binary image, say with black pixels corresponding to the "not-a-character" label, and white pixels corresponding to the "is-a-character" label. Perhaps the simplest way to do that is to use a thresholding function. But that will only work well if the characters have already been emphasized in some way.

As someone mentioned in your other thread, you can do that using the black hat operator, which results in something like this:

If you threshold the image above with, say, Otsu's method (which automatically determines a global threshold level), you get this:

There are several ways to clean that image. For instance, you can find the connected components and throw away those that are too small, too big, too wide or too tall to be a character:

Since the characters in your image are relatively large and fully connected this method works well.

Next, you could filter the remaining components based on the properties of the neighbors until you have the desired number of components (= number of characters). If you want to recognize the character, you could then calculate features for each character and input them to a classifier, which usually is built with supervised learning.

All the steps above are just one way to do it, of course.

By the way, I generated the images above using OpenCV + Python, which is a great combination for computer vision.

ContentLicense: CC BY-SA 2.5


问:
If jQuery form is valid show hidden div
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

```<code><div class="place-form">
   <div class="success-msg" style="display:none;">
    <p>Thanks for your submission! We will contact you shortly.</p>
  </div>
  <div class="form-wrap">
    <form id="place-form-item">
    <div class="form-row">
      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />
    </div>
    <div class="form-row">
      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />
    </div>
    <div class="form-row">
      <input id="form-email" type="email" name="email" placeholder="Your Email" required />
    </div>
    <div class="btn-row">
      <button class="submit-btn">submit</button>
    </div>
      </form>
  </div>
</div>
</code>```

JS:

```<code>$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});
</code>```

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

答:
Intercept the submit event, prevent the default form submission, and substitute your own action.</p>

```<code>$("#my-form").on("submit", function (event) {
    event.preventDefault();
    if ($(this).valid()) {
        // do something
    }
});
</code>```

Title: If jQuery form is valid show hidden div

Body:
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

Thanks for your submission! We will contact you shortly.

    <form id="place-form-item">

      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />

      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />

      <input id="form-email" type="email" name="email" placeholder="Your Email" required />

      <button class="submit-btn">submit</button>

      </form>

JS:

$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

Body:
Intercept the submit event, prevent the default form submission, and substitute your own action.

$("#my-form").on("submit", function (event) {
    event.preventDefault();
    if ($(this).valid()) {
        // do something
    }
});


问:
Passing props as unknown attributes to an element in React
Right now I'm working on an Input component which will represent a form input field. I want it to be universal (like for text, date and numbers). The problem so far is that I don't know how to pass unknown attributes directly to my input element Here's the code:

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Input extends Component {
    render () {
      let required = false
      if (this.props.required) {
        required = true
      }
      return (
        <div className='form-group'>
          <label>{ this.props.label }</label>
          <input
            type={this.props.type}
            name={this.props.name}
            value={this.props.value}
            placeholder={this.props.placeholder}
            className={this.props.className}
            onChange={this.props.handleChange}
            {this.props.attrs}  // error here
            required = {required}
          />
        </div>
      )
    }
}

Input.propTypes = {
  attrs: PropTypes.string,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

export default Input
</code>```

React rejects this.props.attrs when I insert it directly into the input element and I don't know what to do...

Why do I even need this.props.attrs?

I don't know what input type I may want to use in the future. Let's say I want to have a number input. In this case in this.props.attrs I could store min = '1' max = '100' string.

So when I pass this.props.attrs to a component I want to get an input like the following:

```<code><input ... min = '1' max = '100' ... />
</code>```

答:
You should use object spread {...this.props.attrs}

Note that this is a proposal and its on stage 3 at the moment.

Here is a running example:

class MyInput extends React.Component {
  render() {
    const { title, ...restOfProps } = this.props;
    return (

        {title}
        <input {...restOfProps} />

    );
  }
}

ReactDOM.render(<MyInput title="password" type="password" style={{border:'3px solid green', margin:'0 5px'}} />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
Right now I'm working on an Input component which will represent a form input field. I want it to be universal (like for text, date and numbers). The problem so far is that I don't know how to pass unknown attributes directly to my input element Here's the code:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Input extends Component {
    render () {
      let required = false
      if (this.props.required) {
        required = true
      }
      return (

          { this.props.label }
          <input
            type={this.props.type}
            name={this.props.name}
            value={this.props.value}
            placeholder={this.props.placeholder}
            className={this.props.className}
            onChange={this.props.handleChange}
            {this.props.attrs}  // error here
            required = {required}
          />

      )
    }
}

Input.propTypes = {
  attrs: PropTypes.string,
  label: PropTypes.string.isRequired,
  type: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  value: PropTypes.string.isRequired,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  handleChange: PropTypes.func.isRequired,
  required: PropTypes.bool
}

Input.defaultProps = {
  type: 'text',
  required: true
}

export default Input

React rejects this.props.attrs when I insert it directly into the input element and I don't know what to do...

Why do I even need this.props.attrs?

I don't know what input type I may want to use in the future. Let's say I want to have a number input. In this case in this.props.attrs I could store min = '1' max = '100' string.

So when I pass this.props.attrs to a component I want to get an input like the following:

<input ... min = '1' max = '100' ... />

Body:
You should use object spread {...this.props.attrs}

Note that this is a proposal and its on stage 3 at the moment.

Here is a running example:

class MyInput extends React.Component {
  render() {
    const { title, ...restOfProps } = this.props;
    return (
      <div>
        <label>{title}</label>
        <input {...restOfProps} />
      </div>
    );
  }
}

ReactDOM.render(<MyInput title="password" type="password" style={{border:'3px solid green', margin:'0 5px'}} />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
Check if there's some text inside an element
I am creating an If...Else statement and need to check if the element has innerHTML / textContent.
Like this:

```<code>  if (<span class="event"> *yet has some text inside*) {do smth}
  else {do smth else};
</code>```

So, how do I do that using Javascript?
Please, help!

UPD! I have dynamically changing content, and

```<code> element.innerHTML
</code>```

seems not working after I put some text inside my . I mean it still thinks the  is empty. Any cure for that?

答:
Alternate method to innerHTML</p>

```<code>if(document.getElementById("element_id").lastChild) {
    //Has content
}
else {
    //No content
}
</code>```

Body:
I am creating an If...Else statement and need to check if the element has innerHTML / textContent.
Like this:

  if ( *yet has some text inside*) {do smth}
  else {do smth else};

So, how do I do that using Javascript?
Please, help!

UPD! I have dynamically changing content, and

 element.innerHTML

seems not working after I put some text inside my . I mean it still thinks the  is empty. Any cure for that?

Body:
Alternate method to innerHTML

if(document.getElementById("element_id").lastChild) {
    //Has content
}
else {
    //No content
}


问:
Inject http interceptor at component
I've created this http interceptor:

```<code>@Injectable()
export class NoopInterceptor  implements HttpInterceptor {
    public my_status: boolean = true;
    private _statusChange: Subject<boolean> = new Subject<boolean>();
    public statusChange$ = this._statusChange.asObservable();
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.changeStatus(false);
        const my_req = req.clone({
            url: API_PATH + req.url
        });
        return next
            .handle(my_req)
            .do(event => {
                if (event instanceof HttpResponse)
                    this.changeStatus(true);
            });
    }

    private changeStatus(status: boolean) {
        this.my_status = status;
        this._statusChange.next(this.my_status);
    }
}
</code>```

And in my component, I did it:

```<code>export class AppComponent implements OnInit {
    public my_status: boolean;
    constructor(private httpInterceptor: NoopInterceptor) {
        this.my_status = httpInterceptor.my_status;
        httpInterceptor.statusChange$.subscribe(this.changeStatus);
    }

    changeStatus(status: boolean) {
        this.my_status = status;
    }

}
</code>```

At app.module, I provided the interceptor like this:

```<code>providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    }
]
</code>```

When I do in the way above, I get No provider for NoopInterceptor!, because I'm not providing NoopInterceptor, but if I provide NoopInterceptor like this:

```<code>providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    },
    NoopInterceptor
]
</code>```

I'll get two injections and the component will get the wrong one, then I won't be able to subscribe statusChange. How can I workaround this?

答:
Have you tried to put NoopInterceptor before the provide of HTTP_INTERCEPTOR and useExisting instead of useClass ?
In that way you should get only one NoopInterceptor instance.</p>

Title: Inject http interceptor at component

Body:
I've created this http interceptor:

@Injectable()
export class NoopInterceptor  implements HttpInterceptor {
    public my_status: boolean = true;
    private _statusChange: Subject<boolean> = new Subject<boolean>();
    public statusChange$ = this._statusChange.asObservable();
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.changeStatus(false);
        const my_req = req.clone({
            url: API_PATH + req.url
        });
        return next
            .handle(my_req)
            .do(event => {
                if (event instanceof HttpResponse)
                    this.changeStatus(true);
            });
    }

    private changeStatus(status: boolean) {
        this.my_status = status;
        this._statusChange.next(this.my_status);
    }
}

And in my component, I did it:

export class AppComponent implements OnInit {
    public my_status: boolean;
    constructor(private httpInterceptor: NoopInterceptor) {
        this.my_status = httpInterceptor.my_status;
        httpInterceptor.statusChange$.subscribe(this.changeStatus);
    }

    changeStatus(status: boolean) {
        this.my_status = status;
    }

}

At app.module, I provided the interceptor like this:

providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    }
]

When I do in the way above, I get No provider for NoopInterceptor!, because I'm not providing NoopInterceptor, but if I provide NoopInterceptor like this:

providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    },
    NoopInterceptor
]

I'll get two injections and the component will get the wrong one, then I won't be able to subscribe statusChange. How can I workaround this?


问:
Check for more than 1 running instance of powershell script launched using ".\scriptName.ps1"
The below thread explains how to check for more than 1 instance of a powershell script using get-wmiobject win32_process

Assure only 1 instance of PowerShell Script is Running at any given Time

For get-wmiobject win32_process to list a running powershell script, that script needs to be invoked using powershell.exe scriptName.ps1. How can I check for more than 1 instance of the script running where the script was invoked using .\scriptName.ps1?

答:
You could use the below and see if the result is > 1</p>

```<code>(Get-WmiObject Win32_Process | select commandline | where {$_ -ilike "*scriptName.ps1*"} | measure).Count
</code>```

Body:
You could use the below and see if the result is > 1

(Get-WmiObject Win32_Process | select commandline | where {$_ -ilike "*scriptName.ps1*"} | measure).Count


问:
Nodejs and Mongoose wait till document is saved before callback
The following function takes an aggregate cursor containing several arrays of user Ids so the users with the corresponding ids can be modified and then saved.

The issue I am having is getting the function to only return once all the users have been modified and saved. Currently it doesn't do that and when I attempt to access the users later on (literally after this function) the modifications haven't been permeated through.

This is the current code that does the modification (might be some strange async additions as I have been attempting 10s of different options with no success):

```<code>function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;

  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        callBack();
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}
</code>```

The data that is passed is:

dataArray: Aggregation cursor

Result for eachAsync e.g. data is:

```<code>{ _id: 'GroupValue',
users:
 [ 5a0b2f5bcd0813adeac2435b,
   5a0b2f5bcd0813adeac24357,
   5a0b2f5bcd0813adeac24358 ] }
</code>```

答:
You are calling the return statement via the callback after every single iteration of the callback. Thus, you are returning userArray.length times.

If you just want to insert the data and don't want the function that's using it to know whether or not they were successful in inserting, you could just do the callback immediately before even iterating through the loop.

```<code>function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;

  callBack();
  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        //do nothing
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}
</code>```

Otherwise, let's say you want to only callback specifically after the last iteration. One dirty way you could do this is do a temporary variable outside of the loop, and an if statement in the loop that executes on the last iteration.

For this implementation, you must assume the function will never pass a non-zero length array of users. Otherwise, it would never run a single iteration, and not terminate. (You would want to write an if length == 0 case)

```<code>function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;
  let tempVar = 0;

  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        tempVar++;
        if(tempVar == userArray.length) {
          callBack();
        }
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}
</code>```

Body:
The following function takes an aggregate cursor containing several arrays of user Ids so the users with the corresponding ids can be modified and then saved.

The issue I am having is getting the function to only return once all the users have been modified and saved. Currently it doesn't do that and when I attempt to access the users later on (literally after this function) the modifications haven't been permeated through.

This is the current code that does the modification (might be some strange async additions as I have been attempting 10s of different options with no success):

function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;

  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        callBack();
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}

The data that is passed is:

dataArray: Aggregation cursor

Result for eachAsync e.g. data is:

{ _id: 'GroupValue',
users:
 [ 5a0b2f5bcd0813adeac2435b,
   5a0b2f5bcd0813adeac24357,
   5a0b2f5bcd0813adeac24358 ] }

Body:
You are calling the return statement via the callback after every single iteration of the callback. Thus, you are returning userArray.length times.

If you just want to insert the data and don't want the function that's using it to know whether or not they were successful in inserting, you could just do the callback immediately before even iterating through the loop.

function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;

  callBack();
  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        //do nothing
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}

Otherwise, let's say you want to only callback specifically after the last iteration. One dirty way you could do this is do a temporary variable outside of the loop, and an if statement in the loop that executes on the last iteration.

For this implementation, you must assume the function will never pass a non-zero length array of users. Otherwise, it would never run a single iteration, and not terminate. (You would want to write an if length == 0 case)

function updateUsers(dataArray, done) {

dataArray.eachAsync(
 function(data) {
  let userArray = data.users;
  let tempVar = 0;

  async.forEach(userArray, function(userId, callBack){

    mongoose.model('User').findById(userId, function(err, user) {
      // User document modified
      user.save(function(err, user){
        tempVar++;
        if(tempVar == userArray.length) {
          callBack();
        }
      });
    });
  });
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}
},
function(err) {
  //Only come here once all the users have been modified and saved!
  if (err) {
    return done(err, false);
  }

  return done(err, true);
  }
 );
}


问:
While with assignment in swift
What is the proper way to convert this Objective-C code into Swift?

```<code>while ((size = [inputdata readWithByteArray:buf]) != -1) {
  //...
}
</code>```

I need similar to this (from here):

```<code>while let super = view?.superview {
  count++
  view = super
}
</code>```

but in my case i have to compare the value with -1 instead of nil.

答:
I found the tuple-based code from the accepted answer quite interesting for solving the issue posted in the question.

Here the if (..., boolean).1 { expression evaluates the second tuple element, a boolean, and the first tuple element is only evaluated for its side-effect.

So you can do things like inline the index decrement in the while loop condition, rather than on a line before or after:

```<code>var index = 5
while (index -= 1, index >= 0).1 {
    print(index)
}

// 4
// 3
// 2
// 1
// 0
</code>```

Whereas the while case let construct does not allow the previous assignments to index to persist in the next iteration of the loop:

```<code>var index = 0
while case let index = index + 1 {
    print(index)
}

// 1
// 1
// 1
// 1
// infinite loop
</code>```

Title: While with assignment in swift

Body:
What is the proper way to convert this Objective-C code into Swift?

while ((size = [inputdata readWithByteArray:buf]) != -1) {
  //...
}

I need similar to this (from here):

while let super = view?.superview {
  count++
  view = super
}

but in my case i have to compare the value with -1 instead of nil.

Body:
I found the tuple-based code from the accepted answer quite interesting for solving the issue posted in the question.

Here the if (..., boolean).1 { expression evaluates the second tuple element, a boolean, and the first tuple element is only evaluated for its side-effect.

So you can do things like inline the index decrement in the while loop condition, rather than on a line before or after:

var index = 5
while (index -= 1, index >= 0).1 {
    print(index)
}

// 4
// 3
// 2
// 1
// 0

Whereas the while case let construct does not allow the previous assignments to index to persist in the next iteration of the loop:

var index = 0
while case let index = index + 1 {
    print(index)
}

// 1
// 1
// 1
// 1
// infinite loop


问:
Can we move a file from an FTP server to a local directory using apache camel endpoints?
I was wondering if it is possible to move or download a file from FTP server to a local directory using the apache camel endpoints properties?

I already searched this topic and couldn't find anything that could help me. Also, I'm not certain of its feasibility.

The endpoints URI=

sftp://user@ftp.com/outgoingFolder?password=*****&throwExceptionOnConnectFailed=true&maximumReconnectAttempts=0&stepwise=false&fastExistsCheck=true&disconnect=true&consumer.delay=300000&passiveMode=true

I used "&move=C:\folder" as property but it didn't work and I get the following error

```<code>WARN - [SftpConsumer:213] Consumer Consumer[sftp://user@ftp.com/outgoingFolder?consumer.delay=300000&disconnect=true&fastExistsCheck=true&maximumReconnectAttempts=0&move=C%3A%5C%5Cfolders&passiveMode=true&password=xxxxxx&stepwise=false&throwExceptionOnConnectFailed=true] failed polling endpoint: Endpoint[sftp://user@ftp.com/outgoingFolder?consumer.delay=300000&disconnect=true&fastExistsCheck=true&maximumReconnectAttempts=0&move=C%3A%5C%5Cfolder&passiveMode=true&password=xxxxxx&stepwise=false&throwExceptionOnConnectFailed=true]. Will try again at next poll. Caused by: [org.apache.camel.component.file.GenericFileOperationFailedException - Cannot list directory:outgoingFolder]org.apache.camel.component.file.GenericFileOperationFailedException: Cannot list directory: outgoingFolder        at org.apache.camel.component.file.remote.SftpOperations.listFiles(SftpOperations.java:617)        at org.apache.camel.component.file.remote.SftpConsumer.doPollDirectory(SftpConsumer.java:117)        at org.apache.camel.component.file.remote.SftpConsumer.pollDirectory(SftpConsumer.java:79)        at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:131)        at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:175)        at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:102)        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)        at java.lang.Thread.run(Thread.java:745)Caused by: 4:        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2208)        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2215)        at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1565)        at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1526)        at org.apache.camel.component.file.remote.SftpOperations.listFiles(SftpOperations.java:608)        ... 12 more Caused by: java.io.IOException: inputstream is losed        at com.jcraft.jsch.ChannelSftp.fill(ChannelSftp.java:2884)        at com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2908)        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2189)        ... 16 more
</code>```

答:
No, &move option is intended for moving file in scope of remote filesystem.

Use this instead:

```<code>from("sftp://user@ftp.com/outgoingFolder?password=*****&throwExceptionOnConnectFailed=true&maximumReconnectAttempts=0&stepwise=false&fastExistsCheck=true&disconnect=true&consumer.delay=300000&passiveMode=true")
.to("file:C:\\folder");
</code>```

Body:
I was wondering if it is possible to move or download a file from FTP server to a local directory using the apache camel endpoints properties?

I already searched this topic and couldn't find anything that could help me. Also, I'm not certain of its feasibility.

The endpoints URI=

sftp://user@ftp.com/outgoingFolder?password=*****&throwExceptionOnConnectFailed=true&maximumReconnectAttempts=0&stepwise=false&fastExistsCheck=true&disconnect=true&consumer.delay=300000&passiveMode=true

I used "&move=C:\folder" as property but it didn't work and I get the following error

WARN - [SftpConsumer:213] Consumer Consumer[sftp://user@ftp.com/outgoingFolder?consumer.delay=300000&disconnect=true&fastExistsCheck=true&maximumReconnectAttempts=0&move=C%3A%5C%5Cfolders&passiveMode=true&password=xxxxxx&stepwise=false&throwExceptionOnConnectFailed=true] failed polling endpoint: Endpoint[sftp://user@ftp.com/outgoingFolder?consumer.delay=300000&disconnect=true&fastExistsCheck=true&maximumReconnectAttempts=0&move=C%3A%5C%5Cfolder&passiveMode=true&password=xxxxxx&stepwise=false&throwExceptionOnConnectFailed=true]. Will try again at next poll. Caused by: [org.apache.camel.component.file.GenericFileOperationFailedException - Cannot list directory:outgoingFolder]org.apache.camel.component.file.GenericFileOperationFailedException: Cannot list directory: outgoingFolder        at org.apache.camel.component.file.remote.SftpOperations.listFiles(SftpOperations.java:617)        at org.apache.camel.component.file.remote.SftpConsumer.doPollDirectory(SftpConsumer.java:117)        at org.apache.camel.component.file.remote.SftpConsumer.pollDirectory(SftpConsumer.java:79)        at org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:131)        at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:175)        at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:102)        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)        at java.lang.Thread.run(Thread.java:745)Caused by: 4:        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2208)        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2215)        at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1565)        at com.jcraft.jsch.ChannelSftp.ls(ChannelSftp.java:1526)        at org.apache.camel.component.file.remote.SftpOperations.listFiles(SftpOperations.java:608)        ... 12 more Caused by: java.io.IOException: inputstream is losed        at com.jcraft.jsch.ChannelSftp.fill(ChannelSftp.java:2884)        at com.jcraft.jsch.ChannelSftp.header(ChannelSftp.java:2908)        at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:2189)        ... 16 more

Body:
No, &move option is intended for moving file in scope of remote filesystem.

Use this instead:

from("sftp://user@ftp.com/outgoingFolder?password=*****&throwExceptionOnConnectFailed=true&maximumReconnectAttempts=0&stepwise=false&fastExistsCheck=true&disconnect=true&consumer.delay=300000&passiveMode=true")
.to("file:C:\\folder");


问:
How to pass slice into a function by reference
If I have

```<code>a = [1, 2, 3]

def foo (arr):
    for i in len (arr): arr [i] += 1

def bar (arr):
    foo (arr[:2])

bar (a)
print (a)
</code>```

I want output as

```<code>>>> [2, 3, 3 ]
</code>```

How do I go about this?

Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush(). But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.

答:
This will work if a is a numpy array. By default, numpy slices refer to the same block of memory as the original array.

```<code>import numpy as np
a = np.array([1, 2, 3])

def foo(arr):
    for i in range(len(arr)): arr[i] += 1
    # or just arr += 1

def bar(arr):
    foo(arr[:2])

bar(a)
print(a)
# [2, 3, 3 ]
</code>```

Body:
If I have

a = [1, 2, 3]

def foo (arr):
    for i in len (arr): arr [i] += 1

def bar (arr):
    foo (arr[:2])

bar (a)
print (a)

I want output as

>>> [2, 3, 3 ]

How do I go about this?

Motivation: I want a priority queue where I can freeze last N elements, i.e. pass only queue[:N] to heapq.heappush(). But, every time I pass a slice, to it, or to any function in general, it sends a copy of slice and not the actual list to the function, and so my list remains unchanged in the end.

Body:
This will work if a is a numpy array. By default, numpy slices refer to the same block of memory as the original array.

import numpy as np
a = np.array([1, 2, 3])

def foo(arr):
    for i in range(len(arr)): arr[i] += 1
    # or just arr += 1

def bar(arr):
    foo(arr[:2])

bar(a)
print(a)
# [2, 3, 3 ]


答:
It's likely possible to create single interceptor instance with:

```<code>providers: [
    NoopInterceptor,
   {
        provide: HTTP_INTERCEPTORS,
        useExisting: NoopInterceptor,
        multi: true
    }
]
</code>```

But a proper solution for loading indicator state (I guess statusChange serves for this purpose) is to detach it from an interceptor and make it a separate provider.

And as it's shown here, there should be request counter because there can be simultaneous requests, and it should be affected by both success and error do callbacks.

Title: Inject http interceptor at component

Body:
It's likely possible to create single interceptor instance with:

providers: [
    NoopInterceptor,
   {
        provide: HTTP_INTERCEPTORS,
        useExisting: NoopInterceptor,
        multi: true
    }
]

But a proper solution for loading indicator state (I guess statusChange serves for this purpose) is to detach it from an interceptor and make it a separate provider.

And as it's shown here, there should be request counter because there can be simultaneous requests, and it should be affected by both success and error do callbacks.


问:
Default background color of SVG root element
I'd like to set a default background color for the entire SVG document, to red for example.

```<code><svg viewBox="0 0 500 600" style="background: red">/* content */</svg>
</code>```

The solution above works but the background property of the style attribute is unfortunately not a standard one : http://www.w3.org/TR/SVG/styling.html#SVGStylingProperties, and so it gets removed during the cleaning process with SVG Cleaner.

Is there another way to declare this background color?

答:
It is the answer of @Robert Longson, now with code (there was originally no code, it was added later):

<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
 <rect width="100%" height="100%" fill="red"/>
</svg>```

This answer uses:

https://stackoverflow.com/a/11293812/6747994

https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes

Body:
I'd like to set a default background color for the entire SVG document, to red for example.

<svg viewBox="0 0 500 600" style="background: red">/* content */</svg>

The solution above works but the background property of the style attribute is unfortunately not a standard one : http://www.w3.org/TR/SVG/styling.html#SVGStylingProperties, and so it gets removed during the cleaning process with SVG Cleaner.

Is there another way to declare this background color?

Body:
It is the answer of @Robert Longson, now with code (there was originally no code, it was added later):

<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
 <rect width="100%" height="100%" fill="red"/>
</svg>

This answer uses:

https://stackoverflow.com/a/11293812/6747994

https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes