问:
HTML Responsiveness
This is the structure of my HTML and CSS:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
    <!-- LEFT SIDE -->
    <div id="video-container" class="col-xs-8 col-sm-8">
        <div class="row">
            <div id="video" class="col-xs-12 col-sm-12">
                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>
            </div>
        </div>
        <div class="row">
            <div id="banner" class="col-xs-12 col-sm-12 text-center">SAMPLE BANNER</div>
        </div>
        <div class="row">
            <div id="ctrl1" class="col-xs-6 col-sm-6"></div>
            <div id="ctrl2" class="col-xs-6 col-sm-6"></div>
        </div>
    </div>

    <!-- RIGHT SIDE -->
    <div id="updates-container" class="col-xs-4 col-sm-4">
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 1
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 2
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 3
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 4
            </div>
        </div>
    </div>
</div></code>```

Now my problem is, How would i position the DIV updates-container (the one with the red background) to the bottom when the browser screen is small ..

答:
since you're using the bootstrap grid lay-out you're able to use some small tricks to achieve what you want.

As you know bootstrap makes use of 12 columns on one row. So if we would want to create a full width block we'll use col-12.

The lg, md, sm, xs refer to the width of the screen.

lg for large screens (≥ 1200px)

md for medium screens (≥ 992px)

sm for small screens (≥ 576px)

xs for extra small screens (< 576px)

reference

You want that the red area will be on a full-width new <row> on small devices. See the working example below:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
    <!-- LEFT SIDE -->
    <div id="video-container" class="col-xs-8 col-sm-8">
        <div class="row">
            <div id="video" class="col-xs-12 col-sm-12">
                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>
            </div>
        </div>
        <div class="row">
            <div id="banner" class="col-xs-12 col-sm-12 text-center">SAMPLE BANNER</div>
        </div>
        <div class="row">
            <div id="ctrl1" class="col-xs-6 col-sm-6"></div>
            <div id="ctrl2" class="col-xs-6 col-sm-6"></div>
        </div>
    </div>

    <!-- RIGHT SIDE -->
    <div id="updates-container" class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 1
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 2
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 3
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 4
            </div>
        </div>
    </div>
</div></code>```

By adding the lg, md, sm, xs specifics you're able to change the view for each screentype. In this case i've edited the following line:

```<code><div id="updates-container" class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
</code>```

On the lg and md view it will act as a sidebar. Where on the sm view it'll take up half of the screens width. on the xs view each
 inside updates-container will have a full width of the screen.

Hope this helps!

Title: HTML Responsiveness

Body:
This is the structure of my HTML and CSS:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>

SAMPLE BANNER

                SAMPLE UPDATE 1

                SAMPLE UPDATE 2

                SAMPLE UPDATE 3

                SAMPLE UPDATE 4

Now my problem is, How would i position the DIV updates-container (the one with the red background) to the bottom when the browser screen is small ..

Body:
since you're using the bootstrap grid lay-out you're able to use some small tricks to achieve what you want.

As you know bootstrap makes use of 12 columns on one row. So if we would want to create a full width block we'll use col-12.

The lg, md, sm, xs refer to the width of the screen.

lg for large screens (≥ 1200px)

md for medium screens (≥ 992px)

sm for small screens (≥ 576px)

xs for extra small screens (< 576px)

reference

You want that the red area will be on a full-width new <row> on small devices. See the working example below:

/* IMPORTS */

/* COMMON STYLES */
html, body {
 margin: 0;
 height: 100%;
 overflow: hidden
}

h1, h2, h3, h4, h5, h6 {
 margin-top: 5px;
 margin-bottom: 5px;
}

/* PAGE STYLES */
#video-container {
 padding: 0;
 height: 100vh;
}

#video {
 background-color: #6d6;
 height: 65vh;
}

#tv {
 position: absolute;
 top: 0;
 right: 15px;
 height: 50%;
}

#banner {
 height: 5vh;
 background-color: #fff;
}

#ctrl1, #ctrl2 {
 height: 30vh;
}

#ctrl1 {
 background-color: #66d;
}

#ctrl2 {
 background-color: #6dd;
}

#updates-container {
 padding: 0 15px;
 background-color: #d66;
 height: 100vh;
 overflow: auto;
}

.update-data {
 height: 35vh;
 border-bottom: dashed 1px #000;
}

.update-data:last-child {
 border-bottom: none !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="row">
    <!-- LEFT SIDE -->
    <div id="video-container" class="col-xs-8 col-sm-8">
        <div class="row">
            <div id="video" class="col-xs-12 col-sm-12">
                <video autoplay loop id="tv">
                    <source type="video/mp4" src="https://static.videezy.com/system/resources/previews/000/005/571/original/keyboard_02.mp4">
                    <source type="application/ogg" src="https://static.videezy.com/system/resources/preview2s/000/005/571/original/keyboard_02.ogv">
                    <source type="video/webm" src="https://static.videezy.com/system/resources/preview3s/000/005/571/original/keyboard_02.webm">
                    Your browser does not support the video tag.
                </video>
            </div>
        </div>
        <div class="row">
            <div id="banner" class="col-xs-12 col-sm-12 text-center">SAMPLE BANNER</div>
        </div>
        <div class="row">
            <div id="ctrl1" class="col-xs-6 col-sm-6"></div>
            <div id="ctrl2" class="col-xs-6 col-sm-6"></div>
        </div>
    </div>

    <!-- RIGHT SIDE -->
    <div id="updates-container" class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 1
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 2
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 3
            </div>
        </div>
        <div class="update-data row">
            <div class="col-xs-12 col-sm-12">
                SAMPLE UPDATE 4
            </div>
        </div>
    </div>
</div>

By adding the lg, md, sm, xs specifics you're able to change the view for each screentype. In this case i've edited the following line:

<div id="updates-container" class="col-lg-4 col-md-4 col-sm-6 col-xs-12">

On the lg and md view it will act as a sidebar. Where on the sm view it'll take up half of the screens width. on the xs view each <div> inside updates-container will have a full width of the screen.

Hope this helps!


来源: stackexchange

问:
Pushing an object with unique_ptr into vector in C++
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

```<code>#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}
</code>```

I get compiler errors when adding the new state object to the vector:

```<code>Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
</code>```

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

```<code>int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}
</code>```

答:
```<code>// This line causes compiler errors
states.push_back(nstate);
</code>```

The nstate object is an instance of the State class. The State class contains two data members: an int (which is copyable), and a vector of unique_ptrs, that is movable but not copyable (since unique_ptr is movable but not copyable). As a result of that, the whole State class is movable but not copyable. So, you must std::move the nstate object into the states vector:

```<code>states.push_back(std::move(nstate));
</code>```

If you want copy semantics, you should use a vector of shared_ptrs (that are reference counted smart pointers, and are both copyable and movable).

I would do also a few modifications to your State class code:

```<code>class State {
    public:
        State(int num) : num(num), transitions() {}
</code>```

Here, you should mark the constructor explicit, to avoid implicit conversions from int. Moreover, the std::vector data member is automatically initialized, no need to use transitions() here.

Moreover, considering this line of code:

```<code>states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
</code>```

you should to use std::make_unique (introduced in C++14) instead of constructing a std::unique_ptr with the raw pointer returned by an explicit call to new.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}

I get compiler errors when adding the new state object to the vector:

Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}

Body:
// This line causes compiler errors
states.push_back(nstate);

The nstate object is an instance of the State class. The State class contains two data members: an int (which is copyable), and a vector of unique_ptrs, that is movable but not copyable (since unique_ptr is movable but not copyable). As a result of that, the whole State class is movable but not copyable. So, you must std::move the nstate object into the states vector:

states.push_back(std::move(nstate));

If you want copy semantics, you should use a vector of shared_ptrs (that are reference counted smart pointers, and are both copyable and movable).

I would do also a few modifications to your State class code:

class State {
    public:
        State(int num) : num(num), transitions() {}

Here, you should mark the constructor explicit, to avoid implicit conversions from int. Moreover, the std::vector data member is automatically initialized, no need to use transitions() here.

Moreover, considering this line of code:

states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));

you should to use std::make_unique (introduced in C++14) instead of constructing a std::unique_ptr with the raw pointer returned by an explicit call to new.


问:
Representing syntactically different terms in TPTP
I am having a look at first order logic theorem provers such as Vampire and E-Prover, and the TPTP syntax seems to be the way to go. I am more familiar with Logic Programming syntaxes such as Answer Set Programming and Prolog, and although I try refering to a detailed description of the TPTP syntax I still don't seem to grasp how to properly distinguish between interpreted and non interpreted functor (and I might be using the terminology wrong).

Essentially, I am trying to prove a theorem by showing that no model acts as a counter-example. My first difficulty was that I did not expect the following logic program to be satisfiable.

