问:
swap fa-caret right to Caret down using css or jquery method
I'm Currently working on a left side menu in which I'm using list. Everything works fine but now I want to perform action on font-awsome in which I'm trying to move fa-caret-right to fa-caret-down. fa-caret-right when the list is not open and fa-caret-down when the list is open. My question is how can I approach this methodology by css or jquery. I searched for solution but didn't get resolved. Here is my js fiddle working link code

https://fiddle.jshell.net/gLjbyjtm/4/

 Update:1 caret Error Resolved Js fiddle new version

In this version I'm successfully able to toggle my left side menu to the left side by clicking on a checkbox label having fa-angle-right. The problem comes with fa-angle-right that it doesn't move to the left side along with the left -side menu while toggling or the elements in the span should also be move left when its width squeeze whil toggling. Below is my working on js fiddle. Any Suggestions ?

https://fiddle.jshell.net/uLy1xgtn/6/

答:
Adjusting pseudo-element

```<code>/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    content: "\f0d7";
}
</code>```

Explanation:

Since the class .collapsed is added whenever an accordion item is not open, we can use this as a selector to target.

And since there is no class to target accordion items when they are opened we will do this is by using :not() - the negation pseudo-class selector; which, in this case, will select list-item elements which do not have the class .collapsed - implying that they are opened.

The :not() CSS pseudo-class represents elements that do not match a
  list of selectors. Since it prevents specific items from being
  selected, it is known as the negation pseudo-class.

Example

```<code>/* Selects any element that is NOT a paragraph */
:not(p) {
  color: blue;
}
</code>```

Source: :not() - CSS | MDN

Updated JSFiddle

.nav-side-menu {
  overflow: auto;
  font-family: verdana;
  font-size: 12px;
  font-weight: 200;
  background-color: #2e353d;
  position: fixed;
  top: 0px;
  width: 300px;
  height: 100%;
  color: #e1ffff;
}
.nav-side-menu .brand {
  background-color: #23282e;
  line-height: 50px;
  display: block;
  text-align: center;
  font-size: 14px;
}
.nav-side-menu .toggle-btn {
  display: none;
}
.nav-side-menu ul,
.nav-side-menu li {
  list-style: none;
  padding: 0px;
  margin: 0px;
  line-height: 35px;
  cursor: pointer;
  /*
    .collapsed{
       .arrow:before{
                 font-family: FontAwesome;
                 content: "\f053";
                 display: inline-block;
                 padding-left:10px;
                 padding-right: 10px;
                 vertical-align: middle;
                 float:right;
            }
     }
*/
}
.nav-side-menu ul :not(collapsed) .arrow:before,
.nav-side-menu li :not(collapsed) .arrow:before {
  font-family: FontAwesome;
  content: "\f0da";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
  float: right;
}
.nav-side-menu ul .active,
.nav-side-menu li .active {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
}
.nav-side-menu ul .sub-menu li.active,
.nav-side-menu li .sub-menu li.active {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li.active a,
.nav-side-menu li .sub-menu li.active a {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li,
.nav-side-menu li .sub-menu li {
  background-color: #181c20;
  border: none;
  line-height: 28px;
  border-bottom: 1px solid #23282e;
  margin-left: 0px;
}
.nav-side-menu ul .sub-menu li:hover,
.nav-side-menu li .sub-menu li:hover {
  background-color: #020203;
}
.nav-side-menu ul .sub-menu li:before,
.nav-side-menu li .sub-menu li:before {
  font-family: FontAwesome;
  content: "\f105";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
}
.nav-side-menu li {
  padding-left: 0px;
  border-left: 3px solid #2e353d;
  border-bottom: 1px solid #23282e;
}
.nav-side-menu li a {
  text-decoration: none;
  color: #e1ffff;
}
.nav-side-menu li a i {
  padding-left: 10px;
  width: 20px;
  padding-right: 20px;
}
.nav-side-menu li:hover {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  -ms-transition: all 1s ease;
  transition: all 1s ease;
}
@media (max-width: 767px) {
  .nav-side-menu {
    position: relative;
    width: 100%;
    margin-bottom: 10px;
  }
  .nav-side-menu .toggle-btn {
    display: block;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10 !important;
    padding: 3px;
    background-color: #ffffff;
    color: #000;
    width: 40px;
    text-align: center;
  }
  .brand {
    text-align: left !important;
    font-size: 22px;
    padding-left: 20px;
    line-height: 50px !important;
  }
}
@media (min-width: 767px) {
  .nav-side-menu .menu-list .menu-content {
    display: block;
  }
}
body {
  margin: 0px;
  padding: 0px;
}

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    content: "\f0d7";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="/dist/scripts.min.js"></script>

<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

<div class="nav-side-menu">
    <div class="brand">Brand Logo</div>

        <div class="menu-list">

            <ul id="menu-content" class="menu-content">
                <li>

                  <i class="fa fa-dashboard fa-lg"></i> Dashboard

                </li>

                <li  data-toggle="collapse" data-target="#products" class="collapsed active">
                  <i class="fa fa-gift fa-lg"></i> UI Elements <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="products">
                    <li class="active">CSS3 Animation</li>
                    <li>General</li>
                    <li>Buttons</li>
                    <li>Tabs & Accordions</li>
                    <li>Typography</li>
                    <li>FontAwesome</li>
                    <li>Slider</li>
                    <li>Panels</li>
                    <li>Widgets</li>
                    <li>Bootstrap Model</li>
                </ul>

                <li data-toggle="collapse" data-target="#service" class="collapsed">
                  <i class="fa fa-globe fa-lg"></i> Services <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="service">
                  <li>New Service 1</li>
                  <li>New Service 2</li>
                  <li>New Service 3</li>
                </ul>

                <li data-toggle="collapse" data-target="#new" class="collapsed">
                  <i class="fa fa-car fa-lg"></i> New <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="new">
                  <li>New New 1</li>
                  <li>New New 2</li>
                  <li>New New 3</li>
                </ul>

                 <li>

                  <i class="fa fa-user fa-lg"></i> Profile

                  </li>

                 <li>

                  <i class="fa fa-users fa-lg"></i> Users

                </li>
            </ul>
     </div>
</div></code>```

Adjusting existing element

```<code>/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    transform: rotate(90deg);
}

.nav-side-menu ul li .arrow:before {
    transition: .5s;
}
</code>```

Updated JSFiddle

.nav-side-menu {
  overflow: auto;
  font-family: verdana;
  font-size: 12px;
  font-weight: 200;
  background-color: #2e353d;
  position: fixed;
  top: 0px;
  width: 300px;
  height: 100%;
  color: #e1ffff;
}
.nav-side-menu .brand {
  background-color: #23282e;
  line-height: 50px;
  display: block;
  text-align: center;
  font-size: 14px;
}
.nav-side-menu .toggle-btn {
  display: none;
}
.nav-side-menu ul,
.nav-side-menu li {
  list-style: none;
  padding: 0px;
  margin: 0px;
  line-height: 35px;
  cursor: pointer;
  /*
    .collapsed{
       .arrow:before{
                 font-family: FontAwesome;
                 content: "\f053";
                 display: inline-block;
                 padding-left:10px;
                 padding-right: 10px;
                 vertical-align: middle;
                 float:right;
            }
     }
*/
}
.nav-side-menu ul :not(collapsed) .arrow:before,
.nav-side-menu li :not(collapsed) .arrow:before {
  font-family: FontAwesome;
  content: "\f0da";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
  float: right;
}
.nav-side-menu ul .active,
.nav-side-menu li .active {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
}
.nav-side-menu ul .sub-menu li.active,
.nav-side-menu li .sub-menu li.active {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li.active a,
.nav-side-menu li .sub-menu li.active a {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li,
.nav-side-menu li .sub-menu li {
  background-color: #181c20;
  border: none;
  line-height: 28px;
  border-bottom: 1px solid #23282e;
  margin-left: 0px;
}
.nav-side-menu ul .sub-menu li:hover,
.nav-side-menu li .sub-menu li:hover {
  background-color: #020203;
}
.nav-side-menu ul .sub-menu li:before,
.nav-side-menu li .sub-menu li:before {
  font-family: FontAwesome;
  content: "\f105";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
}
.nav-side-menu li {
  padding-left: 0px;
  border-left: 3px solid #2e353d;
  border-bottom: 1px solid #23282e;
}
.nav-side-menu li a {
  text-decoration: none;
  color: #e1ffff;
}
.nav-side-menu li a i {
  padding-left: 10px;
  width: 20px;
  padding-right: 20px;
}
.nav-side-menu li:hover {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  -ms-transition: all 1s ease;
  transition: all 1s ease;
}
@media (max-width: 767px) {
  .nav-side-menu {
    position: relative;
    width: 100%;
    margin-bottom: 10px;
  }
  .nav-side-menu .toggle-btn {
    display: block;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10 !important;
    padding: 3px;
    background-color: #ffffff;
    color: #000;
    width: 40px;
    text-align: center;
  }
  .brand {
    text-align: left !important;
    font-size: 22px;
    padding-left: 20px;
    line-height: 50px !important;
  }
}
@media (min-width: 767px) {
  .nav-side-menu .menu-list .menu-content {
    display: block;
  }
}
body {
  margin: 0px;
  padding: 0px;
}

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    transform: rotate(90deg);
}

.nav-side-menu ul li .arrow:before {
    transition: .5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="/dist/scripts.min.js"></script>

<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

<div class="nav-side-menu">
    <div class="brand">Brand Logo</div>

        <div class="menu-list">

            <ul id="menu-content" class="menu-content">
                <li>

                  <i class="fa fa-dashboard fa-lg"></i> Dashboard

                </li>

                <li  data-toggle="collapse" data-target="#products" class="collapsed active">
                  <i class="fa fa-gift fa-lg"></i> UI Elements <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="products">
                    <li class="active">CSS3 Animation</li>
                    <li>General</li>
                    <li>Buttons</li>
                    <li>Tabs & Accordions</li>
                    <li>Typography</li>
                    <li>FontAwesome</li>
                    <li>Slider</li>
                    <li>Panels</li>
                    <li>Widgets</li>
                    <li>Bootstrap Model</li>
                </ul>

                <li data-toggle="collapse" data-target="#service" class="collapsed">
                  <i class="fa fa-globe fa-lg"></i> Services <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="service">
                  <li>New Service 1</li>
                  <li>New Service 2</li>
                  <li>New Service 3</li>
                </ul>

                <li data-toggle="collapse" data-target="#new" class="collapsed">
                  <i class="fa fa-car fa-lg"></i> New <span class="arrow"></span>
                </li>
                <ul class="sub-menu collapse" id="new">
                  <li>New New 1</li>
                  <li>New New 2</li>
                  <li>New New 3</li>
                </ul>

                 <li>

                  <i class="fa fa-user fa-lg"></i> Profile

                  </li>

                 <li>

                  <i class="fa fa-users fa-lg"></i> Users

                </li>
            </ul>
     </div>
</div></code>```

Body:
Adjusting pseudo-element

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    content: "\f0d7";
}

