问:
Why the below code does not compile with gcc but compiles fine with clang
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

```<code>#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}
</code>```

Error message looks like below for gcc

```<code>In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~
</code>```

答:
This happens because std::function's move ctor is not noexcept, but a std::vector can only use the move ctor if it's noexcept (strong exception guarantee).

The issue is that std::unique_ptr is (obviously) non-copyable, so that makes ABC noncopyable as a whole.
To make ABC noexcept-movable implicitly, it'd need every one of its members to be noexcept-movable as well.

If you remove the std::function, that's what happens: the .resize() doesn't need to copy A.up (a std::vector's move operator is noexcept), so the std::unique_ptrs (inside up) can just be moved, and everything works fine.

See this coliru: if you comment the noexcept, vec.reserve() will need to copy everything, and the issue comes back.

Adding ABC(ABC&&) = default fixes the issue because user-declared (though defaulted) move ctor inhibits the generation of copy constructor (see here).

We can also go the opposite way and manually delete A's copy constructor in the coliru (and keep the move ctor not noexcept): here.

To fix the issue, you could store the std::function in a std::unique_ptr, which has a nothrow move ctor. See here

Body:
Below code compiles fine with clang but not gcc , any explanation is this a bug in gcc?

Its just a class which contains a vector of unique_ptr and std::function as member and when I create vector of this class , I cant say reserve or resize on this. push_back works fine with std::move, while this only happens with gcc and not clang.

#include <algorithm>
#include <memory>
#include <utility>
#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class ABC
{
public:
    ABC()
          {}
  private:
    std::vector<std::unique_ptr<int>> up;
    std::function<void (int*)> func;
};

int main()
{
    ABC a;
    std::vector<ABC> vec;
    vec.reserve(1);
}

Error message looks like below for gcc

In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_tempbuf.h:60:0,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_algo.h:62,
                 from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/algorithm:62,
                 from prog.cc:1:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = std::unique_ptr<int>; _Args = {const std::unique_ptr<int, std::default_delete<int> >&}]':
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*, std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:331:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:10:7:   required from 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = ABC; _Args = {const ABC&}]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:83:18:   required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; bool _TrivialValueTypes = false]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:134:15:   required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const ABC*; _ForwardIterator = ABC*]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_uninitialized.h:289:37:   required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const ABC*; _ForwardIterator = ABC*; _Tp = ABC]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_vector.h:1263:35:   required from 'std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = const ABC*; _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::pointer = ABC*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/vector.tcc:73:40:   required from 'void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = ABC; _Alloc = std::allocator<ABC>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]'
prog.cc:24:18:   required from here
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/stl_construct.h:75:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/wandbox/gcc-7.1.0/include/c++/7.1.0/memory:80:0,
                 from prog.cc:2:
/opt/wandbox/gcc-7.1.0/include/c++/7.1.0/bits/unique_ptr.h:388:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^~~~~~~~~~


来源: stackexchange

问:
Find and return the most recent record by max date and specific ID
What I am trying to do list the most recent event type '1081'

But I am only getting a '1081' if its the most recent event type.

The other event type is '1009'

If 1009 is the most recent event type then the record does not appear at all.

If I search all event types then the number of records returned is correct.

I have manually checked through the records and each has an event type 1081 attached to it.

(The event type is matched to a comment that I want to display and I only want to display the most recent 1081 comment)

This is the code

```<code>SELECT
   o.SiteIdAndName,
   o.Id,
   r.callid,
   o.masterSymptom,
   o.subSymptom,
   o.received,
   o.closed,
   r.eventtype,
   r.datetime,
   r.loggedby,
   r.eventcomments,
   --o.lastedt,
   DATEDIFF(HOUR, received, COALESCE(closed, GETDATE())) AS 'HoursOpen'

FROM
   vw_UserView_OpenAndClosed2016 o
   LEFT JOIN dbo.tblcallev r ON r.callid = o.id --and r.eventtype = 1081

WHERE
   o.SchemeName = 'INDIS'
   AND o.SubSymptom = 'Care'
   AND Closed is NULL
   AND r.datetime = (
   SELECT MAX(datetime)
   FROM dbo.tblcallevents
   WHERE NOT r.eventtype = 1009
   AND callid = r.callid
   )

Order by
  r.eventtype
</code>```

Can you help me at all?

答:
I think this could be very straight foreword query, like below

```<code>SELECT TOP(1) *--column list here
FROM
vw_UserView_OpenAndClosed2016 o
INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
ORDER BY r.datetime
</code>```

Here ORDER BY r.datetime will sort data according to recent datetime values for r.eventtype = 1081

UPDATED :

```<code>;WITH CTE AS(
       SELECT *,
              ROW_NUMBER() OVER(PARTITION BY o.id ORDER BY r.datetime) RN
       FROM
       vw_UserView_OpenAndClosed2016 o
       INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
       WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
)
SELECT *
FROM CTE
WHERE RN=1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I am trying to do list the most recent event type '1081'

But I am only getting a '1081' if its the most recent event type.

The other event type is '1009'

If 1009 is the most recent event type then the record does not appear at all.

If I search all event types then the number of records returned is correct.

I have manually checked through the records and each has an event type 1081 attached to it.

(The event type is matched to a comment that I want to display and I only want to display the most recent 1081 comment)

This is the code

SELECT
   o.SiteIdAndName,
   o.Id,
   r.callid,
   o.masterSymptom,
   o.subSymptom,
   o.received,
   o.closed,
   r.eventtype,
   r.datetime,
   r.loggedby,
   r.eventcomments,
   --o.lastedt,
   DATEDIFF(HOUR, received, COALESCE(closed, GETDATE())) AS 'HoursOpen'

FROM
   vw_UserView_OpenAndClosed2016 o
   LEFT JOIN dbo.tblcallev r ON r.callid = o.id --and r.eventtype = 1081

WHERE
   o.SchemeName = 'INDIS'
   AND o.SubSymptom = 'Care'
   AND Closed is NULL
   AND r.datetime = (
   SELECT MAX(datetime)
   FROM dbo.tblcallevents
   WHERE NOT r.eventtype = 1009
   AND callid = r.callid
   )

Order by
  r.eventtype

Can you help me at all?

Body:
I think this could be very straight foreword query, like below

SELECT TOP(1) *--column list here
FROM
vw_UserView_OpenAndClosed2016 o
INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
ORDER BY r.datetime

Here ORDER BY r.datetime will sort data according to recent datetime values for r.eventtype = 1081

UPDATED :

;WITH CTE AS(
       SELECT *,
              ROW_NUMBER() OVER(PARTITION BY o.id ORDER BY r.datetime) RN
       FROM
       vw_UserView_OpenAndClosed2016 o
       INNER JOIN dbo.tblcallev r ON r.callid = o.id and r.eventtype = 1081
       WHERE o.SchemeName = 'INDIS' AND o.SubSymptom = 'Care' AND Closed is NULL
)
SELECT *
FROM CTE
WHERE RN=1


问:
getting Error: spawn EACCES while ionic build android in ubuntu 14.04
i developed one project in ionic2

while i am doing ionic build android i am getting this error

my ionic info is

Cordova CLI: 6.3.0

Ionic Framework Version: 2.0.0-beta.10

Ionic CLI Version: 2.0.0-beta.36

Ionic App Lib Version: 2.0.0-beta.19

OS: Distributor ID: Ubuntu Description: Ubuntu 14.04.5 LTS

Node Version: v4.4.7

I searched in google but no solution works for me..

How can i fix this Bug?

答:
This is Permission Error While Building App

You Need to Give Permission Gradle

sudo chmod -R 777 /Applications/Android\ Studio\ 3.0\ Preview.app/Contents/gradle

Enjoy :)


问:
avoiding using .bind with ES6 =>
I'm new to React and the concepts are still new to me. I'm working on this example and I would like to know if it would be possible to re-write it in another way and avoid using .bind altogether. The goal here is just to minimize the code written required as much as possible!

Full example can be found here:

https://codepen.io/akamali/pen/awvqeM

The component simply render a menu list and when you click on an item it highlight the selected text.

ES5

```<code><ul className='languages'>
      {languages.map(function (lang) {
        return (
          <li
            style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : null}
            onClick={this.updateLanguage.bind(null, lang)}
            key={lang}>
              {lang}
          </li>
        )
      }, this)}
    </ul>