```<code>fof(all_foo, axiom, ![X] : (pred(X) => (X = foo))).
fof(exists_bar, axiom, pred(bar)).
</code>```

It is indeed satisfiable because nothing prevents bar from being equal to foo. So a first solution would be to insist that these two terms are distinct and we obtain the following unsatisfiable program.

```<code>fof(all_foo, axiom, ![X] : pred(X) => (X = foo)).
fof(exists_bar, axiom, pred(bar)).
fof(foo_not_bar, axiom, foo != bar).
</code>```

The Techinal Report clarifies that different double quoted strings are different objects indeed, so another solution is to put quotes here and there, so as to obtain the following unsatisfiable program.

```<code>fof(all_foo, axiom, ![X] : (pred(X) => (X = "foo"))).
fof(exists_bar, axiom, pred("bar")).
</code>```

I am happy not to have manually specify the inequality as that would obviously not scale to a more realistic scenario. Moving closer to my real situation, I actually have to handle composed terms, and the following program is unfortunately satisfiable.

```<code>fof(all_foo, axiom, ![X] : (pred(X) => (X = f("foo")))).
fof(exists_bar, axiom, pred(g("bar"))).
</code>```

I guess f("foo") is not a term but the function f applied to the object "foo". So it could potentially coincide with function g. Although a manual specification that f and g never coincide does the trick, the following program is unsatisfiable, I feel like I'm doing it wrong. And it probably wouldn't scale to my real setting with plenty of terms all to be interpreted as distinct when they are syntactically distinct.

```<code>fof(all_foo, axiom, ![X] : (pred(X) => (X = f("foo")))).
fof(exists_bar, axiom, pred(g("bar"))).
fof(f_not_g, axiom, ![X, Y] : f(X) != g(Y)).
</code>```

I have tried throwing single quotes around, but I didn't find the proper way to do it.

How do I make syntactically different (composed) terms and test for syntactical equality?

Subsidiary question: the following program is satisfiable, because the automated-theorem prover understands f as a function rather than a uninterpreted functor.

```<code>fof(exists_f_g, axiom, (?[I] : ((f(foo) = f(I)) & pred(g(I))))).
fof(not_g_foo, axiom, ~pred(g(foo))).
</code>```

To make it unsatisfiable, I need to manually specify that f is injective. What would be the natural way to obtain this behaviour without specifying injectivity of all functors that occur in my program?

```<code>fof(exists_f_g, axiom, (?[I] : ((f(foo) = f(I)) & pred(g(I))))).
fof(not_g_foo, axiom, ~pred(g(foo))).
fof(f_injective, axiom, ![X,Y] : (f(X) = f(Y) => (X = Y))).
</code>```

答:
First of all let me point you to the Syntax BNF of TPTP. In principle, you have Prolog terms with some predefined infix/prefix operators of appropriate precedences. This means, variables are written in upper case and constants are written in lower case. Also like Prolog, escaping with single quotes allows us to write a constant starting with a capital letter i.e. 'X'. I have never seen double quoted atoms so far, so you might want look up the instructions of the prover on how to interpret them.

But even though the syntax is Prolog-ish, automated theorem proving is a different kind of beast. There is no closed world assumption nor are different constants assumed to be different - that's why you cannot find a proof for:

```<code>fof(c1, conjecture, a=b ).
</code>```

and neither for:

```<code>fof(c1, conjecture, ~(a=b) ).
</code>```

So if you want to have syntactic dis-equality, you need to axiomatize it. Now, assuming a different from b trivially shows that they are different, so I at least claimed: "Suppose there are two different constants a and b, then there exists some variable which is not b."

```<code>fof(a1, axiom, ~(a=b)).
fof(c1, conjecture, ?[X]: ~(X=b)).
</code>```

Since functions in first-order logic are not necessarily injective, you also don't get around of adding your assumption in there.

Please also note the different roles of input formulas: so far you only stated axioms and no conjectures i.e. you ask the prover to show your axiom set to be inconsistent. Some provers might even give up because they use some resolution refinements (e.g. set of support) which restricts resolution between axioms[1]. In any case, you need to be aware that the formula you are trying to prove is of the form A1 ∧ ... ∧ An → C1 ∨ ... Cm where the A are axioms and the C are conjectures.[2]

I hope that at least the syntax is a bit clearer now - unfortunately the answer to the questions is more that atomated theorem provers don't make the same assumptions as you expect, so you have to axiomatize them. These axiomatizations are also often ineffective and you might get better perfomance from specialized tools.

[1] As you already notice, advanced provers like Vampire or E Prover tell you about (counter-)satisfyability instead.

[2] A resolution based theorem prover will first negate that formula and perform a CNF transformation, but even though most TPTP accepting provers are resolution based, that's not a requirement.

Body:
I am having a look at first order logic theorem provers such as Vampire and E-Prover, and the TPTP syntax seems to be the way to go. I am more familiar with Logic Programming syntaxes such as Answer Set Programming and Prolog, and although I try refering to a detailed description of the TPTP syntax I still don't seem to grasp how to properly distinguish between interpreted and non interpreted functor (and I might be using the terminology wrong).

Essentially, I am trying to prove a theorem by showing that no model acts as a counter-example. My first difficulty was that I did not expect the following logic program to be satisfiable.

fof(all_foo, axiom, ![X] : (pred(X) => (X = foo))).
fof(exists_bar, axiom, pred(bar)).

It is indeed satisfiable because nothing prevents bar from being equal to foo. So a first solution would be to insist that these two terms are distinct and we obtain the following unsatisfiable program.

fof(all_foo, axiom, ![X] : pred(X) => (X = foo)).
fof(exists_bar, axiom, pred(bar)).
fof(foo_not_bar, axiom, foo != bar).

The Techinal Report clarifies that different double quoted strings are different objects indeed, so another solution is to put quotes here and there, so as to obtain the following unsatisfiable program.

fof(all_foo, axiom, ![X] : (pred(X) => (X = "foo"))).
fof(exists_bar, axiom, pred("bar")).

I am happy not to have manually specify the inequality as that would obviously not scale to a more realistic scenario. Moving closer to my real situation, I actually have to handle composed terms, and the following program is unfortunately satisfiable.

fof(all_foo, axiom, ![X] : (pred(X) => (X = f("foo")))).
fof(exists_bar, axiom, pred(g("bar"))).

I guess f("foo") is not a term but the function f applied to the object "foo". So it could potentially coincide with function g. Although a manual specification that f and g never coincide does the trick, the following program is unsatisfiable, I feel like I'm doing it wrong. And it probably wouldn't scale to my real setting with plenty of terms all to be interpreted as distinct when they are syntactically distinct.

fof(all_foo, axiom, ![X] : (pred(X) => (X = f("foo")))).
fof(exists_bar, axiom, pred(g("bar"))).
fof(f_not_g, axiom, ![X, Y] : f(X) != g(Y)).

I have tried throwing single quotes around, but I didn't find the proper way to do it.

How do I make syntactically different (composed) terms and test for syntactical equality?

Subsidiary question: the following program is satisfiable, because the automated-theorem prover understands f as a function rather than a uninterpreted functor.

fof(exists_f_g, axiom, (?[I] : ((f(foo) = f(I)) & pred(g(I))))).
fof(not_g_foo, axiom, ~pred(g(foo))).

To make it unsatisfiable, I need to manually specify that f is injective. What would be the natural way to obtain this behaviour without specifying injectivity of all functors that occur in my program?

fof(exists_f_g, axiom, (?[I] : ((f(foo) = f(I)) & pred(g(I))))).
fof(not_g_foo, axiom, ~pred(g(foo))).
fof(f_injective, axiom, ![X,Y] : (f(X) = f(Y) => (X = Y))).

Body:
First of all let me point you to the Syntax BNF of TPTP. In principle, you have Prolog terms with some predefined infix/prefix operators of appropriate precedences. This means, variables are written in upper case and constants are written in lower case. Also like Prolog, escaping with single quotes allows us to write a constant starting with a capital letter i.e. 'X'. I have never seen double quoted atoms so far, so you might want look up the instructions of the prover on how to interpret them.

But even though the syntax is Prolog-ish, automated theorem proving is a different kind of beast. There is no closed world assumption nor are different constants assumed to be different - that's why you cannot find a proof for:

fof(c1, conjecture, a=b ).

and neither for:

fof(c1, conjecture, ~(a=b) ).

So if you want to have syntactic dis-equality, you need to axiomatize it. Now, assuming a different from b trivially shows that they are different, so I at least claimed: "Suppose there are two different constants a and b, then there exists some variable which is not b."

fof(a1, axiom, ~(a=b)).
fof(c1, conjecture, ?[X]: ~(X=b)).

Since functions in first-order logic are not necessarily injective, you also don't get around of adding your assumption in there.

