问:
Unexpected (wrong) template deduction using armadillo library
I am writing a c++ template function, aimed at computing a function of a matrix, where the matrix type is a template parameter. When using it with the armadillo library, I get an unexpected failure in compilation.
I am using armadillo 8.300 and gcc 7.2.0.
In the following a test program which illustrates the issue.

```<code>#include <armadillo>

arma::Mat<double> sq(const arma::Mat<double>& M)
{
  arma::Mat<double> res(M);
  res = res * M;
  return res;
}

template <class MatrixClass>
MatrixClass sqgen(const MatrixClass& M)
{
  MatrixClass res(M);
  res = res * M;
  return res;
}

int main()
{
  arma::Mat<double> id(3, 3, arma::fill::eye);
  arma::Mat<double> m(3, 3, arma::fill::ones);

  arma::Mat<double> m2(sq(m));
  arma::Mat<double> m_id2(sq(id - m));

  arma::Mat<double> m2gen(sqgen(m));
  arma::Mat<double> m_id2gen(sqgen(id - m)); // Error here
  return 0;
}
</code>```

For illustration I defined two functions sq and sqgen which essentially do the same job. sq is the explicit instantiation of sqgen when the template parameter MatrixClass is arma::Mat<double>. The compilation with

```<code>g++ -std=c++14 -Wall -pedantic -O3 -o test test.cpp -lstdc++ -larmadillo
</code>```

fails giving the error:

```<code>test.cpp: In instantiation of ‘MatrixClass sq(const MatrixClass&) [with MatrixClass = arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>]’:
test.cpp:24:36:   required from here
test.cpp:14:7: error: no match for ‘operator=’ (operand types are ‘arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>’ and ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’)
   res = res * M;
   ~~~~^~~~~~~~~
In file included from /usr/include/armadillo:204:0,
                 from test.cpp:1:
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note: candidate: arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>& arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>::operator=(const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&) <deleted>
 class eGlue : public Base<typename T1::elem_type, eGlue<T1, T2, eglue_type> >
       ^~~~~
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note:   no known conversion for argument 1 from ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’ to ‘const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&’
</code>```

The problem lies in the last call of sqgen. There is no problem in calling sqgen(m), however the call sqgen(id - m) causes the error.  Notice that, instead, using the call sq(id - m) is perfectly legal. Since the function sqgen should be, in the code above, exactly equal to sq, I presume that the compiler does not deduce correctly the template parameter MatrixClass in sqgen(id - m).
In fact, upon substituting

```<code>arma::Mat<double> m_id2gen(sqgen(id - m));
</code>```

with

```<code>arma::Mat<double> m_id2gen(sqgen(arma::Mat<double>(id - m)));
</code>```

the code compiles correctly.