</code>```

**ES6 => **

```<code><ul className='languages'>
      {languages.map(lang => {
        return (
          <li
            style={lang === this.state.selectedLanguage ? {color: '#d0021b'} : null}
            onClick={this.updateLanguage.bind(null, lang)}
            key={lang}>
              {lang}
          </li>
        )
      },)}
    </ul>
</code>```

答:
What you want to do is make each item a component, this way there is no inline binding in your render

```<code>{languages.map(lang => <ListItem lang={lang} updateLanguage={this.updateLanguage} selected={lang === this.state.selectedLanguage } />)}
</code>```

and then your list item handles the click with a single bound instance.

```<code>class ListItem extends Component {
    handleClick = () => {
        this.props.updateLanguage(this.props.lang);
    }
    render() {
        return (
            <li
                style={this.props.selected ? {color: '#d0021b'} : null}
                onClick={this.handleClick}
            >
                {this.props.lang}
            </li>
        )
    }
}
</code>```

Title: avoiding using .bind with ES6 =>

Body:
I'm new to React and the concepts are still new to me. I'm working on this example and I would like to know if it would be possible to re-write it in another way and avoid using .bind altogether. The goal here is just to minimize the code written required as much as possible!

Full example can be found here:

https://codepen.io/akamali/pen/awvqeM

The component simply render a menu list and when you click on an item it highlight the selected text.

ES5

      {languages.map(function (lang) {
        return (

              {lang}

        )
      }, this)}

**ES6 => **

      {languages.map(lang => {
        return (

              {lang}

        )
      },)}

Body:
What you want to do is make each item a component, this way there is no inline binding in your render

{languages.map(lang => <ListItem lang={lang} updateLanguage={this.updateLanguage} selected={lang === this.state.selectedLanguage } />)}

and then your list item handles the click with a single bound instance.

class ListItem extends Component {
    handleClick = () => {
        this.props.updateLanguage(this.props.lang);
    }
    render() {
        return (
            <li
                style={this.props.selected ? {color: '#d0021b'} : null}
                onClick={this.handleClick}
            >
                {this.props.lang}
            </li>
        )
    }
}


问:
Convert character to ASCII code in JavaScript
How can I convert a character to its ASCII code using JavaScript?

For example:

get 10 from "\n".

答:
You can enter a character and get Ascii Code Using this Code

For Example Enter a Character Like A
You Get Ascii Code 65

function myFunction(){
    var str=document.getElementById("id1");
    if (str.value=="") {
       str.focus();
       return;
    }
    var a="ASCII Code is == >  ";
document.getElementById("demo").innerHTML =a+str.value.charCodeAt(0);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Check ASCII code</p>

<p>
  Enter any character:
  <input type="text" id="id1" name="text1" maxLength="1"> </br>
</p>

<button onclick="myFunction()">Get ASCII code</button>

<p id="demo" style="color:red;"></p></code>```

OwnerDisplayName: levik

ContentLicense: CC BY-SA 4.0

Body:
You can enter a character and get Ascii Code Using this Code

For Example Enter a Character Like A
You Get Ascii Code 65

function myFunction(){
    var str=document.getElementById("id1");
    if (str.value=="") {
       str.focus();
       return;
    }
    var a="ASCII Code is == >  ";
document.getElementById("demo").innerHTML =a+str.value.charCodeAt(0);
}

<p>Check ASCII code</p>

<p>
  Enter any character:
  <input type="text" id="id1" name="text1" maxLength="1"> </br>
</p>

<button onclick="myFunction()">Get ASCII code</button>

<p id="demo" style="color:red;"></p>


问:
How to overlap layouts/views within LinearLayout?
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

```<code><!-- parent/root layout -->
<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <!-- Layout1 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

    <!-- Buttons -->
    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <!-- Layout2 -->
    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>
</code>```

答:
Hm, if you don't have any restrictions besides those ones that you've described in the question, you could do it by the next way:</p>

```<code><!-- parent/root layout -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        ...
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        ... >

        <!-- Layout1 -->
        <LinearLayout
            android:layout_weight="1"
             ... />

        <!-- Layout2 -->
        <LinearLayout
            android:layout_weight="1"
            ... />

    </LinearLayout>

    <!-- Buttons -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="horizontal"
        android:background="@android:color/transparent"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

</RelativeLayout>
</code>```

Body:
I would like to create layout that looks like this:

Layout1and Layout2 are some layouts of any kind, nested in a parent LinearLayout. The LinearLayout is necessary to give both child layouts a 50% height by using layout_weight.

The red squares should be Buttons which overlap both Layout1and Layout2 and are centered between the two layouts.

Of course this could achived by using RelativeLayout as parent instead but then I would loose the possibility to use layout_weight...

If I keep using LinearLayout, it seems to be impossible to let the buttons overlap the two other layouts.

Furthermore the buttons cannot be siblings of the two layouts but need to be nested inside a common container layout that takes care of the horizontal positioning (e.g. a LinearLayout with horizontal orientation).

Any idea how to solve this?

I already tried to place the buttons inside Layout1 (or Layout2), place them below the bottom and use android:clipChildren=false, but this had no effect. The button where simple cut in half.

Edit:
Splitting the height between the two layouts 50/50 is just one version. Another view uses the same basic layout but splits the height 70/30 between the two layouts. The buttons should always be centered between the two layouts. Sorry for not pointing this out earlier.

Layout Code:

<LinearLayout
    ...
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    ... >

    <LinearLayout
        android:layout_weight="1"
        ... />

    <LinearLayout
        android:orientation="horizontal"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

    <LinearLayout
        android:layout_weight="1"
        ... />

</LinearLayout>

Body:
Hm, if you don't have any restrictions besides those ones that you've described in the question, you could do it by the next way:

<!-- parent/root layout -->
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        ...
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        ... >

        <!-- Layout1 -->
        <LinearLayout
            android:layout_weight="1"
             ... />

        <!-- Layout2 -->
        <LinearLayout
            android:layout_weight="1"
            ... />

    </LinearLayout>

    <!-- Buttons -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="horizontal"
        android:background="@android:color/transparent"
        ... >

        <Button ... />
        <Button ... />
        <Button ... />

    </LinearLayout>

</RelativeLayout>


问:
How to implement roles in AngularJs
I am working on application with angularJS and php backend, and I need to idientify 2 roles, client and admin, each one with a totally different space of the other. So I think a simple "if" condition in the authentication step can solve the problem.

To understand the code:

The authentication is done by checking the email and password of users from two tables: one admin table and one client table, each table contains an "admin" role column for the "admin" and "client" role for The "client" table.

The problem:

How to put the if condition on the result of the select, and then if the role is admin: it will enter the admin space, if it is the client, the reverse.

What I tried to do:

login.php

```<code> <?php

$data = json_decode(file_get_contents("php://input"));

 $connect = mysqli_connect("localhost", "root", "", "test");

 if(count($data) > 0)

 {

$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);

$query = 'SELECT * FROM `client`,`admin` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';

$q = mysqli_query($connect , $query);

if(mysqli_num_rows($q) > 0 )
  {
       $_SESSION["logged_in"] = true;
       $_SESSION["naam"] = $Email;
       $result['code'] = 200;
       $result['message'] ='Logged In';
  }
  else
  {
       $result['code'] = 603;
       $result['message'] ='The username or password are incorrect!';
  }

$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring;
}

?>
</code>```

app.js

```<code>app.controller('loginCtrl', function($scope, $location,$state,$http,$window){

    $scope.submit = function()
    {
        data = {
            'Email' : $scope.Email,
            'mdp' : $scope.mdp
        };

        $http.post('http://localhost/test/login.php', data)
        .success(function(data, status, headers, config,result)
        {
            console.log(data);
            if(data.code == 200){
              if(data.role=client){
                $state.go('client');
              }
              else{
                $state.go('admin');
              }
          }
          else{
            alert('incorrect');
          }
        })
        .error(function(data, status, headers, config, rsult)
        {

            console.log('error');

        });
    }

});
</code>```

Thanks in advance

答:
A simple approach could be