Explanation:

Since the class .collapsed is added whenever an accordion item is not open, we can use this as a selector to target.

And since there is no class to target accordion items when they are opened we will do this is by using :not() - the negation pseudo-class selector; which, in this case, will select list-item elements which do not have the class .collapsed - implying that they are opened.

The :not() CSS pseudo-class represents elements that do not match a
  list of selectors. Since it prevents specific items from being
  selected, it is known as the negation pseudo-class.

Example

/* Selects any element that is NOT a paragraph */
:not(p) {
  color: blue;
}

Source: :not() - CSS | MDN

Updated JSFiddle

.nav-side-menu {
  overflow: auto;
  font-family: verdana;
  font-size: 12px;
  font-weight: 200;
  background-color: #2e353d;
  position: fixed;
  top: 0px;
  width: 300px;
  height: 100%;
  color: #e1ffff;
}
.nav-side-menu .brand {
  background-color: #23282e;
  line-height: 50px;
  display: block;
  text-align: center;
  font-size: 14px;
}
.nav-side-menu .toggle-btn {
  display: none;
}
.nav-side-menu ul,
.nav-side-menu li {
  list-style: none;
  padding: 0px;
  margin: 0px;
  line-height: 35px;
  cursor: pointer;
  /*
    .collapsed{
       .arrow:before{
                 font-family: FontAwesome;
                 content: "\f053";
                 display: inline-block;
                 padding-left:10px;
                 padding-right: 10px;
                 vertical-align: middle;
                 float:right;
            }
     }
*/
}
.nav-side-menu ul :not(collapsed) .arrow:before,
.nav-side-menu li :not(collapsed) .arrow:before {
  font-family: FontAwesome;
  content: "\f0da";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
  float: right;
}
.nav-side-menu ul .active,
.nav-side-menu li .active {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
}
.nav-side-menu ul .sub-menu li.active,
.nav-side-menu li .sub-menu li.active {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li.active a,
.nav-side-menu li .sub-menu li.active a {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li,
.nav-side-menu li .sub-menu li {
  background-color: #181c20;
  border: none;
  line-height: 28px;
  border-bottom: 1px solid #23282e;
  margin-left: 0px;
}
.nav-side-menu ul .sub-menu li:hover,
.nav-side-menu li .sub-menu li:hover {
  background-color: #020203;
}
.nav-side-menu ul .sub-menu li:before,
.nav-side-menu li .sub-menu li:before {
  font-family: FontAwesome;
  content: "\f105";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
}
.nav-side-menu li {
  padding-left: 0px;
  border-left: 3px solid #2e353d;
  border-bottom: 1px solid #23282e;
}
.nav-side-menu li a {
  text-decoration: none;
  color: #e1ffff;
}
.nav-side-menu li a i {
  padding-left: 10px;
  width: 20px;
  padding-right: 20px;
}
.nav-side-menu li:hover {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  -ms-transition: all 1s ease;
  transition: all 1s ease;
}
@media (max-width: 767px) {
  .nav-side-menu {
    position: relative;
    width: 100%;
    margin-bottom: 10px;
  }
  .nav-side-menu .toggle-btn {
    display: block;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10 !important;
    padding: 3px;
    background-color: #ffffff;
    color: #000;
    width: 40px;
    text-align: center;
  }
  .brand {
    text-align: left !important;
    font-size: 22px;
    padding-left: 20px;
    line-height: 50px !important;
  }
}
@media (min-width: 767px) {
  .nav-side-menu .menu-list .menu-content {
    display: block;
  }
}
body {
  margin: 0px;
  padding: 0px;
}

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    content: "\f0d7";
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="/dist/scripts.min.js"></script>

<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

<div class="nav-side-menu">
    <div class="brand">Brand Logo</div>

        <div class="menu-list">

            <ul id="menu-content" class="menu-content">
                <li>
                  <a href="#">
                  <i class="fa fa-dashboard fa-lg"></i> Dashboard
                  </a>
                </li>

                <li  data-toggle="collapse" data-target="#products" class="collapsed active">
                  <a href="#"><i class="fa fa-gift fa-lg"></i> UI Elements <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="products">
                    <li class="active"><a href="#">CSS3 Animation</a></li>
                    <li><a href="#">General</a></li>
                    <li><a href="#">Buttons</a></li>
                    <li><a href="#">Tabs & Accordions</a></li>
                    <li><a href="#">Typography</a></li>
                    <li><a href="#">FontAwesome</a></li>
                    <li><a href="#">Slider</a></li>
                    <li><a href="#">Panels</a></li>
                    <li><a href="#">Widgets</a></li>
                    <li><a href="#">Bootstrap Model</a></li>
                </ul>

                <li data-toggle="collapse" data-target="#service" class="collapsed">
                  <a href="#"><i class="fa fa-globe fa-lg"></i> Services <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="service">
                  <li>New Service 1</li>
                  <li>New Service 2</li>
                  <li>New Service 3</li>
                </ul>

                <li data-toggle="collapse" data-target="#new" class="collapsed">
                  <a href="#"><i class="fa fa-car fa-lg"></i> New <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="new">
                  <li>New New 1</li>
                  <li>New New 2</li>
                  <li>New New 3</li>
                </ul>

                 <li>
                  <a href="#">
                  <i class="fa fa-user fa-lg"></i> Profile
                  </a>
                  </li>

                 <li>
                  <a href="#">
                  <i class="fa fa-users fa-lg"></i> Users
                  </a>
                </li>
            </ul>
     </div>
</div>

Adjusting existing element

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    transform: rotate(90deg);
}

.nav-side-menu ul li .arrow:before {
    transition: .5s;
}

Updated JSFiddle

.nav-side-menu {
  overflow: auto;
  font-family: verdana;
  font-size: 12px;
  font-weight: 200;
  background-color: #2e353d;
  position: fixed;
  top: 0px;
  width: 300px;
  height: 100%;
  color: #e1ffff;
}
.nav-side-menu .brand {
  background-color: #23282e;
  line-height: 50px;
  display: block;
  text-align: center;
  font-size: 14px;
}
.nav-side-menu .toggle-btn {
  display: none;
}
.nav-side-menu ul,
.nav-side-menu li {
  list-style: none;
  padding: 0px;
  margin: 0px;
  line-height: 35px;
  cursor: pointer;
  /*
    .collapsed{
       .arrow:before{
                 font-family: FontAwesome;
                 content: "\f053";
                 display: inline-block;
                 padding-left:10px;
                 padding-right: 10px;
                 vertical-align: middle;
                 float:right;
            }
     }
*/
}
.nav-side-menu ul :not(collapsed) .arrow:before,
.nav-side-menu li :not(collapsed) .arrow:before {
  font-family: FontAwesome;
  content: "\f0da";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
  float: right;
}
.nav-side-menu ul .active,
.nav-side-menu li .active {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
}
.nav-side-menu ul .sub-menu li.active,
.nav-side-menu li .sub-menu li.active {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li.active a,
.nav-side-menu li .sub-menu li.active a {
  color: #d19b3d;
}
.nav-side-menu ul .sub-menu li,
.nav-side-menu li .sub-menu li {
  background-color: #181c20;
  border: none;
  line-height: 28px;
  border-bottom: 1px solid #23282e;
  margin-left: 0px;
}
.nav-side-menu ul .sub-menu li:hover,
.nav-side-menu li .sub-menu li:hover {
  background-color: #020203;
}
.nav-side-menu ul .sub-menu li:before,
.nav-side-menu li .sub-menu li:before {
  font-family: FontAwesome;
  content: "\f105";
  display: inline-block;
  padding-left: 10px;
  padding-right: 10px;
  vertical-align: middle;
}
.nav-side-menu li {
  padding-left: 0px;
  border-left: 3px solid #2e353d;
  border-bottom: 1px solid #23282e;
}
.nav-side-menu li a {
  text-decoration: none;
  color: #e1ffff;
}
.nav-side-menu li a i {
  padding-left: 10px;
  width: 20px;
  padding-right: 20px;
}
.nav-side-menu li:hover {
  border-left: 3px solid #d19b3d;
  background-color: #4f5b69;
  -webkit-transition: all 1s ease;
  -moz-transition: all 1s ease;
  -o-transition: all 1s ease;
  -ms-transition: all 1s ease;
  transition: all 1s ease;
}
@media (max-width: 767px) {
  .nav-side-menu {
    position: relative;
    width: 100%;
    margin-bottom: 10px;
  }
  .nav-side-menu .toggle-btn {
    display: block;
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 10 !important;
    padding: 3px;
    background-color: #ffffff;
    color: #000;
    width: 40px;
    text-align: center;
  }
  .brand {
    text-align: left !important;
    font-size: 22px;
    padding-left: 20px;
    line-height: 50px !important;
  }
}
@media (min-width: 767px) {
  .nav-side-menu .menu-list .menu-content {
    display: block;
  }
}
body {
  margin: 0px;
  padding: 0px;
}

/* Additional */

.nav-side-menu ul li:not(.collapsed) .arrow:before {
    transform: rotate(90deg);
}

.nav-side-menu ul li .arrow:before {
    transition: .5s;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="/dist/scripts.min.js"></script>

<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

<div class="nav-side-menu">
    <div class="brand">Brand Logo</div>

        <div class="menu-list">

            <ul id="menu-content" class="menu-content">
                <li>
                  <a href="#">
                  <i class="fa fa-dashboard fa-lg"></i> Dashboard
                  </a>
                </li>

                <li  data-toggle="collapse" data-target="#products" class="collapsed active">
                  <a href="#"><i class="fa fa-gift fa-lg"></i> UI Elements <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="products">
                    <li class="active"><a href="#">CSS3 Animation</a></li>
                    <li><a href="#">General</a></li>
                    <li><a href="#">Buttons</a></li>
                    <li><a href="#">Tabs & Accordions</a></li>
                    <li><a href="#">Typography</a></li>
                    <li><a href="#">FontAwesome</a></li>
                    <li><a href="#">Slider</a></li>
                    <li><a href="#">Panels</a></li>
                    <li><a href="#">Widgets</a></li>
                    <li><a href="#">Bootstrap Model</a></li>
                </ul>

                <li data-toggle="collapse" data-target="#service" class="collapsed">
                  <a href="#"><i class="fa fa-globe fa-lg"></i> Services <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="service">
                  <li>New Service 1</li>
                  <li>New Service 2</li>
                  <li>New Service 3</li>
                </ul>

                <li data-toggle="collapse" data-target="#new" class="collapsed">
                  <a href="#"><i class="fa fa-car fa-lg"></i> New <span class="arrow"></span></a>
                </li>
                <ul class="sub-menu collapse" id="new">
                  <li>New New 1</li>
                  <li>New New 2</li>
                  <li>New New 3</li>
                </ul>

                 <li>
                  <a href="#">
                  <i class="fa fa-user fa-lg"></i> Profile
                  </a>
                  </li>

                 <li>
                  <a href="#">
                  <i class="fa fa-users fa-lg"></i> Users
                  </a>
                </li>
            </ul>
     </div>
</div>


来源: stackexchange

问:
How many levels of inheritance
Are there any best practices regarding the maximum depth of the inheritance hierarchy for a framework and guidelines when to use multiple levels of inheritance or join them in a single class?

Some references to established practices/examples that worked well in the Java world would be nice in the answers as this is from the perspective of the community and frameworks surrounding Java.

答:
When it comes to best practices, performance(memory usage) also should be considered.

It will use more memory when you have deep hierarchy of classes (non-abstract). Like creating a new object of last child of 3 level inheritance will use LESS MEMORY than that of 9 level inheritance.
Based on nature of application this point could be considered, in addition to other posts.

ContentLicense: CC BY-SA 2.5

Title: How many levels of inheritance


问:
Not able to get the Value from Drop down Menu
Hello I'm having problem in getting the value from the drop down menu bar. When I choose a course and submit no Value is retrieved but a new empty record is entered in DB. I'm sharing my code I will appreciate any sort of help.

My View

```<code><form method="post" action="<?php echo(base_url()."University/std_assign_cousrse/");?>" >
<select>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>
<input type="Submit">
</form>
</code>```

My Controller

```<code>   public function std_assign_cousrse()
    {
        $data = array(
            'std_course' =>$this->input->post('course_id') ,);
    $this->db->Insert('tbl_student',$data);
    print_r($data);

    }
</code>```

答:
You have not mention the name of the  tag..
Proper tag should be</p>

```<code><select name='course_id'>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hello I'm having problem in getting the value from the drop down menu bar. When I choose a course and submit no Value is retrieved but a new empty record is entered in DB. I'm sharing my code I will appreciate any sort of help.

My View

<form method="post" action="<?php echo(base_url()."University/std_assign_cousrse/");?>" >
<select>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>
<input type="Submit">
</form>

My Controller

   public function std_assign_cousrse()
    {
        $data = array(
            'std_course' =>$this->input->post('course_id') ,);
    $this->db->Insert('tbl_student',$data);
    print_r($data);

    }

Body:
You have not mention the name of the  tag..
Proper tag should be

<select name='course_id'>
 <option value="">--- Select Course ---</option>
<?php

foreach($result as $row)
{
    echo "<option value=".$row['course_id'].">".$row['course_name']."</option>";
}
 ?>
</select>


问:
Programmatically saving image to Django ImageField
Ok, I've tried about near everything and I cannot get this to work.

I have a Django model with an ImageField on it

I have code that downloads an image via HTTP (tested and works)

The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)

All I need to do is associate the already existing image file path with the ImageField

I've written this code about 6 different ways.

The problem I'm running into is all of the code that I'm writing results in the following behavior:
(1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file.  What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.

In case that was unclear, I'll try to illustrate:

```<code>## Image generation code runs....
/Upload
     generated_image.jpg     4kb

## Attempt to set the ImageField path...
/Upload
     generated_image.jpg     4kb
     generated_image_.jpg    0kb

ImageField.Path = /Upload/generated_image_.jpg
</code>```

How can I do this without having Django try to re-store the file?  What I'd really like is something to this effect...

```<code>model.ImageField.path = generated_image_path
</code>```

...but of course that doesn't work.

And yes I've gone through the other questions here like this one as well as the django doc on File

UPDATE
After further testing, it only does this behavior when running under Apache on Windows Server.  While running under the 'runserver' on XP it does not execute this behavior.

I am stumped.

Here is the code which runs successfully on XP...

```<code>f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.save()
</code>```

答:
Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

```<code>import requests

def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo', 'rb')
    resume = open('/path/to/resume', 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason)
</code>```

Body:
Ok, I've tried about near everything and I cannot get this to work.

I have a Django model with an ImageField on it

I have code that downloads an image via HTTP (tested and works)

The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)

All I need to do is associate the already existing image file path with the ImageField

I've written this code about 6 different ways.

The problem I'm running into is all of the code that I'm writing results in the following behavior:
(1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file.  What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.

In case that was unclear, I'll try to illustrate:

## Image generation code runs....
/Upload
     generated_image.jpg     4kb

## Attempt to set the ImageField path...
/Upload
     generated_image.jpg     4kb
     generated_image_.jpg    0kb

ImageField.Path = /Upload/generated_image_.jpg

How can I do this without having Django try to re-store the file?  What I'd really like is something to this effect...

model.ImageField.path = generated_image_path

...but of course that doesn't work.

And yes I've gone through the other questions here like this one as well as the django doc on File

UPDATE
After further testing, it only does this behavior when running under Apache on Windows Server.  While running under the 'runserver' on XP it does not execute this behavior.

I am stumped.

Here is the code which runs successfully on XP...

f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.save()

Body:
Your can use Django REST framework and python Requests library to Programmatically saving image to Django ImageField

Here is a Example:

import requests

def upload_image():
    # PATH TO DJANGO REST API
    url = "http://127.0.0.1:8080/api/gallery/"

    # MODEL FIELDS DATA
    data = {'first_name': "Rajiv", 'last_name': "Sharma"}

    #  UPLOAD FILES THROUGH REST API
    photo = open('/path/to/photo', 'rb')
    resume = open('/path/to/resume', 'rb')
    files = {'photo': photo, 'resume': resume}

    request = requests.post(url, data=data, files=files)
    print(request.status_code, request.reason)

ContentLicense: CC BY-SA 4.0


问:
Parallel.Invoke vs Parallel.Foreach for running parallel process on large list
I have C# list which contains around 8000 items (file paths). I want to run a method on all of these items in parallel. For this i have below 2 options:

1) Manually divide list into small-small chunks (say of 500 size each) and create array of actions for these small lists and then call Parallel.Invoke like below:

```<code>    var partitionedLists = MainList.DivideIntoChunks(500);
    List<Action> actions = new List<Action>();
    foreach (var lst in partitionedLists)
    {
      actions.Add(() => CallMethod(lst));
    }
    Parallel.Invoke(actions.ToArray())
</code>```

2) Second option is to run Parallel.ForEach like below

```<code>Parallel.ForEach(MainList, item => { CallMethod(item) });
</code>```

What will the best option here?

How Parallel.Foreach divide the list
into small chunks?

Please suggest, thanks in advance.

答:
The first option is a form of task-parallelism, in which you divide your task into group of sub-tasks and execute them in parallel. As is obvious from the code you provided, you are responsible for choosing the level of granularity [chunks] while creating the sub-tasks. The selected granularity might be too big or too low, if one does not rely on appropriate heuristics, and the resulting performance gain might not be significant. Task-parallelism is used in scenarios where the operation to be performed takes similar time for all input values.

The second option is a form of data-parallelism, in which the input data is divided into smaller chunks based on the number of hardware threads/cores/processors available, and then each individual chunk is processed in isolation. In this case, the .NET library chooses the right level of granularity for you and ensures better CPU utilization. Conventionally, data-parallelism is used in scenarios when the operation to be performed can vary in terms of time taken, depending on the input value.

In conclusion, if your operation is more or less uniform over the range of input values and you know the right granularity [chunk size], go ahead with the first option. If however that's not the case or if you are unsure about the above questions, go with the second option which usually pans out better in most scenarios.

NOTE: If this is a very performance critical component of your application, I will advise bench-marking the performances in production like environment with both approaches to get more data, in addition to the above recommendations.

Body:
I have C# list which contains around 8000 items (file paths). I want to run a method on all of these items in parallel. For this i have below 2 options:

1) Manually divide list into small-small chunks (say of 500 size each) and create array of actions for these small lists and then call Parallel.Invoke like below:

    var partitionedLists = MainList.DivideIntoChunks(500);
    List<Action> actions = new List<Action>();
    foreach (var lst in partitionedLists)
    {
      actions.Add(() => CallMethod(lst));
    }
    Parallel.Invoke(actions.ToArray())

2) Second option is to run Parallel.ForEach like below

Parallel.ForEach(MainList, item => { CallMethod(item) });

What will the best option here?

How Parallel.Foreach divide the list
into small chunks?

Please suggest, thanks in advance.


问:
Integrating office 365 api
I am new to bot development. I am using bot framework and Visual C# to develop my bot. When I integrate my application with the office365 API, I encountered the problem with my domain. The error is my account doesn't have the access to the particular domain.Even though I signed with the global administrator account of that domain I got the same problem.

答: I resolved my problem by deleting my all the accounts.(In visual studio go to file-> Account settings).Then I signed up for the account.Because there were 2 accounts in the VisualStudio's account.So I delete the previous accounts and signup for the account.</p>

Title: Integrating office 365 api


问:
Why can't I change sql_mode permanently?
I an currently using mysql server 5.6 in windows 10. while using mysql, an error keeps appearing that goes as something like this "the following column does not have a default value" i read on the internet that i can solve this problem if i change the sql_mode. It is currently set to

```<code> sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
</code>```

I took this from "my-default.ini" file in "mysql server 5.6" folder. I read several other answers that say that if you want to permanently change your sql_mode, you should do it through the "my-default.ini" file. So what i did was, i run my notepad as administrator, then i browsed to open "my-default.ini" file that is found in:

```<code>  c:\programs files (x86)\mysql\mysql server 5.6\my-default.ini
</code>```

when i opened the file, i modified the last line:

```<code>  sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
</code>```

to

```<code>  sql_mode=
</code>```

then i saved the file, closed it. then by using task manager i restarted  my sql sever:

```<code>  task manager >> services >> mysql56
</code>```

This is the whole process that should permanently modify my sql_mode. when i look in my "my-default.ini" file, the last line is still modified. but if i log into mysql through the command line and view my sql_mode with the following code:

```<code>  select @@sql_mode;
</code>```

I get that my sql_mode is

```<code>  STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
</code>```

I want all this to be removed (permanently) in order for my error to disappear. IF i try to modify the sql_mode from the command line by using:

```<code>  set @@global.sql_mode="";
</code>```

It worked, but when i restarted MySQL, everything was back as it was before.

Can someone please tell me what i am doing wrong? and if there is another way to solve this problem.

答:
sql_mode need to add to file /etc/init.d/mysql as a argument to start like:

```<code>$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" --sql-mode="" $other_args >/dev/null 2>&1 &
</code>```

Restart MySQL database server to apply new config.

Body:
I an currently using mysql server 5.6 in windows 10. while using mysql, an error keeps appearing that goes as something like this "the following column does not have a default value" i read on the internet that i can solve this problem if i change the sql_mode. It is currently set to

 sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

I took this from "my-default.ini" file in "mysql server 5.6" folder. I read several other answers that say that if you want to permanently change your sql_mode, you should do it through the "my-default.ini" file. So what i did was, i run my notepad as administrator, then i browsed to open "my-default.ini" file that is found in:

  c:\programs files (x86)\mysql\mysql server 5.6\my-default.ini

when i opened the file, i modified the last line:

  sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

to

  sql_mode=

then i saved the file, closed it. then by using task manager i restarted  my sql sever:

  task manager >> services >> mysql56

This is the whole process that should permanently modify my sql_mode. when i look in my "my-default.ini" file, the last line is still modified. but if i log into mysql through the command line and view my sql_mode with the following code:

  select @@sql_mode;

I get that my sql_mode is

  STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

I want all this to be removed (permanently) in order for my error to disappear. IF i try to modify the sql_mode from the command line by using:

  set @@global.sql_mode="";

It worked, but when i restarted MySQL, everything was back as it was before.

Can someone please tell me what i am doing wrong? and if there is another way to solve this problem.

Body:
sql_mode need to add to file /etc/init.d/mysql as a argument to start like:

$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" --sql-mode="" $other_args >/dev/null 2>&1 &

Restart MySQL database server to apply new config.


问:
Xamarin : Date in string
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label inside listview-viewcell, to show time in UI. The date is received as a number like 1510822596449(Java Timestamp). I want to show the date in strings like "n days ago".How can I achieve this?

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Label Text="{Binding createdTime}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

Anybody please suggest a solution with working code.
Thanks in advance.

答:
As suggested in the comments you could do this with a ValueConverter.

Write a converter similar to this, in your shared code.

```<code>    public class TicksToDateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!Int64.TryParse(value, out long ticks))
                return DatTime.Now;

            // TODO you can do a ToString and format it you want here but also in XAML
            return new DateTime(ticks);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Not needed
            throw new NotImplementedException();
        }
    }