答:
Template pattern matching matches exact types (and types of parent types if the exact type doesn't match).

Overload resolution matches exact types, parent types, and types that can be converted to.

Odds are that arma::Mat's operations result in expression templates, which can be converted into matrices, but are not themselves matrices.  They exist so that you can take an entire line of matrix math, and efficiently not do it until you actually convert everything into a matrix.

Because sqgen takes an anything, in this case it tries to consume an expression template whose value is the difference between two matrices.

You then create a temporary expression template instance with no arguments, multiply it with another expression template, assign to it, and return it.  None of these make sense for an expression template.

This is a known problem with expression templates and generic code.  Typically there are ways to force evaluation of expression templates.  Assinging them to a matrix does it (and is how sq works), casting them works, and in this case there is a .eval() member function which does it without having to name the type.

So, try

```<code>arma::Mat<double> m_id2gen(sqgen((id - m).eval()));
</code>```

Body:
I am writing a c++ template function, aimed at computing a function of a matrix, where the matrix type is a template parameter. When using it with the armadillo library, I get an unexpected failure in compilation.
I am using armadillo 8.300 and gcc 7.2.0.
In the following a test program which illustrates the issue.

#include <armadillo>

arma::Mat<double> sq(const arma::Mat<double>& M)
{
  arma::Mat<double> res(M);
  res = res * M;
  return res;
}

template <class MatrixClass>
MatrixClass sqgen(const MatrixClass& M)
{
  MatrixClass res(M);
  res = res * M;
  return res;
}

int main()
{
  arma::Mat<double> id(3, 3, arma::fill::eye);
  arma::Mat<double> m(3, 3, arma::fill::ones);

  arma::Mat<double> m2(sq(m));
  arma::Mat<double> m_id2(sq(id - m));

  arma::Mat<double> m2gen(sqgen(m));
  arma::Mat<double> m_id2gen(sqgen(id - m)); // Error here
  return 0;
}

For illustration I defined two functions sq and sqgen which essentially do the same job. sq is the explicit instantiation of sqgen when the template parameter MatrixClass is arma::Mat<double>. The compilation with

g++ -std=c++14 -Wall -pedantic -O3 -o test test.cpp -lstdc++ -larmadillo

fails giving the error:

test.cpp: In instantiation of ‘MatrixClass sq(const MatrixClass&) [with MatrixClass = arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>]’:
test.cpp:24:36:   required from here
test.cpp:14:7: error: no match for ‘operator=’ (operand types are ‘arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>’ and ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’)
   res = res * M;
   ~~~~^~~~~~~~~
In file included from /usr/include/armadillo:204:0,
                 from test.cpp:1:
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note: candidate: arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>& arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>::operator=(const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&) <deleted>
 class eGlue : public Base<typename T1::elem_type, eGlue<T1, T2, eglue_type> >
       ^~~~~
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note:   no known conversion for argument 1 from ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’ to ‘const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&’

The problem lies in the last call of sqgen. There is no problem in calling sqgen(m), however the call sqgen(id - m) causes the error.  Notice that, instead, using the call sq(id - m) is perfectly legal. Since the function sqgen should be, in the code above, exactly equal to sq, I presume that the compiler does not deduce correctly the template parameter MatrixClass in sqgen(id - m).
In fact, upon substituting

arma::Mat<double> m_id2gen(sqgen(id - m));

with

arma::Mat<double> m_id2gen(sqgen(arma::Mat<double>(id - m)));

the code compiles correctly.

Body:
Template pattern matching matches exact types (and types of parent types if the exact type doesn't match).

Overload resolution matches exact types, parent types, and types that can be converted to.

Odds are that arma::Mat's operations result in expression templates, which can be converted into matrices, but are not themselves matrices.  They exist so that you can take an entire line of matrix math, and efficiently not do it until you actually convert everything into a matrix.

Because sqgen takes an anything, in this case it tries to consume an expression template whose value is the difference between two matrices.

You then create a temporary expression template instance with no arguments, multiply it with another expression template, assign to it, and return it.  None of these make sense for an expression template.

This is a known problem with expression templates and generic code.  Typically there are ways to force evaluation of expression templates.  Assinging them to a matrix does it (and is how sq works), casting them works, and in this case there is a .eval() member function which does it without having to name the type.

So, try

arma::Mat<double> m_id2gen(sqgen((id - m).eval()));


来源: stackexchange

问:
How to switch True to False in Python
What operation do I need to do to always get a False value to become True or to get a True value to become False?
In other words, what do I do to switch the Boolean value of a given variable?

```<code>    new_dict = {}
    for i in range(1, 101):
        new_dict[i] = False

    i = 2
    while i < 101:
        for x in range(1, 101):
            if new_dict[x] % i == 0:
                a = new_dict[x]
                new_dict[x] = not a
        i += 1
    for a in new_dict:
        print 'Light #%d --> %r' % (a, new_dict[a])
</code>```

The output below is only True. From this, I understand that what I did for some reason is not changing every other value to False. Why is this happening?

Does anyone have any idea why?

```<code>    Light #1 --> True
    Light #2 --> True
    Light #3 --> True
    Light #4 --> True
    Light #5 --> True
    Light #6 --> True
    Light #7 --> True
    Light #8 --> True
    Light #9 --> True
    Light #10 --> True
    Light #11 --> True
    Light #12 --> True
    Light #13 --> True
    Light #14 --> True
    Light #15 --> True
    Light #16 --> True
    Light #17 --> True
    Light #18 --> True
    Light #19 --> True
    Light #20 --> True
    Light #21 --> True
    Light #22 --> True
    Light #23 --> True
    Light #24 --> True
    Light #25 --> True
    Light #26 --> True
    Light #27 --> True
    Light #28 --> True
    Light #29 --> True
    Light #30 --> True
    Light #31 --> True
    Light #32 --> True
    Light #33 --> True
    Light #34 --> True
    Light #35 --> True
    Light #36 --> True
    Light #37 --> True
    Light #38 --> True
    Light #39 --> True
    Light #40 --> True
    Light #41 --> True
    Light #42 --> True
    Light #43 --> True
    Light #44 --> True
    Light #45 --> True
    Light #46 --> True
    Light #47 --> True
    Light #48 --> True
    Light #49 --> True
    Light #50 --> True
    Light #51 --> True
    Light #52 --> True
    Light #53 --> True
    Light #54 --> True
    Light #55 --> True
    Light #56 --> True
    Light #57 --> True
    Light #58 --> True
    Light #59 --> True
    Light #60 --> True
    Light #61 --> True
    Light #62 --> True
    Light #63 --> True
    Light #64 --> True
    Light #65 --> True
    Light #66 --> True
    Light #67 --> True
    Light #68 --> True
    Light #69 --> True
    Light #70 --> True
    Light #71 --> True
    Light #72 --> True
    Light #73 --> True
    Light #74 --> True
    Light #75 --> True
    Light #76 --> True
    Light #77 --> True
    Light #78 --> True
    Light #79 --> True
    Light #80 --> True
    Light #81 --> True
    Light #82 --> True
    Light #83 --> True
    Light #84 --> True
    Light #85 --> True
    Light #86 --> True
    Light #87 --> True
    Light #88 --> True
    Light #89 --> True
    Light #90 --> True
    Light #91 --> True
    Light #92 --> True
    Light #93 --> True
    Light #94 --> True
    Light #95 --> True
    Light #96 --> True
    Light #97 --> True
    Light #98 --> True
    Light #99 --> True
    Light #100 --> True
</code>```

The question here How do I get the opposite (negation) of a Boolean in Python? and here python how to "negate" value : if true return false, if false return true seem to be the same but in my case, that simple concept is simply not working...

Thanks, I really appreciate all the help guys!!!

答:
If you are, for instance, being returned a boolean value from a function,
you could do:

```<code>bool_value = not my_function()
</code>```

NOTing the boolean value will invert it to the opposite value.
It works because in Python:

```<code>>>> not True
False
>>> not False
True
</code>```

So:

```<code>>>> value = True
>>> print(value)
True
>>> print(not value)
False
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to switch True to False in Python

Body:
What operation do I need to do to always get a False value to become True or to get a True value to become False?
In other words, what do I do to switch the Boolean value of a given variable?

    new_dict = {}
    for i in range(1, 101):
        new_dict[i] = False

    i = 2
    while i < 101:
        for x in range(1, 101):
            if new_dict[x] % i == 0:
                a = new_dict[x]
                new_dict[x] = not a
        i += 1
    for a in new_dict:
        print 'Light #%d --> %r' % (a, new_dict[a])

The output below is only True. From this, I understand that what I did for some reason is not changing every other value to False. Why is this happening?

Does anyone have any idea why?

    Light #1 --> True
    Light #2 --> True
    Light #3 --> True
    Light #4 --> True
    Light #5 --> True
    Light #6 --> True
    Light #7 --> True
    Light #8 --> True
    Light #9 --> True
    Light #10 --> True
    Light #11 --> True
    Light #12 --> True
    Light #13 --> True
    Light #14 --> True
    Light #15 --> True
    Light #16 --> True
    Light #17 --> True
    Light #18 --> True
    Light #19 --> True
    Light #20 --> True
    Light #21 --> True
    Light #22 --> True
    Light #23 --> True
    Light #24 --> True
    Light #25 --> True
    Light #26 --> True
    Light #27 --> True
    Light #28 --> True
    Light #29 --> True
    Light #30 --> True
    Light #31 --> True
    Light #32 --> True
    Light #33 --> True
    Light #34 --> True
    Light #35 --> True
    Light #36 --> True
    Light #37 --> True
    Light #38 --> True
    Light #39 --> True
    Light #40 --> True
    Light #41 --> True
    Light #42 --> True
    Light #43 --> True
    Light #44 --> True
    Light #45 --> True
    Light #46 --> True
    Light #47 --> True
    Light #48 --> True
    Light #49 --> True
    Light #50 --> True
    Light #51 --> True
    Light #52 --> True
    Light #53 --> True
    Light #54 --> True
    Light #55 --> True
    Light #56 --> True
    Light #57 --> True
    Light #58 --> True
    Light #59 --> True
    Light #60 --> True
    Light #61 --> True
    Light #62 --> True
    Light #63 --> True
    Light #64 --> True
    Light #65 --> True
    Light #66 --> True
    Light #67 --> True
    Light #68 --> True
    Light #69 --> True
    Light #70 --> True
    Light #71 --> True
    Light #72 --> True
    Light #73 --> True
    Light #74 --> True
    Light #75 --> True
    Light #76 --> True
    Light #77 --> True
    Light #78 --> True
    Light #79 --> True
    Light #80 --> True
    Light #81 --> True
    Light #82 --> True
    Light #83 --> True
    Light #84 --> True
    Light #85 --> True
    Light #86 --> True
    Light #87 --> True
    Light #88 --> True
    Light #89 --> True
    Light #90 --> True
    Light #91 --> True
    Light #92 --> True
    Light #93 --> True
    Light #94 --> True
    Light #95 --> True
    Light #96 --> True
    Light #97 --> True
    Light #98 --> True
    Light #99 --> True
    Light #100 --> True

The question here How do I get the opposite (negation) of a Boolean in Python? and here python how to "negate" value : if true return false, if false return true seem to be the same but in my case, that simple concept is simply not working...

Thanks, I really appreciate all the help guys!!!

Body:
If you are, for instance, being returned a boolean value from a function,
you could do:

bool_value = not my_function()

NOTing the boolean value will invert it to the opposite value.
It works because in Python:

>>> not True
False
>>> not False
True

So:

>>> value = True
>>> print(value)
True
>>> print(not value)
False


问:
Client/Server pthreads program not executing under Valgrind. Runs fine normally
I have a C server program that creates & opens the write end of a named pipe (in /var/run), and interrupts on a SIGIO signal for a tty uart, pushing data into the pipe from that interface.

This program also spawns a secondary pthread, which opens the read end of a separate pipe (again, in /var/run), reads from it (blocking), and passes that data back to my main thread for writing out over my tty.

Data is shared between these using a mutex-locked struct. I also have a testing client program that handles the other end of this. Permissions/file access is valid.

This appears to work great running in bash.

I want to make doubly sure with Valgrind, though, specifically with the memcheck and helgrind tools, for memory leaks and thread errors. But when I start my server program in valgrind, it hangs and doesn't run when my client starts up. I don't even see my initial startup printf from the server at the start of the program. Valgrind just sits there, until I kill it.

I'm running with the following options:

```<code>valgrind --tool=helgrind ./server
</code>```

and

```<code>valgrind --undef-value-errors=no ./server
</code>```

Output is as follows (for both commands):

```<code>==7577== Memcheck, a memory error detector
==7577== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==7577== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==7577== Command: ./server
==7577==
--7577-- WARNING: Serious error when reading debug info
--7577-- When reading debug info from /lib/arm-linux-gnueabihf/ld-2.24.so:
--7577-- Ignoring non-Dwarf2/3/4 block in .debug_info
--7577-- WARNING: Serious error when reading debug info
--7577-- When reading debug info from /lib/arm-linux-gnueabihf/ld-2.24.so:
--7577-- Last block truncated in .debug_info; ignoring
</code>```

Suppressing undef-value-errors because ld.so has a ton, and it was flooding my output.

Is there anything you could think of that I may be doing wrong? Maybe the lack of debug info in the ld library? I can dump code if need be, or elaborate further.

Thank you.

答:
It looks like your valgrind version is rather old:

```<code>==7577== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==7577== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
</code>```

Assuming that ld-2.24.so is from glibc, that's around five years of toolchain development, and who knows what kind of improvements when into the gcc and binutils versions which were used to compile that glibc.

Body:
I have a C server program that creates & opens the write end of a named pipe (in /var/run), and interrupts on a SIGIO signal for a tty uart, pushing data into the pipe from that interface.

This program also spawns a secondary pthread, which opens the read end of a separate pipe (again, in /var/run), reads from it (blocking), and passes that data back to my main thread for writing out over my tty.

Data is shared between these using a mutex-locked struct. I also have a testing client program that handles the other end of this. Permissions/file access is valid.

This appears to work great running in bash.

I want to make doubly sure with Valgrind, though, specifically with the memcheck and helgrind tools, for memory leaks and thread errors. But when I start my server program in valgrind, it hangs and doesn't run when my client starts up. I don't even see my initial startup printf from the server at the start of the program. Valgrind just sits there, until I kill it.

I'm running with the following options:

valgrind --tool=helgrind ./server

and

valgrind --undef-value-errors=no ./server

Output is as follows (for both commands):

==7577== Memcheck, a memory error detector
==7577== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==7577== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==7577== Command: ./server
==7577==
--7577-- WARNING: Serious error when reading debug info
--7577-- When reading debug info from /lib/arm-linux-gnueabihf/ld-2.24.so:
--7577-- Ignoring non-Dwarf2/3/4 block in .debug_info
--7577-- WARNING: Serious error when reading debug info
--7577-- When reading debug info from /lib/arm-linux-gnueabihf/ld-2.24.so:
--7577-- Last block truncated in .debug_info; ignoring

Suppressing undef-value-errors because ld.so has a ton, and it was flooding my output.

Is there anything you could think of that I may be doing wrong? Maybe the lack of debug info in the ld library? I can dump code if need be, or elaborate further.

Thank you.

Body:
It looks like your valgrind version is rather old:

==7577== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==7577== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info

Assuming that ld-2.24.so is from glibc, that's around five years of toolchain development, and who knows what kind of improvements when into the gcc and binutils versions which were used to compile that glibc.


问:
How can I query an associative table with matching "where" conditions with Sequelize

I'm trying to retrieve products that belong to multiple collections using sequelize.
Dialect is Postgres and I'm using Sequelize 4.15.1

I have a Product model, a Collection model and the associative model CollectionProduct. Product belongs to many collections and collection belongs to many products.

Product model:

```<code>const Product = sequelize.define( 'Product', {
    id: {
      type: DataTypes.STRING,
      primaryKey: true
    },
    name: DataTypes.STRING,
  } );
  Product.associate = function( models ) {
    Product.belongsToMany( models.Collection, {
      through: models.CollectionProduct
    } );
  }
</code>```

Collection model:

```<code>const Collection = sequelize.define( 'Collection', {
  name: {
    type: Sequelize.STRING
  },
  slug: {
    type: Sequelize.STRING
  },
} );
Collection.associate = function( models ) {
  Collection.belongsToMany( models.Product, {
    through: models.CollectionProduct
  } );
}
</code>```

Here is my sequelize query

```<code>models.Product.findAll( {
  attributes: ["id", "name"],
  include: [ {
    model: models.Collection,
    attributes: ["id", "name", "slug"],
    where: {
      slug: {
        [Op.like]: { [Op.all]: ['collection-a', 'collection-b']}
      }
    }
  } ]
} ).then( products => {
  console.log( products )
} ).catch( function ( err ) {
  console.log( err );
} );
</code>```

Here is the generated postgres query

```<code>SELECT "Product"."id",
       "Product"."name",
       "Collections"."id" AS "Collections.id",
       "Collections"."name" AS "Collections.name",
       "Collections"."slug" AS "Collections.slug",
       "Collections->CollectionProduct"."createdAt" AS "Collections.CollectionProduct.createdAt",
       "Collections->CollectionProduct"."updatedAt" AS "Collections.CollectionProduct.updatedAt",
       "Collections->CollectionProduct"."CollectionId" AS "Collections.CollectionProduct.CollectionId",
       "Collections->CollectionProduct"."ProductId" AS "Collections.CollectionProduct.ProductId"
FROM "Products" AS "Product"
INNER JOIN ("CollectionProducts" AS "Collections->CollectionProduct"
            INNER JOIN "Collections" AS "Collections" ON "Collections"."id" = "Collections->CollectionProduct"."CollectionId") ON "Product"."id" = "Collections->CollectionProduct"."ProductId"
AND "Collections"."slug" LIKE ALL (ARRAY['collection-a',
                                         'collection-b']);
</code>```

I'd like to return the products that belong to both collection A and B.

Unfortunately the query execution does not return any result.

答:
This might do the trick. Grabs all productid's intersecting between collection-a id's and collection-b id's.</p>

```<code>select
  t1.slug as slug_ca,
  t2.slug as slug_cb,
  t1.productid
from
(
  select
    p3.slug,
    p1.id as productid
  from products p1
       inner join collectionproducts p2
         on p1.id = p2.ProductId
       inner join collections p3
         on p2.CollectionId = p3.id
  where lower(p3.slug) like '%collection-a%'
  group by 1,2
) t1
inner join
(
  select
    p3.slug,
    p1.id as productid
  from products p1
       inner join collectionproducts p2
         on p1.id = p2.ProductId
       inner join collections p3
         on p2.CollectionId = p3.id
  where lower(p3.slug) like '%collection-b%'
  group by 1,2
) t2
  on t1.productid = t2.productid
group by 1,2,3;
</code>```

Body:
I'm trying to retrieve products that belong to multiple collections using sequelize.
Dialect is Postgres and I'm using Sequelize 4.15.1

I have a Product model, a Collection model and the associative model CollectionProduct. Product belongs to many collections and collection belongs to many products.

Product model:

const Product = sequelize.define( 'Product', {
    id: {
      type: DataTypes.STRING,
      primaryKey: true
    },
    name: DataTypes.STRING,
  } );
  Product.associate = function( models ) {
    Product.belongsToMany( models.Collection, {
      through: models.CollectionProduct
    } );
  }

Collection model:

const Collection = sequelize.define( 'Collection', {
  name: {
    type: Sequelize.STRING
  },
  slug: {
    type: Sequelize.STRING
  },
} );
Collection.associate = function( models ) {
  Collection.belongsToMany( models.Product, {
    through: models.CollectionProduct
  } );
}

Here is my sequelize query

models.Product.findAll( {
  attributes: ["id", "name"],
  include: [ {
    model: models.Collection,
    attributes: ["id", "name", "slug"],
    where: {
      slug: {
        [Op.like]: { [Op.all]: ['collection-a', 'collection-b']}
      }
    }
  } ]
} ).then( products => {
  console.log( products )
} ).catch( function ( err ) {
  console.log( err );
} );

Here is the generated postgres query

SELECT "Product"."id",
       "Product"."name",
       "Collections"."id" AS "Collections.id",
       "Collections"."name" AS "Collections.name",
       "Collections"."slug" AS "Collections.slug",
       "Collections->CollectionProduct"."createdAt" AS "Collections.CollectionProduct.createdAt",
       "Collections->CollectionProduct"."updatedAt" AS "Collections.CollectionProduct.updatedAt",
       "Collections->CollectionProduct"."CollectionId" AS "Collections.CollectionProduct.CollectionId",
       "Collections->CollectionProduct"."ProductId" AS "Collections.CollectionProduct.ProductId"
FROM "Products" AS "Product"
INNER JOIN ("CollectionProducts" AS "Collections->CollectionProduct"
            INNER JOIN "Collections" AS "Collections" ON "Collections"."id" = "Collections->CollectionProduct"."CollectionId") ON "Product"."id" = "Collections->CollectionProduct"."ProductId"
AND "Collections"."slug" LIKE ALL (ARRAY['collection-a',
                                         'collection-b']);

I'd like to return the products that belong to both collection A and B.

Unfortunately the query execution does not return any result.

Body:
This might do the trick. Grabs all productid's intersecting between collection-a id's and collection-b id's.

select
  t1.slug as slug_ca,
  t2.slug as slug_cb,
  t1.productid
from
(
  select
    p3.slug,
    p1.id as productid
  from products p1
       inner join collectionproducts p2
         on p1.id = p2.ProductId
       inner join collections p3
         on p2.CollectionId = p3.id
  where lower(p3.slug) like '%collection-a%'
  group by 1,2
) t1
inner join
(
  select
    p3.slug,
    p1.id as productid
  from products p1
       inner join collectionproducts p2
         on p1.id = p2.ProductId
       inner join collections p3
         on p2.CollectionId = p3.id
  where lower(p3.slug) like '%collection-b%'
  group by 1,2
) t2
  on t1.productid = t2.productid
group by 1,2,3;


问:
Trying to load new view upon orientation change
I am trying to create an application in Xcode that will switch to a new view when the phone is rotated from one orientation to another.

Here is the "switchviewcontroller.h" file code:

```<code>#import <UIKit/UIKit.h>

@interface SwitchViewController : UIViewController {

}

-(IBAction)switchview:(id)sender;

@end
</code>```

And here is the "switchviewcontroller.m" file code:

```<code>#import "SwitchViewController.h"
#import "secondview.h"

@implementation SwitchViewController

-(IBAction)switchview:(id)sender {}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
       (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
    }

}
</code>```

It runs in iPhone simulator with no errors, but, when I rotate it doesn't load the new view. For starters I think I need the app to open in landscape mode, which I don't know how to do, but it still wouldn't work anyway and I think it has something to to with the "initWithNibName" part of the code because I have .xib files and not .nib files. Can anyone help me with these 2 things? Thanks.

答:
You've got to alloc and init a new view and replace you current viewcontroller's view with the new one.</p>

```<code>- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation) {
        UIView *landscapeView = [[UIView alloc] init];
        // Setup the landscape view here
        self.view = landscapeView;
        [landscapeView release];
    }
    else {
         UIView *portraitView = [[UIView alloc] init];
        // Setup the portrait view here
        self.view = portraitView;
        [portraitView release];
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to create an application in Xcode that will switch to a new view when the phone is rotated from one orientation to another.

Here is the "switchviewcontroller.h" file code:

#import <UIKit/UIKit.h>

@interface SwitchViewController : UIViewController {

}

-(IBAction)switchview:(id)sender;

@end

And here is the "switchviewcontroller.m" file code:

#import "SwitchViewController.h"
#import "secondview.h"

@implementation SwitchViewController

-(IBAction)switchview:(id)sender {}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return YES;
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) ||
       (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight))
    {
        [[secondview alloc] initWithNibName:@"secondview" bundle:[NSBundle mainBundle]];
    }

}