```<code><?php
    $data       = json_decode(file_get_contents("php://input"));
    $connect    = mysqli_connect("localhost", "root", "", "test");
    if(count($data) > 0)
    {

        $Email      = mysqli_real_escape_string($connect, $data->Email);
        $mdp        = mysqli_real_escape_string($connect, $data->mdp);
        $query      = 'SELECT * FROM `admin` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';
        $q          = mysqli_query($connect , $query);
        if(mysqli_num_rows($q) > 0 )
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $Email;
            $result['code'] = 200;
            $result['message'] ='Logged In';
            $result['role'] ='admin';
            $resultstring = json_encode($result);
            $resultstring = str_replace("null",'""',$resultstring);
            echo $resultstring;
            exit;
        }
        $query2     = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';
        $q2         = mysqli_query($connect , $query2);
        if(mysqli_num_rows($q2) > 0 )
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $Email;
            $result['code'] = 200;
            $result['message'] ='Logged In';
            $result['role'] ='client';
            $resultstring = json_encode($result);
            $resultstring = str_replace("null",'""',$resultstring);
            echo $resultstring;
            exit;
        }
        $result['code'] = 603;
        $result['message'] ='The username or password are incorrect!';
        $resultstring = json_encode($result);
        $resultstring = str_replace("null",'""',$resultstring);
        echo $resultstring;
        exit;
    }
</code>```

And in angular check role via if(data.role=='client'){ //client or if(data.role=='admin'){ //admin

Title: How to implement roles in AngularJs

Body:
I am working on application with angularJS and php backend, and I need to idientify 2 roles, client and admin, each one with a totally different space of the other. So I think a simple "if" condition in the authentication step can solve the problem.

To understand the code:

The authentication is done by checking the email and password of users from two tables: one admin table and one client table, each table contains an "admin" role column for the "admin" and "client" role for The "client" table.

The problem:

How to put the if condition on the result of the select, and then if the role is admin: it will enter the admin space, if it is the client, the reverse.

What I tried to do:

login.php

 <?php

$data = json_decode(file_get_contents("php://input"));

 $connect = mysqli_connect("localhost", "root", "", "test");

 if(count($data) > 0)

 {

$Email=mysqli_real_escape_string($connect, $data->Email);
$mdp=mysqli_real_escape_string($connect, $data->mdp);

$query = 'SELECT * FROM `client`,`admin` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';

$q = mysqli_query($connect , $query);

if(mysqli_num_rows($q) > 0 )
  {
       $_SESSION["logged_in"] = true;
       $_SESSION["naam"] = $Email;
       $result['code'] = 200;
       $result['message'] ='Logged In';
  }
  else
  {
       $result['code'] = 603;
       $result['message'] ='The username or password are incorrect!';
  }

$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring;
}

?>

app.js

app.controller('loginCtrl', function($scope, $location,$state,$http,$window){

    $scope.submit = function()
    {
        data = {
            'Email' : $scope.Email,
            'mdp' : $scope.mdp
        };

        $http.post('http://localhost/test/login.php', data)
        .success(function(data, status, headers, config,result)
        {
            console.log(data);
            if(data.code == 200){
              if(data.role=client){
                $state.go('client');
              }
              else{
                $state.go('admin');
              }
          }
          else{
            alert('incorrect');
          }
        })
        .error(function(data, status, headers, config, rsult)
        {

            console.log('error');

        });
    }

});

Thanks in advance

Body:
A simple approach could be

<?php
    $data       = json_decode(file_get_contents("php://input"));
    $connect    = mysqli_connect("localhost", "root", "", "test");
    if(count($data) > 0)
    {

        $Email      = mysqli_real_escape_string($connect, $data->Email);
        $mdp        = mysqli_real_escape_string($connect, $data->mdp);
        $query      = 'SELECT * FROM `admin` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';
        $q          = mysqli_query($connect , $query);
        if(mysqli_num_rows($q) > 0 )
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $Email;
            $result['code'] = 200;
            $result['message'] ='Logged In';
            $result['role'] ='admin';
            $resultstring = json_encode($result);
            $resultstring = str_replace("null",'""',$resultstring);
            echo $resultstring;
            exit;
        }
        $query2     = 'SELECT * FROM `client` WHERE (EmailClient = "'.$Email.'" AND   mdp= "'.$mdp.'") OR (EmailaAdmin = "'.$Email.'" AND   MdpAdmin= "'.$mdp.'")';
        $q2         = mysqli_query($connect , $query2);
        if(mysqli_num_rows($q2) > 0 )
        {
            $_SESSION["logged_in"] = true;
            $_SESSION["naam"] = $Email;
            $result['code'] = 200;
            $result['message'] ='Logged In';
            $result['role'] ='client';
            $resultstring = json_encode($result);
            $resultstring = str_replace("null",'""',$resultstring);
            echo $resultstring;
            exit;
        }
        $result['code'] = 603;
        $result['message'] ='The username or password are incorrect!';
        $resultstring = json_encode($result);
        $resultstring = str_replace("null",'""',$resultstring);
        echo $resultstring;
        exit;
    }

And in angular check role via if(data.role=='client'){ //client or if(data.role=='admin'){ //admin


问:
How to create and enable a user in ldap using java?
I am trying to create a user in ldap using java, however user is being created but it is disabled, how to enable it while creation of the user, posting code that i am using for creation. Is any parameter missing or setting wrong attributes or password setting is wrong? Help me out.

```<code>        Attribute userCn = new BasicAttribute("cn", commonName);
        Attribute samAccountName = new BasicAttribute("samAccountName",samaccountname);
        Attribute userPassword = new BasicAttribute("userPassword",Password);
        Attribute oc = new BasicAttribute("objectClass");
            oc.add("top");
            oc.add("person");
            oc.add("organizationalPerson");
            oc.add("user");
        Attributes entry = new BasicAttributes(true);
        entry.put(userCn);
        entry.put(samAccountName);
        entry.put(oc);
        entry.put(userPassword);
String entryDN = "CN=" + userID.trim() + ",OU=abc,OU=def,DC=ghi,DC=jkl";
dirContext.createSubcontext(entryDN, entry);
</code>```

UPDATE 1

I am getting the following exception/error while updating or modifying user for setting the password of a user and enabling it and i am using private connection between ldap server and my enviroment so should i need to use SSL/TLS configurations.

ErrorCode 53 and WILL_NOT_PERFORM

答:
AFIK, this must be due to the fact that you are setting the "userPassword" attribute which is not present in Microsoft Active Directory (by default).

The unicodePwd is the password attribute in Microsoft Active Directory and it requires "special" encoding to be set from JNDI. We show an example in this source code.

So user entries created within Microsoft Active Directory with no password are disabled by default.

Also, for Microsoft Active Directory you MUST use SSL-TLS to change the unicodePwd.

You may, but not recommended, Try setting the attribute userAccountControl = 544 on the created user entry with no unicodePwd. You may need to do this after creation.

Body:
I am trying to create a user in ldap using java, however user is being created but it is disabled, how to enable it while creation of the user, posting code that i am using for creation. Is any parameter missing or setting wrong attributes or password setting is wrong? Help me out.

        Attribute userCn = new BasicAttribute("cn", commonName);
        Attribute samAccountName = new BasicAttribute("samAccountName",samaccountname);
        Attribute userPassword = new BasicAttribute("userPassword",Password);
        Attribute oc = new BasicAttribute("objectClass");
            oc.add("top");
            oc.add("person");
            oc.add("organizationalPerson");
            oc.add("user");
        Attributes entry = new BasicAttributes(true);
        entry.put(userCn);
        entry.put(samAccountName);
        entry.put(oc);
        entry.put(userPassword);
String entryDN = "CN=" + userID.trim() + ",OU=abc,OU=def,DC=ghi,DC=jkl";
dirContext.createSubcontext(entryDN, entry);

UPDATE 1

I am getting the following exception/error while updating or modifying user for setting the password of a user and enabling it and i am using private connection between ldap server and my enviroment so should i need to use SSL/TLS configurations.

ErrorCode 53 and WILL_NOT_PERFORM


问:
Remove particular string from url Jquery
I need to remove size i.e. resolution of image path from url. Take following example:

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg
</code>```

I need to remove -1024x682

```<code>http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg
</code>```

Need to remove -300x118

答:
use regex pattern </p>

```<code>$(document).ready(function(){
 window.location.href = window.location.href.replace(/(-\d{2-6}x\d{2-6})/g,'');
});
</code>```

Body:
I need to remove size i.e. resolution of image path from url. Take following example:

http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg

I need to remove -1024x682

http://raudevlocal.com/wp/wp-content/uploads/2017/05/rohit-300x118.jpg

Need to remove -300x118

Body:
use regex pattern

$(document).ready(function(){
 window.location.href = window.location.href.replace(/(-\d{2-6}x\d{2-6})/g,'');
});


问:
Overriding css only visible on some pages
our site has a stylesheet.css and a custom.css - on our platform, I only have access to the custom.css.

I have some overrides in the custom.css, but they only show on some pages.

See http://www.daysjewelers.com (background, etc. controlled by custom.css)
see http://www.daysjewelers.com/category/engagement_rings_and_wedding_rings.do and the css overrides are not there.

Here are the overrides:

```<code>body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat;
}