Please also note the different roles of input formulas: so far you only stated axioms and no conjectures i.e. you ask the prover to show your axiom set to be inconsistent. Some provers might even give up because they use some resolution refinements (e.g. set of support) which restricts resolution between axioms[1]. In any case, you need to be aware that the formula you are trying to prove is of the form A1 ∧ ... ∧ An → C1 ∨ ... Cm where the A are axioms and the C are conjectures.[2]

I hope that at least the syntax is a bit clearer now - unfortunately the answer to the questions is more that atomated theorem provers don't make the same assumptions as you expect, so you have to axiomatize them. These axiomatizations are also often ineffective and you might get better perfomance from specialized tools.

[1] As you already notice, advanced provers like Vampire or E Prover tell you about (counter-)satisfyability instead.

[2] A resolution based theorem prover will first negate that formula and perform a CNF transformation, but even though most TPTP accepting provers are resolution based, that's not a requirement.


问:
RecyclewView with nested gridView adjust height
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>
</code>```

RecyclewView Item

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>
</code>```

GridView Item (just for example)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>
</code>```

Can you help me to get the example view?

Thank you.

答:
Call the notifyDataSetChanged() or notifyItemChanged(int position) methods of the RecyclerView.Adapter from the MAIN THREAD.

I hope this can help you

Body:
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>

RecyclewView Item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>

GridView Item (just for example)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>

Can you help me to get the example view?

Thank you.


问:
Spark - Scala - Remove Columns from a dataframe based on condition
We have a specific need wherein I will have to drop columns from a dataframe which has only one unique value in that column. The following is what we are doing

```<code>val rawdata = spark.read.format("csv").option("header","true").option("inferSchema","true").load(filename)
</code>```

Subsequently to find unique values in all columns we are using the HyperLog++ algorithm supported in spark

```<code>val cd_cols  = rawdata.select(rawdata.columns.map(column => approxCountDistinct(col(column)).alias(column)): _*)
</code>```

The output is

```<code>scala> cd_cols.show
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|  ID|First Name|Last Name|Age|Attrition|BusinessTravel|DailyRate|Department|DistanceFromHome|Education|EducationField|EmployeeCount|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|1491|       172|      154| 43|        2|             3|      913|         3|              30|        1|             6|            1|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
</code>```

Notice that I have two columns which has a 1 as the unique value. I want to create another dataframe which has all columns except those two columns (Education and EmployeeCount)

I tried using a for loop, but was not very happy and also tried

```<code>cd_cols.columns.filter(colName => cd_cols.filter(colName) <= 1)
</code>```

that is also not working.

Is there a smarter way to do this please.

Thanks

Bala

答:
You try the following command:

```<code>df.selectExpr(df.first().getValuesMap[Int](df.columns).filter(_._2 != 1).keys.toSeq: _*).show
</code>```

Here we are first taking the first row of the dataframe and converting it into a map using getValueMap with the column names and just filtering the columns whose value is not 1.

Body:
We have a specific need wherein I will have to drop columns from a dataframe which has only one unique value in that column. The following is what we are doing

val rawdata = spark.read.format("csv").option("header","true").option("inferSchema","true").load(filename)

Subsequently to find unique values in all columns we are using the HyperLog++ algorithm supported in spark

val cd_cols  = rawdata.select(rawdata.columns.map(column => approxCountDistinct(col(column)).alias(column)): _*)

The output is

scala> cd_cols.show
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|  ID|First Name|Last Name|Age|Attrition|BusinessTravel|DailyRate|Department|DistanceFromHome|Education|EducationField|EmployeeCount|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|1491|       172|      154| 43|        2|             3|      913|         3|              30|        1|             6|            1|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+

Notice that I have two columns which has a 1 as the unique value. I want to create another dataframe which has all columns except those two columns (Education and EmployeeCount)

I tried using a for loop, but was not very happy and also tried

cd_cols.columns.filter(colName => cd_cols.filter(colName) <= 1)

that is also not working.

Is there a smarter way to do this please.

Thanks

Bala

Body:
You try the following command:

df.selectExpr(df.first().getValuesMap[Int](df.columns).filter(_._2 != 1).keys.toSeq: _*).show

Here we are first taking the first row of the dataframe and converting it into a map using getValueMap with the column names and just filtering the columns whose value is not 1.


问:
BrowserStack + Nightwatch.js How to set up proxy which is password protected (ERROR: httpProxy was not of the form host[:port]
BrowserStack + Nightwatch.js How to set up proxy which is password protected

```<code>  common_capabilities: {
    'browserstack.user': 'user',
    'browserstack.key': 'key',
    'browserstack.debug': true,
},
test_settings: {
    default: {
        desiredCapabilities: {
            'os': 'OS X',
            'os_version': 'Sierra',
            'browser': 'Firefox',
            'browser_version': '53.0',
            'resolution': '1280x960',
            "acceptSslCerts": 'false',
            'proxy': {
                'httpProxy': 'user:password@server:80',
                'protocol': 'http',
                'proxyType': 'manual',
                //'httpProxy': 'server:80',
                //'user': 'user',
                //'pass': 'password'
            }
        },
</code>```

I have en ERROR:

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?

message: 'Could not start Browser / Emulator

Reason:  httpProxy was not of the form host[:port]

答:
BrowserStack Support asked me to provide my solution based on the specifics of my setup:
I had to use BrowserStack.local

```<code>  "scripts": {
      "test": "./bin/BrowserStackLocal --key ACCESS_KEY --local-proxy-host PROXY_HOST --local-proxy-port PROXY_PORT --local-proxy-user PROXY_USER --local-proxy-pass PROXY_PASS --local-identifier Test123 & ./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests",
      "local": "./bin/BrowserStackLocal --key ACCESS_KEY --local-identifier Test123 && ./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests",
      "nightwatch": "./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests"
  },
</code>```

1st step: launching BrowserStackLocal through Proxy (in one Terminal's window
2nd step: run tests in "tests" folder

Body:
BrowserStack + Nightwatch.js How to set up proxy which is password protected

  common_capabilities: {
    'browserstack.user': 'user',
    'browserstack.key': 'key',
    'browserstack.debug': true,
},
test_settings: {
    default: {
        desiredCapabilities: {
            'os': 'OS X',
            'os_version': 'Sierra',
            'browser': 'Firefox',
            'browser_version': '53.0',
            'resolution': '1280x960',
            "acceptSslCerts": 'false',
            'proxy': {
                'httpProxy': 'user:password@server:80',
                'protocol': 'http',
                'proxyType': 'manual',
                //'httpProxy': 'server:80',
                //'user': 'user',
                //'pass': 'password'
            }
        },

I have en ERROR:

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?

message: 'Could not start Browser / Emulator

Reason:  httpProxy was not of the form host[:port]

Body:
BrowserStack Support asked me to provide my solution based on the specifics of my setup:
I had to use BrowserStack.local

  "scripts": {
      "test": "./bin/BrowserStackLocal --key ACCESS_KEY --local-proxy-host PROXY_HOST --local-proxy-port PROXY_PORT --local-proxy-user PROXY_USER --local-proxy-pass PROXY_PASS --local-identifier Test123 & ./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests",
      "local": "./bin/BrowserStackLocal --key ACCESS_KEY --local-identifier Test123 && ./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests",
      "nightwatch": "./node_modules/nightwatch/bin/nightwatch -c conf/local.conf.js tests"
  },

1st step: launching BrowserStackLocal through Proxy (in one Terminal's window
2nd step: run tests in "tests" folder


问:
Laravel 5.4 - Eloquent : Join 3 tables and return 1 collection
I recently started using laravel and having some issues with eloquent join .

I want to join 3 tables :

User (id)

UserBills (id , user_id , company_id , account)

Bills (id , company_id , account , amount)

I start with the user id (e.g=1)

From that i want to query UserBills and find all UB where the user_id = id
Next i want to query bills and find all bills where the bill company_id and account match UserBills

Basically i want to find all the bills that belong to that specific user . Bills does not have user_id however and must check with UserBills(company_id and account)

// This return all user bills with id = user_id

```<code>$results = User::findOrFail(1);
$ub = $results->user_bills;
</code>```

From there , i have no idea how to join the bills or get the collection . Any help would be much appreciated.

Models (might be wrong)

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Eloquent;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [

        'name',
        'email',
        'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function user_bills()
    {
        return $this->hasMany('App\UserBills', 'user_id', 'id');
    }
}
</code>```

UserBills

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserBills extends Model
{

    protected $table = 'ub';

    protected $fillable =
    [
        'user_id',
        'company_id',
        'account',
    ];

    public function user()
    {
        return $this->belongsTo('App\User' , 'id' , 'user_id');
    }

}
</code>```

Bills :

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bills extends Model
{

    protected $table = 'bills';

    protected $fillable =
    [
        'company_id',
        'account',
        'period',
        'amount',
    ];

    public function user_bills()
    {
        return $this->belongsTo('App\UserBills');
    }

}
</code>```

答:
You can read your solution in the docs of HasManyThrough if your UserBills hasMany Bills.

I can't test this code right now, so you can see it as an example:

```<code>class User extends Authenticatable {

   ...

  public function Bills()
  {
    return $this->hasManyThrough('App\UserBills', 'App\Bills');
  }

}
</code>```

Now you can get all bills of the user with

```<code>$User = User::findOrFail(1);
$Bills = $User->Bills()->get(); // collection with bills of your user instance
</code>```

Edit #1

You should add a bill_id into the UserBills table ub.

Now you can try this code

```<code>class User extends Authenticatable {

  ...

  public function getBillsAttribute() {
    $user_id = $this->id;

    return App\Bills::rightJoin('ub', function($join) use ($user_id) {
      $join->on('ub.bill_id', '=', 'bills.id')
           ->where('ub.user_id', '=', $user_id);
    })->get();
  }

}
</code>```

Use it like that

```<code>$User = User::findOrFail(1);
$Bills = $User->Bills; // collection with bills of your user instance
</code>```

Body:
I recently started using laravel and having some issues with eloquent join .

I want to join 3 tables :

User (id)

UserBills (id , user_id , company_id , account)

Bills (id , company_id , account , amount)

I start with the user id (e.g=1)

From that i want to query UserBills and find all UB where the user_id = id
Next i want to query bills and find all bills where the bill company_id and account match UserBills

Basically i want to find all the bills that belong to that specific user . Bills does not have user_id however and must check with UserBills(company_id and account)

// This return all user bills with id = user_id

$results = User::findOrFail(1);
$ub = $results->user_bills;

From there , i have no idea how to join the bills or get the collection . Any help would be much appreciated.

Models (might be wrong)

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Eloquent;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [

        'name',
        'email',
        'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function user_bills()
    {
        return $this->hasMany('App\UserBills', 'user_id', 'id');
    }
}

UserBills

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserBills extends Model
{

    protected $table = 'ub';

    protected $fillable =
    [
        'user_id',
        'company_id',
        'account',
    ];

    public function user()
    {
        return $this->belongsTo('App\User' , 'id' , 'user_id');
    }

}

Bills :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bills extends Model
{

    protected $table = 'bills';

    protected $fillable =
    [
        'company_id',
        'account',
        'period',
        'amount',
    ];

    public function user_bills()
    {
        return $this->belongsTo('App\UserBills');
    }

}

Body:
You can read your solution in the docs of HasManyThrough if your UserBills hasMany Bills.

I can't test this code right now, so you can see it as an example:

class User extends Authenticatable {

   ...

  public function Bills()
  {
    return $this->hasManyThrough('App\UserBills', 'App\Bills');
  }

}

Now you can get all bills of the user with

$User = User::findOrFail(1);
$Bills = $User->Bills()->get(); // collection with bills of your user instance

Edit #1

You should add a bill_id into the UserBills table ub.

Now you can try this code

class User extends Authenticatable {

  ...

  public function getBillsAttribute() {
    $user_id = $this->id;

    return App\Bills::rightJoin('ub', function($join) use ($user_id) {
      $join->on('ub.bill_id', '=', 'bills.id')
           ->where('ub.user_id', '=', $user_id);
    })->get();
  }

}

Use it like that

$User = User::findOrFail(1);
$Bills = $User->Bills; // collection with bills of your user instance


问:
ERROR 1046:No database selected
I would  like  to create a SQL database  but this error occurs I do not know why. Can somebody  help  me?

My SQL statement:

```<code>CREATE TABLE 'users'(
    'user_id' int (11) NOT NULL AUTO_INCREMENT,
    'username' varchar (255) DEFAULT NULL,
    'password' varchar (255) DEFAULT NULL,
    PRIMARY KEY ('user_id')
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
</code>```

Can somebody help me?

答:
Firstly you need to tell MySQL which database you would like to use to create a table:

```<code>USE your_database_name;
</code>```

If your database does not exist yet, you have to create one:

```<code>CREATE DATABASE your_database_name;
</code>```

then tell MySQL that you want to use it:

```<code>USE your_database_name;
</code>```

and then you can create a table.

Hope it will help you to solve this problem :)

Title: ERROR 1046:No database selected

Body:
I would  like  to create a SQL database  but this error occurs I do not know why. Can somebody  help  me?

My SQL statement:

CREATE TABLE 'users'(
    'user_id' int (11) NOT NULL AUTO_INCREMENT,
    'username' varchar (255) DEFAULT NULL,
    'password' varchar (255) DEFAULT NULL,
    PRIMARY KEY ('user_id')
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

Can somebody help me?

Body:
Firstly you need to tell MySQL which database you would like to use to create a table:

USE your_database_name;

If your database does not exist yet, you have to create one:

CREATE DATABASE your_database_name;

then tell MySQL that you want to use it:

USE your_database_name;

and then you can create a table.

Hope it will help you to solve this problem :)


问:
Could not validate the All type conditions using Javascript
I need one help. I am unable to validate properly the conditions present inside if statement using JavaScript.I am explaining my code below.

```<code><?php if($_REQUEST['ids']!=""){ ?>
var isEdit=true;
var edithidnCouponimage=document.getElementById('hidnCouponimage').value;
var edithidnLogoimage=document.getElementById('hidnLogoimage').value;
 <?php }else{ ?>
 var isEdit=false;
var edithidnCouponimage='';
var edithidnLogoimage='';
 <?php } ?>
if(isEdit==false){
  if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
  alert('Please select jpg/jpeg/png type image for coupon image');
  return;
        }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
            alert('Please select jpg/jpeg/png type image for coupon logo');
            return;
        }else{
            return true;
        }
}else{
   $('#btncouponsubmit').removeAttr("disabled")
   $('#blankImagediv').css('display', 'block');
   $('#nonblankimagediv').css('display', 'none');
}
</code>```

Here my problem is when first if statement is true and inside it its checking both if statement if those are not true it should come back from parent if statement and should enter into else part for the checking display block/none but its not happening like that once its entering into first if statement its not entering into else part.Please help me.

答:
The easy way is to copy else block for your need:

```<code>if(isEdit==false){
    if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
        alert('Please select jpg/jpeg/png type image for coupon image');
        return;
    }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
        alert('Please select jpg/jpeg/png type image for coupon logo');
        return;
    }else{
        $('#btncouponsubmit').removeAttr("disabled")
        $('#blankImagediv').css('display', 'block');
        $('#nonblankimagediv').css('display', 'none');
        return true;
    }
}else{
    $('#btncouponsubmit').removeAttr("disabled")
    $('#blankImagediv').css('display', 'block');
    $('#nonblankimagediv').css('display', 'none');
}
</code>```

If you don't want to duplicate code move the duplicate part to a function

```<code>if(isEdit==false){
  if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
    alert('Please select jpg/jpeg/png type image for coupon image');
    return;
  }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
    alert('Please select jpg/jpeg/png type image for coupon logo');
    return;
  }else{
    enable();
    return true;
  }
}else{
  enable();
}

function enable() {
  $('#btncouponsubmit').removeAttr("disabled")
  $('#blankImagediv').css('display', 'block');
  $('#nonblankimagediv').css('display', 'none');
}
</code>```

Body:
I need one help. I am unable to validate properly the conditions present inside if statement using JavaScript.I am explaining my code below.

<?php if($_REQUEST['ids']!=""){ ?>
var isEdit=true;
var edithidnCouponimage=document.getElementById('hidnCouponimage').value;
var edithidnLogoimage=document.getElementById('hidnLogoimage').value;
 <?php }else{ ?>
 var isEdit=false;
var edithidnCouponimage='';
var edithidnLogoimage='';
 <?php } ?>
if(isEdit==false){
  if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
  alert('Please select jpg/jpeg/png type image for coupon image');
  return;
        }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
            alert('Please select jpg/jpeg/png type image for coupon logo');
            return;
        }else{
            return true;
        }
}else{
   $('#btncouponsubmit').removeAttr("disabled")
   $('#blankImagediv').css('display', 'block');
   $('#nonblankimagediv').css('display', 'none');
}