</code>```

Now in your XAML, declare te value convter like this under the root of your page, I'm assuming it's a ContentPage.

```<code><ContentPage.Resources>
    <ResourceDictionary>
        <local:TicksToDateTimeConverter x:Key="TicksConverter" />
    </ResourceDictionary>
</ContentPage.Resources>
</code>```

And don't forget to declare the local namespace in your page root like: xmlns:local="clr-namespace:YourApp.Namespace", which should be the full namespace, without the class name to your converter class.

To finally use the converter in your layout, do this:

```<code><StackLayout>
    <ListView>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                <StackLayout>
                    <Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
</StackLayout>
</code>```

Depending on whether or not you return a string from the converter or a DateTime, in the latter case you can also format it here in XAML, like so:

```<code><Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}, StringFormat='{0:dd-MM-yyyy}'}"/>
</code>```

Or you could choose to do it differently altogether and convert the value inside the model that you bind to the ViewCell.

Title: Xamarin : Date in string

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have a Label inside listview-viewcell, to show time in UI. The date is received as a number like 1510822596449(Java Timestamp). I want to show the date in strings like "n days ago".How can I achieve this?

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance.

Body:
As suggested in the comments you could do this with a ValueConverter.

Write a converter similar to this, in your shared code.

    public class TicksToDateTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!Int64.TryParse(value, out long ticks))
                return DatTime.Now;

            // TODO you can do a ToString and format it you want here but also in XAML
            return new DateTime(ticks);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // Not needed
            throw new NotImplementedException();
        }
    }

Now in your XAML, declare te value convter like this under the root of your page, I'm assuming it's a ContentPage.

<ContentPage.Resources>
    <ResourceDictionary>
        <local:TicksToDateTimeConverter x:Key="TicksConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

And don't forget to declare the local namespace in your page root like: xmlns:local="clr-namespace:YourApp.Namespace", which should be the full namespace, without the class name to your converter class.

To finally use the converter in your layout, do this:

<StackLayout>
    <ListView>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                <StackLayout>
                    <Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}}"/>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
</StackLayout>

Depending on whether or not you return a string from the converter or a DateTime, in the latter case you can also format it here in XAML, like so:

<Label Text="{Binding createdTime, Converter={StaticResource TicksConverter}, StringFormat='{0:dd-MM-yyyy}'}"/>

Or you could choose to do it differently altogether and convert the value inside the model that you bind to the ViewCell.


答:
Use filter and map for this:

```<code>let statusOne = data.filter({ $0.status == 1 }).map({ $0.latitude })
let statusTwo = data.filter({ $0.status == 2 }).map({ $0.latitude })
</code>```

Title: How to find value from dictionary

Body:
I have following simple dictionary and I want latitude array when status 1 it is store one array and status 2 it store second array
Please help me out

 data =     (
            {
        created = "2017-11-13 09:04:18";
        "end_date" = "2017-11-13 11:49:08";
        id = 878;
        latitude = "23.032190322875977000";
        longitude = "72.565238952636720000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 11:49:08";
        "end_date" = "2017-11-13 13:13:15";
        id = 888;
        latitude = "23.032133102416992000";
        longitude = "72.565208435058600000";
        status = 1;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:13:15";
        "end_date" = "2017-11-13 13:26:26";
        id = 891;
        latitude = "23.032199859619140000";
        longitude = "72.565269470214840000";
        status = 2;
        "user_id" = 21;
    },
            {
        created = "2017-11-13 13:26:26";
        "end_date" = "2017-11-13 16:54:20";
        id = 892;
        latitude = "23.032056808471680000";
        longitude = "72.565223693847660000";
        status = 2;
        "user_id" = 21;
    }

)

Body:
Use filter and map for this:

let statusOne = data.filter({ $0.status == 1 }).map({ $0.latitude })
let statusTwo = data.filter({ $0.status == 2 }).map({ $0.latitude })


问:
How Do I Set The Value Of A String In Android?
I have a string and a button as follows:

```<code>String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}
</code>```

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this

答:
For Restarting Shared Preference is the best mechanism but for reinstall allowbackup works on API level 23 and above,
you can consider to update the value on server once you update in your Shared Preferences for the first time and during reinstall can do a API call check for the same for the particular user.</p>

Body:
I have a string and a button as follows:

String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this


问:
show sequence of gif animation files one after another in a single imageview as a video
As the title elaborates I need to implement a way of showing gif images as a sequence in a single imageview container.

the things i have tried so far:

used glide library and found no luck with it since they are using some weird internal threading mechanism to animate gifs so making a sequence is not possible with it.

then i used android-gif-drawable library and found some piece of code but still couldn't manage it to work.
below i have posted the class used to create this ChainedGifDrawable custom drawable.
any help would be highly appreciated in this.

```<code>   public static class ChainedGifDrawable extends Drawable implements AnimationListener {
    private final pl.droidsonroids.gif.GifDrawable[] mDrawables;
    private int mCurrentIndex;

    public ChainedGifDrawable(List<pl.droidsonroids.gif.GifDrawable> drawables) {
        mDrawables = drawables.toArray(new pl.droidsonroids.gif.GifDrawable[0]);

        for (pl.droidsonroids.gif.GifDrawable drawable : drawables) {
            drawable.addAnimationListener(this);

        }
    }

    @Override
    public void onAnimationCompleted(int loopNumber) {
        Log.e("Called ","Checked");
        mCurrentIndex++;
        mCurrentIndex %= mDrawables.length;
        mDrawables[mCurrentIndex].setCallback(getCallback());
        mDrawables[mCurrentIndex].invalidateSelf();
    }

    @Override
    public void invalidateSelf() {
        mDrawables[mCurrentIndex].invalidateSelf();
        Log.e("Called invalidateSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public void scheduleSelf(@NonNull Runnable what, long when) {
        mDrawables[mCurrentIndex].scheduleSelf(what, when);
        Log.e("Called scheduleSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public void unscheduleSelf(@NonNull Runnable what) {
        mDrawables[mCurrentIndex].unscheduleSelf(what);
        Log.e("Called unscheduleSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public int getIntrinsicWidth() {
        Log.e("Called getIntrinsicWidth "+mCurrentIndex ,"Checked");
        return mDrawables[mCurrentIndex].getIntrinsicWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        Log.e("Called getIntrinsicHeight "+mCurrentIndex ,"Checked");
        return mDrawables[mCurrentIndex].getIntrinsicHeight();
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setBounds(bounds);
        }
        Log.e("Called onboundsChange "+mCurrentIndex ,"Checked");
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        mDrawables[mCurrentIndex].draw(canvas);
        Log.e("Called draw "+mCurrentIndex ,"Checked");
    }

    @Override
    public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setAlpha(alpha);
        }
        Log.e("Called setAlpha "+mCurrentIndex ,"Checked");
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setColorFilter(colorFilter);
        }
        Log.e("Called setcolorfilter "+mCurrentIndex ,"Checked");
    }

    @Override
    public int getOpacity() {
        Log.e("Called getOpacity  "+mCurrentIndex ,"Checked");
        return PixelFormat.TRANSLUCENT;
    }

    public void setAnimationEnabled() {

        mDrawables[0].setCallback(getCallback());
    }
}
</code>```

答:
after wasting more than 2 days finally i could figure out a way to do this.It's not an efficient one but it works at least for now.I will post the code for anyone who might come across with a similar problem.
Note: I have used android-gif-drawable library to make this work.

First I have Created an Array list with GifDrawable Objects and assigned eachone an AnimationListner.

```<code>   drawableList = new ArrayList<>();
            count = 0;
            for (j = 0; j < wordsActivity.displayItemsList.size(); j++) {
                Log.e("J value: ", String.valueOf(j));
                pl.droidsonroids.gif.GifDrawable firstDrawable = pl.droidsonroids.gif.GifDrawable.createFromResource(getResources(), wordsActivity.displayItemsList.get(j).getGifId());
                firstDrawable.setLoopCount(0);
                Transform transform = new CornerRadiusTransform(300);
                firstDrawable.setTransform(transform);
                firstDrawable.addAnimationListener(WordsGridViewPagerFragment.this);
                if (j == 0) {
                    wordsActivity.wordsImage.setImageDrawable(firstDrawable);
                }
                drawableList.add(firstDrawable);
            }