.mainLayoutTable {
background: #fff;
padding: 10px;
border: 1px dashed #c0ddea;
margin-top: 15px;
}
</code>```

and I have refreshed my browser cache, thoughts?

答:
The best way to define custom css styles is by adding the !important line to your css declaration. Your code would look like this:

```<code>body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat !important;
}
</code>```

Edit: Just an FYI, I have tested this on your website using Firebug, and it did work.

ContentLicense: CC BY-SA 2.5

Body:
our site has a stylesheet.css and a custom.css - on our platform, I only have access to the custom.css.

I have some overrides in the custom.css, but they only show on some pages.

See http://www.daysjewelers.com (background, etc. controlled by custom.css)
see http://www.daysjewelers.com/category/engagement_rings_and_wedding_rings.do and the css overrides are not there.

Here are the overrides:

body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat;
}

.mainLayoutTable {
background: #fff;
padding: 10px;
border: 1px dashed #c0ddea;
margin-top: 15px;
}

and I have refreshed my browser cache, thoughts?

Body:
The best way to define custom css styles is by adding the !important line to your css declaration. Your code would look like this:

body.main {
background: #fff url(http://www.daysjewelers.com/images/en_US/global/globalgraphics/main_bg.gif) repeat !important;
}

Edit: Just an FYI, I have tested this on your website using Firebug, and it did work.


问:
Refresh component after doing a router.navigate
I am trying to navigate from one component to another component using :

```<code>this.router.navigate(['/path/'], '_blank');
</code>```

The problem is that the component I am navigating to, is already created and its ngOnInit method is not executed when I navigate back to the page. I am trying to refresh the data showing on the page. This is in the ngOnInit function of the target component:

```<code>this.sub = this._DataService.getData().subscribe(data=> {
        this.data= data;
    });
</code>```

How can I tell the target component, that the data on the page is always refreshed when doing a navigation?

I am using Ag-Grid to show the data in a table. In the NgOnInit function:

```<code>this.gridOptions.rowData = this.data;
</code>```

The component I am originally coming from, is a form to add a new object. After submitting that object, it should redirect to the grid and show the new object. That is why the Grid should be updating its data, but because of some reason, it only does that when I manually refresh it through a context menu action in the grid, not on navigation.

The submit function in the form looks as the following:

```<code> onSubmit(data) {
    this._DataService.addData(data.value).subscribe();
    this.router.navigate(['/data/']);
}
</code>```

答:
i implemented an redirect component

this.router.navigate(['/redirect/', window.location.pathname]);

Body:
I am trying to navigate from one component to another component using :

this.router.navigate(['/path/'], '_blank');

The problem is that the component I am navigating to, is already created and its ngOnInit method is not executed when I navigate back to the page. I am trying to refresh the data showing on the page. This is in the ngOnInit function of the target component:

this.sub = this._DataService.getData().subscribe(data=> {
        this.data= data;
    });

How can I tell the target component, that the data on the page is always refreshed when doing a navigation?

I am using Ag-Grid to show the data in a table. In the NgOnInit function:

this.gridOptions.rowData = this.data;

The component I am originally coming from, is a form to add a new object. After submitting that object, it should redirect to the grid and show the new object. That is why the Grid should be updating its data, but because of some reason, it only does that when I manually refresh it through a context menu action in the grid, not on navigation.

The submit function in the form looks as the following:

 onSubmit(data) {
    this._DataService.addData(data.value).subscribe();
    this.router.navigate(['/data/']);
}


问:
can't locate object method "see" via package "Net::IMAP::Simple"
I am trying to fetch unread emails from server and mark them as seen (read) after fetching. I'm using perl script and the package Net::IMAP::Simple. I'm writing this script for the office work.

Below is some code :

```<code>use strict;
use warnings;
use Net::IMAP::Simple;
use Email::Simple;
use HTTP::Date;
#some code....

# Create the object
my $server = Net::IMAP::Simple->new($imap_server) or die "Can't connect to server: $imap_server ";

# Log on
my $login = $server->login($imap_user,$imap_passwd) or die "Login failed (bad username or password)";

#some code.....

# set the message as seen
$server->see($i);

# i also used $server->add_flags($i,'\Seen'); but it throws same error.
</code>```

The Irony is, this code works fine on my Gmail account , which i use for testing. but when i test it in office it throws error ;

can't locate object method "see" via package "Net::IMAP::Simple"

I don't know what's the issue here.

答:
The methods see and unsee were added in Net::IMAP::Simple version 1.1899_05.

```<code>> 1.1899_05: Tue Jun 16 06:42:16 EDT 2009
>    - I started working on ticket 45953,
>    - created sub_flags() and add_flags()
>    - taught delete() to use add_flags() -- adds \Deleted
>    - providing see() and unsee() for ticket 45953
>    - I started building tests for the flag manipulation stuff and
>      put reselect stuff ... noticed a possible bug in
>      Net::IMAP::Server
</code>```

You likely have an older version on your production system. Update it, and include a minimum version in your Makefile.PL or cpanfile or whatever you use to track dependencies.

Body:
I am trying to fetch unread emails from server and mark them as seen (read) after fetching. I'm using perl script and the package Net::IMAP::Simple. I'm writing this script for the office work.

Below is some code :

use strict;
use warnings;
use Net::IMAP::Simple;
use Email::Simple;
use HTTP::Date;
#some code....

# Create the object
my $server = Net::IMAP::Simple->new($imap_server) or die "Can't connect to server: $imap_server ";

# Log on
my $login = $server->login($imap_user,$imap_passwd) or die "Login failed (bad username or password)";

#some code.....

# set the message as seen
$server->see($i);

# i also used $server->add_flags($i,'\Seen'); but it throws same error.

The Irony is, this code works fine on my Gmail account , which i use for testing. but when i test it in office it throws error ;

can't locate object method "see" via package "Net::IMAP::Simple"

I don't know what's the issue here.

Body:
The methods see and unsee were added in Net::IMAP::Simple version 1.1899_05.

> 1.1899_05: Tue Jun 16 06:42:16 EDT 2009
>    - I started working on ticket 45953,
>    - created sub_flags() and add_flags()
>    - taught delete() to use add_flags() -- adds \Deleted
>    - providing see() and unsee() for ticket 45953
>    - I started building tests for the flag manipulation stuff and
>      put reselect stuff ... noticed a possible bug in
>      Net::IMAP::Server

You likely have an older version on your production system. Update it, and include a minimum version in your Makefile.PL or cpanfile or whatever you use to track dependencies.


问:
Why does xDebug do not work with Php Storm on Ubuntu?
I have installed xdebug and tried to use it with phpstorm. But it doesn't want work correctly.

I tried to put following settings to /etc/php5/apache/php.ini and /etc/php5/mods-avaible/xdebug.ini:

```<code>zend_extension="xdebug.so"

; Debugging
xdebug.remote_enable= 1
xdebug.remote_port= 9000
xdebug.idekey = "PHPSTORM"

; Var-Display
xdebug.var_display_max_children = 2048
xdebug.var_display_max_data = 8192
xdebug.var_display_max_depth = 99
xdebug.max_nesting_level = 3000
</code>```

I thought the `xdebug.ini should be the correct place for this settings.

Then I restarted apache with sudo service apache2 restart and opened a page where I print out phpinfo(). But as you can see on screenshot - it says all the time netbeans-xdebug.