Here my problem is when first if statement is true and inside it its checking both if statement if those are not true it should come back from parent if statement and should enter into else part for the checking display block/none but its not happening like that once its entering into first if statement its not entering into else part.Please help me.

Body:
The easy way is to copy else block for your need:

if(isEdit==false){
    if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
        alert('Please select jpg/jpeg/png type image for coupon image');
        return;
    }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
        alert('Please select jpg/jpeg/png type image for coupon logo');
        return;
    }else{
        $('#btncouponsubmit').removeAttr("disabled")
        $('#blankImagediv').css('display', 'block');
        $('#nonblankimagediv').css('display', 'none');
        return true;
    }
}else{
    $('#btncouponsubmit').removeAttr("disabled")
    $('#blankImagediv').css('display', 'block');
    $('#nonblankimagediv').css('display', 'none');
}

If you don't want to duplicate code move the duplicate part to a function

if(isEdit==false){
  if(!backFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
    alert('Please select jpg/jpeg/png type image for coupon image');
    return;
  }else if(!logoFileInput.files[0].name.match(/.(jpg|jpeg|png|gif)$/i)){
    alert('Please select jpg/jpeg/png type image for coupon logo');
    return;
  }else{
    enable();
    return true;
  }
}else{
  enable();
}

function enable() {
  $('#btncouponsubmit').removeAttr("disabled")
  $('#blankImagediv').css('display', 'block');
  $('#nonblankimagediv').css('display', 'none');
}