It runs in iPhone simulator with no errors, but, when I rotate it doesn't load the new view. For starters I think I need the app to open in landscape mode, which I don't know how to do, but it still wouldn't work anyway and I think it has something to to with the "initWithNibName" part of the code because I have .xib files and not .nib files. Can anyone help me with these 2 things? Thanks.

Body:
You've got to alloc and init a new view and replace you current viewcontroller's view with the new one.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation) {
        UIView *landscapeView = [[UIView alloc] init];
        // Setup the landscape view here
        self.view = landscapeView;
        [landscapeView release];
    }
    else {
         UIView *portraitView = [[UIView alloc] init];
        // Setup the portrait view here
        self.view = portraitView;
        [portraitView release];
    }
}


答:
Assuming a variable myBool, you can set it with the not keyword.

```<code>myBool = True
print(myBool)
myBool = not myBool
print(myBool)
</code>```

Results in:

```<code>True
False
</code>```

Title: How to switch True to False in Python

Body:
Assuming a variable myBool, you can set it with the not keyword.

myBool = True
print(myBool)
myBool = not myBool
print(myBool)

Results in:

True
False


问:
What's the sudo apt-get install command for installing flask-cache?
I can't find it anywhere and pip install is not working for me on Windows bash.

I am using a virtualenv in Windows bash. When I run a python file that has a flask cache import, I get the following error:

Traceback (most recent call last):
  File "run.py", line 3, in <module>
    from app import app
  File "/mnt/c/Users/.../app/__init__.py", line 1, in <module>
    from main import *
  File "/mnt/c/Users/.../app/main.py", line 2, in <module>
    from flask_cache import Cache
ImportError: No module named flask_cache
```

答:
Turns out, some of the packages were missing from the requirements file I was given. After several searches, I was able to resolve this by installing flask cache for both python 2.7 and 3 distribution.

I used pip2.7 install PACKAGE_NAME and check the same for pip3 install PACKAGE_NAME in my virtual environment.

For any newbie coders out there, it may be really difficult to get through a problem but you can do it! If you need to seek someone out to help you please reach out to me and we can pair program together and help each other out.

I will NEVER turn you away or think your question is dumb. I know how frustrating dealing with a programming problem on your own is with little to no documentation on an application you're supposed to be supporting.


问:
XPath trying to get the third position
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

```<code><publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>
</code>```

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

答:
For Xpath 1.0 you can use next expression

```<code>//authors[substring-after(substring-after( . ,',' ),',')]
 /substring-before(concat(normalize-space(substring-after(substring-after(.,',' ),',')),","),",")