What can I do? I searched my whole system for other php.ini files, but there aren't any other files.

答:
It usually happens (if the path to xdebug.so is correct) because the remote_enable is set to off.

```<code>xdebug.remote_enable=on
</code>```

might solve the issue.

Body:
I have installed xdebug and tried to use it with phpstorm. But it doesn't want work correctly.

I tried to put following settings to /etc/php5/apache/php.ini and /etc/php5/mods-avaible/xdebug.ini:

zend_extension="xdebug.so"

; Debugging
xdebug.remote_enable= 1
xdebug.remote_port= 9000
xdebug.idekey = "PHPSTORM"

; Var-Display
xdebug.var_display_max_children = 2048
xdebug.var_display_max_data = 8192
xdebug.var_display_max_depth = 99
xdebug.max_nesting_level = 3000

I thought the `xdebug.ini should be the correct place for this settings.

Then I restarted apache with sudo service apache2 restart and opened a page where I print out phpinfo(). But as you can see on screenshot - it says all the time netbeans-xdebug.

What can I do? I searched my whole system for other php.ini files, but there aren't any other files.

Body:
It usually happens (if the path to xdebug.so is correct) because the remote_enable is set to off.

xdebug.remote_enable=on

might solve the issue.


问:
fix cut tile javascript
i have code cut tile:
TITL1 - TITLE2 [XXX]

```<code>   var Enumber1 = new Array();
           $("#id").each(function(i){
           var text = $(this).text();
           if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
             var Ntext1      = text.split('[')[0];
             Enumber1[i] = text.split('[')[1].split(']')[0];
             $(this).text(Ntext1);
           }
         });
         $("#id").each(function(i){
           $(this).fadeIn("slow");
           if(Enumber1[i] != undefined){
             $(this).text(Enumber1[i]);
           }else{
             $(this).css('N/A');
           }

    });
</code>```

TITLE1 -TITL2  >>> div class="title"

[XXX] >>> div class="cut"
DEMO: https://jsfiddle.net/bro69zvb/

Help me fix it

TILE1 in >>> in

2.TITLE >>> in

XXX >>> in

thanks!!!

答:
Use this in your script area:

```<code>var Enumber1 = new Array();
var longOfArray=0;
$(".title").each(function(i){
  var text = $(this).text();
  var res = text.replace(" -","");
  res =  res.split(" ");
  //res contains "title1,title2,[xxx]"
    longOfArray = res.length;
  //lenght of this array is 3
  Enumber1 = res;
  //stored into your array
  $(".title").html("");
  //emptied first title
  });

  $(".cut").each(function(i){
  //iterate through array to fill .cut div
  for(i=0;i<longOfArray; i++){

    if(Enumber1[i].indexOf("[")!=-1){
  //remove first lash [
             var firstLash = Enumber1[i].indexOf("[");
       Enumber1[i] = Enumber1[i].substring(firstLash+1);
    }
    if(Enumber1[i].indexOf("]")!=-1){
     //remove last lash ]
       var lastLash = Enumber1[i].indexOf("]");
       Enumber1[i] = Enumber1[i].substring(0,lastLash);
    }

   $(".cut").append("<p>"+(i+1)+" "+Enumber1[i]+"</p>");
  }
  });
</code>```

Being your html like this:

```<code><div class="title">
Title1 - Title2 [XXX]
</div>
<div class="cut">
</div>
</code>```

Title: fix cut tile javascript

Body:
i have code cut tile:
TITL1 - TITLE2 [XXX]

   var Enumber1 = new Array();
           $("#id").each(function(i){
           var text = $(this).text();
           if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
             var Ntext1      = text.split('[')[0];
             Enumber1[i] = text.split('[')[1].split(']')[0];
             $(this).text(Ntext1);
           }
         });
         $("#id").each(function(i){
           $(this).fadeIn("slow");
           if(Enumber1[i] != undefined){
             $(this).text(Enumber1[i]);
           }else{
             $(this).css('N/A');
           }

    });

TITLE1 -TITL2  >>> div class="title"

[XXX] >>> div class="cut"
DEMO: https://jsfiddle.net/bro69zvb/

Help me fix it

TILE1 in >>> in

2.TITLE >>> in

XXX >>> in

thanks!!!

Body:
Use this in your script area:

var Enumber1 = new Array();
var longOfArray=0;
$(".title").each(function(i){
  var text = $(this).text();
  var res = text.replace(" -","");
  res =  res.split(" ");
  //res contains "title1,title2,[xxx]"
    longOfArray = res.length;
  //lenght of this array is 3
  Enumber1 = res;
  //stored into your array
  $(".title").html("");
  //emptied first title
  });

  $(".cut").each(function(i){
  //iterate through array to fill .cut div
  for(i=0;i<longOfArray; i++){

    if(Enumber1[i].indexOf("[")!=-1){
  //remove first lash [
             var firstLash = Enumber1[i].indexOf("[");
       Enumber1[i] = Enumber1[i].substring(firstLash+1);
    }
    if(Enumber1[i].indexOf("]")!=-1){
     //remove last lash ]
       var lastLash = Enumber1[i].indexOf("]");
       Enumber1[i] = Enumber1[i].substring(0,lastLash);
    }

   $(".cut").append("<p>"+(i+1)+" "+Enumber1[i]+"</p>");
  }
  });

Being your html like this:

<div class="title">
Title1 - Title2 [XXX]
</div>
<div class="cut">
</div>


问:
How do I list all the files in a commit?
How can I print a plain list of all files that were part of a given commit?

Although the following lists the files, it also includes unwanted diff information for each:

```<code>git show a303aa90779efdd2f6b9d90693e2cbbbe4613c1d
</code>```

答:
If you want to get the list of changed files:

```<code>git diff-tree --no-commit-id --name-only -r <commit-ish>
</code>```

If you want to get the list of all files in a commit, you can use

```<code>git ls-tree --name-only -r <commit-ish>
</code>```

OwnerDisplayName: Philip Fourie

Body:
How can I print a plain list of all files that were part of a given commit?

Although the following lists the files, it also includes unwanted diff information for each:

git show a303aa90779efdd2f6b9d90693e2cbbbe4613c1d

LastEditorDisplayName: Philip Fourie

Body:
If you want to get the list of changed files:

git diff-tree --no-commit-id --name-only -r <commit-ish>

If you want to get the list of all files in a commit, you can use

git ls-tree --name-only -r <commit-ish>

OwnerDisplayName: Jakub Narębski


问:
Packaging java project
I have one java project with two class. One of them is with main method. I also have two files one of them is a.properties and second one i b.xls. The way I want to export this project is in one executable jar but withour these two files(a.properties and b.xls) being compressed inside this executable jar. The reason for this is, user who run this project should able to change the properties file(a.properties) and also excel file(b.xls). I also want to include the libraries I have used for this project.

I am using Eclipse helios and jdk 1.6.

I really appreciate if somebody will provide me the steps for this. I already tried the Export option with executable jar but it compress everything including two files.

Thanks

答:
1> Keep the 2 files(a.properties and b.xls file in root directory)

2> Keep only the the src file in \src folder

3> compile the src file .java to .class file

4> the respective .class file appears in \classes folder

5> run the jar command on classes folder only

usage  jar -cvf *.class example.jar

6>you get the desired jar file which contains only the .class file.

Hope my solution works out

Good Luck !!!

Title: Packaging java project


问:
How to set the callbacks for Android Firebase Phone Authentication?
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

```<code>PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks
</code>```

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.

答:
I believe this solved my problem.

```<code>submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

    });
</code>```

I tried to make a method to handle the button clicked, I dont know why but it worked..

```<code> public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    phoneNumber,        // Phone number to verify
                    60,                 // Timeout duration
                    TimeUnit.SECONDS,   // Unit of timeout
                    this,               // Activity (for callback binding)
                    mCallbacks);        // OnVerificationStateChangedCallbac
        }