</code>```

then in the implemented onAnimationCompleted method I have created the logic to move in to the next gif animation and keep repeat the task.

```<code>   @Override
public void onAnimationCompleted(int loopNumber) {
    Log.e("animation " + count, "completed");
    count++;
    if (count < drawableList.size()) {

        wordsActivity.wordsImage.setImageDrawable(drawableList.get(count));
        Log.e("animation " + count, "started");

    }else{
        count=0;
        wordsActivity.wordsImage.setImageDrawable(drawableList.get(0));

    }
}
</code>```

Body:
As the title elaborates I need to implement a way of showing gif images as a sequence in a single imageview container.

the things i have tried so far:

used glide library and found no luck with it since they are using some weird internal threading mechanism to animate gifs so making a sequence is not possible with it.

then i used android-gif-drawable library and found some piece of code but still couldn't manage it to work.
below i have posted the class used to create this ChainedGifDrawable custom drawable.
any help would be highly appreciated in this.

   public static class ChainedGifDrawable extends Drawable implements AnimationListener {
    private final pl.droidsonroids.gif.GifDrawable[] mDrawables;
    private int mCurrentIndex;

    public ChainedGifDrawable(List<pl.droidsonroids.gif.GifDrawable> drawables) {
        mDrawables = drawables.toArray(new pl.droidsonroids.gif.GifDrawable[0]);

        for (pl.droidsonroids.gif.GifDrawable drawable : drawables) {
            drawable.addAnimationListener(this);

        }
    }

    @Override
    public void onAnimationCompleted(int loopNumber) {
        Log.e("Called ","Checked");
        mCurrentIndex++;
        mCurrentIndex %= mDrawables.length;
        mDrawables[mCurrentIndex].setCallback(getCallback());
        mDrawables[mCurrentIndex].invalidateSelf();
    }

    @Override
    public void invalidateSelf() {
        mDrawables[mCurrentIndex].invalidateSelf();
        Log.e("Called invalidateSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public void scheduleSelf(@NonNull Runnable what, long when) {
        mDrawables[mCurrentIndex].scheduleSelf(what, when);
        Log.e("Called scheduleSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public void unscheduleSelf(@NonNull Runnable what) {
        mDrawables[mCurrentIndex].unscheduleSelf(what);
        Log.e("Called unscheduleSelf "+mCurrentIndex ,"Checked");
    }

    @Override
    public int getIntrinsicWidth() {
        Log.e("Called getIntrinsicWidth "+mCurrentIndex ,"Checked");
        return mDrawables[mCurrentIndex].getIntrinsicWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        Log.e("Called getIntrinsicHeight "+mCurrentIndex ,"Checked");
        return mDrawables[mCurrentIndex].getIntrinsicHeight();
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setBounds(bounds);
        }
        Log.e("Called onboundsChange "+mCurrentIndex ,"Checked");
    }

    @Override
    public void draw(@NonNull Canvas canvas) {
        mDrawables[mCurrentIndex].draw(canvas);
        Log.e("Called draw "+mCurrentIndex ,"Checked");
    }

    @Override
    public void setAlpha(@IntRange(from = 0, to = 255) int alpha) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setAlpha(alpha);
        }
        Log.e("Called setAlpha "+mCurrentIndex ,"Checked");
    }

    @Override
    public void setColorFilter(@Nullable ColorFilter colorFilter) {
        for (pl.droidsonroids.gif.GifDrawable drawable : mDrawables) {
            drawable.setColorFilter(colorFilter);
        }
        Log.e("Called setcolorfilter "+mCurrentIndex ,"Checked");
    }

    @Override
    public int getOpacity() {
        Log.e("Called getOpacity  "+mCurrentIndex ,"Checked");
        return PixelFormat.TRANSLUCENT;
    }

    public void setAnimationEnabled() {

        mDrawables[0].setCallback(getCallback());
    }
}

Body:
after wasting more than 2 days finally i could figure out a way to do this.It's not an efficient one but it works at least for now.I will post the code for anyone who might come across with a similar problem.
Note: I have used android-gif-drawable library to make this work.

First I have Created an Array list with GifDrawable Objects and assigned eachone an AnimationListner.

   drawableList = new ArrayList<>();
            count = 0;
            for (j = 0; j < wordsActivity.displayItemsList.size(); j++) {
                Log.e("J value: ", String.valueOf(j));
                pl.droidsonroids.gif.GifDrawable firstDrawable = pl.droidsonroids.gif.GifDrawable.createFromResource(getResources(), wordsActivity.displayItemsList.get(j).getGifId());
                firstDrawable.setLoopCount(0);
                Transform transform = new CornerRadiusTransform(300);
                firstDrawable.setTransform(transform);
                firstDrawable.addAnimationListener(WordsGridViewPagerFragment.this);
                if (j == 0) {
                    wordsActivity.wordsImage.setImageDrawable(firstDrawable);
                }
                drawableList.add(firstDrawable);
            }

then in the implemented onAnimationCompleted method I have created the logic to move in to the next gif animation and keep repeat the task.

   @Override
public void onAnimationCompleted(int loopNumber) {
    Log.e("animation " + count, "completed");
    count++;
    if (count < drawableList.size()) {

        wordsActivity.wordsImage.setImageDrawable(drawableList.get(count));
        Log.e("animation " + count, "started");

    }else{
        count=0;
        wordsActivity.wordsImage.setImageDrawable(drawableList.get(0));

    }
}


问:
How to stop labels from moving up when navigation bar disappears?
The layout in Xcode:

Output, in an iPhone 5s simulator once the navigation bar is removed:

Initially, at the start of this view, the navigation bar is required, but when I hit the record button, the navigation bar is to disappear, which it does. However, in doing so, it moves the timer labels up with it. How do I stop autolayout from moving the labels up?

Thanks.

答: This happens with respect to how you put your auto layout constraints. Put label constraints with respect to Top layout guide. If labels are inside another view make sure that view has top constraint with respect to parentview controller toplayout guide. Check with respect to what you have given. If with respect to Navigation Layout is there. You will have this problem.


问:
JW Player won't play the video in Drupal
I'm trying to fix some issues on a website somebody else did in Drupal. One of them is that the videos that are played with the JW Player plugin are not being played correctly. Only the sound is heard, and there is a visualization where the video should be. Only when the video is paused you can see the still shot of where the playhead is stopped in the video. You can see what I am talking about in this page:
http://www.xxtrusion.tv/xx-trusiontv

Is there an obvious problem I am not seeing? I am pretty new with Drupal, and the project is very urgent. I would be grateful for any help I can get.

答: the Revolt plugin was on :/ Tech support helped me out. Kudos to them.</p>


问:
Group by in Datagrid View
i have a scenario where i have to group the PinCode by city name like one city can have many pincode.

I have to do this in winform in datagrid. How can i do this so in datagrid i can see the + and - on before city.

I thing it can be done by nested grid. please, help.

     Column A   |   Column B   |   Column C

Country

Zip Code  |       10,00     |       15,00

Zip Code  |       10,00     |       15,00

Country

Zip Code  |       10,00     |       15,00

Zip Code  |       10,00     |       15,00

Thanks.
Shivam

答: Use TreeView for grouping data.</p>

Title: Group by in Datagrid View

Body: Use TreeView for grouping data.


问:
How to check a variable is printable using print / echo?
I've a function that receives a $mixed value.
I need to check whether it can be printed, then print that value other wise print its type.

Sample values

$Object

$string

$number

And my function

```<code>function dmp( $value ) {
   echo $value ;
}
</code>```

In the above conditions when i try to print $Object, it cause a catchable error.
Is there a way or a builtin function to check whether a value can be printed ? Or do I've to write one manually ?

答:
You can get the type of variable using gettype like :

```<code><?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>
</code>```

The above example will output something similar to:

```<code>integer
double
NULL
object
string
</code>```

For more details : http://php.net/manual/en/function.gettype.php

Body:
I've a function that receives a $mixed value.
I need to check whether it can be printed, then print that value other wise print its type.

Sample values

$Object

$string

$number

And my function

function dmp( $value ) {
   echo $value ;
}

In the above conditions when i try to print $Object, it cause a catchable error.
Is there a way or a builtin function to check whether a value can be printed ? Or do I've to write one manually ?

Body:
You can get the type of variable using gettype like :

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

?>

The above example will output something similar to:

integer
double
NULL
object
string

For more details : http://php.net/manual/en/function.gettype.php


问:
Hide/handle servlet exception stack trace output
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

```<code>public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}
</code>```

The log says:

```<code>    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
</code>```

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

```<code><filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</code>```

答: Did you try writing a Session filter yourself? Find a nice example here.</p>

Body:
From this post I have thought of another question I cannot seem to find the answer to on the interweb.

I have a servlet filter which detects session timeouts and redirects to an error page.  Due to my fledgling java I've used try catch blocks to catch exceptions and handle them gracefully, but in a session timeout situation, the context is invalid so I don't think I've got any code I can do that with which will stop the 'viewId could not be restored' stace trace appearing in my log even though I have a filter handling it.

How can I stop the exception trace from appearing in my log?  It will be monitored autoamtically in live and it will be a false positive call out to the support team for this sort of error.

Any help appreciated.

EDIT

To be more clear, my code clip is currently

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
    try {
        chain.doFilter(request, response);
    } catch (ServletException e) {
        logger.error("Caught Servlet Exception");
        Throwable rootCause = e.getRootCause();
        logger.error("Root cause is " + rootCause.toString());

        if (rootCause instanceof RuntimeException) { // This is true for any FacesException.
            logger.error("Rethrowing exception as RuntimeException" + rootCause.toString());
            throw (RuntimeException) rootCause; // Throw wrapped RuntimeException instead of ServletException.
        } else {
            throw e;
        }
    }
}

The log says:

    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Exception in the filter chain
    javax.servlet.ServletException: viewId:/index.jsf - View /index.jsf could not be restored.
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
<snip>
        at java.lang.Thread.run(Unknown Source)
    Caused by: javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
<snip>
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:265)
        ... 21 more
    19-Jan-2011 10:40:57 org.apache.catalina.core.StandardWrapperValve invoke
    SEVERE: Servlet.service() for servlet Faces Servlet threw exception
    javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
        at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:185)
<snip>
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Unknown Source)
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Caught Servlet Exception
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Root cause is javax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.
    |STDOUT| 2011-01-19 10:40:57,803 | ERROR | [http-8080-5]: Rethrowing exception as RuntimeExceptionjavax.faces.application.ViewExpiredException: viewId:/index.jsf - View /index.jsf could not be restored.

As you can see from the code, I've caught the servlet exception in the filter, but the stack is still appearing in the log.

NEXT EDIT
The complete list of filters in my web.xml is as follows:

<filter>
    <filter-name>Error</filter-name>
    <filter-class>prismClient.ErrorFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Error</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
    <display-name>RichFaces Filter</display-name>
    <filter-name>richfaces</filter-name>
    <filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
    <filter-name>richfaces</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>


问:
Laravel: get a model through another table
I have gotten a model called User. in this model i have a function called UserActivity where i return this:

```<code>return $this->hasMany('App\UserActivity', 'userid');
</code>```

After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:

```<code>public function Activity() {
      return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}