</code>```

The 1st part of Xpath selects authors tag having not less that 2 comma.

If you want to get the name of the third author not using a programming language, the second part will do that.

I've splitted the Xpath for readability

Title: XPath trying to get the third position

Body:
I want to get the authors on the third position. I am using //authors[3]. Is there any reason this way does not work? When i type //authors[1] i get the whole row.

<publications>

    <publication>

    <publication_name> Group agency: The possibility, design, and status of corporate agents </publication_name>
    <authors> C List,P Pettit  </authors>
    <publisher> Oxford University Press </publisher>
    <year> 2011 </year>
    <citation> 598 </citation>

</publication>

<publication>

    <publication_name> Aggregating sets of judgments: An impossibility result</publication_name>
    <authors> C List, P Pettit  </authors>
    <publisher> Economics and Philosophy </publisher>
    <volume> 18 </volume>
    <number> 1 </number>
    <pages> 89- 110 </pages>
    <citation> 558 </citation>
    <year> 2002 </year>e

</publication>

<publication>

    <publication_name> Epistemic democracy: generalizing the Condorcet jury theorem</publication_name>
    <authors> C List, RE Goodin  </authors>
    <publisher> Journal of Political Philosophy </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 277-306 </pages>
    <citation> 409 </citation>
    <year> 2001 </year>

</publication>

<publication>

    <publication_name> Arrow’s theorem in judgment aggregation </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Social Choice and Welfare </publisher>
    <volume> 29 </volume>
    <number> 1 </number>
    <pages> 19 - 33 </pages>
    <citation> 220 </citation>
    <year> 2007 </year>

</publication>

<publication>

    <publication_name> Deliberation, single-peakedness, and the possibility of meaningful democracy: evidence from deliberative polls </publication_name>
    <authors> C List, RC Luskin, JS Fishkin, I McLean  </authors>
    <publisher> Journal of Politics </publisher>
    <volume> 75 </volume>
    <number> 01 </number>
    <pages> 80-95 </pages>
    <citation> 143 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Swarm intelligence: When uncertainty meets conflict </publication_name>
    <authors> L Conradt, C List, TJ Roper </authors>
    <publisher> The American Naturalist </publisher>
    <volume> 182 </volume>
    <number> 5 </number>
    <pages> 592-610 </pages>
    <citation> 10 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Intradimensional Single-peakedness and the Multidimensional Arrow Problem </publication_name>
    <authors> C List </authors>
    <publisher> Theory and Decision </publisher>
    <citation> 10 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> The methodology of political theory </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> The Oxford Handbook of Philosophical Methodology </publisher>
    <citation> 8 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Social choice theory and deliberative democracy: a response to Aldred </publication_name>
    <authors> JS Dryzek, C List </authors>
    <publisher> British Journal of Political Science </publisher>
    <volume> 34 </volume>
    <number> 4 </number>
    <pages> 752-758 </pages>
    <citation> 8 </citation>
    <year> 2004 </year>

</publication>

<publication>

    <publication_name> Episteme symposium on group agency: Replies to Gaus, Cariani, Sylvan, and Briggs </publication_name>
    <authors> C List, P Pettit </authors>
    <publisher> Episteme </publisher>
    <volume> 9 </volume>
    <number> 3 </number>
    <pages> 293 </pages>
    <citation> 5 </citation>
    <year> 2012 </year>

</publication>

<publication>

    <publication_name> Two intuitions about free will: Alternative possibilities and intentional endorsement </publication_name>
    <authors> C List, W Rabinowicz  </authors>
    <publication> Philosophical Perspectives </publication>
    <volume> 28 </volume>
    <number> 1 </number>
    <pages> 155-172 </pages>
    <citation> 4 </citation>
    <year> 2014 </year>

</publication>

<publication>

    <publication_name> Reasons for (prior) belief in Bayesian epistemology </publication_name>
    <authors> F Dietrich, C List  </authors>
    <publisher> Synthese </publisher>
    <volume> 190 </volume>
    <number> 5 </number>
    <pages> 787-808 </pages>
    <citation> 4 </citation>
    <year> 2013 </year>

</publication>

<publication>

    <publication_name> Freedom as independence </publication_name>
    <authors> C List, L Valentini  </authors>
    <publisher> Ethics </publisher>
    <volume> 126 </volume>
    <number> 4 </number>
    <pages> 1043-1074 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

<publication>

    <publication_name> Belief revision generalized: A joint characterization of Bayes' and Jeffrey's rules </publication_name>
    <authors> F Dietrich, C List, R Bradley </authors>
    <publisher> Journal of Economic Theory </publisher>
    <volume> 162</volume>
    <pages> 352–371 </pages>
    <citation> 3 </citation>
    <year> 2016 </year>

</publication>

    <publication>

        <publication_name>Which worlds are possible? A judgment aggregation problem</publication_name>
        <authors>C List</authors>
        <publisher>Journal of Philosophical Logic</publisher>
        <volume>37</volume>
        <number>1</number>
        <pages>57-65</pages>
        <citation>12</citation>
        <year>2008</year>

    </publication>

</publications>

I only want to get the author on the third position.

There is no result and i get an error saying: The XPath query returned no results. XPath scope:current file.

Body:
For Xpath 1.0 you can use next expression

//authors[substring-after(substring-after( . ,',' ),',')]
 /substring-before(concat(normalize-space(substring-after(substring-after(.,',' ),',')),","),",")

The 1st part of Xpath selects authors tag having not less that 2 comma.

If you want to get the name of the third author not using a programming language, the second part will do that.

I've splitted the Xpath for readability


问:
PostgreSQL ERROR: canceling statement due to conflict with recovery
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

```<code>ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed
</code>```

Any suggestions on how to resolve? Thanks

答:
No need to touch hot_standby_feedback. As others have mentioned, setting it to on can bloat master. Imagine opening a transaction on a slave and not closing it.

Instead, set max_standby_archive_delay and max_standby_streaming_delay to sane values:

```<code># /etc/postgresql/10/main/postgresql.conf on a slave
max_standby_archive_delay = 900s
max_standby_streaming_delay = 900s
</code>```

This way queries on slaves with a duration less than 900 seconds won't be cancelled. If your workload requires longer queries, just set these options to a higher value.

The postgres docs discuss this at some length. Key advice from there is:

if the standby server is meant for executing long-running queries, then a high or even infinite delay value [in max_standby_archive_delay and max_standby_streaming_delay] may be preferable

and

Users should be clear that tables that are regularly and heavily updated on the primary server will quickly cause cancellation of longer running queries on the standby. In such cases the setting of a finite value for max_standby_archive_delay or max_standby_streaming_delay can be considered similar to setting statement_timeout.

You can also consider setting vacuum_defer_cleanup_age (on the primary) in combination with the max standby delays. As the docs say:

Another option is to increase vacuum_defer_cleanup_age on the primary server, so that dead rows will not be cleaned up as quickly as they normally would be. This will allow more time for queries to execute before they are canceled on the standby, without having to set a high max_standby_streaming_delay

Body:
I'm getting the following error when running a query on a PostgreSQL db in standby mode. The query that causes the error works fine for 1 month but when you query for more than 1 month an error results.

ERROR: canceling statement due to conflict with recovery
Detail: User query might have needed to see row versions that must be removed

Any suggestions on how to resolve? Thanks

Body:
No need to touch hot_standby_feedback. As others have mentioned, setting it to on can bloat master. Imagine opening a transaction on a slave and not closing it.

Instead, set max_standby_archive_delay and max_standby_streaming_delay to sane values:

# /etc/postgresql/10/main/postgresql.conf on a slave
max_standby_archive_delay = 900s
max_standby_streaming_delay = 900s

This way queries on slaves with a duration less than 900 seconds won't be cancelled. If your workload requires longer queries, just set these options to a higher value.

The postgres docs discuss this at some length. Key advice from there is:

if the standby server is meant for executing long-running queries, then a high or even infinite delay value [in max_standby_archive_delay and max_standby_streaming_delay] may be preferable

and

Users should be clear that tables that are regularly and heavily updated on the primary server will quickly cause cancellation of longer running queries on the standby. In such cases the setting of a finite value for max_standby_archive_delay or max_standby_streaming_delay can be considered similar to setting statement_timeout.

You can also consider setting vacuum_defer_cleanup_age (on the primary) in combination with the max standby delays. As the docs say:

Another option is to increase vacuum_defer_cleanup_age on the primary server, so that dead rows will not be cleaned up as quickly as they normally would be. This will allow more time for queries to execute before they are canceled on the standby, without having to set a high max_standby_streaming_delay

ContentLicense: CC BY-SA 4.0


问:
Not using Github anymore - Sourcetree keeps asking for password
I've moved my repositories from Github (where they were created) to Bitbucket and have been working happy for a while. Every now and then Source Tree asks for my Github password.

My Local Repositories pages doesn't have any repos that are on Github.

My Remote Repositories doesn't have any repos on it.

My Tools>Options>Authentications page doesn't have any Github accounts.

Are there other places I need to remove my Github account from?

What might be causing this?

Why is it asking?

答: Are you running windows? If so you might want to uninstall your git-credential-manager and check to see if your windows credential manager has an entry for github. If so delete that too.</p>


问:
interactive stack using checkbox s1 and s2 and different functions
I am trying to make working model of Stack in which user can select the stack s1 or s2 and can perform operations like push and pop.

        <title>Stack With Constructor </title>

                stack

            <input type="checkbox" id="stack1" value="s1">s1

            <input type="checkbox" id="stack2" value="s2">s2

            <textarea id="tdisplay"></textarea>
            <textarea id="tpush"></textarea>
            <button onclick="doJob()">push</button>

            <button onclick="doJob1()">pop</button>
            <textarea id="tpop"></textarea>

    ```

I don't know how to use checkbox method. It means when i select s1 checkbox it should create s1 stack and I can do operations on it and same as for s2.