问:
How to mock Ruby Module functions?

How can I mock module functions of a self-written module inside my project?

Given the module and function

module ModuleA::ModuleB
  def self.my_function( arg )
  end
end
```

<p>which is called like</p>

<pre class="lang-ruby prettyprint-override"><code>ModuleA::ModuleB::my_function( with_args )
</code>```

How should I mock it when it's used inside a function I'm writing specs for?

Doubling it (obj = double("ModuleA::ModuleB")) makes no sense for me as the function is called on the module and not on an object.

I've tried stubbing it (ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something)). Obviously, it did not work. stub is not defined there.

Then I've tried it with should_receive. Again NoMethodError.

What is the preferred way of mocking a module and it's functions?

答:
For rspec 3.6 see How to mock class method in RSpec expect syntax?

To avoid link-only-answer, here is copy of answer by Andrey Deineko:

```<code>allow(Module)
  .to receive(:profile)
  .with("token")
  .and_return({"name" => "Hello", "id" => "14314141", "email" => "hello@me.com"})
</code>```

Title: How to mock Ruby Module functions?

Body:
How can I mock module functions of a self-written module inside my project?

Given the module and function

module ModuleA::ModuleB
  def self.my_function( arg )
  end
end

which is called like

ModuleA::ModuleB::my_function( with_args )

How should I mock it when it's used inside a function I'm writing specs for?

Doubling it (obj = double("ModuleA::ModuleB")) makes no sense for me as the function is called on the module and not on an object.

I've tried stubbing it (ModuleA::ModuleB.stub(:my_function).with(arg).and_return(something)). Obviously, it did not work. stub is not defined there.

Then I've tried it with should_receive. Again NoMethodError.

What is the preferred way of mocking a module and it's functions?

Body:
For rspec 3.6 see How to mock class method in RSpec expect syntax?

To avoid link-only-answer, here is copy of answer by Andrey Deineko:

allow(Module)
  .to receive(:profile)
  .with("token")
  .and_return({"name" => "Hello", "id" => "14314141", "email" => "hello@me.com"})


问:
Flexbox wrap does not work properly in firefox
Compare example below on chrome and firefox.

It wraps properly on chrome for me, but firefox instead of wrapping, stretches flexbox and overflows parent. So who is right here, chrome or firefox? And how can I achieve same effect as on chrome on both?

html,
body,
#app {
  margin: 0;
  padding: 0;
}

#app {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

#top {
  flex: 0 0 40px;
  background-color: #ff0000;
}

#content {
  flex: 1;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.item {
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
  <div id="top">

  </div>
  <div id="content">
    <div class="item">
      1
    </div>
    <div class="item">
      2
    </div>
    <div class="item">
      3
    </div>
    <div class="item">
      4
    </div>
    <div class="item">
      5
    </div>
    <div class="item">
      6
    </div>
  </div>
</div></code>```

答:
Try setting a min-height and min-width on parent like so</p>

```<code> #content {
 min-height: 0;
 min-width: 0; }
</code>```

Body:
Compare example below on chrome and firefox.

It wraps properly on chrome for me, but firefox instead of wrapping, stretches flexbox and overflows parent. So who is right here, chrome or firefox? And how can I achieve same effect as on chrome on both?

html,
body,
#app {
  margin: 0;
  padding: 0;
}

#app {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

#top {
  flex: 0 0 40px;
  background-color: #ff0000;
}

#content {
  flex: 1;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.item {
  height: 200px;
}

      1

      2

      3

      4

      5

      6

Body:
Try setting a min-height and min-width on parent like so

 #content {
 min-height: 0;
 min-width: 0; }


问:
Buddypress Xprofile Custom Fields Type (Loop user profile field)
I'm trying to create a site where the members can search for each other based on various profile fields like "games", "platform", "skill level" etc.

I want to be able to fetch datas on how many people have different tags on them.

Under the skill level for example i have "beginner", "intermediate" and "hardcore" I wanna grab the number from each so i can pull them out like Beginner: 30 people, intermediate: 199 people etc.

Is this possible? And how?

答:
```<code> global $wpdb;

 $results = $wpdb->query( "SELECT count( `user_id`)  FROM `sf_bp_xprofile_data` WHERE `field_id`= 8 AND `value` = 'woman'" );
</code>```

change field id and value according for you

Body:
 global $wpdb;

 $results = $wpdb->query( "SELECT count( `user_id`)  FROM `sf_bp_xprofile_data` WHERE `field_id`= 8 AND `value` = 'woman'" );

change field id and value according for you


问:
Node.js: Can't insert form data in MongoDB with POST request
I'm trying to insert data into MongoDB with a script. Inserting it through the browser works fine, but not like this. I've followed posts like this but with no sucess. My console does log the data, but then it says

```<code>body: cannot post
</code>```

Can anyone tell me what is wrong with this code? The request file:

```<code>const options = {
    host: '127.0.0.1',
    port: '8081',
    protocol: 'http:',
    path: '/',
    method: 'POST',
     headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var http = require('http');
var req = http.request(options);
var querystring = require('querystring');
var opn = require('opn');
var data = querystring.stringify({
      scoutName: 'john',
      scoutSurname: 'doe',
      scoutPassword:'123'

    });
 //opn('http://127.0.0.1:8081/');

    var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
console.log(data);
req.end();
</code>```

And the server file:

```<code>app.post('/scout_post', urlencodedParser,function (req,res){

   var name= req.body.scoutName,
        surname=req.body.scoutSurname,
        password=req.body.scoutPassword;

            db.collection('scoutPost').insertOne(
                { 'name': name, 'surname': surname,'password':password},
                function (err, r) {
                    assert.equal(null, err);
                    res.send("Document inserted with _id: " + r.insertedId);
                }
            );
     console.log("post received: " + name);

})
</code>```

答:
Use Mongoose for working with MongoDB in Node.js

```<code>var mongoose = require( 'mongoose' );
var Employee = mongoose.model( 'Employee' );

exports.addEmployee=function(req,res){

                  var newEmployee=new Employee();

                  newEmployee.email=req.body.email;
                  newEmployee.name=req.body.name;
                  newEmployee.dob=req.body.dob;
                  newEmployee.sex=req.body.sex;
                  newEmployee.department=req.body.department;
                  newEmployee.age=req.body.age;

                  newEmployee.save(function(err,savedEmployee){
                       if(err){
                          var message="Error occured while storing new employee !!!";
                          console.log(message+"\n"+err);
                          res.status(500).send("Error Occured while saving Employee");
                        }else{
                         res.status(201).send(savedEmployee);
                          }
                 });

              }
</code>```

And here is the mongoose schema

```<code>var employeeSchema = new mongoose.Schema({
  email: {type: String},
  name: {type: String},
  dob: {type: Date},
  sex:{type:String},
  department:{type:String},
  age:{type:Number}
});

mongoose.model( 'Employee', employeeSchema );
</code>```

Body:
I'm trying to insert data into MongoDB with a script. Inserting it through the browser works fine, but not like this. I've followed posts like this but with no sucess. My console does log the data, but then it says

body: cannot post

Can anyone tell me what is wrong with this code? The request file:

const options = {
    host: '127.0.0.1',
    port: '8081',
    protocol: 'http:',
    path: '/',
    method: 'POST',
     headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var http = require('http');
var req = http.request(options);
var querystring = require('querystring');
var opn = require('opn');
var data = querystring.stringify({
      scoutName: 'john',
      scoutSurname: 'doe',
      scoutPassword:'123'

    });
 //opn('http://127.0.0.1:8081/');

    var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
console.log(data);
req.end();

And the server file:

app.post('/scout_post', urlencodedParser,function (req,res){

   var name= req.body.scoutName,
        surname=req.body.scoutSurname,
        password=req.body.scoutPassword;

            db.collection('scoutPost').insertOne(
                { 'name': name, 'surname': surname,'password':password},
                function (err, r) {
                    assert.equal(null, err);
                    res.send("Document inserted with _id: " + r.insertedId);
                }
            );
     console.log("post received: " + name);

})

Body:
Use Mongoose for working with MongoDB in Node.js

var mongoose = require( 'mongoose' );
var Employee = mongoose.model( 'Employee' );

exports.addEmployee=function(req,res){

                  var newEmployee=new Employee();

                  newEmployee.email=req.body.email;
                  newEmployee.name=req.body.name;
                  newEmployee.dob=req.body.dob;
                  newEmployee.sex=req.body.sex;
                  newEmployee.department=req.body.department;
                  newEmployee.age=req.body.age;

                  newEmployee.save(function(err,savedEmployee){
                       if(err){
                          var message="Error occured while storing new employee !!!";
                          console.log(message+"\n"+err);
                          res.status(500).send("Error Occured while saving Employee");
                        }else{
                         res.status(201).send(savedEmployee);
                          }
                 });

              }

And here is the mongoose schema

var employeeSchema = new mongoose.Schema({
  email: {type: String},
  name: {type: String},
  dob: {type: Date},
  sex:{type:String},
  department:{type:String},
  age:{type:Number}
});

mongoose.model( 'Employee', employeeSchema );


问:
Is there any method in Kotlin which allow me to translate a value from a range into another range?
I have a value inside a range of numbers (for instance 0..100) which I want to translate it into another range, (for instance to 0..9). So the result would be:

50 -> 4 or 100 -> 9, ...

Is there any method in Kotlin which helps me in this regard?

答:
I think this should works,

```<code>val original = 0..100
val new = original.step((original.endInclusive - original.start) / 9).map{it /10}.forEach{ println(it)}
</code>```

output,

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

Body:
I think this should works,

val original = 0..100
val new = original.step((original.endInclusive - original.start) / 9).map{it /10}.forEach{ println(it)}

output,

0
1
2
3
4
5
6
7
8
9


问:
Using Distinct with LINQ and Objects
Until recently, I was using a Distinct in LINQ to select a distinct category (an enum) from a table. This was working fine.

I now need to have it distinct on a class containing a category and country (both enums). The Distinct isn't working now.

What am I doing wrong?

答:
I believe this post explains your problem:
http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.

```<code>var distinctItems = items
       .GroupBy(x => x.PropertyToCompare)
       .Select(x => x.First());
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using Distinct with LINQ and Objects

Body:
I believe this post explains your problem:
http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

The content of the above link can be summed up by saying that the Distinct() method can be replaced by doing the following.

var distinctItems = items
       .GroupBy(x => x.PropertyToCompare)
       .Select(x => x.First());


问:
UINavigationBar : Add SearchBar as TitleView
I want to add uisearchbar in place of title of controller.

I am facing 2 problems currently.

1)
I do not know from where this gray background is coming. Please check this picture.