</code>```

Body:
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.

Body:
I believe this solved my problem.

submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNum = editText.getText().toString();
                Toast.makeText(MainActivity.this, phoneNum, Toast.LENGTH_SHORT).show();
                verifyPhone(phoneNum,mCallBacks);
            }

    });

I tried to make a method to handle the button clicked, I dont know why but it worked..

 public void verifyPhone(String phoneNumber, PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks){
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    phoneNumber,        // Phone number to verify
                    60,                 // Timeout duration
                    TimeUnit.SECONDS,   // Unit of timeout
                    this,               // Activity (for callback binding)
                    mCallbacks);        // OnVerificationStateChangedCallbac
        }


答:
use regular expression

var string = "http://raudevlocal.com/wp/wp-content/uploads/2017/05/0000362_chocolate-layer-cake-1024x682.jpeg";

console.log(string.replace(/-\d+x\d+/g,''));

window.loaction.href= window.location.href.replace(/-\d+x\d+/g,'');```

Title: Remove particular string from url Jquery


问:
how to give ctrl+c command in robot framework
In Robot Framework how do I give the ctrl+c command?

I have tried this line but it does not work

```<code>${crtl_c}    Evaluate    chr(int(3))    SSHLibrary.Write Bare    ${crtl_c}
</code>```

答:
Use  imagehorizon as a library : </p>

```<code>Press Combination    KEY.CTRL    C
</code>```

Body:
In Robot Framework how do I give the ctrl+c command?

I have tried this line but it does not work

${crtl_c}    Evaluate    chr(int(3))    SSHLibrary.Write Bare    ${crtl_c}

Body:
Use  imagehorizon as a library :

Press Combination    KEY.CTRL    C


问:
Plotting Windrose: making a pollution rose with concentration set to color
Trying to plot a windrose diagram with speed and direction being plotted and the concentration determining the color. Unfortunately, matplotlib only supports two variables. Can make a nice scatter that shows what I want but not sure how to bin it so that it comes out like the image attached (Halliday et al 2016).

Scatter plot that should be turned into windrose. Areas of high concentration marked by color

image from paper that I would like to recreate

答:
The plots shown can be created using a pcolormesh.

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

theta = np.linspace(0,2*np.pi)
r = np.linspace(2,15,16)

Theta, R = np.meshgrid(theta, r)
C = np.sinc(Theta-2)+(5-np.sqrt(R))+np.random.rand(len(r),len(theta))
C = np.ma.masked_less_equal(C,2)

fig, ax = plt.subplots(subplot_kw={"projection":"polar"})

ax.pcolormesh(Theta, R, C, vmin=2, vmax=5)

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

Body:
The plots shown can be created using a pcolormesh.

import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0,2*np.pi)
r = np.linspace(2,15,16)

Theta, R = np.meshgrid(theta, r)
C = np.sinc(Theta-2)+(5-np.sqrt(R))+np.random.rand(len(r),len(theta))
C = np.ma.masked_less_equal(C,2)

fig, ax = plt.subplots(subplot_kw={"projection":"polar"})

ax.pcolormesh(Theta, R, C, vmin=2, vmax=5)

plt.show()


问:
How can I update all empty string fields in a table to be null?
I have a table with 15 columns ( 10 of them are string value) and about 50000 rows.

It contain a lot empty string value ... I search if is there a query that I can pass a table name for it to iterate all values and if it equal empty then update it to NULL ..

答:
this is a simple way to do it based on table. just pass the proc the table names. you can also make a sister proc to loop thought table names and call this proc inside the while loop to work on each table in your loop logic.</p>

```<code>CREATE PROC setNullFields
(@TableName NVARCHAR(100))
AS

CREATE TABLE #FieldNames
(
pk INT IDENTITY(1, 1) ,
Field NVARCHAR(1000) NULL
);

INSERT INTO #FieldNames
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName

DECLARE @maxPK INT;
SELECT @maxPK = MAX(PK) FROM #FieldNames

DECLARE @pk INT;
SET @pk = 1

DECLARE @dynSQL NVARCHAR(1000)

WHILE @pk <= @maxPK
BEGIN

 DECLARE @CurrFieldName NVARCHAR(100);
 SET @CurrFieldName = (SELECT Field FROM #FieldNames WHERE PK = @pk)

    -- update the field to null here:

    SET @dynSQL = 'UPDATE ' + @TableName + ' SET ' + @CurrFieldName + ' = NULLIF('+ @CurrFieldName+ ', '''' )'
    EXEC (@dynSQL)

 SELECT @pk = @pk + 1
END
</code>```

Body:
this is a simple way to do it based on table. just pass the proc the table names. you can also make a sister proc to loop thought table names and call this proc inside the while loop to work on each table in your loop logic.

CREATE PROC setNullFields
(@TableName NVARCHAR(100))
AS

CREATE TABLE #FieldNames
(
pk INT IDENTITY(1, 1) ,
Field NVARCHAR(1000) NULL
);

INSERT INTO #FieldNames
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName

DECLARE @maxPK INT;
SELECT @maxPK = MAX(PK) FROM #FieldNames

DECLARE @pk INT;
SET @pk = 1

DECLARE @dynSQL NVARCHAR(1000)