</code>```

And in my view i want to use this like this:

```<code>$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());
</code>```

But then i get an error saying this:

```<code>Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)
</code>```

I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:

Users: pk: id

user_activities: pk: userid, activityid

activities: pk: id

Thank you in advance!

答:
The Activity function should be in the User model. So then you can call it this way:

```<code>$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->Activity); //gives you a collection of activities
</code>```

However, you need belongsToMany function rather than hasManyThrough since the relationship between users and activities is many-to-many.

This mean you cut down going through the Intermediate model. You can check the doc on belongsToMany to understand what to do better.

A side note: Why are your functions name starting with capital letter?

Also using hasMany relations should affect the function name as well, so that 'activity' becomes 'activities' (just to keep the functionality and interpretation in sync).

Update:

```<code>//User model

public function activities() {
  return $this->belongsToMany('App\Activity', 'user_activity', 'userid', 'activityid');
}
</code>```

This uses the 'user_activity' table, to find the relationship between users and activities, so that you may now access by User::first()->activities for example.

Body:
I have gotten a model called User. in this model i have a function called UserActivity where i return this:

return $this->hasMany('App\UserActivity', 'userid');

After this i have a function that gets the activity name from the Activity table, but i do not know how to do this, i have currently gotten this:

public function Activity() {
      return $this->hasManyThrough('App\UserActivity', 'App\Activity', 'userid', 'activityid');
}

And in my view i want to use this like this:

$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->UserActivity()->Activity());

But then i get an error saying this:

Call to undefined method Illuminate\Database\Query\Builder::Activity() (View: /var/www/vhosts/cpned.nl/intranet.cpned.nl/laravel/resources/views/dashboard.blade.php)

I can do it using inner joins but i am really wondering if i can do this with Laravel models. I do not know how currently, and because i don't know what the name is for the function in laravel i can't find it either, so I am sorry if this will be a duplicate.
My tables have the following keys and foreign keys:

Users: pk: id

user_activities: pk: userid, activityid

activities: pk: id

Thank you in advance!

Body:
The Activity function should be in the User model. So then you can call it this way:

$activiteiten = \App\User::find(Auth::user()->id);
dd($activiteiten->Activity); //gives you a collection of activities

However, you need belongsToMany function rather than hasManyThrough since the relationship between users and activities is many-to-many.

This mean you cut down going through the Intermediate model. You can check the doc on belongsToMany to understand what to do better.

A side note: Why are your functions name starting with capital letter?

Also using hasMany relations should affect the function name as well, so that 'activity' becomes 'activities' (just to keep the functionality and interpretation in sync).

Update:

//User model

public function activities() {
  return $this->belongsToMany('App\Activity', 'user_activity', 'userid', 'activityid');
}

This uses the 'user_activity' table, to find the relationship between users and activities, so that you may now access by User::first()->activities for example.


问:
Can I pass an Account via an Intent to another activity?
Is it possible to pass an Android Account object from one activity to another via an Intent?  If so, how?  Is it good programming practice?</p>

答:
You can send in the account to other activities through Intent

First get the account if the user is already signed in

```<code>GoogleSignInAccount account;
account = GoogleSignIn.getLastSignedInAccount(this);
</code>```

Then pass the account as an Extra in the Intent

```<code>Intent intent = new Intent(this,ReceiverActivity.class);
            intent.putExtra("ACCOUNT",account);
            startActivity(intent);