2) I need this searchbar in other inner screens also. But when I push another controller this searchbar is removed.

Here is my code :

```<code>// Seachbar Container View
    let searchBarContainer = ERView(frame: CGRectMake(0,0,280,44))
    searchBarContainer.autoresizingMask = [.FlexibleWidth]
    searchBarContainer.backgroundColor = UIColor.clearColor()

// Search Bar
    let searchBar = ERSearchBar(frame: searchBarContainer.bounds)
    searchBarContainer.addSubview(searchBar)

// Add View as Title View in Navigation Bar
    self.navigationController!.navigationBar.topItem?.titleView = searchBarContainer
</code>```

Here is Code of my UISearchBar Class

```<code> func commonInit() -> Void {
    // Update UI

    if let searchField = self.valueForKey("searchField") as? UITextField{
        // To change background color
        searchField.backgroundColor = UIColor.appNavigationBarDarkRedColor()

        // Tint Color
        if let leftViewRef = searchField.leftView {
            leftViewRef.tintColor = UIColor.whiteColor()
        }else if let imgLeftView = searchField.leftView as? UIImageView{
            imgLeftView.tintColor = UIColor.whiteColor()
        }

        // Font Color
        searchField.font = UIFont.robotoRegularFont(WithSize: 14.0)

        // Text Color
        searchField.textColor = UIColor.whiteColor()

        // PlaceHolder Attributes
        searchField.attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()])
    }

    self.setImage(UIImage(named: "ic_search_white"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
    // To change placeholder text color
}
</code>```

Please someone help me here.

答:
For 1) Set the searchBarStyle property to minimal. This will provides no default background color in UIsearchBar.

2)I'm not quite sure what'd you mean by "inner screen". But if what you want is a Search Bar that can work across different view controllers, UISearchController is the one you're looking for.
You can fine the Apple sample code here

Body:
I want to add uisearchbar in place of title of controller.

I am facing 2 problems currently.

1)
I do not know from where this gray background is coming. Please check this picture.

2) I need this searchbar in other inner screens also. But when I push another controller this searchbar is removed.

Here is my code :

// Seachbar Container View
    let searchBarContainer = ERView(frame: CGRectMake(0,0,280,44))
    searchBarContainer.autoresizingMask = [.FlexibleWidth]
    searchBarContainer.backgroundColor = UIColor.clearColor()

// Search Bar
    let searchBar = ERSearchBar(frame: searchBarContainer.bounds)
    searchBarContainer.addSubview(searchBar)

// Add View as Title View in Navigation Bar
    self.navigationController!.navigationBar.topItem?.titleView = searchBarContainer