WHILE @pk <= @maxPK
BEGIN

 DECLARE @CurrFieldName NVARCHAR(100);
 SET @CurrFieldName = (SELECT Field FROM #FieldNames WHERE PK = @pk)

    -- update the field to null here:

    SET @dynSQL = 'UPDATE ' + @TableName + ' SET ' + @CurrFieldName + ' = NULLIF('+ @CurrFieldName+ ', '''' )'
    EXEC (@dynSQL)

 SELECT @pk = @pk + 1
END


问:
Returning a view with previous inputs using Laravel
I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.

My Laravel Code:

```<code>Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

$var= parse_str($m['inputs'], $output);//data from ajax is a string

if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){//if no error, return the next view
        return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
    }
    return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});
</code>```

My Ajax request:

```<code>$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
        success: function(data){
            $('#tabShow').html((data.view));
        },
        error: function () {
            alert('error');
        }
    });
});
</code>```

I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.

Body:
I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.

My Laravel Code:

Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

$var= parse_str($m['inputs'], $output);//data from ajax is a string

if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){//if no error, return the next view
        return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
    }
    return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});

My Ajax request:

$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
        success: function(data){
            $('#tabShow').html((data.view));
        },
        error: function () {
            alert('error');
        }
    });
});

I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.

Body: 'view' => view('template')->withInput()?


问:
Minimum value on a 2d array python
I have an array of the following structure which is simplified for this question:

```<code>8 2 3 4 5 6
3 6 6 7 2 6
3 8 5 1 2 9
6 4 2 7 8 3
</code>```

I wish to find the minimum value in this 2D array however using the inbuilt min function returns a value error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have looked into the alternative of using np.argmin:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

If it is possible to return the index values of the lowest item in the array then that would be preferable also as from that the lowest value can easily be found.

EDIT: Thanks to the comments below np.min is the solution I was looking for and I was not aware of it existing so my answer is solved.

Title: Minimum value on a 2d array python

Body:
I have an array of the following structure which is simplified for this question:

8 2 3 4 5 6
3 6 6 7 2 6
3 8 5 1 2 9
6 4 2 7 8 3

I wish to find the minimum value in this 2D array however using the inbuilt min function returns a value error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have looked into the alternative of using np.argmin:

https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html

However it only evaluates along a single axis and returns the index of the minimum value along a single row/column whereas I wish to evaluate the whole array and return the lowest value not the indices.

If it is possible to return the index values of the lowest item in the array then that would be preferable also as from that the lowest value can easily be found.

EDIT: Thanks to the comments below np.min is the solution I was looking for and I was not aware of it existing so my answer is solved.

Body:
Alternatively for a non-numpy solution:

>>> a = [[8,2,3,4,5,6],
... [3,6,6,7,2,6],
... [3,8,5,1,2,9],
... [6,4,2,7,8,3]]
>>> mymin = min([min(r) for r in a])
>>> mymin
1


问:
Using JavaScript to alter attributes in a MVC web application
I am trying to increase the progress of the progress bar by a fixed parameter irrespective of the current value. However, I am not able to extract the current value using the .value function. So, any help is great.

Also, is it okay to include this in my view itself or should I use a controller for the same?

@{
    ViewBag.Title = "Test";
}

@ViewBag.Title.

@ViewBag.Message

Testing Page

        45% Complete

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />

```

答:
You just need to use parseInt:

```<code><script type="text/javascript">
    function increase() {
        var pwidth = parseInt(document.getElementById("pb1").style.width);
        console.log(pwidth);  // output to console
        pwidth += 10;
        var str = pwidth + "%";
        document.getElementById("pb1").style.width = str;
    }
</script>
</code>```

Note: In future you can just use console.log(pwidth); for debugging - will show value on console in the F12 Dev tools console. In the original case it was showing as undefined.

Body:
You just need to use parseInt:

<script type="text/javascript">
    function increase() {
        var pwidth = parseInt(document.getElementById("pb1").style.width);
        console.log(pwidth);  // output to console
        pwidth += 10;
        var str = pwidth + "%";
        document.getElementById("pb1").style.width = str;
    }
</script>

Note: In future you can just use console.log(pwidth); for debugging - will show value on console in the F12 Dev tools console. In the original case it was showing as undefined.


问:
how to get each data from a parseJSON array
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

```<code><html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript">
    var BASE_URL = "<?php echo base_url(); ?>";
    </script>
 <script type="text/javascript">
  // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

function drawChart() {

     $.ajax({

   type: 'POST',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "json",

    success: function (data1) {
    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('string', 'solid');
  var jsonData = $.parseJSON(data1);

  for (var i = 0; i < jsonData.length; i++) {
        data.addRows([jsonData[i].timeline, jsonData[i].solid_t1]);
  }
  var options = {

    title: 'Solid chart',
    width: 900,
    height: 500,

  };

  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
   }
});
}
  </script>
</head>
<body>

  <div id="line_chart"></div>
</body>
</html>
</code>```

Here under is the function getdata in my controller:

```<code>    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}
</code>```

I tried to output the json_encode data, and I am able to get the result below:

```<code>[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]
</code>```

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

```<code>function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}
</code>```

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

```<code>$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});
</code>```

答:
try using this

```<code>    $.post(BASE_URL+'index.php/Chart_varnish/getdata',function(data1){
      $.each(data1,function(index,value){
      data.addColumn(value.timeline,value.solid_t1);
         });
//more CODE HERE
    },'JSON');
</code>```

I hope it will help you solve the problem. you should also want to echo the json like this

```<code>echo json_encode($data1);
</code>```

Body:
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

Here under is the function getdata in my controller:

    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}

I tried to output the json_encode data, and I am able to get the result below:

[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});

Body:
try using this

    $.post(BASE_URL+'index.php/Chart_varnish/getdata',function(data1){
      $.each(data1,function(index,value){
      data.addColumn(value.timeline,value.solid_t1);
         });
//more CODE HERE
    },'JSON');

I hope it will help you solve the problem. you should also want to echo the json like this

echo json_encode($data1);


问:
How to add new line separator into data for oracle
I'm working on displaying data from oracle.

is there a way to make the following data inside the table:

example :

'1.somedata, 2.somedata, 3.somedata, 4.somedata, 5.somedata'

to display like:

example:

'1. somedata

   2. somedata

   3. somedata

   4. somedata

   5. somedata'

on the interface?

do i add new line separator directly into the data?

or do i separator them into new line when i query it?

or is there any other simple way?

Thanks.

答:
I personally would use the listagg function and use '
' as the delimiter.

SELECT LISTAGG(last_name, '
 ')
         WITHIN GROUP (ORDER BY hire_date, last_name) "Emp_list",
       MIN(hire_date) "Earliest"
  FROM employees
  WHERE department_id = 30;


答:
Perl to the rescue:

```<code>perl -nE 'chomp;
          if ($previous =~ /1$/ and /2$/) {
              say "$previous $_";
              $previous = "";
          } else {
              say $previous if $previous;
              $previous = $_;
          }
          }{ say $previous if $previous
         ' -- input
</code>```

You keep the previous line in $previous. If it ends in 1 and the current line (stored in $_ by -n) ends in 2, you print both of them on the same line and clear the $previous; otherwise, you print the previous one if there's any, and store the current one in $previous. The last line prints the last number if it wasn't printed with the previous one.

Title: Merge two lines conditionally

Body:
200005251|AAAAAA
200005252|BBBBB
200005261|CCCCCC
200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF
200005302|VVVVVV
200005311|AAAAAA
200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS
200006022|HHHHHH
200006051|OOOOOO
200006052|GGGGGG
200006061|KKKKKK
200006062|FFFFF
200006071|TTTTTT

I have a file in first field as above. I need to merge every two lines if they only end ......1 and ......2. and leave the others as is. Desired output:

200005251|AAAAAA 200005252|BBBBB
200005261|CCCCCC 200005262|DDDDD
200005292|EEEEEE
200005301|FFFFFF 200005302|VVVVVV
200005311|AAAAAA 200005312|JJJJJJ
200006011|LLLLLL
200006021|SSSSSS 200006022|HHHHHH
200006051|OOOOOO 200006052|GGGGGG
200006061|KKKKKK 200006062|FFFFF
200006071|TTTTTT

Thanks in advance.

Body:
Perl to the rescue:

perl -nE 'chomp;
          if ($previous =~ /1$/ and /2$/) {
              say "$previous $_";
              $previous = "";
          } else {
              say $previous if $previous;
              $previous = $_;
          }
          }{ say $previous if $previous
         ' -- input

You keep the previous line in $previous. If it ends in 1 and the current line (stored in $_ by -n) ends in 2, you print both of them on the same line and clear the $previous; otherwise, you print the previous one if there's any, and store the current one in $previous. The last line prints the last number if it wasn't printed with the previous one.


问:
Hide login/register button when logged in and hide logout button when logged out
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

```<code><?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>
    </head>
    </body>
        <section>
        <p style="color:red;"><?php echo $error; ?> </p>
            <form method="POST" action="">
                <div class="accPanel">
                <h1 style="color: black; padding-bottom: 5%;">Login</h1>
                <form method="POST" action="">
                    <div class="login-input">
                        <label class="accLabel"><b>Username<span style="color:red;">*</span></b></label>
                        <input type="text" placeholder="Enter Username" name="username" required>

                        <label class="accLabel"><b>Password<span style="color:red;">*</span></b></label>
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>
                    </div>
                </form>
            </div>
        </section>
    </body>
</html>
</code>```

And this is my navbar.php where the buttons are:

```<code><ul>
  <li><a href="index.php">Home</a></li>
  <li><a href="#bannerTwo">Services</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Our Work</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Account</a>
    <div class="dropdown-content">
      <a href="login.php">Login</a>
      <a href="register.php">Register</a>
      <a href="logout.php">Logout</a>
    </div>
  </li>
</ul>
</code>```

Thanks

答:
You may try</p>

```<code><?php session_start(); ?>

<ul>
  <li><a href="index.php">Home</a></li>
  <li><a href="#bannerTwo">Services</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Our Work</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Account</a>
    <div class="dropdown-content">

    <?php if(!isset($_SESSION['username']))
    echo "<a href=\"login.php\">Login</a>
          <a href=\"register.php\">Register</a>"; ?>

    <?php if(isset($_SESSION['username']))
    echo "<a href=\"logout.php\">Logout</a>"; ?>

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

Body:
i'm kinda new in PHP and I have some issues. When I'm logged in on my website I want to hide the 'Login' and 'Register' button, and when I'm logged out I want to hide the 'logout' button.

This is my login.php page:

<?php
    include "navbar.php";
?>
<?php
    include_once "check.php";

    $error = ""; //Variable for storing our errors.
    if(isset($_POST["submit"]))
    {
        if(empty($_POST["username"]) || empty($_POST["password"]))
        {
            $error = "Both fields are required.";
        }else
        {
            // Define $username and $password
            $username=$_POST['username'];
            $password=$_POST['password'];

            // To protect from MySQL injection
            $username = stripslashes($username);
            $password = stripslashes($password);
            $username = mysqli_real_escape_string($db, $username);
            $password = mysqli_real_escape_string($db, $password);
            $password = md5($password);

            //Check username and password from database
            $sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
            $result=mysqli_query($db,$sql);
            $row=mysqli_fetch_array($result,MYSQLI_ASSOC);

            //If username and password exist in our database then create a session.
            //Otherwise echo error.

            if(mysqli_num_rows($result) == 1)
            {
                $_SESSION['username'] = $username;
                header("location: index.php");
            }else
            {
                $error = "Incorrect username or password.";
            }

        }
    }

?>

        <link rel="stylesheet" type="text/css" href="assets/css/acc.css">
        <link rel="stylesheet" type="text/css" href="assets/css/acc2.css">
        <link rel="stylesheet" type="text/css" href="assets/css/navbar.css">
        <title>Login | Peerbolte-ICT</title>

<?php echo $error; ?>

            <form method="POST" action="">

Login

                <form method="POST" action="">

                        Username*
                        <input type="text" placeholder="Enter Username" name="username" required>

                        Password*
                        <input type="password" placeholder="Enter Password" name="password" required>

                        <button class="submitButton" type="submit" name="submit">Login</button>

                </form>

And this is my navbar.php where the buttons are:

Home

Services

    Our Work

      Link 1
      Link 2
      Link 3

    Account

      Login
      Register
      Logout

Thanks

Body:
You may try

<?php session_start(); ?>

<ul>
  <li><a href="index.php">Home</a></li>
  <li><a href="#bannerTwo">Services</a></li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Our Work</a>
    <div class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="javascript:void(0)" class="dropbtn">Account</a>
    <div class="dropdown-content">

    <?php if(!isset($_SESSION['username']))
    echo "<a href=\"login.php\">Login</a>
          <a href=\"register.php\">Register</a>"; ?>

    <?php if(isset($_SESSION['username']))
    echo "<a href=\"logout.php\">Logout</a>"; ?>

    </div>
  </li>
</ul>


问:
Oracle Inserting or Updating a row through a procedure
I have a table

```<code>CREATE TABLE STUDENT
(
  ID            INTEGER PRIMARY KEY,
  FIRSTNAME     VARCHAR2(1024 CHAR),
  LASTNAME      VARCHAR2(1024 CHAR),
  MODIFIEDDATE  DATE  DEFAULT sysdate
)
</code>```

I am inserting a row of data

```<code>insert into STUDENT (ID, FIRSTNAME, LASTNAME, MODIFIEDDATE)  values (1,'Scott', 'Tiger', sysdate);
</code>```

When I have to insert a record of data, I need to write a procedure or function which does the following:

if there is no record for the same id insert the row.

if there is a record for the same id and data matches then do nothing.

if there is a record for the same id but data does not match then update the data.

I am new to oracle. From the java end, It is possible to select the record by id and then update that record, but that would make 2 database calls. just to avoid that I am trying update the table using a procedure. If the same can be done in a single database call please mention.

答:
To solve the second task - "if there is a record for the same id and data matches then do nothing." - starting with 10g we have additional "where" clause in update and insert sections of merge operator.
To do the task we can add some checks for data changes:

```<code>    when matched then update
        set student.last_name = query.last_name
           where student.last_name <> query.last_name
</code>```

This will update only matched rows, and only for rows where data were changed

Body:
I have a table

CREATE TABLE STUDENT
(
  ID            INTEGER PRIMARY KEY,
  FIRSTNAME     VARCHAR2(1024 CHAR),
  LASTNAME      VARCHAR2(1024 CHAR),
  MODIFIEDDATE  DATE  DEFAULT sysdate
)

I am inserting a row of data

insert into STUDENT (ID, FIRSTNAME, LASTNAME, MODIFIEDDATE)  values (1,'Scott', 'Tiger', sysdate);

When I have to insert a record of data, I need to write a procedure or function which does the following:

if there is no record for the same id insert the row.

if there is a record for the same id and data matches then do nothing.

if there is a record for the same id but data does not match then update the data.

I am new to oracle. From the java end, It is possible to select the record by id and then update that record, but that would make 2 database calls. just to avoid that I am trying update the table using a procedure. If the same can be done in a single database call please mention.

Body:
To solve the second task - "if there is a record for the same id and data matches then do nothing." - starting with 10g we have additional "where" clause in update and insert sections of merge operator.
To do the task we can add some checks for data changes:

    when matched then update
        set student.last_name = query.last_name
           where student.last_name <> query.last_name

This will update only matched rows, and only for rows where data were changed


问:
AS3: How do I set a value of a class and prevent it from being changed?
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

```<code>package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}
</code>```

Edit. The solution I went with:

```<code>package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}
</code>```

答:
Assuming your variables are NEVER going to be as big as uint.MAX_VALUE:</p>

```<code>package{
  public class MyClass{
    private var _x:uint = uint.MAX_VALUE;
    public function set x(x:uint){
      if (x != MAX_VALUE)
        //error
      _x = x;
    }
  }
}
</code>```

Body:
Solution found thanks to everyone's answers. Check bottom of this post.

I am using MVC and the problem concerns my model. With my code I am creating a board which in turn creates tiles. Every tile on the board gets an X and a Y value. After this I want to prevent access to the setter to prevent myself from accidentally changing the value ever again.

I was thinking of using a constant instead of a variable, but it seems I have to define the value at the time of creation. In other words: const myConst:uint; myConst = 2; // does not work

Right now I have a work-around which I am not happy with. Surely there's a cleaner way. You can see my work-around below.

package myboardgame
{
 internal class Tile
 {
  private var _x:uint;
  private var _y:uint;

  private var _xLock:Boolean; // Makes sure that the X and Y values of a tile can only be set once to prevent errors
  private var _yLock:Boolean; //  " "

  internal function set x(x:uint):void
  { if(!_xLock) {_x = x; _xLock = true;} else { throw new Error("Trying to change the one-time write access X tile value")}}
  internal function get x():uint
  { return _x; }
 }
}

Edit. The solution I went with:

package myboardgame
{
    internal class Tile
{
    private var _x:uint;
    private var _y:uint;

    public function Tile(x:uint, y:uint):void
    {
        _x = x;
        _y = y;
    }
    internal function get x():uint
    { return _x; }

    internal function get y():uint
    { return _y; }
}
}

Body:
Assuming your variables are NEVER going to be as big as uint.MAX_VALUE:

package{
  public class MyClass{
    private var _x:uint = uint.MAX_VALUE;
    public function set x(x:uint){
      if (x != MAX_VALUE)
        //error
      _x = x;
    }
  }
}


问:
Below Code is not printing anything
```<code>#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int ma(float array[], int N)
{
    int k = 0;
    float max = array[k];
    for (int i = 0; i < N; ++i) {
        if (array[i] > max) {
            max = array[i];
            k = i;
        }
    }
    return k;
}

int main()
{
    int t;
    while (t--) {
        int n;
        cin >> n;
        int w[n], p[n];
        for (int i = 0; i < n; i++)
            cin >> w[i];
        for (int i = 0; i < n; i++)
            cin >> p[i];
        float x[n];
        for (int i = 0; i < n; i++)
            x[i] = p[i] / w[i];
        int weigth = 0, profit = 0;
        while (weigth <= 20) {
            // int k=distance(x, max_element(x, x + n));
            // int k=  std::distance(x, max_element(x, x + sizeof(x)/sizeof(x)));
            int k = ma(x, n);
            weigth = weigth + w[k];
            profit = profit + p[k];
            x[k] = p[k] = w[k] = 0;
        }
        cout << weigth << endl
             << profit << endl;
    }
}
</code>```

The above code is not printing anything. If you want the question refer to "catch-the-match":

答: You have to declare int n as a const int n in order for you code to compile correctly.

Title: Below Code is not printing anything

Body:
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int ma(float array[], int N)
{
    int k = 0;
    float max = array[k];
    for (int i = 0; i < N; ++i) {
        if (array[i] > max) {
            max = array[i];
            k = i;
        }
    }
    return k;
}

int main()
{
    int t;
    while (t--) {
        int n;
        cin >> n;
        int w[n], p[n];
        for (int i = 0; i < n; i++)
            cin >> w[i];
        for (int i = 0; i < n; i++)
            cin >> p[i];
        float x[n];
        for (int i = 0; i < n; i++)
            x[i] = p[i] / w[i];
        int weigth = 0, profit = 0;
        while (weigth <= 20) {
            // int k=distance(x, max_element(x, x + n));
            // int k=  std::distance(x, max_element(x, x + sizeof(x)/sizeof(x)));
            int k = ma(x, n);
            weigth = weigth + w[k];
            profit = profit + p[k];
            x[k] = p[k] = w[k] = 0;
        }
        cout << weigth << endl
             << profit << endl;
    }
}

The above code is not printing anything. If you want the question refer to "catch-the-match":