</code>```

And in the ReceiverActivity

```<code>GoogleSignInAccount account =getIntent().getParcelableExtra("ACCOUNT");
</code>```

Then you can get other details from the user's profile like

```<code>String personName = account.getDisplayName();
            String personGivenName = account.getGivenName();
            String personFamilyName = account.getFamilyName();
            String personEmail = account.getEmail();
            String personId = account.getId();
            Uri personPhoto = account.getPhotoUrl();
</code>```

Body:
You can send in the account to other activities through Intent

First get the account if the user is already signed in

GoogleSignInAccount account;
account = GoogleSignIn.getLastSignedInAccount(this);

Then pass the account as an Extra in the Intent

Intent intent = new Intent(this,ReceiverActivity.class);
            intent.putExtra("ACCOUNT",account);
            startActivity(intent);

And in the ReceiverActivity

GoogleSignInAccount account =getIntent().getParcelableExtra("ACCOUNT");

Then you can get other details from the user's profile like

String personName = account.getDisplayName();
            String personGivenName = account.getGivenName();
            String personFamilyName = account.getFamilyName();
            String personEmail = account.getEmail();
            String personId = account.getId();
            Uri personPhoto = account.getPhotoUrl();


答:
Try to force the navigation bar to not be hidden. Inside the viewDidLoad()

```<code>self.navigationController?.setNavigationBarHidden(false, animated: false)
</code>```

Title: How to stop labels from moving up when navigation bar disappears?

Body:
The layout in Xcode:

Output, in an iPhone 5s simulator once the navigation bar is removed:

Initially, at the start of this view, the navigation bar is required, but when I hit the record button, the navigation bar is to disappear, which it does. However, in doing so, it moves the timer labels up with it. How do I stop autolayout from moving the labels up?

Thanks.

Body:
Try to force the navigation bar to not be hidden. Inside the viewDidLoad()

self.navigationController?.setNavigationBarHidden(false, animated: false)


问:
Problems with async code in Jest tests
I am having problem with getting the code into the beforeAll function finish and wait for the promise that resolves the storyLinks. The console log at the end of the snippet returns undefined but I need it to return the hrefs of the stories in my storybook. I cannot wrap this into an async function because of the testing pipeline being clogged on fail.

```<code>const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });
const timeout = 5000;
describe('visual tests', () => {

  let page, browser, storyLinks;
  const selector = `a[href*="selectedStory="]`;
  beforeAll(async() => {
    browser = await puppeteer.connect({browserWSEndpoint});
    page = await browser.newPage();
    await page.goto('http://localhost:8080');
    await page.evaluate(() => {
      const components = Array.from(document.querySelectorAll('div[data-name]'));
      for(let i = 1; i < components.length; i++) {
        components[i].addEventListener('click',() => {});
        components[i].click();
      }
    });

    storyLinks = await page.evaluate((selector) => {
      const stories = Array.from(document.querySelectorAll(selector));
      const links = stories.map(story => {
        let href = story.href;
        let name = story.text.replace(/[^A-Z0-9]/ig, '-').replace(/-{2,}/,'-');
        let component = href.match(/selectedKind=(.*?)\&/).pop();
        return {href: href, name: component + '-' + name};
      });
      return links;
    }, selector);
  }, timeout);

  afterAll(async () => {
        await page.close();
        await browser.disconnect();
  })

  console.log(storyLinks);

}, timeout);
</code>```

答:
There's a few things I notice might be causing your issues. You need to add async to your describe block. Also, "describe" groups together multiple tests so you're missing an it or test block. Jest docs also note adding the expect.assertions(NUM_OF_ASSERTIONS); I'd do something like:</p>

```<code>const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });
const timeout = 5000;

