问:
Makefile from one source Directory trying to access a cpp file from other Directory
I've an issue with object creation for a cpp files residing in 2 different directories as show below:

```<code>- Project-xyz
  - Hello
    - Hello.cpp
  - World
    - Main.cpp
    - World.cpp
    - Makefile
</code>```

For better clarity here is how the code looks (just a dummy code).

hello/Hello.h

```<code>#ifndef HELLO_H
#define HELLO_H

void HelloPrint();

#endif // HELLO_H
</code>```

hello/Hell.cpp

```<code>#include <iostream>
#include "Hello.h"

void HelloPrint()
{
  std::cout <<"Hello" << std::endl;
}
</code>```

world/World.h

```<code> #ifndef WORLD_H
 #define WORLD_H

 void WorldPrint();

 #endif // WORLD_H
</code>```

world/World.cpp

```<code>#include <iostream>
#include "World.h"

void WorldPrint()
{
 std::cout <<"World!" << std::endl;
}
</code>```

world/Makefile
Using a makefile given in here. Which is working fine. But it doesn't create any obj files.

```<code># set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors

# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=

# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')

# find headers
HEADERS := $(shell find . -name '*.h')

OUTPUT := HelloWorld

# Everything depends on the output
all: $(OUTPUT)

# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)

clean:
     $(RM) $(OUTPUT)
</code>```

I'm  looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.

Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working.
How to get it working?

world/Makefile

```<code>GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)
</code>```

When i try to run the make it throws the following error.

```<code>g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4
</code>```

It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.

Any help from the makefile Masters is appreciated! :)

答:
You cannot compile multiple c or cpp files at a time AND specify ONE object file for them. See also this question Compile multiple C source fles into a unique object file The following command gives you error:

```<code>g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
</code>```

The following compiles to object files giving you a Main.o and Hello.o and World.o in the current directory:

```<code>g++ -I./hello -c -Wall -c world/Main.cpp hello/Hello.cpp world/World.cpp
</code>```

You could compile each cpp file one by one and generate object file for each then link them together. This is how any big project with multiple source code files is build. By hand do this:

```<code>cd world
g++ -I../hello -c -Wall -c Main.cpp -o objdir/Main.o
g++ -c -Wall -c ../hello/Hello.cpp -o objdir/Hello.o
g++ -c -Wall -c World.cpp -o objdir/World.o
# link:
g++ objdir/Main.o objdir/Hello.o objdir/World.o -o HelloWorld
</code>```

from man gcc

```<code>   -c  Compile or assemble the source files, but do not link.  The linking stage simply is not done.  The ultimate output is in the form of an object file for each source file.

   -o file
       Place output in file file.  This applies to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.
</code>```

Answer: I meant to not directly answer :-P but it is a little bit tricky. Here is what you need to look at in your Makefile:

```<code># you want to add reference to hello as include dir
#  for compiling Main.cpp, In CPPFLAGS add -I ../hello

# the OBJ list is missing a reference to files in hello directory:
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
OBJ+=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(notdir $(wildcard ../hello/*.cpp))))

# no change needed for the %.cpp
# new rule needed to allow it to find hello dir:

$(OBJDIR)/%.o:
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(OBJDIR)/%.o: ../hello/%.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
</code>```

read: https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html

Body:
I've an issue with object creation for a cpp files residing in 2 different directories as show below:

- Project-xyz
  - Hello
    - Hello.cpp
  - World
    - Main.cpp
    - World.cpp
    - Makefile

For better clarity here is how the code looks (just a dummy code).

hello/Hello.h

#ifndef HELLO_H
#define HELLO_H

void HelloPrint();

#endif // HELLO_H

hello/Hell.cpp

#include <iostream>
#include "Hello.h"

void HelloPrint()
{
  std::cout <<"Hello" << std::endl;
}

world/World.h

 #ifndef WORLD_H
 #define WORLD_H

 void WorldPrint();

 #endif // WORLD_H

world/World.cpp

#include <iostream>
#include "World.h"

void WorldPrint()
{
 std::cout <<"World!" << std::endl;
}

world/Makefile
Using a makefile given in here. Which is working fine. But it doesn't create any obj files.

# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors

# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=

# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')

# find headers
HEADERS := $(shell find . -name '*.h')

OUTPUT := HelloWorld

# Everything depends on the output
all: $(OUTPUT)

# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)

clean:
     $(RM) $(OUTPUT)

I'm  looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.

Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working.
How to get it working?

world/Makefile

GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld

.PHONY: all clean

all: $(OBJDIR) $(TARGET)

$(OBJDIR):
    mkdir $(OBJDIR)

$(OBJDIR)/%.o: %.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
    $(GCC) $(LDFLAGS) -o $@ $^
clean:
    @rm -f $(TARGET) $(wildcard *.o)
    @rm -rf $(OBJDIR)

When i try to run the make it throws the following error.

g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4

It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.

Any help from the makefile Masters is appreciated! :)

Body:
You cannot compile multiple c or cpp files at a time AND specify ONE object file for them. See also this question Compile multiple C source fles into a unique object file The following command gives you error:

g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o

The following compiles to object files giving you a Main.o and Hello.o and World.o in the current directory:

g++ -I./hello -c -Wall -c world/Main.cpp hello/Hello.cpp world/World.cpp

You could compile each cpp file one by one and generate object file for each then link them together. This is how any big project with multiple source code files is build. By hand do this:

cd world
g++ -I../hello -c -Wall -c Main.cpp -o objdir/Main.o
g++ -c -Wall -c ../hello/Hello.cpp -o objdir/Hello.o
g++ -c -Wall -c World.cpp -o objdir/World.o
# link:
g++ objdir/Main.o objdir/Hello.o objdir/World.o -o HelloWorld

from man gcc

   -c  Compile or assemble the source files, but do not link.  The linking stage simply is not done.  The ultimate output is in the form of an object file for each source file.

   -o file
       Place output in file file.  This applies to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code.

Answer: I meant to not directly answer :-P but it is a little bit tricky. Here is what you need to look at in your Makefile:

# you want to add reference to hello as include dir
#  for compiling Main.cpp, In CPPFLAGS add -I ../hello