The result should be proper browser functions for interactive stack so it can work like in following steps:

User select s1 or s2 stack
If he/she selects s1 then they can work for all operations for s1.
User can switch between s2 too and can perform all operations.
I am having issues on the checkbox working.

答:
I think that you could have more luck with radio buttons. If s1 and s2 were a radio button group, like

  <input type="radio" name="stack_select" id="stack1" value="s1">s1

  <input type="radio" name="stack_select" id="stack2" value="s2">s2

Then you can listen to when either changes in one function, and have the other ui components update the proper, selected stack.

The problem with checkboxes for your case is that they aren't mutually exclusive, and it seems like you never want to have both s1 and s2 selected at the same time.

Body:
I am trying to make working model of Stack in which user can select the stack s1 or s2 and can perform operations like push and pop.

        <title>Stack With Constructor </title>

                stack

            <input type="checkbox" id="stack1" value="s1">s1

            <input type="checkbox" id="stack2" value="s2">s2

            <textarea id="tdisplay"></textarea>
            <textarea id="tpush"></textarea>
            <button onclick="doJob()">push</button>

            <button onclick="doJob1()">pop</button>
            <textarea id="tpop"></textarea>

I don't know how to use checkbox method. It means when i select s1 checkbox it should create s1 stack and I can do operations on it and same as for s2.

The result should be proper browser functions for interactive stack so it can work like in following steps:

User select s1 or s2 stack
If he/she selects s1 then they can work for all operations for s1.
User can switch between s2 too and can perform all operations.
I am having issues on the checkbox working.

Body:
I think that you could have more luck with radio buttons. If s1 and s2 were a radio button group, like

  <input type="radio" name="stack_select" id="stack1" value="s1">s1
  <br>
  <input type="radio" name="stack_select" id="stack2" value="s2">s2

Then you can listen to when either changes in one function, and have the other ui components update the proper, selected stack.

The problem with checkboxes for your case is that they aren't mutually exclusive, and it seems like you never want to have both s1 and s2 selected at the same time.


问:
R- How to add parts of a column to another column in a dataframe?
I have a very specific problem. My dataframe looks like this:

My problem is the Date and Day columns. Currently its like this:

Year-month-1  - And then in the next column the day.

I want it look like a normal Date-Column, like Year-month-day. So I want to take the days out of the 2nd column and replace them with the 01 in the first column.

Any idea how to do that?

答:
Here you go

```<code>library(lubridate)
library(tidyr)
library(dplyr)

df %>% unite(new_Date, Date, Day, sep = ' ') %>% mutate(new_Date = ymd(gsub("([0-9]{2} Day)", "", new_Date)))
</code>```

This uses tidyr::unite and lubridate::ymd along with dplyr functions.

Body:
Here you go

library(lubridate)
library(tidyr)
library(dplyr)

df %>% unite(new_Date, Date, Day, sep = ' ') %>% mutate(new_Date = ymd(gsub("([0-9]{2} Day)", "", new_Date)))

This uses tidyr::unite and lubridate::ymd along with dplyr functions.


问:
How to use an object of type class from an generic class as a parameter? - generics and reflection combined
I have two classes:

```<code>public abstract class MyAbstractSuperClass<A, B> {

    public MyAbstractSuperClass(Class<A> a, Class<B> b) {
        ...
    }

    ...
}

public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass<A>> {

    public MyClass(Class<A> a) {
    super(a, MyOtherClass.class));
            ...
    }

    ...
}
</code>```

Now you see, the subclass has to call the superclass's constructor. At that line I get the following error:

```<code>The constructor MySuperClass<A, MyOtherClass<A>>(Class<A>, Class<MyOtherClass>) is undefined
</code>```

So how do I get an object of type Class<MyOtherClass>?

And how do I do it in the super constructor call, where I can't execute much?

Thanks in advance.

答:
You must add a second argument to the MyClass constructor:

```<code>public MyClass(Class<A> a, Class<MyOtherClass<A>> bClass) {
    super(a, bclass));
}
</code>```

@Bert F: This does "pass the buck" in some sense, but it passes the buck to someone who can actually provide a class literal of the appropriate type.  The caller knows the actual value of the type variable A, and so can provide a class literal of the correct type.  Due to erasure, MyClass can't do that.

Body:
I have two classes:

public abstract class MyAbstractSuperClass {

    public MyAbstractSuperClass(Class a, Class b) {
        ...
    }

    ...
}

public class MyClass extends MyAbstractSuperClass<A, MyOtherClass> {

    public MyClass(Class a) {
    super(a, MyOtherClass.class));
            ...
    }

    ...
}

Now you see, the subclass has to call the superclass's constructor. At that line I get the following error:

The constructor MySuperClass<A, MyOtherClass>(Class, Class<MyOtherClass>) is undefined

So how do I get an object of type Class<MyOtherClass>?

And how do I do it in the super constructor call, where I can't execute much?

Thanks in advance.

Body:
You must add a second argument to the MyClass constructor:

public MyClass(Class<A> a, Class<MyOtherClass<A>> bClass) {
    super(a, bclass));
}

@Bert F: This does "pass the buck" in some sense, but it passes the buck to someone who can actually provide a class literal of the appropriate type.  The caller knows the actual value of the type variable A, and so can provide a class literal of the correct type.  Due to erasure, MyClass can't do that.


问:
How to migrate Nexus to Artifactory ? Any manual or automation process steps ?
Migration steps from nexus to Artifactory (local, remote, virtual )

-> manual steps or automation ?

答: We have a tool for that :) Welcome!</p>

Body: We have a tool for that :) Welcome!


问:
How to login a user with spring 3.2 new mvc testing
This works fine until I have to test a service that needs a logged in user, how do I add user to context :</p>

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
@WebAppConfiguration
public class FooTest {
@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Resource(name = "aService")
private AService aService; //uses logged in user

@Before
public void setup() {
    this.mockMvc = webAppContextSetup(this.webApplicationContext).build();
}
</code>```

答:
Yet another way... I use the following annotations:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    WithSecurityContextTestExcecutionListener.class})
@WithMockUser
public class WithMockUserTests {
    ...
}
</code>```

(source)

Body:
This works fine until I have to test a service that needs a logged in user, how do I add user to context :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-test.xml")
@WebAppConfiguration
public class FooTest {
@Autowired
private WebApplicationContext webApplicationContext;

private MockMvc mockMvc;

@Resource(name = "aService")
private AService aService; //uses logged in user

@Before
public void setup() {
    this.mockMvc = webAppContextSetup(this.webApplicationContext).build();
}

Body:
Yet another way... I use the following annotations:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(listeners={ServletTestExecutionListener.class,
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    WithSecurityContextTestExcecutionListener.class})
@WithMockUser
public class WithMockUserTests {
    ...
}

(source)


问:
SQL Query Criteria Syntax
I have a question on a select query that I'm running within a MS Access database that's comparing two tables.
My query returns blanks if I type in the criteria section:

```<code>Like "*[Name of field]*"
</code>```

However I get the expected results if I type the below instead:

```<code>Like "*" & [Name of field] & "*"
</code>```

Can anyone explain me the difference?

Thanks!

答:
"*[name of field]*"  gets interpreted exactly as written, where as "*" & [name of field] & "*" interprets the field, takes its value, and concatenates the leading and trailing *.  So if the value of [name of field] is "something", then

"*[name of field]*" --> "*[name of field]*"

"*" & [name of field] & "*" --> "*something*"

Title: SQL Query Criteria Syntax

Body:
I have a question on a select query that I'm running within a MS Access database that's comparing two tables.
My query returns blanks if I type in the criteria section:

Like "*[Name of field]*"

However I get the expected results if I type the below instead:

Like "*" & [Name of field] & "*"

Can anyone explain me the difference?

Thanks!


问:
Using .js file extensions whilst writing scripts that return jsx
I started using react as my ui framework of choice. Upon my adventure through the documentation I noticed that when using the create-react-app script to spin up a new react boilerplate, they used .js file extension on scripts that where returning jsx code. When I asked my buddy he told me that you should use the .jsx extension on scripts that are returning this kind of code.

Im a bit lost here as if both works, wouldn't it just be better to go with the .js extension as at the end of the day its javascript we writing.

Please help me with what is considered best practise. (I kinda have a feeling it would be to use the .jsx extensions on these types of scripts, but I'd love to hear the community's view on this)

Thanks in advance :)

答:
It's really up to personal preference.

My personal opinion is JavaScript is JavaScript, and I just use .js. Others will prefer to use .jsx in files that are JSX and .js in for things like utilities, in order to differentiate. The only important thing is to be consistent in whatever you choose (at least within one project).

In general, it doesn't matter.

The only time it might actually matter is based on your build pipeline. Some build pipelines may be configured to compile .js and .jsx with slightly different rules, but that would be based on your application (things like create-react-app don't care).

At the end of the day, you could use a .cookiemonster extension and it'd work just fine (as long as your build pipeline is configured to handle it).


问:
How do I create an input box with Python?
I want to create an on-screen input box that a user can interact with.

The user would see a window with an input field they can click with the mouse. The user could type or erase text in the field, then press OK once they have finished adding text. Lastly, my program would store this text for later use.

How can I create a text box in Python which allows user input?

答:
The simplest way to do it is to set an input equal to a variable for later use, and then call the variable later in the program.</p>

```<code>variable = str(input("Type into the text box."))
</code>```

Body:
The simplest way to do it is to set an input equal to a variable for later use, and then call the variable later in the program.

variable = str(input("Type into the text box."))


问:
Access respective parent object from $('.class').appendTo()
I'm trying to adapt some slideshow code I found here to be reusable based on classes.  The first slideshow toggles once, but then there is no other change.  I'm assuming this is due to the use of $(this).parent().  If so, how would I access the respective parent properly? If not, what is going on?

Edit: To be clear, both boxes contents should change independently!

$('.widget-slide:first').show();
setInterval(function() {
    $('.widget-slide:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo($(this).parent());
}, 2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}</code>```

        1

        2

        3

        4

        A

        B

        C

        D

```

答:
If you want to make your code reusable you must use the each() function so it will loop through as match slider as you add and make them fiddle in/out :

```<code>$(".widget-slideshow").find('.widget-slide:first').each(function() {
    $(this).fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this).parent());
});
</code>```

Working Snippet

$('.widget-slide:first').show();
setInterval(function() {
  $(".widget-slideshow").find('.widget-slide:first').each(function() {
    $(this).fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this).parent());
  });
}, 3000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child) {
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}</code>```

    1

    2

    3

    4

    1

    2

    3

    4

```

Body:
I'm trying to adapt some slideshow code I found here to be reusable based on classes.  The first slideshow toggles once, but then there is no other change.  I'm assuming this is due to the use of $(this).parent().  If so, how would I access the respective parent properly? If not, what is going on?

Edit: To be clear, both boxes contents should change independently!

$('.widget-slide:first').show();
setInterval(function() {
    $('.widget-slide:first')
        .fadeOut(1000)
        .next()
        .fadeIn(1000)
        .end()
        .appendTo($(this).parent());
}, 2000);

.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child){
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}

        1

        2

        3

        4

        A

        B

        C

        D