async function myStoryLinkTest(page) {
  const selector = `a[href*="selectedStory="]`;

  await page.goto('http://localhost:8080');

  await page.evaluate(() => {
    Array.from(document.querySelectorAll('div[data-name]'), item => {
      item.addEventListener('click', () => {});
      item.click();
    });
  });

  const storyLinks = await page.evaluate(selector => {
    return Array.from(document.querySelectorAll(selector), story => {
      let href = story.href;
      let name = story.text.replace(/[^A-Z0-9]/gi, '-').replace(/-{2,}/, '-');
      let component = href.match(/selectedKind=(.*?)\&/).pop();
      return { href: href, name: component + '-' + name };
    });
  });

  return storyLinks;
}

describe('visual tests', async () => {
    let page, browser;

    beforeAll(async () => {
      browser = await puppeteer.connect({ browserWSEndpoint });
      page = await browser.newPage();
    });

    afterAll(async () => {
      await page.close();
      await browser.disconnect();
    });

    it('should do something with storyLinks', async () => {
        expect.assertions(1);
        const storyLinkResult = await myStoryLinkTest(page);
        expect(storyLinkResult).toEqual('Some value you expect');
     }, timeout);
  });
</code>```

Title: Problems with async code in Jest tests

Body:
I am having problem with getting the code into the beforeAll function finish and wait for the promise that resolves the storyLinks. The console log at the end of the snippet returns undefined but I need it to return the hrefs of the stories in my storybook. I cannot wrap this into an async function because of the testing pipeline being clogged on fail.

const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });
const timeout = 5000;
describe('visual tests', () => {

  let page, browser, storyLinks;
  const selector = `a[href*="selectedStory="]`;
  beforeAll(async() => {
    browser = await puppeteer.connect({browserWSEndpoint});
    page = await browser.newPage();
    await page.goto('http://localhost:8080');
    await page.evaluate(() => {
      const components = Array.from(document.querySelectorAll('div[data-name]'));
      for(let i = 1; i < components.length; i++) {
        components[i].addEventListener('click',() => {});
        components[i].click();
      }
    });

    storyLinks = await page.evaluate((selector) => {
      const stories = Array.from(document.querySelectorAll(selector));
      const links = stories.map(story => {
        let href = story.href;
        let name = story.text.replace(/[^A-Z0-9]/ig, '-').replace(/-{2,}/,'-');
        let component = href.match(/selectedKind=(.*?)\&/).pop();
        return {href: href, name: component + '-' + name};
      });
      return links;
    }, selector);
  }, timeout);

  afterAll(async () => {
        await page.close();
        await browser.disconnect();
  })

  console.log(storyLinks);

}, timeout);

Body:
There's a few things I notice might be causing your issues. You need to add async to your describe block. Also, "describe" groups together multiple tests so you're missing an it or test block. Jest docs also note adding the expect.assertions(NUM_OF_ASSERTIONS); I'd do something like:

const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });
const timeout = 5000;

async function myStoryLinkTest(page) {
  const selector = `a[href*="selectedStory="]`;

  await page.goto('http://localhost:8080');

  await page.evaluate(() => {
    Array.from(document.querySelectorAll('div[data-name]'), item => {
      item.addEventListener('click', () => {});
      item.click();
    });
  });

  const storyLinks = await page.evaluate(selector => {
    return Array.from(document.querySelectorAll(selector), story => {
      let href = story.href;
      let name = story.text.replace(/[^A-Z0-9]/gi, '-').replace(/-{2,}/, '-');
      let component = href.match(/selectedKind=(.*?)\&/).pop();
      return { href: href, name: component + '-' + name };
    });
  });

  return storyLinks;
}

describe('visual tests', async () => {
    let page, browser;

    beforeAll(async () => {
      browser = await puppeteer.connect({ browserWSEndpoint });
      page = await browser.newPage();
    });

    afterAll(async () => {
      await page.close();
      await browser.disconnect();
    });

    it('should do something with storyLinks', async () => {
        expect.assertions(1);
        const storyLinkResult = await myStoryLinkTest(page);
        expect(storyLinkResult).toEqual('Some value you expect');
     }, timeout);
  });


问:
ld can not find symbol _start error after assemble and link .asm file to 64 bit executables
I have a shellcode file.
Then use ndisasm to build the assembly code.

```<code> ndisasm -b 64 shellcode > shellcode.asm
 cat shellcode.asm | cut -c29->key.asm