Here is Code of my UISearchBar Class

 func commonInit() -> Void {
    // Update UI

    if let searchField = self.valueForKey("searchField") as? UITextField{
        // To change background color
        searchField.backgroundColor = UIColor.appNavigationBarDarkRedColor()

        // Tint Color
        if let leftViewRef = searchField.leftView {
            leftViewRef.tintColor = UIColor.whiteColor()
        }else if let imgLeftView = searchField.leftView as? UIImageView{
            imgLeftView.tintColor = UIColor.whiteColor()
        }

        // Font Color
        searchField.font = UIFont.robotoRegularFont(WithSize: 14.0)

        // Text Color
        searchField.textColor = UIColor.whiteColor()

        // PlaceHolder Attributes
        searchField.attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()])
    }

    self.setImage(UIImage(named: "ic_search_white"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
    // To change placeholder text color
}

Please someone help me here.


问:
SMACSS how to identify what to put in modules?
I've just started learning front end web development and a few days ago I got familiar with SMACSS methodology. I've red the concept on the official website and a couple of other articles. But I am still very confused with modules.

What I understood is that I should create a partial for any little element that's inside a layout.

For example let's say, that there is a sidebar that contains just headline and paragraph. As I understood, the sidebar itself will go to layouts. But where should I style headline and paragraph? Are they going to separate modules or I should just simply write them in the layout?

This is just an example, but I have a lot of struggles like this while trying to use SMACSS. Could anybody please explain me this part in a easy and simple way?

答:
I believe that the simplest thing that you can do is learn how to do basic things in react.js. How to work with react components. They are basically separate modules. Every component should have its own styles.

Look here for example: https://blog.risingstack.com/the-react-way-getting-started-tutorial/#howshouldiimagineit

There is this really cool image that describes what should be component.


问:
How to change label text in nativescript angular2
I don't know how to change the label text dynamically. When I'm clicking on the second tab position, it is triggering onIndexChanged(args) and printing the console.log("One" +"Test"); in command prompt. But it doesn't change the text.

first.page.html:

```<code><ActionBar title="Dashboard" class="action-bar">

   <Label [text]="'times'" textWrap="true"></Label>

</ActionBar>
</code>```

first.page.ts:

```<code>export class FirstPage {

  public times = "Ratings";

 ....
   public onIndexChanged(args) {

        let tabView = <TabView>args.object;

       if(tabView.selectedIndex == 1){

            console.log("One" +"Test");

             this.times  = "Ratings";

       }

    }

  }
</code>```

答:
html:

```<code><ActionBar title="Dashboard" class="action-bar">
    <Label [text]="labelText" textWrap="true"></Label>
</ActionBar>
<StackLayout>
    <Button text="click me" (tap)="changeText()"></Button>
</StackLayout>
</code>```

ts:

```<code>export class FirstPage {
    labelText: string = "Times";
    changeText() {
        this.labelText = "Ratings";
    }
}
</code>```

That should do the trick, the button is only there to see the change, you could do the call however you wanted to.

--EDIT--

swap  with

Body:
I don't know how to change the label text dynamically. When I'm clicking on the second tab position, it is triggering onIndexChanged(args) and printing the console.log("One" +"Test"); in command prompt. But it doesn't change the text.

first.page.html:

<ActionBar title="Dashboard" class="action-bar">

</ActionBar>

first.page.ts:

export class FirstPage {

  public times = "Ratings";

 ....
   public onIndexChanged(args) {

        let tabView = <TabView>args.object;

       if(tabView.selectedIndex == 1){

            console.log("One" +"Test");

             this.times  = "Ratings";

       }

    }

  }

Body:
html:

<ActionBar title="Dashboard" class="action-bar">
    <Label [text]="labelText" textWrap="true"></Label>
</ActionBar>
<StackLayout>
    <Button text="click me" (tap)="changeText()"></Button>
</StackLayout>

ts:

export class FirstPage {
    labelText: string = "Times";
    changeText() {
        this.labelText = "Ratings";
    }
}

That should do the trick, the button is only there to see the change, you could do the call however you wanted to.

--EDIT--

swap <Label [text]="labelText" textWrap="true"></Label> with <Label text="{{ labelText }}" textWrap="true"></Label>


问:
How to parse String data from xml dom parser?
I am using XMLparser WS.so I get below kind of data in response.

```<code> <?xml version="1.0" encoding="utf-8"?>
 <string xmlns="http://tempuri.org/">

     {"DBVersionList":[]}

 </string>
</code>```

I want to parse above data and need only {"DBVersionList":[]} this as value.

I tried as below code.

```<code>    Document doc = xmlparser.getDomElement(response); // getting DOM
    NodeList n2 = doc.getElementsByTagName("string");
    Log.e("Log","value="+n2.item(0));
</code>```

Thanks in Advance

答: you coud write like this, ok , there must be at least 30 characters</p>

Body:
I am using XMLparser WS.so I get below kind of data in response.

 <?xml version="1.0" encoding="utf-8"?>
 <string xmlns="http://tempuri.org/">

     {"DBVersionList":[]}

 </string>

I want to parse above data and need only {"DBVersionList":[]} this as value.

I tried as below code.

    Document doc = xmlparser.getDomElement(response); // getting DOM
    NodeList n2 = doc.getElementsByTagName("string");
    Log.e("Log","value="+n2.item(0));

Thanks in Advance


问:
Is it possible to change storyboard language at runtime?
I'm using storyboard file in my application and have 2 language supports, I create

'Localizable Strings'

for both languages and have one .storyboard file in

Base.lproj

During log in user should change language , so I need to change language at runtime... Is it possible to do withour restarting application?

here is my code, but is doesn't work :) , cause 'bundle' is not loaded

```<code>var bundle = NSBundle.FromPath (NSBundle.MainBundle.PathForResource ("ru", "lproj"));
            bundle.Load ();
            var st = NSStoryboard.FromName ("Main", bundle);
            NSViewController contentVC = st?.InstantiateControllerWithIdentifier (NSConstants.MainSplitViewControllerID) as NSViewController;
            NSApplication.SharedApplication.Windows.FirstOrDefault ().ContentViewController = contentVC;
</code>```

答:
use this:</p>

```<code>let path = Bundle.main.path(forResource: "ru", ofType: "lproj")
        let bundle = Bundle(path: path!)
        let storyboard = UIStoryboard(name: "Main", bundle: bundle)
</code>```

Body:
I'm using storyboard file in my application and have 2 language supports, I create

'Localizable Strings'

for both languages and have one .storyboard file in

Base.lproj

During log in user should change language , so I need to change language at runtime... Is it possible to do withour restarting application?

here is my code, but is doesn't work :) , cause 'bundle' is not loaded

var bundle = NSBundle.FromPath (NSBundle.MainBundle.PathForResource ("ru", "lproj"));
            bundle.Load ();
            var st = NSStoryboard.FromName ("Main", bundle);
            NSViewController contentVC = st?.InstantiateControllerWithIdentifier (NSConstants.MainSplitViewControllerID) as NSViewController;
            NSApplication.SharedApplication.Windows.FirstOrDefault ().ContentViewController = contentVC;

Body:
use this:

let path = Bundle.main.path(forResource: "ru", ofType: "lproj")
        let bundle = Bundle(path: path!)
        let storyboard = UIStoryboard(name: "Main", bundle: bundle)


问:
How to get the list of all database users
I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.

So far, I have been able to come up with the following query:

```<code>SELECT * FROM sys.database_principals where (type='S' or type = 'U')
</code>```

This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.

How can I change this query or should I use another one?

答:
```<code>EXEC sp_helpuser
</code>```

or

```<code>SELECT * FROM sysusers
</code>```

Both of these select all the users of the current database (not the server).

Body:
I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.

So far, I have been able to come up with the following query:

SELECT * FROM sys.database_principals where (type='S' or type = 'U')

This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.

How can I change this query or should I use another one?

Body:
EXEC sp_helpuser

or

SELECT * FROM sysusers

Both of these select all the users of the current database (not the server).


问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
Old answer below

You can initialize a string with strcpy, like in your code, or directly when declaring the char array.

```<code>char a1[100] = "Vivek";
</code>```

Other than that, you can do it char-by-char

```<code>a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';
</code>```

Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.

Old answer

You have

```
        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
    b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]
```

and you want

```
        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]
```

so ...

```<code>a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';
</code>```

but with loops and stuff, right? :D

Try this (remember to add missing bits)

```<code>for (aindex = 5; aindex < 14; aindex++) {
    a1[aindex] = b1[aindex - 5];
}
</code>```

Now think about the 5 and 14 in the loop above.

What can you replace them with? When you answer this, you have solved the programming problem you have :)

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
Old answer below

You can initialize a string with strcpy, like in your code, or directly when declaring the char array.

char a1[100] = "Vivek";

Other than that, you can do it char-by-char

a1[0] = 'V';
a1[1] = 'i';
// ...
a1[4] = 'k';
a1[5] = '\0';

Or you can write a few lines of code that replace strcpy and make them a function or use directly in your main function.

Old answer

You have

        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|0|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_]
    b1 [R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_|_|_|_|_|_]

and you want

        0 1 2 3 4 5 6 7 8 9 ...
    a1 [V|i|v|e|k|R|a|t|n|a|v|e|l|0|_|_|_|_|_|_|_|_]

so ...

a1[5] = 'R';
a1[6] = 'a';
// ...
a1[12] = 'l';
a1[13] = '\0';

but with loops and stuff, right? :D

Try this (remember to add missing bits)

for (aindex = 5; aindex < 14; aindex++) {
    a1[aindex] = b1[aindex - 5];
}

Now think about the 5 and 14 in the loop above.

What can you replace them with? When you answer this, you have solved the programming problem you have :)


问:
Pandas resampling to the existing index
I have a long timeseries that ends with the following data.

```<code>               ABC     CDE
Date
2017-05-26  107.00  241.71
2017-05-30  107.27  241.50
2017-05-31  107.32  241.44
2017-06-01  107.10  243.36
2017-06-02  107.57  244.17
</code>```

I would like to resample it so that it becomes monthly data but I am interested in retaining the actual last monthly dates in the time series. If I do,

```<code>df.resample('BM').last()
</code>```

gives the following tail-end output

```<code>2017-05-31  107.32  241.44
2017-06-30  107.57  244.17
</code>```

which does not give the correct last date of the dataframe. There are other dates within the resampled dataframe that are off as well. Essentially Pandas isn't using the existing index to find the month end but it's own business day calendar.

Is there an option I can feed into the Pandas resampling function so that it uses the existing index to achieve the desired result which is

```<code>2017-05-31  107.32  241.44
2017-06-02  107.57  244.17
</code>```

答:
You need create new column from index and last set_index:

```<code>df = df.assign(Date=df.index).resample('BM').last().set_index('Date')
print (df)
               ABC     CDE
Date
2017-05-31  107.32  241.44
2017-06-02  107.57  244.17
</code>```

But if need resample by month period only:

```<code>m = df.index.to_period('m')
df = df.reset_index().groupby(m).last().set_index('Date')
print (df)
               ABC     CDE
Date
2017-05-31  107.32  241.44
2017-06-02  107.57  244.17
</code>```

Title: Pandas resampling to the existing index

Body:
I have a long timeseries that ends with the following data.

               ABC     CDE
Date
2017-05-26  107.00  241.71
2017-05-30  107.27  241.50
2017-05-31  107.32  241.44
2017-06-01  107.10  243.36
2017-06-02  107.57  244.17

I would like to resample it so that it becomes monthly data but I am interested in retaining the actual last monthly dates in the time series. If I do,

df.resample('BM').last()

gives the following tail-end output

2017-05-31  107.32  241.44
2017-06-30  107.57  244.17

which does not give the correct last date of the dataframe. There are other dates within the resampled dataframe that are off as well. Essentially Pandas isn't using the existing index to find the month end but it's own business day calendar.

Is there an option I can feed into the Pandas resampling function so that it uses the existing index to achieve the desired result which is