# the OBJ list is missing a reference to files in hello directory:
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
OBJ+=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(notdir $(wildcard ../hello/*.cpp))))

# no change needed for the %.cpp
# new rule needed to allow it to find hello dir:

$(OBJDIR)/%.o:
    $(GCC) $(CPPFLAGS) -c $< -o $@
$(OBJDIR)/%.o: ../hello/%.cpp
    $(GCC) $(CPPFLAGS) -c $< -o $@

read: https://www.gnu.org/software/make/manual/html_node/File-Name-Functions.html


来源: stackexchange

问:
Avoid looping to get one particular column of values from Set<Entity> in Java
I have a code snippet in Java as follows:

```<code>Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }
</code>```

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?

答:
It is not Possible but you can optimize that code using lambda expression</p>

```<code>Set<BookDO> bookSet = [dataSorce]
Collection<String> bookCollection;
if (bookSet != null && bookSet.isEmpty()) {
    bookCollection = new ArrayList<String>();
    bookSet.forEach((book) -> {
        bookCollection.add(book.getName());
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a code snippet in Java as follows:

Set<BookDO> bookSet = shopDO.getBooks();
    Collection<String> bookCollection = null;
    if (bookSet != null && !bookSet .isEmpty()) {
      bookCollection = new ArrayList<String>();
      for (BookDO book : bookSet) {
        bookCollection .add(book.getName());
      }
    }

Finally I want the only Collection of book names to pass it to an API which displays the output.

Is it possible to avoid the for loop to improve performance ?

Body:
It is not Possible but you can optimize that code using lambda expression

Set<BookDO> bookSet = [dataSorce]
Collection<String> bookCollection;
if (bookSet != null && bookSet.isEmpty()) {
    bookCollection = new ArrayList<String>();
    bookSet.forEach((book) -> {
        bookCollection.add(book.getName());
    });
}


问:
Disable Thread.sleep()
I want to disable possibility of using Thread.sleep() in a java project and use my own method instead:

```<code>sleep(int time, String info)
</code>```

That will wait for given amount of time, and print info why is waiting necessary here.

Is disabling Thread.sleep() possible?

If yes, what's best method to do so?

答:
Yes, sure.

Just make sure that no code in that project is calling Thread.sleep(); but your MyUtility.sleep() replacement.

If the question is: can I somehow change the behavior of the existing Thread.sleep(), then the answer is: depends on context/effort you are willing to spend.

Well, with certain tricks; it might be possible; but simply speaking: it is a most likely a bad idea; and not worth following up on. I would really shy away from changing the code behavior, if at all I would look into those solutions that can identify usages of that unwanted sleep calls at compile time.

Title: Disable Thread.sleep()

Body:
I want to disable possibility of using Thread.sleep() in a java project and use my own method instead:

sleep(int time, String info)

That will wait for given amount of time, and print info why is waiting necessary here.

Is disabling Thread.sleep() possible?

If yes, what's best method to do so?


问:
ImportError: No module named ssl_match_hostname when importing the docker SDK for Python
In order to use the Docker SDK for Python, I'm trying to import docker in a Python script, but it's resulting in an ImportError with the following traceback:

```<code>Traceback (most recent call last):
  File "/home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils/docker_utils.py", line 1, in <module>
    import docker
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/__init__.py", line 6, in <module>
    from .client import Client, AutoVersionClient, from_env # flake8: noqa
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/client.py", line 11, in <module>
    from . import api
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/api/__init__.py", line 2, in <module>
    from .build import BuildApiMixin
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/api/build.py", line 9, in <module>
    from .. import utils
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/utils/__init__.py", line 2, in <module>
    from .utils import (
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/utils/utils.py", line 19, in <module>
    from .. import tls
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/tls.py", line 5, in <module>
    from .ssladapter import ssladapter
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/ssladapter/__init__.py", line 1, in <module>
    from .ssladapter import SSLAdapter # flake8: noqa
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/ssladapter/ssladapter.py", line 21, in <module>
    from backports.ssl_match_hostname import match_hostname
ImportError: No module named ssl_match_hostname
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "/home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils/docker_utils.py"]
[dir: /home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
</code>```

The strange thing is that the import does work in other places, for example in an iPython prompt:

```<code>Python 2.7.12 (default, Nov 19 2016, 06:48:10)
Type "copyright", "credits" or "license" for more information.

IPython 2.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import docker

In [2]:
</code>```

Why is the import not working in the first case?

答:
I had backports.ssl-match-hostname installed locally, which was preventing it from being installed at the system level. I solved it by

```<code>sudo pip uninstall backports.ssl-match-hostname
</code>```

followed by

```<code>sudo pip install --upgrade docker
</code>```

Body:
In order to use the Docker SDK for Python, I'm trying to import docker in a Python script, but it's resulting in an ImportError with the following traceback:

Traceback (most recent call last):
  File "/home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils/docker_utils.py", line 1, in <module>
    import docker
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/__init__.py", line 6, in <module>
    from .client import Client, AutoVersionClient, from_env # flake8: noqa
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/client.py", line 11, in <module>
    from . import api
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/api/__init__.py", line 2, in <module>
    from .build import BuildApiMixin
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/api/build.py", line 9, in <module>
    from .. import utils
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/utils/__init__.py", line 2, in <module>
    from .utils import (
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/utils/utils.py", line 19, in <module>
    from .. import tls
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/tls.py", line 5, in <module>
    from .ssladapter import ssladapter
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/ssladapter/__init__.py", line 1, in <module>
    from .ssladapter import SSLAdapter # flake8: noqa
  File "/home/kurt/.local/lib/python2.7/site-packages/docker/ssladapter/ssladapter.py", line 21, in <module>
    from backports.ssl_match_hostname import match_hostname
ImportError: No module named ssl_match_hostname
[Finished in 0.2s with exit code 1]
[shell_cmd: python -u "/home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils/docker_utils.py"]
[dir: /home/kurt/dev/clones8/ipercron-compose/furion/iclib/tests/test_utils]
[path: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]

The strange thing is that the import does work in other places, for example in an iPython prompt:

Python 2.7.12 (default, Nov 19 2016, 06:48:10)
Type "copyright", "credits" or "license" for more information.

IPython 2.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import docker

In [2]:

Why is the import not working in the first case?

Body:
I had backports.ssl-match-hostname installed locally, which was preventing it from being installed at the system level. I solved it by

sudo pip uninstall backports.ssl-match-hostname

followed by

sudo pip install --upgrade docker


问:
Python Skips Numbers
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

```<code>toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break
</code>```

And here is the output:

```<code>Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83
</code>```

The number under "Trying" is calc and the number after "Trying" is guess.

答:
```<code>>>> round(1.73 * 1.73, 2)
2.99
>>> round(1.732 * 1.732, 2)
3.0
>>> round(1.74 * 1.74, 2)
3.03
</code>```

9*9 = 81, 10*10 = 100 and we don't say numbers between 81 to 100 are skipped.

You are trying with 1.73 and 1.74, neither of them can produce exact value of 3 by squaring.

This behavior is "not skipping numbers", but it is all about the precision.

Floating point numbers are not that simple to deal. For this particular problem, using a difference of 0.001 solved the issue, but may not work for all other numbers.

However the below is code that solves the issue.

```<code>toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)

while 1+1==2:

    print "Trying ", guess, "..."
    calc = guess * guess
    calc = round(calc, 2)
    print calc
    guess = guess - 0.001
    if calc == toCalc:
            break
</code>```

Title: Python Skips Numbers

Body:
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break

And here is the output:

Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83

The number under "Trying" is calc and the number after "Trying" is guess.

Body:
>>> round(1.73 * 1.73, 2)
2.99
>>> round(1.732 * 1.732, 2)
3.0
>>> round(1.74 * 1.74, 2)
3.03

9*9 = 81, 10*10 = 100 and we don't say numbers between 81 to 100 are skipped.

You are trying with 1.73 and 1.74, neither of them can produce exact value of 3 by squaring.

This behavior is "not skipping numbers", but it is all about the precision.

Floating point numbers are not that simple to deal. For this particular problem, using a difference of 0.001 solved the issue, but may not work for all other numbers.

However the below is code that solves the issue.

toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)

while 1+1==2:

    print "Trying ", guess, "..."
    calc = guess * guess
    calc = round(calc, 2)
    print calc
    guess = guess - 0.001
    if calc == toCalc:
            break


问:
Unit Testing involving databases
Suppose I have a directory

```<code>  home/user/my_python_scripts/
                   /src
                       /my_script.py
                   /tests
                      /test_my_script.py
</code>```

I am running some unit tests to test my_script.py from the ~/my_python_scripts/test directory. I am importing the function from my_script in to my test_my_script.py.

The problem however arises since the function in my_script.py imports two other functions from another script. Those two functions query a database for specific data. I am mocking and patching these two functions in my test script however when I run pytest on this script the function ends up querying the database regardless. I looked at the two functions that my_script.py uses. Each of them queries a different database and furthermore one of the functions ends up using three other functions that live in the same file as it does.

Am I not accounting for these functions and/or database properly in my unit test? I cannot share the code since it is proprietary but I am more than happy to share my unit test code below:

```<code>from pytest_mock import mocker

params = [(3141, 55)]
raw_data = [{'a': 'fizz', 'b': 'buzz', 'c': 'foo', 'd': 'hello'}]
descriptors = ['taxi', 3141, 55, 1]

def test_get_data(mocker):
    setattr(get_data, 'get_raw_data', params)
    mocker.patch.object(get_data, 'get_raw_data')
    get_data.get_raw_data.return_value = params
    setattr(get_data, 'get_data_by_day', raw_data)
    mocker.patch.object(get_data, 'get_data_by_day')
    get_data.get_data_by_day.return_value = raw_data
    assert get_data('taxi', 3141, '1', '3') == raw_data, descriptors
</code>```

Looking for any advice as well as tips.

答:
So I figured it out. I was not correctly setting the values on the patched mock functions. This is the code that ended up working properly.

```<code>from mock import patch
from .relative.path import get_data

params = [(3141, 55)]
raw_data = [{'a': 'fizz', 'b': 'buzz', 'c': 'foo', 'd': 'hello'}]
descriptors = ['taxi', 3141, 55, 1]

@patch.object(get_data, 'get_raw_data')
@patch.object(get_data, 'get_data_by_day')
def test_get_stuff_1(mock_get_data_by_day, mock_get_raw_data):
    mock_get_data_by_day.return_value = raw_data
    mock_get_raw_data.return_value = params
    result = get_data.get_stuff('taxi', 3141, '1', '3')
    assert result == (raw_data, descriptors)
</code>```

I import the script get_data.py as an object, and then patch each function get_raw_data and get_data_by_day as attributes of this object. Then when I run the unit test on the mock values I provide it returns the results I expect.

Title: Unit Testing involving databases

Body:
Suppose I have a directory

  home/user/my_python_scripts/
                   /src
                       /my_script.py
                   /tests
                      /test_my_script.py

I am running some unit tests to test my_script.py from the ~/my_python_scripts/test directory. I am importing the function from my_script in to my test_my_script.py.

The problem however arises since the function in my_script.py imports two other functions from another script. Those two functions query a database for specific data. I am mocking and patching these two functions in my test script however when I run pytest on this script the function ends up querying the database regardless. I looked at the two functions that my_script.py uses. Each of them queries a different database and furthermore one of the functions ends up using three other functions that live in the same file as it does.

Am I not accounting for these functions and/or database properly in my unit test? I cannot share the code since it is proprietary but I am more than happy to share my unit test code below:

from pytest_mock import mocker

params = [(3141, 55)]
raw_data = [{'a': 'fizz', 'b': 'buzz', 'c': 'foo', 'd': 'hello'}]
descriptors = ['taxi', 3141, 55, 1]

def test_get_data(mocker):
    setattr(get_data, 'get_raw_data', params)
    mocker.patch.object(get_data, 'get_raw_data')
    get_data.get_raw_data.return_value = params
    setattr(get_data, 'get_data_by_day', raw_data)
    mocker.patch.object(get_data, 'get_data_by_day')
    get_data.get_data_by_day.return_value = raw_data
    assert get_data('taxi', 3141, '1', '3') == raw_data, descriptors

Looking for any advice as well as tips.

Body:
So I figured it out. I was not correctly setting the values on the patched mock functions. This is the code that ended up working properly.

from mock import patch
from .relative.path import get_data

params = [(3141, 55)]
raw_data = [{'a': 'fizz', 'b': 'buzz', 'c': 'foo', 'd': 'hello'}]
descriptors = ['taxi', 3141, 55, 1]

@patch.object(get_data, 'get_raw_data')
@patch.object(get_data, 'get_data_by_day')
def test_get_stuff_1(mock_get_data_by_day, mock_get_raw_data):
    mock_get_data_by_day.return_value = raw_data
    mock_get_raw_data.return_value = params
    result = get_data.get_stuff('taxi', 3141, '1', '3')
    assert result == (raw_data, descriptors)

I import the script get_data.py as an object, and then patch each function get_raw_data and get_data_by_day as attributes of this object. Then when I run the unit test on the mock values I provide it returns the results I expect.


问:
Unit Tests not discovered in Visual Studio 2017
I have been struggling with VS 2017 since I installed it. Now it seems Unit Tests will only run from the command line "dotnet test."

My project is .NET Core 1.1.1. I have the SDK and the framework update for 1.1.1 installed.

I have tried the sample at MSDN (https://msdn.microsoft.com/en-us/library/ms182532.aspx) which also fails exactly the same way.

All NuGet packages for the tests and the main project are current. And both the test project and the main project build without errors. An the tests run successfully from the command line.

Has anyone gotten Unit Tests to run in VS 2017, if so how?

Thanks,
John

Update - Extend

Here is an example of a simple test project that is not working on GitHub. This is an example with xUnit but I have tried NUnit and visual studio built in MS tests. No matter what testing or what changes I make I cannot get the VS test runner to find any tests.

What I've Tried

Deleting VS test cache files DEL %TEMP%\VisualStudioTestExplorerExtensions

Restarting VS

Closing/Opening test explorer

for xUnit installed Microsoft.DotNet.InternalAbstractions (see SO post)

for NUnit ensure adapter installed and same version (3) as NUnit package

test -> test settings -> default processor architecture is set to x86

The Question

Can anyone please provide a working example of a .Net Core 1.1.0 solution in VS2017 (.csproj project files) where the VS test explorer successfully finds the unit tests OR show me the issue in the example given.

答:
In my case, it was UWP project present in the solution causing the issue.

When I unloaded the UWP project, tests were discovered. When I loaded it back, test disappeard again.

Try to unload all projects and keep test project only. Ten rebuild solution and test shound appear in Test Runner. Load projects one by one and rebuild solution each time to find out what project are causing the problem

sample repo

VS bug report


问:
Handling physical keyboard's Enter key in SearchView
I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener):

```<code>viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        //Log.d(TAG, "Query: " + newText);
        return false;
    }
});
</code>```

Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried:

```<code>viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        Log.d(TAG, "Query: " + keyEvent);
        return false;
    }
});
</code>```

But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible?

Any idea?

答:
In layout set your input method options to search.

```<code><EditText
android:imeOptions="actionSearch"
android:inputType="text" />
</code>```

In your java class add editor action listener.

```<code>  viewHolder.mTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        performSearch();
        return true;
    }
    return false;
}
</code>```

});

Body:
I've implemented a SearchView in my application which is working properly when I hit the search button while I'm using the soft keyboard (using the QueryTextListener):

viewHolder.mTextSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        new SearchForEquipmentTask(false, viewHolder.mTextSearch.getQuery().toString()).execute();
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        //Log.d(TAG, "Query: " + newText);
        return false;
    }
});

Now I'm planning to use a physical keyboard for my users to be able to work with the app, but I can't figure out how to fire the search event from the physical keyboard (onQueryTextChange is not getting invoked with that key). Same thing happens when I'm running the emulator in Android Studio. I've tried:

viewHolder.mTextSearch.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        Log.d(TAG, "Query: " + keyEvent);
        return false;
    }
});

But the SearchView seems to ignore the listener for any key... It seems that QueryTextListener is the only way to handle searches, but how to deal with special characters? Should I switch it to EditText which is more flexible?

Any idea?

Body:
In layout set your input method options to search.

<EditText
android:imeOptions="actionSearch"
android:inputType="text" />

In your java class add editor action listener.

  viewHolder.mTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        performSearch();
        return true;
    }
    return false;
}

});


问:
Python Celery single base class instance for all tasks
I have a tasks.py that contains a subclass of Task.
According to the docs the base class is instantiated only once per tasks.

But this is only true for same tasks method. Calling a different task creates a new instance. So I can't access sessions via get_sessions created with create_session. How may I have only a single instance that is shared between different tasks?

```<code>class AuthentificationTask(Task):
    connections = {}

    def login(self, user, password, server):

    if not user in self.connections:
        self.connections = {user: ServerConnection(verbose=True)}
    # from celery.contrib import rdb
    # rdb.set_trace()

    self.connections[user].login(user=user, password=password, server=server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def create_session(self, user, password, server):
    self.login(user, password, server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def get_sessions(self, user, password, server):
    return self.connections[user].sessions
</code>```

答:
Set the task_cls arg for your Celery application like this:

```<code>class AuthentificationTask(Task):

    def example(self):
        logger.info('AuthentificationTask.example() method was called')

@celery.task(bind=True)
def test_my_task(self):
    # call AuthentificationTask.example
    self.example()

app = celery.Celery(
   __name__,
   broker='redis://localhost:6379/0',
   task_cls=AuthentificationTask,
   # other args
)
</code>```

In this case will be use your custom class for all tasks as default.

Body:
I have a tasks.py that contains a subclass of Task.
According to the docs the base class is instantiated only once per tasks.

But this is only true for same tasks method. Calling a different task creates a new instance. So I can't access sessions via get_sessions created with create_session. How may I have only a single instance that is shared between different tasks?

class AuthentificationTask(Task):
    connections = {}

    def login(self, user, password, server):

    if not user in self.connections:
        self.connections = {user: ServerConnection(verbose=True)}
    # from celery.contrib import rdb
    # rdb.set_trace()

    self.connections[user].login(user=user, password=password, server=server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def create_session(self, user, password, server):
    self.login(user, password, server)

@task(bind=True, max_retries=1, queue='test', base=AuthentificationTask)
def get_sessions(self, user, password, server):
    return self.connections[user].sessions

Body:
Set the task_cls arg for your Celery application like this:

class AuthentificationTask(Task):

    def example(self):
        logger.info('AuthentificationTask.example() method was called')

@celery.task(bind=True)
def test_my_task(self):
    # call AuthentificationTask.example
    self.example()

app = celery.Celery(
   __name__,
   broker='redis://localhost:6379/0',
   task_cls=AuthentificationTask,
   # other args
)

In this case will be use your custom class for all tasks as default.


问:
How do i check a radio button is checked or not using jquery
How do i check a radio button is checked or not using jquery???

here is the code:

```<code>     function handlesClick(myRadio) {
        debugger
       var selectedmerchant = [];
        if (myRadio != '') {
            var myRadios = $('input[name=myRadio]');
            //var checkedValue = $("#myRadio").attr('checked', 'checked');
            //if ($('#myRadio').is(':checked')) { alert("it's checked"); }
            //$('input[type="radio"][class="icheck-list"]:checked').val()
            if ($("#myRadio").is(":checked") === true)
            {
                selectedmerchant.push(myradio);
                selectedmerchant.join(",");
            }
            else
            {
 var index = selectedmerchant.indexof(merchant);
               selectedmerchant.splice(index, 1);
            }
     //if (document.getelementbyid(myradio).checked == true) {
            //    selectedmerchant.push(myradio);
            //    selectedmerchant.join(",");
            //}
            //else {
            //    var index = selectedmerchant.indexof(merchant);
            //    selectedmerchant.splice(index, 1);
            //}
</code>```

i want to check is the checkbox is checked or not so that i can push or slice in a array using javascript.
any code???

here is the html:

```<code>  <div class="row">
    <div class="form-group">
      <div class="col-md-12">
        <label>3.sdfdsfsdfds</label>
        <div class="icheck-list">
          <label class="icheck-list" id="11">

            <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="12">
            <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="13">
            <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="14">
            <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree
            <span></span>
          </label>
        </div>
        <div class="icheck-list">
          <label class="icheck-list" id="15">
            <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree
            <span></span>
          </label>
        </div>
      </div>
    </div>
  </div>
</code>```

答:
Check this,

window.selectedmerchant = {};
function handlesClick(myRadio) {
  if ($(myRadio).is(":checked")) {
   window.selectedmerchant[$(myRadio).attr("name")] = $(myRadio).attr("id");
  }
  console.log(window.selectedmerchant);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>3.sdfdsfsdfds
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="11">
          <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="12">
          <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="13">
          <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="14">
          <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="15">
          <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>4. fourth question
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="13">
          <input name="4" onclick="handlesClick(this);" id="4_13" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="14">
          <input name="4" onclick="handlesClick(this);" id="4_14" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="15">
          <input name="4" onclick="handlesClick(this);" id="4_15" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="16">
          <input name="4" onclick="handlesClick(this);" id="4_16" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="17">
          <input name="4" onclick="handlesClick(this);" id="4_17" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>5.5th question
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="18">
          <input name="5" onclick="handlesClick(this);" id="5_18" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="19">
          <input name="5" onclick="handlesClick(this);" id="5_19" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="20">
          <input name="5" onclick="handlesClick(this);" id="5_20" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="21">
          <input name="5" onclick="handlesClick(this);" id="5_21" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="22">
          <input name="5" onclick="handlesClick(this);" id="5_22" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/></code>```

I have taken only three examples just as demo, but check the code, its working fine now.

I hope this will help.

Body:
How do i check a radio button is checked or not using jquery???

here is the code:

     function handlesClick(myRadio) {
        debugger
       var selectedmerchant = [];
        if (myRadio != '') {
            var myRadios = $('input[name=myRadio]');
            //var checkedValue = $("#myRadio").attr('checked', 'checked');
            //if ($('#myRadio').is(':checked')) { alert("it's checked"); }
            //$('input[type="radio"][class="icheck-list"]:checked').val()
            if ($("#myRadio").is(":checked") === true)
            {
                selectedmerchant.push(myradio);
                selectedmerchant.join(",");
            }
            else
            {
 var index = selectedmerchant.indexof(merchant);
               selectedmerchant.splice(index, 1);
            }
     //if (document.getelementbyid(myradio).checked == true) {
            //    selectedmerchant.push(myradio);
            //    selectedmerchant.join(",");
            //}
            //else {
            //    var index = selectedmerchant.indexof(merchant);
            //    selectedmerchant.splice(index, 1);
            //}

i want to check is the checkbox is checked or not so that i can push or slice in a array using javascript.
any code???

here is the html:

        3.sdfdsfsdfds

            <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree

            <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree

            <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree

            <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree

            <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree

Body:
Check this,

window.selectedmerchant = {};
function handlesClick(myRadio) {
  if ($(myRadio).is(":checked")) {
   window.selectedmerchant[$(myRadio).attr("name")] = $(myRadio).attr("id");
  }
  console.log(window.selectedmerchant);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>3.sdfdsfsdfds
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="11">
          <input name="3" onclick="handlesClick(this);" id="3_11" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="12">
          <input name="3" onclick="handlesClick(this);" id="3_12" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="13">
          <input name="3" onclick="handlesClick(this);" id="3_13" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="14">
          <input name="3" onclick="handlesClick(this);" id="3_14" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="15">
          <input name="3" onclick="handlesClick(this);" id="3_15" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>4. fourth question
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="13">
          <input name="4" onclick="handlesClick(this);" id="4_13" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="14">
          <input name="4" onclick="handlesClick(this);" id="4_14" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="15">
          <input name="4" onclick="handlesClick(this);" id="4_15" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="16">
          <input name="4" onclick="handlesClick(this);" id="4_16" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="17">
          <input name="4" onclick="handlesClick(this);" id="4_17" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/>
<div class="row">
  <div class="form-group">
    <div class="col-md-12">
      <label>5.5th question
      </label>
      <div class="icheck-list">
        <label class="icheck-list" id="18">
          <input name="5" onclick="handlesClick(this);" id="5_18" type="radio">Strongly Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="19">
          <input name="5" onclick="handlesClick(this);" id="5_19" type="radio">Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="20">
          <input name="5" onclick="handlesClick(this);" id="5_20" type="radio">Neither Agree or Disagree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="21">
          <input name="5" onclick="handlesClick(this);" id="5_21" type="radio">Agree
          <span></span>
        </label>
      </div>
      <div class="icheck-list">
        <label class="icheck-list" id="22">
          <input name="5" onclick="handlesClick(this);" id="5_22" type="radio">Strongly Agree
          <span></span>
        </label>
      </div>
    </div>
  </div>
</div>
<hr/>

I have taken only three examples just as demo, but check the code, its working fine now.

I hope this will help.


问:
how can i show data of listview in other activity using database query?
I have a listview which take the value form two edittext. First sqlite database saves the value of these edittextand then convert it in listviews.What I want is that when the user click on list item it will show the values of that item in next activity using database queries. Can anyone tell me how can I do that. Please answer me in detail because I am new in android</p>

答:
On item click fetch the row id of item.
Call query using row id fetch specific row</p>

```<code>String selection = KEYID + " = ? ";
String[] selectionArgs = new String[]{rowId};
        Cursor cursor = database.query(TABLENAME, null, selection, selectionArgs, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                //PARSE AND RETURN DATA
            }
        }
</code>```

Body:
On item click fetch the row id of item.
Call query using row id fetch specific row

String selection = KEYID + " = ? ";
String[] selectionArgs = new String[]{rowId};
        Cursor cursor = database.query(TABLENAME, null, selection, selectionArgs, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                //PARSE AND RETURN DATA
            }
        }


问:
android - RecyclerView item not clickable after drag and drop in Nougat (Android 7.0)
I'm facing this issue only on android Nougat. After drag and dropping an item, the OnClick event doesn't fire on this item anymore.

Here's the adapter :

```<code>public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.VideoListViewHolder> implements ItemTouchHelperAdapter {

    private List<Media> videos;
    private LayoutInflater inflater;
    private Context context;

    private int selectedItemPosition;
    private Media selectedMedia;
    private static final int NOTHING_SELECTED = -1;

    public VideoListAdapter(Context context, List<Media> videos, Delegate delegate) {
        inflater = LayoutInflater.from(context);
        setVideos(videos);
        this.context = context;
        setSelectedItem(NOTHING_SELECTED);
    }

    public void setSelectedItem(int pos) {
        selectedItemPosition = pos;
        if(pos != NOTHING_SELECTED)
            selectedMedia = videos.get(pos);
        else
            selectedMedia = null;
    }

    public void setVideos(List<Media> videos) {
        this.videos = videos;
        setSelectedItem(NOTHING_SELECTED);
    }

    private void onVideosReordered() {
        if(selectedMedia != null)
            setSelectedItem(videos.indexOf(selectedMedia));
    }

    public void unselectAll() {
        setSelectedItem(NOTHING_SELECTED);
        notifyDataSetChanged();
    }

    @Override
    public VideoListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_video_list, parent, false);
        return new VideoListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final VideoListViewHolder holder, int position) {
        String imagePath = videos.get(position).getFilePath();

        boolean isEmptyItem = imagePath == null || imagePath.isEmpty();

        if (isEmptyItem) {
            holder.video_list_item_selected.setVisibility(View.GONE);
            holder.img_image.setVisibility(View.GONE);
        } else {

            UtilsMedia.loadThumbnailImageNoSpinAnimation(holder.img_image, imagePath);

            boolean isSelected = selectedItemPosition == position;
            if (isSelected && !isEmptyItem)
                holder.video_list_item_selected.setVisibility(View.VISIBLE);
            else
                holder.video_list_item_selected.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return videos.size();
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {

        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++)
                Collections.swap(videos, i, i + 1);
        } else {
            for (int i = fromPosition; i > toPosition; i--)
                Collections.swap(videos, i, i - 1);
        }

        notifyItemMoved(fromPosition, toPosition);

        return true;
    }

    @Override
    public void onItemDropped() {
        onVideosReordered();
        notifyDataSetChanged();
    }

    class VideoListViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {
        public ImageView img_image;
        public ImageView video_list_item_selected;
        public FrameLayout fl_root;
        public Context context;
        public boolean isSelected;

        private static final String TAG = "VideoListViewHolder";

        public VideoListViewHolder(View view) {
            super(view);
            img_image = (ImageView) view.findViewById(R.id.img_image);
            video_list_item_selected = (ImageView) view.findViewById(R.id.video_list_item_selected);
            fl_root = (FrameLayout) view.findViewById(R.id.fl_root);
            context = view.getContext();
            isSelected = false;

            fl_root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int currentPosition = getAdapterPosition();

                    if (selectedItemPosition == currentPosition) {
                        setSelectedItem(NOTHING_SELECTED);
                    } else {
                        if (selectedItemPosition != -1)
                            notifyItemChanged(selectedItemPosition);
                        setSelectedItem(currentPosition);

                    }

                    notifyItemChanged(currentPosition);
                }
            });
        }

        @Override
        public void onItemSelected() {
            final Animation zoomOut = AnimationUtils.loadAnimation(context, R.anim.zoom_out);
            zoomOut.setDuration(300);
            fl_root.startAnimation(zoomOut);
        }

        @Override
        public void onItemClear() {
            final Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoom_in);
            zoomIn.setDuration(300);
            fl_root.startAnimation(zoomIn);
        }
    }
}
</code>```

And here is the item touch helper callback :

```<code>public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
    public static final float ALPHA_FULL = 1.0f;

    protected final ItemTouchHelperAdapter mAdapter;

    public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        mAdapter = adapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return false;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        final int swipeFlags = 0;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    private int moveSource = -1;
    private int moveTarget = -1;

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
        if (source.getItemViewType() != target.getItemViewType())
            return false;

        if(moveSource == -1)
            moveSource = source.getAdapterPosition();

        moveTarget = target.getAdapterPosition();

        mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemSelected();
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setAlpha(ALPHA_FULL);
        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemClear();
        }

        if(moveSource != -1 && moveTarget != -1 && moveSource != moveTarget)
            mAdapter.onItemDropped();

        moveSource = moveTarget = -1;
    }
}
</code>```

Any help would be appreciated, thanks !

答: I had to remove every notifyDataSet changed and replace them by other notifyXXX (notifyItemRangeInserted, notifyItemRangeRemoved, notifyItemRangeChanged, etc)</p>

Body:
I'm facing this issue only on android Nougat. After drag and dropping an item, the OnClick event doesn't fire on this item anymore.

Here's the adapter :

public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.VideoListViewHolder> implements ItemTouchHelperAdapter {

    private List<Media> videos;
    private LayoutInflater inflater;
    private Context context;

    private int selectedItemPosition;
    private Media selectedMedia;
    private static final int NOTHING_SELECTED = -1;

    public VideoListAdapter(Context context, List<Media> videos, Delegate delegate) {
        inflater = LayoutInflater.from(context);
        setVideos(videos);
        this.context = context;
        setSelectedItem(NOTHING_SELECTED);
    }

    public void setSelectedItem(int pos) {
        selectedItemPosition = pos;
        if(pos != NOTHING_SELECTED)
            selectedMedia = videos.get(pos);
        else
            selectedMedia = null;
    }

    public void setVideos(List<Media> videos) {
        this.videos = videos;
        setSelectedItem(NOTHING_SELECTED);
    }

    private void onVideosReordered() {
        if(selectedMedia != null)
            setSelectedItem(videos.indexOf(selectedMedia));
    }

    public void unselectAll() {
        setSelectedItem(NOTHING_SELECTED);
        notifyDataSetChanged();
    }

    @Override
    public VideoListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_video_list, parent, false);
        return new VideoListViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final VideoListViewHolder holder, int position) {
        String imagePath = videos.get(position).getFilePath();

        boolean isEmptyItem = imagePath == null || imagePath.isEmpty();

        if (isEmptyItem) {
            holder.video_list_item_selected.setVisibility(View.GONE);
            holder.img_image.setVisibility(View.GONE);
        } else {

            UtilsMedia.loadThumbnailImageNoSpinAnimation(holder.img_image, imagePath);

            boolean isSelected = selectedItemPosition == position;
            if (isSelected && !isEmptyItem)
                holder.video_list_item_selected.setVisibility(View.VISIBLE);
            else
                holder.video_list_item_selected.setVisibility(View.GONE);
        }
    }

    @Override
    public int getItemCount() {
        return videos.size();
    }

    @Override
    public boolean onItemMove(int fromPosition, int toPosition) {

        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++)
                Collections.swap(videos, i, i + 1);
        } else {
            for (int i = fromPosition; i > toPosition; i--)
                Collections.swap(videos, i, i - 1);
        }

        notifyItemMoved(fromPosition, toPosition);

        return true;
    }

    @Override
    public void onItemDropped() {
        onVideosReordered();
        notifyDataSetChanged();
    }

    class VideoListViewHolder extends RecyclerView.ViewHolder implements ItemTouchHelperViewHolder {
        public ImageView img_image;
        public ImageView video_list_item_selected;
        public FrameLayout fl_root;
        public Context context;
        public boolean isSelected;

        private static final String TAG = "VideoListViewHolder";

        public VideoListViewHolder(View view) {
            super(view);
            img_image = (ImageView) view.findViewById(R.id.img_image);
            video_list_item_selected = (ImageView) view.findViewById(R.id.video_list_item_selected);
            fl_root = (FrameLayout) view.findViewById(R.id.fl_root);
            context = view.getContext();
            isSelected = false;

            fl_root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int currentPosition = getAdapterPosition();

                    if (selectedItemPosition == currentPosition) {
                        setSelectedItem(NOTHING_SELECTED);
                    } else {
                        if (selectedItemPosition != -1)
                            notifyItemChanged(selectedItemPosition);
                        setSelectedItem(currentPosition);

                    }

                    notifyItemChanged(currentPosition);
                }
            });
        }

        @Override
        public void onItemSelected() {
            final Animation zoomOut = AnimationUtils.loadAnimation(context, R.anim.zoom_out);
            zoomOut.setDuration(300);
            fl_root.startAnimation(zoomOut);
        }

        @Override
        public void onItemClear() {
            final Animation zoomIn = AnimationUtils.loadAnimation(context, R.anim.zoom_in);
            zoomIn.setDuration(300);
            fl_root.startAnimation(zoomIn);
        }
    }
}

And here is the item touch helper callback :

public class ItemTouchHelperCallback extends ItemTouchHelper.Callback {
    public static final float ALPHA_FULL = 1.0f;

    protected final ItemTouchHelperAdapter mAdapter;

    public ItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
        mAdapter = adapter;
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return true;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return false;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
        final int swipeFlags = 0;
        return makeMovementFlags(dragFlags, swipeFlags);
    }

    private int moveSource = -1;
    private int moveTarget = -1;

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder source, RecyclerView.ViewHolder target) {
        if (source.getItemViewType() != target.getItemViewType())
            return false;

        if(moveSource == -1)
            moveSource = source.getAdapterPosition();

        moveTarget = target.getAdapterPosition();

        mAdapter.onItemMove(source.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int i) {
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemSelected();
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setAlpha(ALPHA_FULL);
        if (viewHolder instanceof ItemTouchHelperViewHolder) {
            ItemTouchHelperViewHolder itemViewHolder = (ItemTouchHelperViewHolder) viewHolder;
            itemViewHolder.onItemClear();
        }

        if(moveSource != -1 && moveTarget != -1 && moveSource != moveTarget)
            mAdapter.onItemDropped();

        moveSource = moveTarget = -1;
    }
}

Any help would be appreciated, thanks !


答:
You can use all function to accomplish you requirement. But for that you should use subquery for the condition.

```<code>SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from sku where sellerID in (3,4,10));
</code>```

or else if you are getting those values directly from some query then you can include the same in that as subquery.

```<code>SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from from_ur_table_for_codition);
</code>```

Title: 'AND' condition for (id array) in mysql

Body:
I have an mysql table like this.

+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
| id | sku      | sellerID | name                                                                      | mode | created             |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+
|  1 | Sample   |        1 | SampleItem                                                                |    1 | 2016-05-20 12:04:33 |
|  2 | Sample   |        2 | Sample1                                                                   |    1 | 2016-06-14 12:23:24 |
|  3 | SDGS046  |        1 | Shivaprasad                                                               |    2 | 2016-06-18 05:26:27 |
|  4 | PAWA006  |        1 | Panda Baby Walker Music                                                   |    2 | 2016-06-18 06:19:10 |
|  5 | PAWA005  |        1 | WonderKart Panda Walker for Kids (colour may vary)                        |    2 | 2016-06-18 06:24:23 |
|  6 | WKBR1301 |        1 | Planet of Toys New Born Toddler Protable Rocker                           |    2 | 2016-06-18 06:26:30 |
|  7 | PAKS001  |        1 | Panda Baby Musical Swing With Multiple Age Settings | 4 Stages | (Orange) |    2 | 2016-06-18 06:28:19 |
|  8 | WKGS046  |        1 | The Flyers Bay Flyer's Bay Ultra Durable Big Wheel Scooter (Silver)       |    2 | 2016-06-18 06:57:25 |
|  9 | MABS001  |        1 | Mastela Booster to Toddler 6M+ Seat (DarkGray)                            |    2 | 2016-06-20 06:25:00 |
| 10 | WKGS546  |        1 | Saffire Kids Scooter with Tractor Wheels Green                            |    2 | 2016-06-20 06:26:50 |
+----+----------+----------+---------------------------------------------------------------------------+------+---------------------+

I want get data by query like.

SELECT * FROM `sku` WHERE `sellerID` = 1 AND id = 3 AND id = 4 AND id = 10;

but m trying this like

SELECT * FROM sku WHERE sellerID = 1 AND id IN (3,4,10);

it returns rows, if id(3,4,10) any available in table, but i want return row, if every id(3 and 4 and 10) available in table.

I want to pass an array to check AND Condition. Please suggest me if there is any solution available.

Body:
You can use all function to accomplish you requirement. But for that you should use subquery for the condition.

SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from sku where sellerID in (3,4,10));

or else if you are getting those values directly from some query then you can include the same in that as subquery.

SELECT * FROM sku WHERE sellerID = 1 AND id=all (select sellerID  from from_ur_table_for_codition);


问:
Django-Admin: CharField as TextArea
I have

```<code>class Cab(models.Model):
    name  = models.CharField( max_length=20 )
    descr = models.CharField( max_length=2000 )

class Cab_Admin(admin.ModelAdmin):
    ordering     = ('name',)
    list_display = ('name','descr', )
    # what to write here to make descr using TextArea?

admin.site.register( Cab, Cab_Admin )
</code>```

how to assign TextArea widget to 'descr' field in admin interface?

upd:

In Admin interface only!

Good idea to use ModelForm.

答:
For this case, the best option is probably just to use a TextField instead of CharField in your model.  You can also override the formfield_for_dbfield method of your ModelAdmin class:

```<code>class CabAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(CabAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'descr':
            formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
        return formfield
</code>```

OwnerDisplayName: maxp

ContentLicense: CC BY-SA 2.5

Title: Django-Admin: CharField as TextArea

Body:
I have

class Cab(models.Model):
    name  = models.CharField( max_length=20 )
    descr = models.CharField( max_length=2000 )

class Cab_Admin(admin.ModelAdmin):
    ordering     = ('name',)
    list_display = ('name','descr', )
    # what to write here to make descr using TextArea?

admin.site.register( Cab, Cab_Admin )

how to assign TextArea widget to 'descr' field in admin interface?

upd:

In Admin interface only!

Good idea to use ModelForm.

LastEditorDisplayName: maxp

Body:
For this case, the best option is probably just to use a TextField instead of CharField in your model.  You can also override the formfield_for_dbfield method of your ModelAdmin class:

class CabAdmin(admin.ModelAdmin):
    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(CabAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'descr':
            formfield.widget = forms.Textarea(attrs=formfield.widget.attrs)
        return formfield

OwnerDisplayName: Carl Meyer


问:
how to retrieve one to many relationship data in mysql
I have two table

table#1

```<code>name_id |  name
--------|-------
  1     | abc
  2     |  def
</code>```

table#2

```<code>subject_id| name_id |subject
----------|---------|--------
1         | 1       |malayalam
2         | 1       | english
3         | 1       | hindi
4         | 2       | malayalam
5         | 2       | hindi
</code>```

i want to join these two tables and get output in the following format

```<code>id |name |subject1  |subject2 |subject3
---|-----|--------- |---------|--------
1  |abc  |malayalam |english  |hindi
2  |def  |malayalam |hindi    |
</code>```

is it possible in mySql?
can anyone help?

答:
I'll leave my other answer up because again, I think you should really consider redesigning your DB schema. You're using MySQL so have you tried using group_concat() ? It's not going to put it in table form like that but will give you the expected data, where the different subjects will be in CSV form.

```<code>SELECT one.name_id as id, name, group_concat(subject)
FROM one
INNER JOIN two
ON id = two.name_id
GROUP BY id;
</code>```

Output

```<code>1 | abc | malayalam, english, hindi
2 | def | malayalam, hindi
</code>```

Body:
I have two table

table#1

name_id |  name
--------|-------
  1     | abc
  2     |  def

table#2

subject_id| name_id |subject
----------|---------|--------
1         | 1       |malayalam
2         | 1       | english
3         | 1       | hindi
4         | 2       | malayalam
5         | 2       | hindi

i want to join these two tables and get output in the following format

id |name |subject1  |subject2 |subject3
---|-----|--------- |---------|--------
1  |abc  |malayalam |english  |hindi
2  |def  |malayalam |hindi    |

is it possible in mySql?
can anyone help?

Body:
I'll leave my other answer up because again, I think you should really consider redesigning your DB schema. You're using MySQL so have you tried using group_concat() ? It's not going to put it in table form like that but will give you the expected data, where the different subjects will be in CSV form.

SELECT one.name_id as id, name, group_concat(subject)
FROM one
INNER JOIN two
ON id = two.name_id
GROUP BY id;

Output

1 | abc | malayalam, english, hindi
2 | def | malayalam, hindi


问:
Get Annotation parameter from ActiveAnnotation
I'm trying to implement a parameterized ActiveAnnotation and try to get the supplied annotations.

```<code>@Active(ExampleProcessor)
annotation ExampleAnnotation {
    val String value
}

class ExampleProcessor extends AbstractClassProcessor {
    override doRegisterGlobals(ClassDeclaration annotatedClass, extension RegisterGlobalsContext context)
    {
        val annotation = ??
        annotation.value
    }
}
</code>```

What I did

```<code>annotatedClass.annotations.filter(ExampleAnnotation).head.value
</code>```

which sadly leads to a null pointer when using it like so:

```<code>@ExampleAnnotation("Hello!")
class MyClass { }
</code>```

答:
annotatedClass.annotations consist of elements of AnnotationReference type, not Class<?>, you should look up a type for your class and then use it to filter out annotations, e.g.:

```<code>val annotation = annotatedClass.findAnnotation(ExampleAnnotation.findUpstreamType)
val value = annotation.getStringValue('value');
</code>```

Body:
I'm trying to implement a parameterized ActiveAnnotation and try to get the supplied annotations.

@Active(ExampleProcessor)
annotation ExampleAnnotation {
    val String value
}

class ExampleProcessor extends AbstractClassProcessor {
    override doRegisterGlobals(ClassDeclaration annotatedClass, extension RegisterGlobalsContext context)
    {
        val annotation = ??
        annotation.value
    }
}

What I did

annotatedClass.annotations.filter(ExampleAnnotation).head.value

which sadly leads to a null pointer when using it like so:

@ExampleAnnotation("Hello!")
class MyClass { }

Body:
annotatedClass.annotations consist of elements of AnnotationReference type, not Class<?>, you should look up a type for your class and then use it to filter out annotations, e.g.:

val annotation = annotatedClass.findAnnotation(ExampleAnnotation.findUpstreamType)
val value = annotation.getStringValue('value');


问:
Ant filter tokenize with 2 or 3 tokens per line
I have a document with lines following this pattern:

```<code>"key1", "value1", "trash1"
"key2", "value2"
"key3", "value3", "trash3"
</code>```

I need (a filter) to remove the third token of a line, if any.

```<code>"key1", "value1"
"key2", "value2"
"key3", "value3"
</code>```

How can I do that with Apache Ant?

Note: Apache Ant does not support lookarounds in regular expressions.

答:
You can match three tokens and replace with groups.
Simple search with

("[^"]*?")(, "[^"]*?")(?:, "[^"]*?")? and replace with \1\2 will do the job.

First two groups are captured. Third one is non-capturing group.

Regex101 Demo

Code for Apache Ant would be as following:

```<code><replaceregexp file="${src}/build.properties"
           match='("[^"]*?")(, "[^"]*?")(?:, "[^"]*?")?'
           replace="\1\2"
           byline="true"
/>
</code>```

Body:
I have a document with lines following this pattern:

"key1", "value1", "trash1"
"key2", "value2"
"key3", "value3", "trash3"

I need (a filter) to remove the third token of a line, if any.

"key1", "value1"
"key2", "value2"
"key3", "value3"

How can I do that with Apache Ant?

Note: Apache Ant does not support lookarounds in regular expressions.

Body:
You can match three tokens and replace with groups.
Simple search with

("[^"]*?")(, "[^"]*?")(?:, "[^"]*?")? and replace with \1\2 will do the job.

First two groups are captured. Third one is non-capturing group.

Regex101 Demo

Code for Apache Ant would be as following:

<replaceregexp file="${src}/build.properties"
           match='("[^"]*?")(, "[^"]*?")(?:, "[^"]*?")?'
           replace="\1\2"
           byline="true"
/>


问:
Accessing remote folder from win form C#
I am developing a winform application on C# where I need to access a network folder but i get logon user password exception. How can i provide user credentials through application?</p>

```<code>double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) / 1024;
</code>```

答:
```<code> private void ConnectToNetwork()
    {
        NetworkCredential theNetworkCredential = new NetworkCredential(@"UserName", "Password");
        CredentialCache theNetCache = new CredentialCache();
        theNetCache.Add(new Uri(@"\\NAS"), "Basic", theNetworkCredential);
    }
</code>```

Body:
I am developing a winform application on C# where I need to access a network folder but i get logon user password exception. How can i provide user credentials through application?

double length = ((Directory.GetFiles("\\192.168.50.107\Destination", "*", SearchOption.AllDirectories).Sum(t => (new FileInfo(t).Length)) / 1024) / 1024) / 1024;


问:
Is PHP used for quick and easy website where other languages are used in more complex websites?
I just put this question in serverfault.com and I know that this question may be rejected in Stackoverflow.

But I thought programmers know better.

This stat shows that PHP is used by 75.2% of all the websites whose server-side programming language.

http://w3techs.com/technologies/overview/programming_language/all

And this page shows that PHP is the least used server-side language in ranked by usage on top websites

http://w3techs.com/technologies/topsite/programming_language

Q1. Does this mean PHP is used for quick and easy website where other languages are used in more complex websites?

Q2. Why PHP is ranked at the bottom? Or why big company tend to use other language than PHP?

Update: I know that facebook and other biggies uses PHP. But it does not tell why there are more other languages are used in top websites.

答:
No, it can mean that PHP servers are easier to get (from any ISP) as compared to other technologies. For java, you will need to setup Apache Server, Your own Java server (e.g. GlassFish, JBoss, or Tomcat (it's a servlet container)) and that can be costly whereas PHP is readily setup when registering for a DNS.

I wrote a PHP system for a friend of mine (after he bought his Domain Name and a server box) because I felt lazy to setup java.

I don't know if this enlightens your questions.


问:
How to OrderBy ASC or DESC a specific column in LINQ according to parameters
I am generating a result using the following LINQ query:

```<code>var field = "FirstName"; // or "LastName"
var type = "asc"; // or "desc"

var result = (from x in db.ContactSet
              select new
              {
                  x.FirstName,
                  x.LastName
              }).ToList();
</code>```

I need to orderby asc or desc (based off the type variable) for the field variable.

How can I do this in a clean way?

EDIT: The question referred to by the duplicate does not answer this.

答:
Use Dynamic Linq

Then you can write something like this...

```<code>var field = "FirstName"; // or "LastName"
var type = "ascending"; // or "descending" <-- full

var result = (from x in db.ContactSet
          select new
          {
              x.FirstName,
              x.LastName
          }).ToList();

result = result.OrderBy(field + " " + type).ToList();
</code>```

Body:
I am generating a result using the following LINQ query:

var field = "FirstName"; // or "LastName"
var type = "asc"; // or "desc"

var result = (from x in db.ContactSet
              select new
              {
                  x.FirstName,
                  x.LastName
              }).ToList();

I need to orderby asc or desc (based off the type variable) for the field variable.

How can I do this in a clean way?

EDIT: The question referred to by the duplicate does not answer this.

Body:
Use Dynamic Linq

Then you can write something like this...

var field = "FirstName"; // or "LastName"
var type = "ascending"; // or "descending" <-- full

var result = (from x in db.ContactSet
          select new
          {
              x.FirstName,
              x.LastName
          }).ToList();

result = result.OrderBy(field + " " + type).ToList();


问:
Injections are stopping after adding @Transactional annotation
I have created a class that makes easy to add and update Employees. I have added @Transactional annotation to the createEmployee method, then my instances started to give error while I try to retrieve data.

```<code>    @Transactional
    @Override
    public void createEmployee(Employee employee) {
        internalCreateEmployee(employee);
    }
</code>```

without @Transactional everything works but I can save anything to the database. When I add this annotation I got this error.

java.lang.IllegalAccessError: tried to access method
  rd.EmployeeManagerImpl.(Lrd./EmployeeDao;Lrd./DepartmentDao;)V
  from class rd.EmployeeManagerImpl$$EnhancerByGuice$$5db9fd74

Inside the EmployeemanagerImpl I am also injecting my DAO objects in the constructor.

```<code>    @Inject
    EmployeeManagerImpl(EmployeeDao employeeDao, DepartmentDao departmentDao){
        this.employeeDao = employeeDao;
        this.departmentDao = departmentDao;
    }
</code>```

What can be the reason for that @Transactional breaks things?

I just don't know which information is necessary to provide, If you need any further information just ask.

Note: Employee is a hibernate entity class. EmployeeDao, DepartmentDao and EmployeeManagerImpl are all have the @Singleton annotation.

Note2: In the stack trace, It seems like EmployeeManager instance can't be initialized.

```<code>com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
    com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)
    org.apache.wicket.guice.GuiceProxyTargetLocator.locateProxyTarget(GuiceProxyTargetLocator.java:105)
    org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:430)
    com.sun.proxy.$Proxy133.getDepartmentList(Unknown Source)
    rd.EmployeeFormComponent.addDepartmentDropDown(EmployeeFormComponent.java:59)
    rd.EmployeeFormComponent.<init>(EmployeeFormComponent.java:47)
    rd.EmployeeAddPanel.<init>(EmployeeAddPanel.java:61)
    rd.EmployeeAddModalWindow$1.<init>(EmployeeAddModalWindow.java:20)
    rd.EmployeeAddModalWindow.<init>(EmployeeAddModalWindow.java:20)
    rd.ManageEmployeePage$1.<init>(ManageEmployeePage.java:49)
    rd.ManageEmployeePage.<init>(ManageEmployeePage.java:49)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)
</code>```

答: If you are injecting EmployeeManager twice that could be the problem. I am guessing that EmployeeFormComponent is a Wicket Component. Wicket has its own Guice Injector for its components. So if you are injecting your EmployeeManager with @Inject and if you try to attempt inject with something else as well, this means you inject it twice. This might cause a problem like that.

Body:
I have created a class that makes easy to add and update Employees. I have added @Transactional annotation to the createEmployee method, then my instances started to give error while I try to retrieve data.

    @Transactional
    @Override
    public void createEmployee(Employee employee) {
        internalCreateEmployee(employee);
    }

without @Transactional everything works but I can save anything to the database. When I add this annotation I got this error.

java.lang.IllegalAccessError: tried to access method
  rd.EmployeeManagerImpl.(Lrd./EmployeeDao;Lrd./DepartmentDao;)V
  from class rd.EmployeeManagerImpl$$EnhancerByGuice$$5db9fd74

Inside the EmployeemanagerImpl I am also injecting my DAO objects in the constructor.

    @Inject
    EmployeeManagerImpl(EmployeeDao employeeDao, DepartmentDao departmentDao){
        this.employeeDao = employeeDao;
        this.departmentDao = departmentDao;
    }

What can be the reason for that @Transactional breaks things?

I just don't know which information is necessary to provide, If you need any further information just ask.

Note: Employee is a hibernate entity class. EmployeeDao, DepartmentDao and EmployeeManagerImpl are all have the @Singleton annotation.

Note2: In the stack trace, It seems like EmployeeManager instance can't be initialized.

com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987)
    com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1009)
    org.apache.wicket.guice.GuiceProxyTargetLocator.locateProxyTarget(GuiceProxyTargetLocator.java:105)
    org.apache.wicket.proxy.LazyInitProxyFactory$JdkHandler.invoke(LazyInitProxyFactory.java:430)
    com.sun.proxy.$Proxy133.getDepartmentList(Unknown Source)
    rd.EmployeeFormComponent.addDepartmentDropDown(EmployeeFormComponent.java:59)
    rd.EmployeeFormComponent.<init>(EmployeeFormComponent.java:47)
    rd.EmployeeAddPanel.<init>(EmployeeAddPanel.java:61)
    rd.EmployeeAddModalWindow$1.<init>(EmployeeAddModalWindow.java:20)
    rd.EmployeeAddModalWindow.<init>(EmployeeAddModalWindow.java:20)
    rd.ManageEmployeePage$1.<init>(ManageEmployeePage.java:49)
    rd.ManageEmployeePage.<init>(ManageEmployeePage.java:49)
    sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    java.lang.reflect.Constructor.newInstance(Constructor.java:526)


问:
how to list users name from firebase with angular / angularfire in front end?
I'm trying to display the front end of all the name of my users in a list.

I'm creating users like that:

```<code> firebase.initializeApp(config);

var app =  angular
.module('app', ['firebase'])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
return $firebaseAuth();
}
]);

 app.controller("SampleCtrl", ["$scope", "Auth",
 function($scope, Auth) {
$scope.createUser = function() {
  $scope.message = "One or more field is not correctly entered !";
  $scope.error = null;

Auth.$createUserWithEmailAndPassword($scope.email, $scope.password, $scope.name)
    .then(function(firebaseUser) {
      $scope.message = "User created with uid: " + firebaseUser.uid;
      const uid = firebaseUser.uid;
      const dbref = firebase.database().ref().child('users').child(uid);

      dbref.update({
        email: $scope.email,
        id: uid,
        name: $scope.name
      });
        console.log(dbref.uid);
    }).catch(function(error) {
      $scope.error = error;
    });
};

 $scope.deleteUser = function() {
  $scope.message = null;
  $scope.error = null;

  $scope.auth.$onAuthStateChanged(function(firebaseUser) {
  $scope.firebaseUser = firebaseUser;
});

  // Delete the currently signed-in user
  Auth.$deleteUser().then(function() {
    $scope.message = "User deleted";
  }).catch(function(error) {
    $scope.error = error;
  });
 };
 }
 ]);
</code>```

Where the users are registered in the Auth of Firebase, as well in the Database, -working like a charm!

To call all the name of users in front end I've try the following:

```<code>  <ul><li ng-repeat='user in users'>{{users.name}}</li></ul>
</code>```

Without any success.

Does anybody know how to achieve this? What is wrong with my code?

Thanks a lot!

答:
use this one you will get the all registered user of the firebase         </p>

```<code>    var myapp = angular.module('sampleApp', ['firebase'])
    myapp.factory('usersList', function($firebaseArray) {
    //Get the firebase reference
    var ref = firebase.database().ref('users');
    //return the array of users
    return $firebaseArray(ref);
  });

  myapp.controller('SampleCtrl', function (usersList, $scope) {
    //Put the users array in the scope.users
    $scope.users = usersList;
  })
</code>```

<p>and for the display user the same code you used and also initialize your firebase application
I think it may help you </p>

```<code>      <ul><li ng-repeat='user in users'>{{users.name}}</li></ul>
</code>```

Body:
I'm trying to display the front end of all the name of my users in a list.

I'm creating users like that:

 firebase.initializeApp(config);

var app =  angular
.module('app', ['firebase'])
app.factory("Auth", ["$firebaseAuth",
function($firebaseAuth) {
return $firebaseAuth();
}
]);

 app.controller("SampleCtrl", ["$scope", "Auth",
 function($scope, Auth) {
$scope.createUser = function() {
  $scope.message = "One or more field is not correctly entered !";
  $scope.error = null;

Auth.$createUserWithEmailAndPassword($scope.email, $scope.password, $scope.name)
    .then(function(firebaseUser) {
      $scope.message = "User created with uid: " + firebaseUser.uid;
      const uid = firebaseUser.uid;
      const dbref = firebase.database().ref().child('users').child(uid);

      dbref.update({
        email: $scope.email,
        id: uid,
        name: $scope.name
      });
        console.log(dbref.uid);
    }).catch(function(error) {
      $scope.error = error;
    });
};

 $scope.deleteUser = function() {
  $scope.message = null;
  $scope.error = null;

  $scope.auth.$onAuthStateChanged(function(firebaseUser) {
  $scope.firebaseUser = firebaseUser;
});

  // Delete the currently signed-in user
  Auth.$deleteUser().then(function() {
    $scope.message = "User deleted";
  }).catch(function(error) {
    $scope.error = error;
  });
 };
 }
 ]);

Where the users are registered in the Auth of Firebase, as well in the Database, -working like a charm!

To call all the name of users in front end I've try the following:

{{users.name}}

Without any success.

Does anybody know how to achieve this? What is wrong with my code?

Thanks a lot!

Body:
use this one you will get the all registered user of the firebase

    var myapp = angular.module('sampleApp', ['firebase'])
    myapp.factory('usersList', function($firebaseArray) {
    //Get the firebase reference
    var ref = firebase.database().ref('users');
    //return the array of users
    return $firebaseArray(ref);
  });

  myapp.controller('SampleCtrl', function (usersList, $scope) {
    //Put the users array in the scope.users
    $scope.users = usersList;
  })

and for the display user the same code you used and also initialize your firebase application
I think it may help you

      <ul><li ng-repeat='user in users'>{{users.name}}</li></ul>


问:
Inappropriate ioctl for device when trying to SSH
I'm trying to SSH few servers and trying to get sudo -l output of each server.

Below is the script I'm executing

```<code>#!/bin/bash
serverlist="/tmp/servers"

while IFS=, read -r server netgroup username user
do
        ssh -tt -q root@$server sudo -U $username -l < /dev/null
done < "$serverlist"
</code>```

I have found that -tt option in this script as the cause of this error. Any thought on this?

Also i have noted that I don't see this error when i execute below command just for 1 server.

ssh -tt -q root@myserver sudo -U cham01 -l

Below is the complete error message I'am getting:
tcgetattr: Inappropriate ioctl for device

答:
tcgetattr: Inappropriate ioctl for device normally means that some program attempted to do a terminal control operation but its standard I/O streams weren't connected to a terminal.  (I know this because tcgetattr is the name of a C library function that does terminal control operations.)

Now, the whole point of the -tt option to ssh is to guarantee that the program run on the remote host is connected to a terminal, and stty printing out speed 38400 baud; line = 0; -brkint -imaxbel demonstrates that it was.  This is what I get when I run these commands with my servers:

$ ssh myserver stty < /dev/null
stty: 'standard input': Inappropriate ioctl for device

$ ssh -tt myserver stty < /dev/null
speed 38400 baud; line = 0;
-brkint -imaxbel
Connection to myserver closed.
```

<p>But what you are getting is</p>

<pre class="lang-none prettyprint-override"><code>$ ssh -tt yourserver stty < /dev/null
tcsetattr: Inappropriate ioctl for device
speed 38400 baud; line = 0;
-brkint -imaxbel
</code>```

The tcsetattr error is not coming from stty.  First something tried to do something terminal-related and failed, and then stty ran successfully.
This suggests a bug in your shell startup scripts, which are doing something that is inappropriate when run "non-interactively", causing you to get this error even though you are running commands connected to a terminal.  I can't help you any further, but perhaps this old answer about a similar problem offers some clues.

Body:
I'm trying to SSH few servers and trying to get sudo -l output of each server.

Below is the script I'm executing

#!/bin/bash
serverlist="/tmp/servers"

while IFS=, read -r server netgroup username user
do
        ssh -tt -q root@$server sudo -U $username -l < /dev/null
done < "$serverlist"

I have found that -tt option in this script as the cause of this error. Any thought on this?

Also i have noted that I don't see this error when i execute below command just for 1 server.

ssh -tt -q root@myserver sudo -U cham01 -l

Below is the complete error message I'am getting:
tcgetattr: Inappropriate ioctl for device

Body:
tcgetattr: Inappropriate ioctl for device normally means that some program attempted to do a terminal control operation but its standard I/O streams weren't connected to a terminal.  (I know this because tcgetattr is the name of a C library function that does terminal control operations.)

Now, the whole point of the -tt option to ssh is to guarantee that the program run on the remote host is connected to a terminal, and stty printing out speed 38400 baud; line = 0; -brkint -imaxbel demonstrates that it was.  This is what I get when I run these commands with my servers:

$ ssh myserver stty < /dev/null
stty: 'standard input': Inappropriate ioctl for device

$ ssh -tt myserver stty < /dev/null
speed 38400 baud; line = 0;
-brkint -imaxbel
Connection to myserver closed.

But what you are getting is

$ ssh -tt yourserver stty < /dev/null
tcsetattr: Inappropriate ioctl for device
speed 38400 baud; line = 0;
-brkint -imaxbel

The tcsetattr error is not coming from stty.  First something tried to do something terminal-related and failed, and then stty ran successfully.
This suggests a bug in your shell startup scripts, which are doing something that is inappropriate when run "non-interactively", causing you to get this error even though you are running commands connected to a terminal.  I can't help you any further, but perhaps this old answer about a similar problem offers some clues.


问:
Pass multiple parameter from angularjs to asp mvc controller
I want to pass multiple parameter from angularjs to asp mvc controller using viewmodel, but its not working. For reference please look into the image of the html page.

I want to pass OrderId and array of Id and Rating.

Here is the html code :

Here is my angularjs controller and factory code :

Here are the two viewmodel classes :

Here is the mvc controller :

As you can see I am not able to get OrderDetails from the viewmodel. So how to get it?

答:
Try like below. While push just Identify duplicate data.

var app = angular.module('myApp', []);
app.controller('testCtrl', function($scope) {
$scope.company = [{id:1, name:"Sole Trader", rating:4},{id:2, name:"Pvt Ltd", rating:3},{id:3, name:"LLC", rating:5}];
$scope.Newrat = [];
  $scope.addRatingbyId = function(pushdata){
  if($scope.Newrat.length != 0){
  angular.forEach($scope.Newrat, function(value, index){
  if(value.id == pushdata.id){
   $scope.Newrat[index].rating = pushdata.rating;
  }else{
   $scope.Newrat.push(pushdata);
   }
  });
 }else{
 $scope.Newrat.push(pushdata);
 }
  }
  $scope.sendRating= function(){
  //send $scope.Newrat
  console.log($scope.Newrat);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="testCtrl" >
{{company}}
<table><tr><th>id</th><th>Name</th><th>Rating</th>
</tr>
<tr ng-repeat="com in company">
<td>{{com.id}}</td>
<td>{{com.name}}</td>
<td>
<input type="text" ng-model="com.rating" ng-change="addRatingbyId(com)">
</td>
</tr></table>
<input type="submit" ng-click="sendRating()">
{{Newrat}}
</div>

</body>
</html></code>```

Body:
Try like below. While push just Identify duplicate data.

var app = angular.module('myApp', []);
app.controller('testCtrl', function($scope) {
$scope.company = [{id:1, name:"Sole Trader", rating:4},{id:2, name:"Pvt Ltd", rating:3},{id:3, name:"LLC", rating:5}];
$scope.Newrat = [];
  $scope.addRatingbyId = function(pushdata){
  if($scope.Newrat.length != 0){
  angular.forEach($scope.Newrat, function(value, index){
  if(value.id == pushdata.id){
   $scope.Newrat[index].rating = pushdata.rating;
  }else{
   $scope.Newrat.push(pushdata);
   }
  });
 }else{
 $scope.Newrat.push(pushdata);
 }
  }
  $scope.sendRating= function(){
  //send $scope.Newrat
  console.log($scope.Newrat);
  }
});

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="testCtrl" >
{{company}}
<table><tr><th>id</th><th>Name</th><th>Rating</th>
</tr>
<tr ng-repeat="com in company">
<td>{{com.id}}</td>
<td>{{com.name}}</td>
<td>
<input type="text" ng-model="com.rating" ng-change="addRatingbyId(com)">
</td>
</tr></table>
<input type="submit" ng-click="sendRating()">
{{Newrat}}
</div>

</body>
</html>