</code>```

I add 2 lines to the key.asm file

global_start:

       _start:

```<code>$vi key.asm
global_start:
_start:
xor eax,eax
push rax
push qword 0x79237771
push qword 0x76772427
push qword 0x25747320
.    .     .
.    .     .
.    .     .
push qword 0x20757577
push rsp
pop rsi
mov edi,esi
mov edx,edi
cld
mov ecx,0x80
mov ebx,0x41
xor eax,eax
push rax
lodsb
xor eax,ebx
</code>```

An then I assemble and link it to 64 bit executables

```<code>$nasm -f elf64 -g -F stabs key.asm
$ld -o key key.o
</code>```

It gives me a warning

```<code>ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080
</code>```

I tested it out with gcc

```<code>gcc -o key key.o
</code>```

I still get an error almost the same as the first one

```<code>/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In
function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

And when I run ./key with gdb after I use $ld NOT $gcc

```<code>$gdb -q ./key
$run
</code>```

I get a seg fault

```<code>Starting program: /mnt/c/Users/owner/Documents/U
M/Computer_Security/ExtraCredit/key
Program received signal SIGSEGV, Segmentation fault.
0x000000000040013a in global_start ()
</code>```

If I debug after run with gcc then the file will not be found because of exit status

Can you explain why does it happen? And how can I fix this problem? Thanks

答:
Your code is wrong. Between global and _start must have a space. That is one of your problems.

```<code>section .text

global _start

_start:
    xor eax,eax
    push rax
    ...
</code>```

In addition, to get why the segmentation fault is happening, you have to debug it. You could look the assembly instruction that does the segfault.

```<code>x/5i $eip
</code>```

Body:
I have a shellcode file.
Then use ndisasm to build the assembly code.

 ndisasm -b 64 shellcode > shellcode.asm
 cat shellcode.asm | cut -c29->key.asm

I add 2 lines to the key.asm file

global_start:

       _start:

$vi key.asm
global_start:
_start:
xor eax,eax
push rax
push qword 0x79237771
push qword 0x76772427
push qword 0x25747320
.    .     .
.    .     .
.    .     .
push qword 0x20757577
push rsp
pop rsi
mov edi,esi
mov edx,edi
cld
mov ecx,0x80
mov ebx,0x41
xor eax,eax
push rax
lodsb
xor eax,ebx

An then I assemble and link it to 64 bit executables

$nasm -f elf64 -g -F stabs key.asm
$ld -o key key.o

It gives me a warning

ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080

I tested it out with gcc

gcc -o key key.o

I still get an error almost the same as the first one

/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In
function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

And when I run ./key with gdb after I use $ld NOT $gcc

$gdb -q ./key
$run

I get a seg fault

Starting program: /mnt/c/Users/owner/Documents/U
M/Computer_Security/ExtraCredit/key
Program received signal SIGSEGV, Segmentation fault.
0x000000000040013a in global_start ()

If I debug after run with gcc then the file will not be found because of exit status

Can you explain why does it happen? And how can I fix this problem? Thanks

Body:
Your code is wrong. Between global and _start must have a space. That is one of your problems.

section .text

global _start

_start:
    xor eax,eax
    push rax
    ...

In addition, to get why the segmentation fault is happening, you have to debug it. You could look the assembly instruction that does the segfault.

x/5i $eip


问:
Protractor waitForAngular or .count() not working
I have this annoying issue where count() is not being updated after a change. My test sets some input values, and then runs the following:

```<code>$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    $$('.label-entry').count().then(count => expect(count).toEqual(beforeCount + 1));
});
</code>```

The test is supposed to click a save button that makes an API call, wait for that call to end, and check if the # of divs has increased by one (it does when testing manually). Somehow, the test manages to fail. The first call to count() works properly, but the second call does not. What am I missing here?

```<code><div class="label-entry" *ngFor="let labelEntry of labelEntries">
</code>```

答:
Hmm... maybe you don't need your second then(), because the expect should already resolve your promise.

Can you try this:

```<code>$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    expect($$('.label-entry').count()).toEqual(beforeCount + 1);
});
</code>```

or eventually this:

```<code>$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    //wrap it in a browser.wait() to see, if you get the result before timeout
    browser.wait(expect($$('.label-entry').count()).toEqual(beforeCount + 1), 5000);
});
</code>```

or eventually this (though experimental):

```<code>$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    browser.wait(($$('.label-entry').count() > beforeCount), 5000);
    expect($$('.label-entry').count()).toEqual(beforeCount + 1);
});
</code>```

Body:
I have this annoying issue where count() is not being updated after a change. My test sets some input values, and then runs the following:

$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    $$('.label-entry').count().then(count => expect(count).toEqual(beforeCount + 1));
});

The test is supposed to click a save button that makes an API call, wait for that call to end, and check if the # of divs has increased by one (it does when testing manually). Somehow, the test manages to fail. The first call to count() works properly, but the second call does not. What am I missing here?

Body:
Hmm... maybe you don't need your second then(), because the expect should already resolve your promise.

Can you try this:

$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    expect($$('.label-entry').count()).toEqual(beforeCount + 1);
});

or eventually this:

$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    //wrap it in a browser.wait() to see, if you get the result before timeout
    browser.wait(expect($$('.label-entry').count()).toEqual(beforeCount + 1), 5000);
});

or eventually this (though experimental):

$$('.label-entry').count().then(beforeCount => {
    btnSaveLabel.click();
    browser.waitForAngular();
    browser.wait(($$('.label-entry').count() > beforeCount), 5000);
    expect($$('.label-entry').count()).toEqual(beforeCount + 1);
});