2017-05-31  107.32  241.44
2017-06-02  107.57  244.17

Body:
You need create new column from index and last set_index:

df = df.assign(Date=df.index).resample('BM').last().set_index('Date')
print (df)
               ABC     CDE
Date
2017-05-31  107.32  241.44
2017-06-02  107.57  244.17

But if need resample by month period only:

m = df.index.to_period('m')
df = df.reset_index().groupby(m).last().set_index('Date')
print (df)
               ABC     CDE
Date
2017-05-31  107.32  241.44
2017-06-02  107.57  244.17


问:
using awk to match a PATH starting with /root/ and ending before character "
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

```<code>error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text
</code>```

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

```<code>command.sh | grep error  |awk '/root/{mypath=$6}'.
</code>```

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

```<code>i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"
</code>```

Anyone can help please?

答:
awk solution:

```<code>command.sh | awk '/^error/{ match($0,/\/root[^"]+/); print substr($0,RSTART,RLENGTH) }'
</code>```

The output:

```<code>/root/this/is/my/path/
</code>```

Body:
i have a command that produces a random output with a path in it
And i need to extract this path using awk.
The path always starts with the same pattern (lets assume it always starts with /root) but the rest can change

for example :

error reason  05/30/2017 12:18:37 [74575:45687]: "/root/this/is/my/path/" random text random text random text random text random text random    text

to extract /root/this/is/my/path/ : I have tryed using grep + awk in the following way :

command.sh | grep error  |awk '/root/{mypath=$6}'.

But i then figured out my path was not always located at the same place. more over, i don't want to extract the double quotes.

i need to have /root/this/is/my/path/ not "/root/this/is/my/path/"

Anyone can help please?

Body:
awk solution:

command.sh | awk '/^error/{ match($0,/\/root[^"]+/); print substr($0,RSTART,RLENGTH) }'

The output:

/root/this/is/my/path/


问:
Why does attr_accessor :type return nil?
When overriding the to_s method of one of my classes, I'm getting that the field type is nil. I'm positive that it has a not null value. I have a legacy DB so I'm using self.inheritance_column = nil to tell rails not to look for inheritance. This is my class:

```<code>class BookEntry < ApplicationRecord
  self.inheritance_column = nil
  attr_accessor :type
  self.table_name = 'bookEntries'
  has_many :users_payout_methods, class_name: 'UsersBooks', primary_key: 'id', foreign_key: 'bookId_fk'
  has_many :users, :through => :users_payout_methods

  def to_s
    "type: "+ type + ", genre:" + genre
  end
end
</code>```

Other fields, like genre do work properly. Why does this happen?

答:
Remove the line

```<code>attr_accessor :type
</code>```

that basically overrides default Rails getter and setter for a field.

What happens under the hood, is that attr_accessor declares two dummy methods:

```<code>def type
  @type
end

def type=(value)
  @type = value
end
</code>```

Unless you have explicitly set the @type instance variable, it’s value is nil since the explicit attr_accessor broke the magic that reads the value from the database field.

Body:
When overriding the to_s method of one of my classes, I'm getting that the field type is nil. I'm positive that it has a not null value. I have a legacy DB so I'm using self.inheritance_column = nil to tell rails not to look for inheritance. This is my class:

class BookEntry < ApplicationRecord
  self.inheritance_column = nil
  attr_accessor :type
  self.table_name = 'bookEntries'
  has_many :users_payout_methods, class_name: 'UsersBooks', primary_key: 'id', foreign_key: 'bookId_fk'
  has_many :users, :through => :users_payout_methods

  def to_s
    "type: "+ type + ", genre:" + genre
  end
end

Other fields, like genre do work properly. Why does this happen?

Body:
Remove the line

attr_accessor :type

that basically overrides default Rails getter and setter for a field.

What happens under the hood, is that attr_accessor declares two dummy methods:

def type
  @type
end

def type=(value)
  @type = value
end

Unless you have explicitly set the @type instance variable, it’s value is nil since the explicit attr_accessor broke the magic that reads the value from the database field.


问:
vectorizer.fit_transform gives NotImplementedError : adding a nonzero scalar to a sparse matrix is not supported
I am trying to create a term document matrix using my custom analyser to extract features out of the documents. Following is the code for the same :

```<code>vectorizer = CountVectorizer(  \
                           ngram_range=(1,2),
                        )
analyzer=vectorizer.build_analyzer()
def customAnalyzer(text):
    grams = analyzer(text)
    tgrams = [gram for gram in grams if not re.match("^[0-9\s]+$",gram)]
    return tgrams
</code>```

This function is called to create the custom analyser, which is used by the countVectorizer to extract the features.

```<code>for i in xrange( 0, num_rows ):
    clean_query.append( review_to_words( inp["keyword"][i] , units))
vectorizer = CountVectorizer(analyzer = customAnalyzer,   \
                            tokenizer = None,    \
                            ngram_range=(1,2),  \
                            preprocessor = None, \
                            stop_words = None,   \
                            max_features = n,
                           )
features = vectorizer.fit_transform(clean_query)
z = vectorizer.get_feature_names()
</code>```

This call throws the following error:

```<code>(<type 'exceptions.NotImplementedError'>, 'python.py', 128,NotImplementedError('adding a nonzero scalar to a sparse matrix is not supported',))
</code>```

This error comes when we call the vectorizer to fit and transform.
But the value of the variable clean_query is not scalar. I am using sklearn-0.17.1

```<code> np.isscalar(clean_query)
 False
</code>```

答:
This is a small test which I did to reproduce the error, but it did not throw the same error for me. (This example has been taken from : scikit-learn Feature extraction)

scikit-learn version : 0.19.dev0

```<code>In [1]: corpus = [
   ...: ...     'This is the first document.',
   ...: ...     'This is the second second document.',
   ...: ...     'And the third one.',
   ...: ...     'Is this the first document?',
   ...: ... ]

In [2]: from sklearn.feature_extraction.text import TfidfVectorizer

In [3]: vectorizer = TfidfVectorizer(min_df=1)

In [4]: vectorizer.fit_transform(corpus)
Out[4]:
<4x9 sparse matrix of type '<type 'numpy.float64'>'
    with 19 stored elements in Compressed Sparse Row format>

In [5]: import numpy as np

In [6]: np.isscalar(corpus)
Out[6]: False

In [7]: type(corpus)
Out[7]: list
</code>```

From the code above you can see, corpus is not a scalar and has the type list.

I think your solution lies in creating the clean_query variable, as expected by the vectorizer.fit_transform function.

Body:
I am trying to create a term document matrix using my custom analyser to extract features out of the documents. Following is the code for the same :

vectorizer = CountVectorizer(  \
                           ngram_range=(1,2),
                        )
analyzer=vectorizer.build_analyzer()
def customAnalyzer(text):
    grams = analyzer(text)
    tgrams = [gram for gram in grams if not re.match("^[0-9\s]+$",gram)]
    return tgrams

This function is called to create the custom analyser, which is used by the countVectorizer to extract the features.

for i in xrange( 0, num_rows ):
    clean_query.append( review_to_words( inp["keyword"][i] , units))
vectorizer = CountVectorizer(analyzer = customAnalyzer,   \
                            tokenizer = None,    \
                            ngram_range=(1,2),  \
                            preprocessor = None, \
                            stop_words = None,   \
                            max_features = n,
                           )
features = vectorizer.fit_transform(clean_query)
z = vectorizer.get_feature_names()

This call throws the following error:

(<type 'exceptions.NotImplementedError'>, 'python.py', 128,NotImplementedError('adding a nonzero scalar to a sparse matrix is not supported',))

This error comes when we call the vectorizer to fit and transform.
But the value of the variable clean_query is not scalar. I am using sklearn-0.17.1

 np.isscalar(clean_query)
 False

Body:
This is a small test which I did to reproduce the error, but it did not throw the same error for me. (This example has been taken from : scikit-learn Feature extraction)

scikit-learn version : 0.19.dev0

In [1]: corpus = [
   ...: ...     'This is the first document.',
   ...: ...     'This is the second second document.',
   ...: ...     'And the third one.',
   ...: ...     'Is this the first document?',
   ...: ... ]

In [2]: from sklearn.feature_extraction.text import TfidfVectorizer

In [3]: vectorizer = TfidfVectorizer(min_df=1)

In [4]: vectorizer.fit_transform(corpus)
Out[4]:
<4x9 sparse matrix of type '<type 'numpy.float64'>'
    with 19 stored elements in Compressed Sparse Row format>

In [5]: import numpy as np

In [6]: np.isscalar(corpus)
Out[6]: False

In [7]: type(corpus)
Out[7]: list

From the code above you can see, corpus is not a scalar and has the type list.

I think your solution lies in creating the clean_query variable, as expected by the vectorizer.fit_transform function.