Body:
If you want to make your code reusable you must use the each() function so it will loop through as match slider as you add and make them fiddle in/out :

$(".widget-slideshow").find('.widget-slide:first').each(function() {
    $(this).fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this).parent());
});

Working Snippet

$('.widget-slide:first').show();
setInterval(function() {
  $(".widget-slideshow").find('.widget-slide:first').each(function() {
    $(this).fadeOut(1000)
      .next()
      .fadeIn(1000)
      .end()
      .appendTo($(this).parent());
  });
}, 3000);

.widget-slideshow {
  position: relative;
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}

.widget-slide:not(:first-child) {
  display: none;
}

.widget-slide {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  font-size: 20px;
  line-height: 50px;
  text-align: center;
  overflow: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-slideshow">
  <div class="widget-slide">
    1
  </div>
  <div class="widget-slide">
    2
  </div>
  <div class="widget-slide">
    3
  </div>
  <div class="widget-slide">
    4
  </div>
</div>

<div class="widget-slideshow">
  <div class="widget-slide">
    1
  </div>
  <div class="widget-slide">
    2
  </div>
  <div class="widget-slide">
    3
  </div>
  <div class="widget-slide">
    4
  </div>
</div>


问:
Tabulating the Data MySQL PHP
Anyone can help me out in tabulating this data on PHP/HTML as I am only able to get to raw data which is not formulated. This is the code I am using:</p>

```<code>// Price and Flight Select Statements
$pricesql = "select PriceID,RouteID,ClassID,Price from price;";
$printpricesql=mysqli_query($connect,$pricesql);

while($row=mysqli_fetch_array($printpricesql))
{
     echo $row['PriceID'];
echo $row['RouteID'];
echo $row['ClassID'];
echo $row['Price'];
}

$flightsql = "select flightid,routeid,departuredate,arrivaldate from
flightschedule;";
$printflightsql=mysqli_query($connect,$flightsql);

while($row=mysqli_fetch_array($printflightsql))
{
echo $row['flightid'];
echo $row['routeid'];
echo $row['departuredate'];
echo $row['arrivaldate'];
 }
</code>```

答:
```<code>// Price and Flight Select Statements
$pricesql = "select PriceID,RouteID,ClassID,Price from price";
$printpricesql=mysqli_query($connect,$pricesql);

echo '<table>';

// headers
echo '<tr>';
    echo '<th>Price Id</th>';
    echo '<th>Route Id</th>';
    echo '<th>Class Id</th>';
    echo '<th>Price</th>';
echo '</tr>';

while($row=mysqli_fetch_array($printpricesql)) {
    echo '<tr>';
    echo '<td>'.$row['PriceID'].'</td>';
    echo '<td>'.$row['RouteID'].'</td>';
    echo '<td>'.$row['ClassID'].'</td>';
    echo '<td>'.$row['Price'].'</td>';
    echo '</tr>';
}
echo '</table>';

$flightsql = "select flightid,routeid,departuredate,arrivaldate from flightschedule";
$printflightsql=mysqli_query($connect,$flightsql);

echo '<table>';

// headers
echo '<tr>';
    echo '<th>Flight Id</th>';
    echo '<th>Route Id</th>';
    echo '<th>Departure Date</th>';
    echo '<th>Arrival Date</th>';
echo '</tr>';

while($row=mysqli_fetch_array($printflightsql)) {
    echo '<tr>';
    echo '<td>'.$row['flightid'].'</td>';
    echo '<td>'.$row['routeid'].'</td>';
    echo '<td>'.$row['departuredate'].'</td>';
    echo '<td>'.$row['arrivaldate'].'</td>';
    echo '</tr>';
}
echo '</table>';
</code>```

Title: Tabulating the Data MySQL PHP

Body:
Anyone can help me out in tabulating this data on PHP/HTML as I am only able to get to raw data which is not formulated. This is the code I am using:

// Price and Flight Select Statements
$pricesql = "select PriceID,RouteID,ClassID,Price from price;";
$printpricesql=mysqli_query($connect,$pricesql);

while($row=mysqli_fetch_array($printpricesql))
{
     echo $row['PriceID'];
echo $row['RouteID'];
echo $row['ClassID'];
echo $row['Price'];
}

$flightsql = "select flightid,routeid,departuredate,arrivaldate from
flightschedule;";
$printflightsql=mysqli_query($connect,$flightsql);

while($row=mysqli_fetch_array($printflightsql))
{
echo $row['flightid'];
echo $row['routeid'];
echo $row['departuredate'];
echo $row['arrivaldate'];
 }


问:
Determining endianness at compile time
Is there a safe, portable way to determine (during compile time) the endianness of the platform that my program is being compiled on? I'm writing in C.

[EDIT]
Thanks for the answers, I decided to stick with the runtime solution!

答:
From Finally, one-line endianness detection in the C preprocessor:

```<code>#include <stdint.h>

#define IS_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100)
</code>```

Any decent optimizer will resolve this at compile-time. gcc does at -O1.

Of course stdint.h is C99. For ANSI/C89 portability see Doug Gwyn's Instant C9x library.

Title: Determining endianness at compile time

Body:
From Finally, one-line endianness detection in the C preprocessor:

#include <stdint.h>

#define IS_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100)

Any decent optimizer will resolve this at compile-time. gcc does at -O1.

Of course stdint.h is C99. For ANSI/C89 portability see Doug Gwyn's Instant C9x library.


问:
Ranking Data Based on Matches
I have a query that identifies 'potential' duplicates based on multiple columns (V1,V2,V3,V4) in my database, but it is returning many matches making it difficult for a manual review, so I would like  to assign some ranks to the data based on:

a. if V5,V6 match - rank -1

b. if V7,V8 match - rank -2

and so on.

Along with the above, V1,V2,V3,V4 will match based on my current query. Is this possible with dense_rank()?

My current query is along the lines of:

```<code>SELECT ID, V1, V2, V3, V4, CreatedDate
FROM   (
  SELECT T1.ID, V1, V2, V3, V4, CreatedDate,
         COUNT(*)
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct,
         COUNT( CASE CreatedDate WHEN DATE '2017-08-01' THEN 1 END )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_date_match
  FROM   T1
         INNER JOIN T2
         ON ( T1.ID = T2.ID )
         INNER JOIN T3
         ON ( T1.ID = T3.ID )
)
WHERE  ct > 1
AND    ct_date_match > 0
</code>```

T1

```<code>ID |   V1 |  V2 |  V5   | V6 | CreatedDate
---| ---  | ---    ---   --- ----------
1  |   A  |  US |  1984 | QR | 01-AUG-2017
2  |   B  |  FR |  1991 | TY | 01-JAN-2017
3  |   C  |  AU |  1989 | GH | 25-SEP-2017
4  |   B  |  FR |  1995 | BN | 01-AUG-2017
5  |   A  |  US |  1984 | QR | 30-MAR-2016
6  |   C  |  AU |  1999 | MK | 14-JUN-2015
</code>```

T2

```<code>ID | V3    | V7
---| ---    ---
1  | Apple   D12
1  | Kiwi    S45
2  | Pear    T23
3  | Banana  U78
4  | Pear    T23
5  | Apple   D12
6  | Banana  P90
</code>```

T3

```<code>ID | V4      V8
---|  ---    ---
1  | Spinach A678
1  | Beets   V902
2  | Celery  T456
3  | Radish  Y675
4  | Celery  T456
5  | Spinach G890
6  | Celery  F567
6  | Radish  R453
</code>```

Current Output:

```<code>1 A US Apple Spinach
5 A US Apple Spinach
2 B FR Pear  Celery
4 B FR Pear  Celery
</code>```

Expected Output:                     Rnk

```<code>1 A US Apple Spinach 1984 QR D12 A678 1
5 A US Apple Spinach 1984 QR D12 G890 1
2 B FR Pear  Celery  1991 TY T23 T456 2
4 B FR Pear  Celery  1995 BN T23 T456 2
</code>```

答:
Not entirely sure I follow, but it looks like you can add partition counts of distinct V5/6/7/8 values to your inner query, and then evaluate those in the outer query:

```<code>SELECT ID, V1, V2, V3, V4, CreatedDate,
  CASE WHEN ct_v5 = 1 AND ct_v6 = 1 THEN 1
       WHEN ct_v7 = 1 AND ct_v8 = 1 THEN 2
  END AS rnk
FROM   (
  SELECT T1.ID, V1, V2, V3, V4, CreatedDate,
         COUNT(*)
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct,
         COUNT( CASE CreatedDate WHEN DATE '2017-08-01' THEN 1 END )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_date_match,
         COUNT( DISTINCT V5 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v5,
         COUNT( DISTINCT V6 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v6,
         COUNT( DISTINCT V7 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v7,
         COUNT( DISTINCT V8 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v8
  FROM   T1
         INNER JOIN T2
         ON ( T1.ID = T2.ID )
         INNER JOIN T3
         ON ( T1.ID = T3.ID )
)
WHERE  ct > 1
AND    ct_date_match > 0;
</code>```

Which with your data gets:

```<code>        ID V V2 V3     V4      CREATEDDAT        RNK
---------- - -- ------ ------- ---------- ----------
         1 A US Apple  Spinach 2017-08-01          1
         5 A US Apple  Spinach 2016-03-30          1
         2 B FR Pear   Celery  2017-01-01          2
         4 B FR Pear   Celery  2017-08-01          2
</code>```

This doesn't have a row for US/Kiwi/Beets, but the sample data only seems to have one set of those, and your original query doesn't report it either.

Title: Ranking Data Based on Matches

Body:
I have a query that identifies 'potential' duplicates based on multiple columns (V1,V2,V3,V4) in my database, but it is returning many matches making it difficult for a manual review, so I would like  to assign some ranks to the data based on:

a. if V5,V6 match - rank -1

b. if V7,V8 match - rank -2

and so on.

Along with the above, V1,V2,V3,V4 will match based on my current query. Is this possible with dense_rank()?

My current query is along the lines of:

SELECT ID, V1, V2, V3, V4, CreatedDate
FROM   (
  SELECT T1.ID, V1, V2, V3, V4, CreatedDate,
         COUNT(*)
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct,
         COUNT( CASE CreatedDate WHEN DATE '2017-08-01' THEN 1 END )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_date_match
  FROM   T1
         INNER JOIN T2
         ON ( T1.ID = T2.ID )
         INNER JOIN T3
         ON ( T1.ID = T3.ID )
)
WHERE  ct > 1
AND    ct_date_match > 0

T1

ID |   V1 |  V2 |  V5   | V6 | CreatedDate
---| ---  | ---    ---   --- ----------
1  |   A  |  US |  1984 | QR | 01-AUG-2017
2  |   B  |  FR |  1991 | TY | 01-JAN-2017
3  |   C  |  AU |  1989 | GH | 25-SEP-2017
4  |   B  |  FR |  1995 | BN | 01-AUG-2017
5  |   A  |  US |  1984 | QR | 30-MAR-2016
6  |   C  |  AU |  1999 | MK | 14-JUN-2015

T2

ID | V3    | V7
---| ---    ---
1  | Apple   D12
1  | Kiwi    S45
2  | Pear    T23
3  | Banana  U78
4  | Pear    T23
5  | Apple   D12
6  | Banana  P90

T3

ID | V4      V8
---|  ---    ---
1  | Spinach A678
1  | Beets   V902
2  | Celery  T456
3  | Radish  Y675
4  | Celery  T456
5  | Spinach G890
6  | Celery  F567
6  | Radish  R453

Current Output:

1 A US Apple Spinach
5 A US Apple Spinach
2 B FR Pear  Celery
4 B FR Pear  Celery

Expected Output:                     Rnk

1 A US Apple Spinach 1984 QR D12 A678 1
5 A US Apple Spinach 1984 QR D12 G890 1
2 B FR Pear  Celery  1991 TY T23 T456 2
4 B FR Pear  Celery  1995 BN T23 T456 2

Body:
Not entirely sure I follow, but it looks like you can add partition counts of distinct V5/6/7/8 values to your inner query, and then evaluate those in the outer query:

SELECT ID, V1, V2, V3, V4, CreatedDate,
  CASE WHEN ct_v5 = 1 AND ct_v6 = 1 THEN 1
       WHEN ct_v7 = 1 AND ct_v8 = 1 THEN 2
  END AS rnk
FROM   (
  SELECT T1.ID, V1, V2, V3, V4, CreatedDate,
         COUNT(*)
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct,
         COUNT( CASE CreatedDate WHEN DATE '2017-08-01' THEN 1 END )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_date_match,
         COUNT( DISTINCT V5 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v5,
         COUNT( DISTINCT V6 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v6,
         COUNT( DISTINCT V7 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v7,
         COUNT( DISTINCT V8 )
           OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_v8
  FROM   T1
         INNER JOIN T2
         ON ( T1.ID = T2.ID )
         INNER JOIN T3
         ON ( T1.ID = T3.ID )
)
WHERE  ct > 1
AND    ct_date_match > 0;

Which with your data gets:

        ID V V2 V3     V4      CREATEDDAT        RNK
---------- - -- ------ ------- ---------- ----------
         1 A US Apple  Spinach 2017-08-01          1
         5 A US Apple  Spinach 2016-03-30          1
         2 B FR Pear   Celery  2017-01-01          2
         4 B FR Pear   Celery  2017-08-01          2

This doesn't have a row for US/Kiwi/Beets, but the sample data only seems to have one set of those, and your original query doesn't report it either.


问:
How to switch True to False in Python
What operation do I need to do to always get a False value to become True or to get a True value to become False?
In other words, what do I do to switch the Boolean value of a given variable?

```<code>    new_dict = {}
    for i in range(1, 101):
        new_dict[i] = False

    i = 2
    while i < 101:
        for x in range(1, 101):
            if new_dict[x] % i == 0:
                a = new_dict[x]
                new_dict[x] = not a
        i += 1
    for a in new_dict:
        print 'Light #%d --> %r' % (a, new_dict[a])
</code>```

The output below is only True. From this, I understand that what I did for some reason is not changing every other value to False. Why is this happening?

Does anyone have any idea why?

```<code>    Light #1 --> True
    Light #2 --> True
    Light #3 --> True
    Light #4 --> True
    Light #5 --> True
    Light #6 --> True
    Light #7 --> True
    Light #8 --> True
    Light #9 --> True
    Light #10 --> True
    Light #11 --> True
    Light #12 --> True
    Light #13 --> True
    Light #14 --> True
    Light #15 --> True
    Light #16 --> True
    Light #17 --> True
    Light #18 --> True
    Light #19 --> True
    Light #20 --> True
    Light #21 --> True
    Light #22 --> True
    Light #23 --> True
    Light #24 --> True
    Light #25 --> True
    Light #26 --> True
    Light #27 --> True
    Light #28 --> True
    Light #29 --> True
    Light #30 --> True
    Light #31 --> True
    Light #32 --> True
    Light #33 --> True
    Light #34 --> True
    Light #35 --> True
    Light #36 --> True
    Light #37 --> True
    Light #38 --> True
    Light #39 --> True
    Light #40 --> True
    Light #41 --> True
    Light #42 --> True
    Light #43 --> True
    Light #44 --> True
    Light #45 --> True
    Light #46 --> True
    Light #47 --> True
    Light #48 --> True
    Light #49 --> True
    Light #50 --> True
    Light #51 --> True
    Light #52 --> True
    Light #53 --> True
    Light #54 --> True
    Light #55 --> True
    Light #56 --> True
    Light #57 --> True
    Light #58 --> True
    Light #59 --> True
    Light #60 --> True
    Light #61 --> True
    Light #62 --> True
    Light #63 --> True
    Light #64 --> True
    Light #65 --> True
    Light #66 --> True
    Light #67 --> True
    Light #68 --> True
    Light #69 --> True
    Light #70 --> True
    Light #71 --> True
    Light #72 --> True
    Light #73 --> True
    Light #74 --> True
    Light #75 --> True
    Light #76 --> True
    Light #77 --> True
    Light #78 --> True
    Light #79 --> True
    Light #80 --> True
    Light #81 --> True
    Light #82 --> True
    Light #83 --> True
    Light #84 --> True
    Light #85 --> True
    Light #86 --> True
    Light #87 --> True
    Light #88 --> True
    Light #89 --> True
    Light #90 --> True
    Light #91 --> True
    Light #92 --> True
    Light #93 --> True
    Light #94 --> True
    Light #95 --> True
    Light #96 --> True
    Light #97 --> True
    Light #98 --> True
    Light #99 --> True
    Light #100 --> True
</code>```

The question here How do I get the opposite (negation) of a Boolean in Python? and here python how to "negate" value : if true return false, if false return true seem to be the same but in my case, that simple concept is simply not working...

Thanks, I really appreciate all the help guys!!!

答:
Use the not operator:

```<code>In [1]: b = True

In [2]: not b
Out[2]: False

In [3]: b = not b

In [4]: b
Out[4]: False

In [5]: not b
Out[5]: True
</code>```

Title: How to switch True to False in Python

Body:
What operation do I need to do to always get a False value to become True or to get a True value to become False?
In other words, what do I do to switch the Boolean value of a given variable?

    new_dict = {}
    for i in range(1, 101):
        new_dict[i] = False

    i = 2
    while i < 101:
        for x in range(1, 101):
            if new_dict[x] % i == 0:
                a = new_dict[x]
                new_dict[x] = not a
        i += 1
    for a in new_dict:
        print 'Light #%d --> %r' % (a, new_dict[a])

The output below is only True. From this, I understand that what I did for some reason is not changing every other value to False. Why is this happening?

Does anyone have any idea why?

    Light #1 --> True
    Light #2 --> True
    Light #3 --> True
    Light #4 --> True
    Light #5 --> True
    Light #6 --> True
    Light #7 --> True
    Light #8 --> True
    Light #9 --> True
    Light #10 --> True
    Light #11 --> True
    Light #12 --> True
    Light #13 --> True
    Light #14 --> True
    Light #15 --> True
    Light #16 --> True
    Light #17 --> True
    Light #18 --> True
    Light #19 --> True
    Light #20 --> True
    Light #21 --> True
    Light #22 --> True
    Light #23 --> True
    Light #24 --> True
    Light #25 --> True
    Light #26 --> True
    Light #27 --> True
    Light #28 --> True
    Light #29 --> True
    Light #30 --> True
    Light #31 --> True
    Light #32 --> True
    Light #33 --> True
    Light #34 --> True
    Light #35 --> True
    Light #36 --> True
    Light #37 --> True
    Light #38 --> True
    Light #39 --> True
    Light #40 --> True
    Light #41 --> True
    Light #42 --> True
    Light #43 --> True
    Light #44 --> True
    Light #45 --> True
    Light #46 --> True
    Light #47 --> True
    Light #48 --> True
    Light #49 --> True
    Light #50 --> True
    Light #51 --> True
    Light #52 --> True
    Light #53 --> True
    Light #54 --> True
    Light #55 --> True
    Light #56 --> True
    Light #57 --> True
    Light #58 --> True
    Light #59 --> True
    Light #60 --> True
    Light #61 --> True
    Light #62 --> True
    Light #63 --> True
    Light #64 --> True
    Light #65 --> True
    Light #66 --> True
    Light #67 --> True
    Light #68 --> True
    Light #69 --> True
    Light #70 --> True
    Light #71 --> True
    Light #72 --> True
    Light #73 --> True
    Light #74 --> True
    Light #75 --> True
    Light #76 --> True
    Light #77 --> True
    Light #78 --> True
    Light #79 --> True
    Light #80 --> True
    Light #81 --> True
    Light #82 --> True
    Light #83 --> True
    Light #84 --> True
    Light #85 --> True
    Light #86 --> True
    Light #87 --> True
    Light #88 --> True
    Light #89 --> True
    Light #90 --> True
    Light #91 --> True
    Light #92 --> True
    Light #93 --> True
    Light #94 --> True
    Light #95 --> True
    Light #96 --> True
    Light #97 --> True
    Light #98 --> True
    Light #99 --> True
    Light #100 --> True

The question here How do I get the opposite (negation) of a Boolean in Python? and here python how to "negate" value : if true return false, if false return true seem to be the same but in my case, that simple concept is simply not working...

Thanks, I really appreciate all the help guys!!!

Body:
Use the not operator:

In [1]: b = True

In [2]: not b
Out[2]: False

In [3]: b = not b

In [4]: b
Out[4]: False

In [5]: not b
Out[5]: True


问:
Ember get filtered data from the store/mirage
I am trying to build an app for smarthome devices with ember. I already have installed mirage and declare an array which is called data. It holds arrays like households, users and devices. Now I am stuck with get filtered data from the store and i am really confused by the behaviour of the store. For this reason I already read some equal topics like this Filtering store data in ember but this doesn´t work in my case.

Actually this is my router.js

```<code>Router.map(function() {
  this.route('about');
  this.route('users', function() {
  });
  this.route('households', function() {
    this.route('index', { path: '/:user_id' })
    this.route('rooms',{ path: '/:household_id' });
    this.route('devices');
  });
});
</code>```

If I am going to households.index I want to see all households which have the user-id in his member-array. The following code snipped shows an example of my data-structure.

```<code>  "users": [
      {
          "id":101,
          "forename":"Peter",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      },
      {
          "id":102,
          "forename":"Anna",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      }
]

  "households":[
      {
          "id":501,
          "name":"Zuhause",
          "admin":131000,
          "member":[
              101,
              102
          ]
}
</code>```

I am calling the route household.index like this {{#link-to "households.index" user.id}} and my route in household.index looks like this

```<code>model(params) {
    //holt alle Haushalte und gibt dann nur die Haushalte weiter, die auch den aktuellen Benutzer als Member haben.
   return this.get('store').findAll('household').then(results => results.filter((site) => {
       return site.get('member').filter(x => x == params.user_id).length > 0;
   }));
  }
</code>```

And my config.js part at mirage like this:

```<code>  this.get('/households', function(db, request) {
    return { households: data.households };
});
</code>```

This works fine!
But in my opinion the server is responsible for giving me the data I am requesting for. So all I want is that I send a specific request and just get the households that I need.

My attempt:
index.js:

```<code>export default Route.extend({
    model(params) {
        return this.get('store').find('household', params.user_id);
      }
});
</code>```

config js part:

```<code>  this.get('/households/:id', function(db, request) {
      console.log('household get');
      console.log(data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0));
    return  { households: data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };
});
</code>```

Debug Error:

Error while processing route: households.index payload.data is null

I cant understand why this error occurs. The log gives me the array i want to return.

答:
Make sure you are using RestSerializer in mirage,

```<code>// mirage/serializers/application.js
import { RestSerializer } from 'ember-cli-mirage';

export default RestSerializer;
</code>```

and for the right format refer RESTAdapterAPI.

Just ensure are you returning data in the below format,

for the single response,

```<code>{
  "posts": {
    "id": 1,
    "title": "I'm Running to Reform the W3C's Tag",
    "author": "Yehuda Katz"
  }
}
</code>```

and for more than one,

```<code>{
  "posts": [
    {
      "id": 1,
      "title": "I'm Running to Reform the W3C's Tag",
      "author": "Yehuda Katz"
    },
    {
      "id": 2,
      "title": "Rails is omakase",
      "author": "D2H"
    }
  ]
}
</code>```

Body:
I am trying to build an app for smarthome devices with ember. I already have installed mirage and declare an array which is called data. It holds arrays like households, users and devices. Now I am stuck with get filtered data from the store and i am really confused by the behaviour of the store. For this reason I already read some equal topics like this Filtering store data in ember but this doesn´t work in my case.

Actually this is my router.js

Router.map(function() {
  this.route('about');
  this.route('users', function() {
  });
  this.route('households', function() {
    this.route('index', { path: '/:user_id' })
    this.route('rooms',{ path: '/:household_id' });
    this.route('devices');
  });
});

If I am going to households.index I want to see all households which have the user-id in his member-array. The following code snipped shows an example of my data-structure.

  "users": [
      {
          "id":101,
          "forename":"Peter",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      },
      {
          "id":102,
          "forename":"Anna",
          "surname":"Peterson",
          "memberIn":[
              501
          ]
      }
]

  "households":[
      {
          "id":501,
          "name":"Zuhause",
          "admin":131000,
          "member":[
              101,
              102
          ]
}

I am calling the route household.index like this {{#link-to "households.index" user.id}} and my route in household.index looks like this

model(params) {
    //holt alle Haushalte und gibt dann nur die Haushalte weiter, die auch den aktuellen Benutzer als Member haben.
   return this.get('store').findAll('household').then(results => results.filter((site) => {
       return site.get('member').filter(x => x == params.user_id).length > 0;
   }));
  }

And my config.js part at mirage like this:

  this.get('/households', function(db, request) {
    return { households: data.households };
});

This works fine!
But in my opinion the server is responsible for giving me the data I am requesting for. So all I want is that I send a specific request and just get the households that I need.

My attempt:
index.js:

export default Route.extend({
    model(params) {
        return this.get('store').find('household', params.user_id);
      }
});

config js part:

  this.get('/households/:id', function(db, request) {
      console.log('household get');
      console.log(data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0));
    return  { households: data.households.filter(x => x.member.filter(x => x == request.params.id).length > 0) };
});

Debug Error:

Error while processing route: households.index payload.data is null

I cant understand why this error occurs. The log gives me the array i want to return.

Body:
Make sure you are using RestSerializer in mirage,

// mirage/serializers/application.js
import { RestSerializer } from 'ember-cli-mirage';

export default RestSerializer;

and for the right format refer RESTAdapterAPI.

Just ensure are you returning data in the below format,

for the single response,

{
  "posts": {
    "id": 1,
    "title": "I'm Running to Reform the W3C's Tag",
    "author": "Yehuda Katz"
  }
}

and for more than one,

{
  "posts": [
    {
      "id": 1,
      "title": "I'm Running to Reform the W3C's Tag",
      "author": "Yehuda Katz"
    },
    {
      "id": 2,
      "title": "Rails is omakase",
      "author": "D2H"
    }
  ]
}


问:
Provide arguments with a method
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

```<code>anotherMethod(method())
</code>```

where anotherMethod has arbitrary arguments like

```<code>public void anotherMethod(int a, int b, String c)
</code>```

And what is if the types stay the same, like with

```<code>public int add(int a, int b, int c)
</code>```

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

答:
There is nothing that works the way you wish for at compile time. As the other answers are pointing out, there are varargs. But that is just syntactical sugar. That is just the compiler implicitly creating an array of a certain type for you.

But beyond that, there is reflection. Reflection allows you to dynamically inspect classes and methods at *runtime.

In other words: you can do something like

```<code>Object whatever = ...
Class<?> someClass = whatever.getClass();
</code>```

And now you can ask someClass about the methods it has. And which parameters they need.

But as said: all of that is runtime only. And it the reflection APIs are very easy to get wrong. And you only find out at runtime, when some exception is thrown.

Title: Provide arguments with a method

Body:
Is there a way in Java to create a method that would return the list of parameters of another method such that I am able to call

anotherMethod(method())

where anotherMethod has arbitrary arguments like

public void anotherMethod(int a, int b, String c)

And what is if the types stay the same, like with

public int add(int a, int b, int c)

If there is no such way, how could I model the list of parameters such that it would work? Is it a List or an array or something else?

Body:
There is nothing that works the way you wish for at compile time. As the other answers are pointing out, there are varargs. But that is just syntactical sugar. That is just the compiler implicitly creating an array of a certain type for you.

But beyond that, there is reflection. Reflection allows you to dynamically inspect classes and methods at *runtime.

In other words: you can do something like

Object whatever = ...
Class<?> someClass = whatever.getClass();

And now you can ask someClass about the methods it has. And which parameters they need.

But as said: all of that is runtime only. And it the reflection APIs are very easy to get wrong. And you only find out at runtime, when some exception is thrown.