问:
Future and asynchronism
I use a extern api (ESRI API for Android) where I have a loop for which me return a class Future

```<code>...
for (Layer layer : layers) {

// ListenableFuture extends Future<V>
final ListenableFuture<FeatureQueryResult> future= gdbFeatureTable.queryFeaturesAsync(query);

future.addDoneListener(() -> {
                try {
                    FeatureQueryResult result = future.get();
...
}
</code>```

OR

```<code>try {
                FeatureQueryResult result = future.get();

    }
    ...
</code>```

Is it possible to launch all queryFeaturesAsync and obtain the global result (result1 + result2 + etc..) with asynchronously after the loop for ?
What's the best way ? promises? ThreadPoolExecutor ?

Thanks for your help

答:
If I use CompletableFuture is it the best way ?
I don't understand all ...

```<code>List<CompletableFuture<FeatureQueryResult>> futures = new ArrayList<>();
for (Layer layer : layers) {
    FeatureTable gdbFeatureTable = ((FeatureLayer) layer).getFeatureTable();
    CompletableFuture<FeatureQueryResult>  completableFuture = new CompletableFuture<>();
    ListenableFuture<FeatureQueryResult> future = gdbFeatureTable.queryFeaturesAsync(query);
    future.addDoneListener(() -> {
                        FeatureQueryResult result = future.get();
                        completableFuture.complete(result);
    }
    futures.add(future);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
</code>```

Do you have a another solution with completablefuture ?

Thanks for your reponse

Title: Future and asynchronism

Body:
I use a extern api (ESRI API for Android) where I have a loop for which me return a class Future

...
for (Layer layer : layers) {

// ListenableFuture extends Future<V>
final ListenableFuture<FeatureQueryResult> future= gdbFeatureTable.queryFeaturesAsync(query);

future.addDoneListener(() -> {
                try {
                    FeatureQueryResult result = future.get();
...
}

OR

try {
                FeatureQueryResult result = future.get();

    }
    ...

Is it possible to launch all queryFeaturesAsync and obtain the global result (result1 + result2 + etc..) with asynchronously after the loop for ?
What's the best way ? promises? ThreadPoolExecutor ?

Thanks for your help

Body:
If I use CompletableFuture is it the best way ?
I don't understand all ...

List<CompletableFuture<FeatureQueryResult>> futures = new ArrayList<>();
for (Layer layer : layers) {
    FeatureTable gdbFeatureTable = ((FeatureLayer) layer).getFeatureTable();
    CompletableFuture<FeatureQueryResult>  completableFuture = new CompletableFuture<>();
    ListenableFuture<FeatureQueryResult> future = gdbFeatureTable.queryFeaturesAsync(query);
    future.addDoneListener(() -> {
                        FeatureQueryResult result = future.get();
                        completableFuture.complete(result);
    }
    futures.add(future);
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));

Do you have a another solution with completablefuture ?

Thanks for your reponse


来源: stackexchange

问:
cmake error: no such file?
first of all i'm using clion and built-in cmake on ubuntu 17

build massage log:

```<code>[ 20%] Linking C executable pacman
cc: error: SDL2_image: No such file or directory
CMakeFiles/pacman.dir/build.make:172: recipe for target 'pacman' failed
make[3]: *** [pacman] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/pacman.dir/all' failed
make[2]: *** [CMakeFiles/pacman.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/pacman.dir/rule' failed
make[1]: *** [CMakeFiles/pacman.dir/rule] Error 2
Makefile:118: recipe for target 'pacman' failed
make: *** [pacman] Error 2
</code>```

cmakeList.txt:

```<code>cmake_minimum_required(VERSION 3.9)
project(pacman C)
set(CMAKE_C_STANDARD 99)
set(SOURCE src/main.c src/input.c src/input.h src/view.c src/view.h src/models.h src/models.c)
add_executable(pacman "${SOURCE}")
include_directories(src)
include_directories(src/SDL2-2.0.7/include)
INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED)
set(SDL2_IMAGE_INCLUDE_DIR "src/SDL2_image-2.0.2")
include_directories("${SDL2_IMAGE_INCLUDE_DIR}")
target_link_libraries(pacman "${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES}")
</code>```

and a file named Makefile: (I don't know much about it! and the error finally rises from here, unfortunately)

```<code># Makefile for showimage

CC = gcc
CFLAGS = $(shell sdl2-config --cflags) -Wall -O
LIBS = $(shell sdl2-config --libs) -lSDL2_image
EXE = showimage

all: $(EXE)

showimage: showimage.c Makefile
    $(CC) -o $@ $@.c $(CFLAGS) $(LIBS)

clean:
    -rm *.o $(EXE)
</code>```

note that i'm 100% sure i've installed all sdl2 libraries using this command:

```<code>sudo apt-get install libsdl2*
</code>```

and it worked right and everything finished without any errors output this:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libsdl2-mixer-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-image-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-doc' for glob 'libsdl2*'
Note, selecting 'libsdl2-mixer-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-doc' for glob 'libsdl2*'
Note, selecting 'libsdl2-ttf-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-net-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-net-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-image-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-1.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-ttf-2.0-0' for glob 'libsdl2*'
libsdl2-2.0-0 is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-dev is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-doc is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-gfx-1.0-0 is already the newest version (1.0.1+dfsg-5).
libsdl2-gfx-dev is already the newest version (1.0.1+dfsg-5).
libsdl2-gfx-doc is already the newest version (1.0.1+dfsg-5).
libsdl2-image-2.0-0 is already the newest version (2.0.1+dfsg-3).
libsdl2-image-dev is already the newest version (2.0.1+dfsg-3).
libsdl2-mixer-2.0-0 is already the newest version (2.0.1+dfsg1-3).
libsdl2-mixer-dev is already the newest version (2.0.1+dfsg1-3).
libsdl2-net-2.0-0 is already the newest version (2.0.1+dfsg1-3).
libsdl2-net-dev is already the newest version (2.0.1+dfsg1-3).
libsdl2-ttf-2.0-0 is already the newest version (2.0.14+dfsg1-2).
libsdl2-ttf-dev is already the newest version (2.0.14+dfsg1-2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

thanks for help beforehands:)))))

答:
I've fixed it all by changing the cmake code this way:
simply giving the sdl directory paths manually!</p>

```<code>cmake_minimum_required(VERSION 3.9)
project(pacman C)

set(CMAKE_C_STANDARD 99)
set(SOURCE src/main.c src/input.c src/input.h src/view.c src/view.h src/models.h src/models.c src/controler.c src/controler.h)
add_executable(pacman "${SOURCE}")
include_directories(src)

include_directories("/usr/include/SDL2")
target_link_libraries(pacman m SDL2 SDL2_gfx SDL2_image)

ADD_DEFINITIONS(-D_REENTRANT)
</code>```

ContentLicense: CC BY-SA 3.0

Title: cmake error: no such file?

Body:
first of all i'm using clion and built-in cmake on ubuntu 17

build massage log:

[ 20%] Linking C executable pacman
cc: error: SDL2_image: No such file or directory
CMakeFiles/pacman.dir/build.make:172: recipe for target 'pacman' failed
make[3]: *** [pacman] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/pacman.dir/all' failed
make[2]: *** [CMakeFiles/pacman.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/pacman.dir/rule' failed
make[1]: *** [CMakeFiles/pacman.dir/rule] Error 2
Makefile:118: recipe for target 'pacman' failed
make: *** [pacman] Error 2

cmakeList.txt:

cmake_minimum_required(VERSION 3.9)
project(pacman C)
set(CMAKE_C_STANDARD 99)
set(SOURCE src/main.c src/input.c src/input.h src/view.c src/view.h src/models.h src/models.c)
add_executable(pacman "${SOURCE}")
include_directories(src)
include_directories(src/SDL2-2.0.7/include)
INCLUDE(FindPkgConfig)
PKG_SEARCH_MODULE(SDL2 REQUIRED sdl2)
PKG_SEARCH_MODULE(SDL2IMAGE REQUIRED)
set(SDL2_IMAGE_INCLUDE_DIR "src/SDL2_image-2.0.2")
include_directories("${SDL2_IMAGE_INCLUDE_DIR}")
target_link_libraries(pacman "${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES}")

and a file named Makefile: (I don't know much about it! and the error finally rises from here, unfortunately)

# Makefile for showimage

CC = gcc
CFLAGS = $(shell sdl2-config --cflags) -Wall -O
LIBS = $(shell sdl2-config --libs) -lSDL2_image
EXE = showimage

all: $(EXE)

showimage: showimage.c Makefile
    $(CC) -o $@ $@.c $(CFLAGS) $(LIBS)

clean:
    -rm *.o $(EXE)

note that i'm 100% sure i've installed all sdl2 libraries using this command:

sudo apt-get install libsdl2*

and it worked right and everything finished without any errors output this:

Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libsdl2-mixer-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-image-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-doc' for glob 'libsdl2*'
Note, selecting 'libsdl2-mixer-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-doc' for glob 'libsdl2*'
Note, selecting 'libsdl2-ttf-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-net-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-net-dev' for glob 'libsdl2*'
Note, selecting 'libsdl2-image-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-2.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-gfx-1.0-0' for glob 'libsdl2*'
Note, selecting 'libsdl2-ttf-2.0-0' for glob 'libsdl2*'
libsdl2-2.0-0 is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-dev is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-doc is already the newest version (2.0.6+dfsg1-3ubuntu1).
libsdl2-gfx-1.0-0 is already the newest version (1.0.1+dfsg-5).
libsdl2-gfx-dev is already the newest version (1.0.1+dfsg-5).
libsdl2-gfx-doc is already the newest version (1.0.1+dfsg-5).
libsdl2-image-2.0-0 is already the newest version (2.0.1+dfsg-3).
libsdl2-image-dev is already the newest version (2.0.1+dfsg-3).
libsdl2-mixer-2.0-0 is already the newest version (2.0.1+dfsg1-3).
libsdl2-mixer-dev is already the newest version (2.0.1+dfsg1-3).
libsdl2-net-2.0-0 is already the newest version (2.0.1+dfsg1-3).
libsdl2-net-dev is already the newest version (2.0.1+dfsg1-3).
libsdl2-ttf-2.0-0 is already the newest version (2.0.14+dfsg1-2).
libsdl2-ttf-dev is already the newest version (2.0.14+dfsg1-2).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

thanks for help beforehands:)))))

Body:
I've fixed it all by changing the cmake code this way:
simply giving the sdl directory paths manually!

cmake_minimum_required(VERSION 3.9)
project(pacman C)

set(CMAKE_C_STANDARD 99)
set(SOURCE src/main.c src/input.c src/input.h src/view.c src/view.h src/models.h src/models.c src/controler.c src/controler.h)
add_executable(pacman "${SOURCE}")
include_directories(src)

include_directories("/usr/include/SDL2")
target_link_libraries(pacman m SDL2 SDL2_gfx SDL2_image)

ADD_DEFINITIONS(-D_REENTRANT)


答:
Change

```<code>$data = array('Year','Sales','Expenses','Profit');
</code>```

To

```<code>$data[] = array('Year','Sales','Expenses','Profit');
</code>```

Title: Modify Array formatting in php

Body:
I want to change array formatting in php but i'm getting error.

I want output like this

    [
      ['Year', 'Sales', 'Expenses', 'Profit'],
      ['2014', 1000, 400, 200],
      ['2015', 1170, 460, 250],
      ['2016', 660, 1120, 300],
      ['2017', 1030, 540, 350]
    ]

php code

$sql = mysql_query("SELECT `year`, `sales`,`expenses`,`profit`
              FROM chart
              ORDER BY `year` ASC");

$data = array('Year','Sales','Expenses','Profit');

while ($row = mysql_fetch_array($sql)) {
   $data[] = array($row['year'], $row['sales'], $row['expenses'],
   $row['profit']);
}

echo json_encode($data);

Output

["Year","Sales","Expenses","Profit",
["2012","20000","15000","5000"],
["2013","30000","18000","12000"],
["2014","100000","60000","40000"],
["2015","250000","150000","100000"],
["2016","15000","12000","3000"]
]

Body:
Change

$data = array('Year','Sales','Expenses','Profit');

To

$data[] = array('Year','Sales','Expenses','Profit');


问:
TextureAtlas and renderCalls in libgdx
I'm creating two textures and put them in the same TextureAtlas as shown in the code:

```<code>public void create () {
    pix = new Pixmap(100, 100, Pixmap.Format.RGBA8888);
    textureAtlas = new TextureAtlas();

    pix.setColor(Color.WHITE);
    pix.fill();
    textureAtlas.addRegion("white", new TextureRegion(new Texture(pix)));
    pix.setColor(Color.RED);
    pix.fill();
    textureAtlas.addRegion("red", new TextureRegion(new Texture(pix)));

    tr_list = textureAtlas.getRegions();

    pix.dispose()
}
</code>```

and then when rendering:

```<code>public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    for (int i = 0; i < 200; ++i) {
        batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
    }
    font.draw(batch, "FPS: " + Integer.toString(Gdx.graphics.getFramesPerSecond()), 0, Gdx.graphics.getHeight() - 20);
    font.draw(batch, "Render Calls: " + Integer.toString(batch.renderCalls), 0, Gdx.graphics.getHeight() - 60);
    batch.end();
}
</code>```

I was expecting batch.renderCalls to be equal to 1, since the textures are in the same TextureAtlas, but instead it's equal to 200. What am I doing wrong?

答:
You are drawing them in loop 200 times.

```<code>for (int i = 0; i < 200; ++i) {
    // this will be called 200 times
    batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
}
</code>```

And also TextureAtlas class doesn't create pig picture of textures that you add to it. It is just container of TextureRegions how @Arctic23 noticed.

So main problem for you is to draw 2 textures in one render call. I wouldn't recommend you doing this. It is possible but it will be hard to work with them.

Calling batch.draw(..) every time you draw a texture is not a big performance problem. So i don't know why you detach this.

Title: TextureAtlas and renderCalls in libgdx

Body:
I'm creating two textures and put them in the same TextureAtlas as shown in the code:

public void create () {
    pix = new Pixmap(100, 100, Pixmap.Format.RGBA8888);
    textureAtlas = new TextureAtlas();

    pix.setColor(Color.WHITE);
    pix.fill();
    textureAtlas.addRegion("white", new TextureRegion(new Texture(pix)));
    pix.setColor(Color.RED);
    pix.fill();
    textureAtlas.addRegion("red", new TextureRegion(new Texture(pix)));

    tr_list = textureAtlas.getRegions();

    pix.dispose()
}

and then when rendering:

public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    batch.begin();
    for (int i = 0; i < 200; ++i) {
        batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
    }
    font.draw(batch, "FPS: " + Integer.toString(Gdx.graphics.getFramesPerSecond()), 0, Gdx.graphics.getHeight() - 20);
    font.draw(batch, "Render Calls: " + Integer.toString(batch.renderCalls), 0, Gdx.graphics.getHeight() - 60);
    batch.end();
}

I was expecting batch.renderCalls to be equal to 1, since the textures are in the same TextureAtlas, but instead it's equal to 200. What am I doing wrong?

Body:
You are drawing them in loop 200 times.

for (int i = 0; i < 200; ++i) {
    // this will be called 200 times
    batch.draw(tr_list.get(i % tr_list.size), (int)(Math.random()* 500), (int)(Math.random()* 500));
}

And also TextureAtlas class doesn't create pig picture of textures that you add to it. It is just container of TextureRegions how @Arctic23 noticed.

So main problem for you is to draw 2 textures in one render call. I wouldn't recommend you doing this. It is possible but it will be hard to work with them.

Calling batch.draw(..) every time you draw a texture is not a big performance problem. So i don't know why you detach this.


问:
Tuning GC for Java audio application
I've noticed that when playing audio in java, MarkSweepCompact stage in gc is too long and results in short periods of silence, which is unacceptable. So I need to use a low pause gc. I've tried Parallel and CMS, they seem to work better because I suppose the pause is shorter and they don't do full collection as often as the default one.

So far I've tested my program with the following options for ParallelGC:

```<code>-XX:+UseParallelGC
-XX:MaxGCPauseMillis=70
</code>```

and for ConcurrentMarkSweep:

```<code>-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
</code>```

I also tried G1GC, but it's still experimental in java 6. Options for both modes:

```<code>-Xms15m
-Xmx40m
-XX:+UnlockExperimentalVMOptions
-XX:+CMSClassUnloadingEnabled
-XX:+TieredCompilation
-XX:+AggressiveOpts
-XX:+UseAdaptiveSizePolicy
-Dsun.java2d.noddraw=false
-Dswing.aatext=true
-XX:MaxPermSize=25m
-XX:MaxHeapFreeRatio=10
-XX:MinHeapFreeRatio=10
</code>```

Which GC is better in this situation? Can any of these settings be optimized for best CPU performance and minimal memory usage as well?

EDIT To recognize the pause I record time to write audio data to the output line, usually it's between 92 to 120 ms (I'm writing 16384 bytes = ~92ms), ad when Full GC is run, it's 200+ ms:

```<code>65.424: [Full GC (System) [PSYoungGen: 872K->0K(2432K)] [PSOldGen: 12475K->12905K(16960K)] 13348K->12905K(19392K) [PSPermGen: 15051K->15051K(22272K)], 0.2145081 secs] [Times: user=0.20 sys=0.00, real=0.21 secs]
Was writing 16384 bytes, time to write 263 ms
</code>```

EDIT2 Allocation pattern for my app is the following: it loads bunch of objects at startup, then it starts playing and I guess most of the objects after that are allocated by the gui, because staring/pausing the audio doesn't change the GC graph much. This is what visualgc shows with parallel gc:

The graph starts at startup and I start playback. Labeled are

1) sound delay and full gc, I think it increased Old size:

```<code>101.646: [Full GC [PSYoungGen: 64K->0K(6848K)] [PSOldGen: 15792K->12773K(19328K)] 15856K->12773K(26176K) [PSPermGen: 15042K->14898K(23808K)], 0.2411479 secs] [Times: user=0.19 sys=0.00, real=0.24 secs]
</code>```

2) I open the app window and pause playback. Nothing really changes, a bit later it increases eden size.

3) I open the windows and start playback again.

So I need to increase allocated Old Gen size? How do I do that? I'm running with -XX:NewRatio=10 and -XX:NewSize=10m

Thank you.

答:
The log you provide is too small to provide real analysis but it says that it spent 200ms doing v little as the old gen is basically full. This means your heap is too small or you have a memory leak. There is not much you can do to tune the GC algorithm in this situation. Therefore the rest of this reply is about how you can get more information out of the app and/or how to tune GC once you have eliminated the memory leak or have a bigger heap.

To a large extent, low pause means doing all you can to keep the collections as young collections only.

You really need to log exactly when you start and finish writing and then correlate that with the STW pauses that occur in the JVM during that period otherwise you really have no idea what might be causing the issue or how severe the issue really is.

Things I'd do immediately;

change your logging so that you output a single line easily parseable by a script (perhaps starttime,endtime,duration)

add the PrintGCApplicationStoppedTime and PrintGCApplicationConcurrentTime switches so that you get a record of every STW pause and not just GC events

use the latest JVM (i.e. 6u23) as there have been a lot of improvements to hotspot over the last year or two so there point using an older one

You don't say if you're memory constrained but I'd definitely increase the heap size if you can, 40M is pretty small so you don't have much space to play with

Run the app with visualgc connected, it's gives a more comprehensive view on what is going on IMO as you have all the different views up at one time

The key thing is determine where you're running out of space and why. The answer to that likely lies in what the allocation pattern of your app is like, is it generating a load of short lived objects such that you're burning through your tiny eden really quickly? is the tenuring threshold too high such that you're ping ponging objects through the survivor spaces before they get tenured anyway and thus forcing frequent tenured gcs (slow)?

A few other things to bear in mind...

iCMS (incremental) was intended for use on 1 or 2 core machines, does that describe your machine? how many cores do you have? you may just want to drop that option

CMS does have a single threaded phase (init mark), this might be hurting you

CMS typically prefers a bigger heap than other collectors, yours is pretty small

Edit after visualgc graph added to question
Since you're memory constrained then you need to make best use of the space you have, the only way to do this is going to be through repeated benchmarking... ideally with a repeatable test.

you can use -Xmn to specify set the size of the young generation, the remainder will be given to tenured.

you might want to tune your use of the survivor spaces so that you let them get fuller before they're swapped and to let objects live there for longer before they get tenured

-XX:TargetSurvivorRatio=90 sets it so a survivor space needs to be 90% full before it is copied, obviously there is a trade off here between the cost of copying and using the space

use -XX:+PrintTenuringDistribution to show the size of each space and how things are, you can also see this in visualgc

use -XX:+MaxTenuringThreshold to specify how many times an object can survive a young collection (be copied from 1 survivor space to another) before it is tenured, e.g. if you know you only get short lived garbage or stuff that lives forever then setting this to 1 is sensible

you need to understand what is triggering the tenured collections and might consider taking action to make it trigger later

for CMS this may involve tweaking -XX:CMSInitiatingOccupancyFraction=<value>, e.g. set to 80 and it will trigger CMS at 80% occupancy of tenured (NB: this is be a bad thing to get wrong so you may prefer to let hotspot manage this; set it too small and it collects too often killing performance, set it too big and it may trigger too late causing an unscheduled full collection with correspondingly long pause time

if it really is old collections that are hurting you and you need low pause then use CMS and ParNew

Finally get a profiler and work out where the garbage is coming from, you might find it is easier to control the rate at which garbage is generated then pouring effort into the black hole that can be GC tuning!

ContentLicense: CC BY-SA 2.5

Title: Tuning GC for Java audio application

Body:
I've noticed that when playing audio in java, MarkSweepCompact stage in gc is too long and results in short periods of silence, which is unacceptable. So I need to use a low pause gc. I've tried Parallel and CMS, they seem to work better because I suppose the pause is shorter and they don't do full collection as often as the default one.

So far I've tested my program with the following options for ParallelGC:

-XX:+UseParallelGC
-XX:MaxGCPauseMillis=70

and for ConcurrentMarkSweep:

-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing

I also tried G1GC, but it's still experimental in java 6. Options for both modes:

-Xms15m
-Xmx40m
-XX:+UnlockExperimentalVMOptions
-XX:+CMSClassUnloadingEnabled
-XX:+TieredCompilation
-XX:+AggressiveOpts
-XX:+UseAdaptiveSizePolicy
-Dsun.java2d.noddraw=false
-Dswing.aatext=true
-XX:MaxPermSize=25m
-XX:MaxHeapFreeRatio=10
-XX:MinHeapFreeRatio=10

Which GC is better in this situation? Can any of these settings be optimized for best CPU performance and minimal memory usage as well?

EDIT To recognize the pause I record time to write audio data to the output line, usually it's between 92 to 120 ms (I'm writing 16384 bytes = ~92ms), ad when Full GC is run, it's 200+ ms:

65.424: [Full GC (System) [PSYoungGen: 872K->0K(2432K)] [PSOldGen: 12475K->12905K(16960K)] 13348K->12905K(19392K) [PSPermGen: 15051K->15051K(22272K)], 0.2145081 secs] [Times: user=0.20 sys=0.00, real=0.21 secs]
Was writing 16384 bytes, time to write 263 ms

EDIT2 Allocation pattern for my app is the following: it loads bunch of objects at startup, then it starts playing and I guess most of the objects after that are allocated by the gui, because staring/pausing the audio doesn't change the GC graph much. This is what visualgc shows with parallel gc:

The graph starts at startup and I start playback. Labeled are

1) sound delay and full gc, I think it increased Old size:

101.646: [Full GC [PSYoungGen: 64K->0K(6848K)] [PSOldGen: 15792K->12773K(19328K)] 15856K->12773K(26176K) [PSPermGen: 15042K->14898K(23808K)], 0.2411479 secs] [Times: user=0.19 sys=0.00, real=0.24 secs]

2) I open the app window and pause playback. Nothing really changes, a bit later it increases eden size.

3) I open the windows and start playback again.

So I need to increase allocated Old Gen size? How do I do that? I'm running with -XX:NewRatio=10 and -XX:NewSize=10m

Thank you.

ContentLicense: CC BY-SA 4.0


问:
Why do I keep getting the Error: E/RecyclerView: No adapter attached; skipping layout?
I'm working on an app for my A-levels and while the app loads fine, none of my data appears. When I check the debug code I got this error:

E/RecyclerView: No adapter attached; skipping layout

I'm new to Android Studio, so I don't know where to put what adapter.

```<code>public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference Category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, MakeupViewHolder> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Makeup");
    setSupportActionBar(toolbar);

    //Init Firebase

    database = FirebaseDatabase.getInstance();
    Category = database.getReference("Category");

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //Set Name for user
    View headerView = navigationView.getHeaderView(0);
    txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
    txtFullName.setText(Common.currentUser.getName());

    //Load menu
    recycler_menu = (RecyclerView)findViewById(R.id.recycler_menu);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);
    recycler_menu.setAdapter(adapter);

    loadMenu();
}
</code>```

答:
I do not believe that this is an error that you need to handle. I do not know why the Android team choose to mark this log as "error".

A method called dispatchLayout is called as part of the layout phase, and that method should basically do nothing if either LayoutManager or Adapter are null. Which makes sense, and this log is printed in those cases.

It will just disappear when you have set both your LayoutManager and Adapter to the RecyclerView

Body:
I'm working on an app for my A-levels and while the app loads fine, none of my data appears. When I check the debug code I got this error:

E/RecyclerView: No adapter attached; skipping layout

I'm new to Android Studio, so I don't know where to put what adapter.

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
FirebaseDatabase database;
DatabaseReference Category;
TextView txtFullName;
RecyclerView recycler_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, MakeupViewHolder> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Makeup");
    setSupportActionBar(toolbar);

    //Init Firebase

    database = FirebaseDatabase.getInstance();
    Category = database.getReference("Category");

    FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    //Set Name for user
    View headerView = navigationView.getHeaderView(0);
    txtFullName = (TextView)headerView.findViewById(R.id.txtFullName);
    txtFullName.setText(Common.currentUser.getName());

    //Load menu
    recycler_menu = (RecyclerView)findViewById(R.id.recycler_menu);
    recycler_menu.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recycler_menu.setLayoutManager(layoutManager);
    recycler_menu.setAdapter(adapter);

    loadMenu();
}


问:
Pass File Directory between button click
How can I pass file directory between two button click method?

I'm selecting csv file and put the CSV name to TextBox

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
  OpenFileDialog ofd = new OpenFileDialog();
  ofd.Filter = "CSV|*.csv";
  ofd.ShowDialog();

  csvName.Text = ofd.SafeFileName;
}
</code>```

Second button should start reading CSV file selected into first step

```<code>private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //string path = ;
    StreamReader srd = new StreamReader();
}
</code>```

答:
csvName.Text = ofd.SafeFileName; SafeFileName doesn't return the full path it just returns the filename, which is not enough for the button(Button_Click_1) the start reading .
Instead use ofd.FileName; this give the complete path.
Assuming csvName as TextBox.

declare global variable

```<code>public string FullFileName{get;set;}

private void Button_Click(object sender, RoutedEventArgs e)
{
 OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "CSV|*.csv";
ofd.ShowDialog();
csvName.Text = ofd.SafeFileName;
</code>```

FullFileName=ofd.FileName;
    }

```<code>private void Button_Click_1(object sender, RoutedEventArgs e)
{
using(var reader = new StreamReader(FullFileName))
{
// do your action here
}
}
</code>```

Body:
How can I pass file directory between two button click method?

I'm selecting csv file and put the CSV name to TextBox

private void Button_Click(object sender, RoutedEventArgs e)
{
  OpenFileDialog ofd = new OpenFileDialog();
  ofd.Filter = "CSV|*.csv";
  ofd.ShowDialog();

  csvName.Text = ofd.SafeFileName;
}

Second button should start reading CSV file selected into first step

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //string path = ;
    StreamReader srd = new StreamReader();
}

Body:
csvName.Text = ofd.SafeFileName; SafeFileName doesn't return the full path it just returns the filename, which is not enough for the button(Button_Click_1) the start reading .
Instead use ofd.FileName; this give the complete path.
Assuming csvName as TextBox.

declare global variable

public string FullFileName{get;set;}

private void Button_Click(object sender, RoutedEventArgs e)
{
 OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "CSV|*.csv";
ofd.ShowDialog();
csvName.Text = ofd.SafeFileName;

FullFileName=ofd.FileName;
    }

private void Button_Click_1(object sender, RoutedEventArgs e)
{
using(var reader = new StreamReader(FullFileName))
{
// do your action here
}
}


问:
aws upload object to S3 bucket and pass details of data to lambda
Working my way through tutorials for AWS...So ive created an S3 bucket which when a file is dropped into it calls my lambda 'testHelloWorld' which sends an email...this all works fine (see below)

```<code> 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

    var eParams = {
        Destination: {
            ToAddresses: ["johnb@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: "Hey! What is up?"
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnb@hotmail.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

but I want to extend the email to include data on the file that was uploaded to the bucket. I have found How to trigger my Lambda Function once the file is uploaded to s3 bucket which gives a node.js code snippet which should capture the data. I have tried to import this into my existing lambda

```<code> 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context, exit){
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

 // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucketName',
       Key: 'keyName',
       Source : 'SourceName',
       Destination : 'DestinationName',
       Message : 'MessageName'
    };

     s3.getObject(function(err, data){
         if (err) {
           console.log('ERROR ' + err);
          // exit(err);
         } else {
           // the data has the content of the uploaded file
           var eParams = {
        Destination: {
            ToAddresses: ["johnboy@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: data
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnboy@hotmail.com"
    };
         }
     });

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

but this is failing on the params

```<code>message: 'There were 3 validation errors:
</code>```

* MissingRequiredParameter: Missing required key \'Source\' in params
* MissingRequiredParameter: Missing required key \'Destination\' in params
* MissingRequiredParameter: Missing required key \'Message\' in params',
  code: 'MultipleValidationErrors',
  errors:

These source, destination and message are listed in the params, are they not correctly formatted and it isnt picking them up?

I cant find much online....any help appreciated

UPDATE
Ok iv got it working without failing...if i use the test function in the lambda with the following code...

```<code>   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

   var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

     s3.getObject(params, function(err, data){
         if (err) {
           console.log('ERROR ' + err);
           exit(err);
         } else {
           testData = data;
         }
     });

    var eParams = {
        Destination: {
            ToAddresses: ["jim@him.com"]
        },
        Message: {
            Body: {
                Text: { Data: 'testData2' + testData}
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "jim@him.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};
</code>```

I get the email with the body- testData2null

So I tried uploading an image through the s3 bucket and I still get the email with the body testData2null

is there anyway to debug this further or does anyone kno who it is saying null. I never actually tested the code from the other post which passes the data over to the email I just assumed it would work. Does anyone else know who to obtain the data from the upload please? thanks

答:
You are declaring the var eParams within the callback of s3.getObject, but then you run the ses.sendMail outside of the callback. I think that's why!

You also need to move the ses.sendEmail to inside the callback of s3.getObject if you want to send the data from your object inside the email.

Try this:

```<code>s3.getObject(function(err, objectData) {
    if (err) {
        console.log('Could not fetch object data: ', err);
    } else {
        console.log('Data was successfully fetched from object');
        var eParams = {
            Destination: {
                ToAddresses: ["johnboy@hotmail.com"]
            },
            Message: {
                Body: {
                    Text: {
                        Data: objectData
                    }
                },
                Subject: {
                    Data: "Email Subject!!!"
                }
            },
            Source: "johnboy@hotmail.com"
        };

        console.log('===SENDING EMAIL===');

        var email = ses.sendEmail(eParams, function(err, emailResult) {
            if (err) console.log('Error while sending email', err);
            else {
                console.log("===EMAIL SENT===");
                console.log(objectData);
                console.log("EMAIL CODE END");
                console.log('EMAIL: ', emailResult);
                context.succeed(event);
            }
        });
    }
});
</code>```

Body:
Working my way through tutorials for AWS...So ive created an S3 bucket which when a file is dropped into it calls my lambda 'testHelloWorld' which sends an email...this all works fine (see below)

 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

    var eParams = {
        Destination: {
            ToAddresses: ["johnb@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: "Hey! What is up?"
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnb@hotmail.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

but I want to extend the email to include data on the file that was uploaded to the bucket. I have found How to trigger my Lambda Function once the file is uploaded to s3 bucket which gives a node.js code snippet which should capture the data. I have tried to import this into my existing lambda

 'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});
var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context, exit){
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

 // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucketName',
       Key: 'keyName',
       Source : 'SourceName',
       Destination : 'DestinationName',
       Message : 'MessageName'
    };

     s3.getObject(function(err, data){
         if (err) {
           console.log('ERROR ' + err);
          // exit(err);
         } else {
           // the data has the content of the uploaded file
           var eParams = {
        Destination: {
            ToAddresses: ["johnboy@hotmail.com"]
        },
        Message: {
            Body: {
                Text: {
                    Data: data
                }
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "johnboy@hotmail.com"
    };
         }
     });

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

but this is failing on the params

message: 'There were 3 validation errors:

* MissingRequiredParameter: Missing required key \'Source\' in params
* MissingRequiredParameter: Missing required key \'Destination\' in params
* MissingRequiredParameter: Missing required key \'Message\' in params',
  code: 'MultipleValidationErrors',
  errors:

These source, destination and message are listed in the params, are they not correctly formatted and it isnt picking them up?

I cant find much online....any help appreciated

UPDATE
Ok iv got it working without failing...if i use the test function in the lambda with the following code...

   'use strict';

console.log('Loading function');

var aws = require('aws-sdk');
var ses = new aws.SES({
   region: 'us-west-2'
});

var s3 = new aws.S3({ apiVersion: '2006-03-01', accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_KEY, region: process.env.LAMBDA_REGION });

exports.handler = function(event, context) {
    console.log("Incoming: ", event);
   // var output = querystring.parse(event);

   var testData = null;

   // Get the object from the event and show its content type
   // const bucket = event.Records[0].s3.bucket.name;
   // const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
       Bucket: 'bucket',
       Key: 'key',
    };

     s3.getObject(params, function(err, data){
         if (err) {
           console.log('ERROR ' + err);
           exit(err);
         } else {
           testData = data;
         }
     });

    var eParams = {
        Destination: {
            ToAddresses: ["jim@him.com"]
        },
        Message: {
            Body: {
                Text: { Data: 'testData2' + testData}
            },
            Subject: {
                Data: "Email Subject!!!"
            }
        },
        Source: "jim@him.com"
    };

    console.log('===SENDING EMAIL===');
    var email = ses.sendEmail(eParams, function(err, data){
        if(err) console.log(err);
        else {
            console.log("===EMAIL SENT===");
            console.log(data);

            console.log("EMAIL CODE END");
            console.log('EMAIL: ', email);
            context.succeed(event);

        }
    });

};

I get the email with the body- testData2null

So I tried uploading an image through the s3 bucket and I still get the email with the body testData2null

is there anyway to debug this further or does anyone kno who it is saying null. I never actually tested the code from the other post which passes the data over to the email I just assumed it would work. Does anyone else know who to obtain the data from the upload please? thanks

Body:
You are declaring the var eParams within the callback of s3.getObject, but then you run the ses.sendMail outside of the callback. I think that's why!

You also need to move the ses.sendEmail to inside the callback of s3.getObject if you want to send the data from your object inside the email.

Try this:

s3.getObject(function(err, objectData) {
    if (err) {
        console.log('Could not fetch object data: ', err);
    } else {
        console.log('Data was successfully fetched from object');
        var eParams = {
            Destination: {
                ToAddresses: ["johnboy@hotmail.com"]
            },
            Message: {
                Body: {
                    Text: {
                        Data: objectData
                    }
                },
                Subject: {
                    Data: "Email Subject!!!"
                }
            },
            Source: "johnboy@hotmail.com"
        };

        console.log('===SENDING EMAIL===');

        var email = ses.sendEmail(eParams, function(err, emailResult) {
            if (err) console.log('Error while sending email', err);
            else {
                console.log("===EMAIL SENT===");
                console.log(objectData);
                console.log("EMAIL CODE END");
                console.log('EMAIL: ', emailResult);
                context.succeed(event);
            }
        });
    }
});


问:
Better way to store query results from db in Qt Lists
I have a select query from which i want to store results in QT lists after query execution. Some of my code is:

```<code>QSqlQuery querySelect;

QStringList rfid;
QList<QDateTime> datetimeIN;
QList<QDateTime> datetimeOUT;
</code>```

... Some other code + querySelect prepare.....

```<code>if(querySelect.exec())
{
    while( querySelect.next() )
    {
        rfid.append(querySelect.value( 0 ).toString());
        datetimeIN.append(querySelect.value( 1 ).toDateTime());
        datetimeOUT.append(querySelect.value( 2 ).toDateTime());
    }
}
else
{
    qDebug()  << querySelect.lastError();
}
</code>```

I want to know is there another, more optimized faster approach to store the results in the lists, other than with the query.next while cycle because i think this is rather slow?

答:
On the Qt side, the only optimization that I can think of is

```<code>querySelect.setForwardOnly(true)
</code>```

By the way, I think you can change approach and create a single class and a list for it, rather then three separated lists.

```<code>struct Data
{
    QString rfid;
    QDateTime dtIn;
    QDateTime dtOut;
};
</code>```

Then store the results this way:

```<code>QList<Data> list;
while( querySelect.next() ) {
    list.append( {querySelect.value(0).toString(),
                  querySelect.value(1).toDateTime(),
                  querySelect.value(2).toDateTime()} );
}
</code>```

Body:
I have a select query from which i want to store results in QT lists after query execution. Some of my code is:

QSqlQuery querySelect;

QStringList rfid;
QList<QDateTime> datetimeIN;
QList<QDateTime> datetimeOUT;

... Some other code + querySelect prepare.....

if(querySelect.exec())
{
    while( querySelect.next() )
    {
        rfid.append(querySelect.value( 0 ).toString());
        datetimeIN.append(querySelect.value( 1 ).toDateTime());
        datetimeOUT.append(querySelect.value( 2 ).toDateTime());
    }
}
else
{
    qDebug()  << querySelect.lastError();
}

I want to know is there another, more optimized faster approach to store the results in the lists, other than with the query.next while cycle because i think this is rather slow?

Body:
On the Qt side, the only optimization that I can think of is

querySelect.setForwardOnly(true)

By the way, I think you can change approach and create a single class and a list for it, rather then three separated lists.

struct Data
{
    QString rfid;
    QDateTime dtIn;
    QDateTime dtOut;
};

Then store the results this way:

QList<Data> list;
while( querySelect.next() ) {
    list.append( {querySelect.value(0).toString(),
                  querySelect.value(1).toDateTime(),
                  querySelect.value(2).toDateTime()} );
}


问:
What happend if guava cache is full and no evictable element?
I am using google guava cache with reference-based eviction.
I wonder what happened if the cache is full and no element of it is marked as evictable? Is there an out of memory exception thrown?</p>

答: Reference-based eviction is essentially no different than Java's standard GC behavior - the GC just ignores the reference's presence in the cache. If an object falls out of scope (everywhere but the cache) it will be evicted from the cache during GC. If all elements of the cache are in scope somewhere else and therefore cannot be GCed you will run into memory problems exactly like you would if you weren't using a cache. You cannot have more data in memory than the JVM is configured to permit. Using a reference-evicting cache doesn't change this.</p>


问:
Help in :hover CSS
Does :hover in css only works on  tags? Or it can work on any HTML tags? Thank you.

答: It applies to any element, but IE6 and earlier have a bug which only lets it work on links ( elements with an href attribute).

Title: Help in :hover CSS

Body: It applies to any element, but IE6 and earlier have a bug which only lets it work on links (<a> elements with an href attribute).


问:
Enum Constructor using switch (this)
In my enum constructor, I'm trying to initialize their members. I need to use a switch statement to know which enum is currently being instantiated. However for some reason this seems to return null which makes little sense to me. Is this null until the constructor completes? If so, how can I differentiate which enum is being constructed at run time? The example below is a simplified version of my actual code to demonstrate the problem.

```<code>Food f = Food.APPLE;
System.out.println(f.getTastes());
</code>```

Food Enum

```<code>public enum Food
{
    APPLE,
    PANCAKES,
    PASTA;

    private List<String> tastes = new ArrayList<>();

    Food()
    {
        switch(this)
        {
        case APPLE:
            tastes.add("Sour");
            tastes.add("Sweet");
            break;
        case PANCAKES:
            tastes.add("Dough-y");
            break;
        case PASTA:
            tastes.add("Creamy");
            tastes.add("Rich");
            tastes.add("Velvet");
        }
    }

    public List<String> getTastes()
    {
        return tastes;
    }
}
</code>```

I get the following exception

```<code>Exception in thread "main" java.lang.ExceptionInInitializerError
    at Food.<init>(Food.java:18)
    at Food.<clinit>(Food.java:10)
    at Tester.main(Tester.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
    at Food.values(Food.java:8)
    at Food$1.<clinit>(Food.java:18)
    ... 8 more
</code>```

答:
I`m not sure if this would suit you, but i belive to be the correct pattern, instead of figuring out what taste each food have in constructor, you could just declare it.</p>

```<code>public enum Food
{
  APPLE("good", "sweet"),
  PANCAKES("delicious","omg"),
  PASTA("too fat", "but its gud");

  private List<String> tastes = new ArrayList<>();

      Food(String ... tastes) {
        // add to the list
     }
  }
</code>```

Title: Enum Constructor using switch (this)

Body:
In my enum constructor, I'm trying to initialize their members. I need to use a switch statement to know which enum is currently being instantiated. However for some reason this seems to return null which makes little sense to me. Is this null until the constructor completes? If so, how can I differentiate which enum is being constructed at run time? The example below is a simplified version of my actual code to demonstrate the problem.

Food f = Food.APPLE;
System.out.println(f.getTastes());

Food Enum

public enum Food
{
    APPLE,
    PANCAKES,
    PASTA;

    private List<String> tastes = new ArrayList<>();

    Food()
    {
        switch(this)
        {
        case APPLE:
            tastes.add("Sour");
            tastes.add("Sweet");
            break;
        case PANCAKES:
            tastes.add("Dough-y");
            break;
        case PASTA:
            tastes.add("Creamy");
            tastes.add("Rich");
            tastes.add("Velvet");
        }
    }

    public List<String> getTastes()
    {
        return tastes;
    }
}

I get the following exception

Exception in thread "main" java.lang.ExceptionInInitializerError
    at Food.<init>(Food.java:18)
    at Food.<clinit>(Food.java:10)
    at Tester.main(Tester.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
    at Food.values(Food.java:8)
    at Food$1.<clinit>(Food.java:18)
    ... 8 more

Body:
I`m not sure if this would suit you, but i belive to be the correct pattern, instead of figuring out what taste each food have in constructor, you could just declare it.

public enum Food
{
  APPLE("good", "sweet"),
  PANCAKES("delicious","omg"),
  PASTA("too fat", "but its gud");

  private List<String> tastes = new ArrayList<>();

      Food(String ... tastes) {
        // add to the list
     }
  }


问:
Mongoengine query based on reference field attribute
I have the following Documents

```<code>Food(Document)
  title = fields.StringField()
  type = fields.StringField()

Recipe(Document)
  title = fields.StringField()
  food = fields.ReferenceField(Food)
</code>```

I would like to get the list of recipes whose food.type == "nonveg"

Can I do something like the following?

```<code>Recipe.objects.where(food__type="nonveg")
</code>```

Thanks!

答:
This is impossible with a single query, as Reference Field hold only the id of the actual document.
Hence, you need to do, two queries,

Which gets all the objects of Food, that fall under your type. This can be done via the code foods = Food.objects(type='nonveg')

Now, use the foods Objects List to filter the Recipe collection as : Recipe.objects(food__in=foods). Also, keep in mind that the in operation takes a list, so always pass a list into the filter query, even if you are getting a single instance in Step 1 using .get()

Wrapping up the steps:

```<code>foods = Food.objects(type="nonveg")
recipes = Recipe.objects(food__in=foods)
</code>```

Body:
I have the following Documents

Food(Document)
  title = fields.StringField()
  type = fields.StringField()

Recipe(Document)
  title = fields.StringField()
  food = fields.ReferenceField(Food)

I would like to get the list of recipes whose food.type == "nonveg"

Can I do something like the following?

Recipe.objects.where(food__type="nonveg")

Thanks!

Body:
This is impossible with a single query, as Reference Field hold only the id of the actual document.
Hence, you need to do, two queries,

Which gets all the objects of Food, that fall under your type. This can be done via the code foods = Food.objects(type='nonveg')

Now, use the foods Objects List to filter the Recipe collection as : Recipe.objects(food__in=foods). Also, keep in mind that the in operation takes a list, so always pass a list into the filter query, even if you are getting a single instance in Step 1 using .get()

Wrapping up the steps:

foods = Food.objects(type="nonveg")
recipes = Recipe.objects(food__in=foods)


问:
Select the specific column of ListView and print it in a new messagebox in C#.net
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

```<code>        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }
</code>```

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?

答:
you could do this by

foreach(ListViewItem item in listView1.Items)
{
  foreach(var subtem in item.SubItems)
{
   // Do what ever you want to do with the items.
}
}

Body:
I've just started to use ListView in C#.net.

I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.

I want to know how to do this.

I found this code to list a specific selected data from a row:

ListView.SelectedIndexCollection sel = listView1.SelectedIndices;

        if (sel.Count == 1)
        {
            ListViewItem selItem = listView1.Items[sel[0]];
            MessageBox.Show(selItem.SubItems[2].Text);
        }

That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?


问:
Persisting a @OneToOne child entity with @MapsId throws "error:detached entity passed to persist" in Hibernate
I read https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/.
I tried suggestion config like(using spring data JPA,hibernate 5.0 as vendor ):

```<code>public class PaperSubjectType{
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private PaperSetting paperSetting;
..
}

class PaperSetting{
  @Id
  @GeneratedValue
  private Long id;
..
}
</code>```

first I tried the example:

```<code>PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);
</code>```

error:detached entity passed to persist:PaperSetting.
it seems hibernate take PaperSetting as detached when cascade

2 if I want to create both PaperSubjectType and PaperSetting together,do I need to do this:

```<code>PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSetting  paperSettingInDbNew = paperSettingRepository.save(paperSetting);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);
</code>```

or I should use bidirectional in this situation?
thank you！

答:
I tried it Hibernate 5.2 and it works like a charm.

Assuming you have these entities:

```<code>@Entity(name = "Person")
public static class Person  {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    public Person() {}

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }
}

@Entity(name = "PersonDetails")
public static class PersonDetails  {

    @Id
    private Long id;

    private String nickName;

    @OneToOne
    @MapsId
    private Person person;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}
</code>```

And this data access logic:

```<code>Person _person = doInJPA( this::entityManagerFactory, entityManager -> {
    Person person = new Person( "ABC-123" );
    entityManager.persist( person );

    return person;
} );

doInJPA( this::entityManagerFactory, entityManager -> {
    Person person = entityManager.find( Person.class, _person.getId() );

    PersonDetails personDetails = new PersonDetails();
    personDetails.setNickName( "John Doe" );
    personDetails.setPerson( person );

    entityManager.persist( personDetails );
} );
</code>```

The test passes just fine in Hibernate ORM.

Maybe it was a bug in 5.0 that got fixed, so you are better of upgrading.

Body:
I read https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/.
I tried suggestion config like(using spring data JPA,hibernate 5.0 as vendor ):

public class PaperSubjectType{
    @Id
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private PaperSetting paperSetting;
..
}

class PaperSetting{
  @Id
  @GeneratedValue
  private Long id;
..
}

first I tried the example:

PaperSetting paperSettingInDb = paperSettingRepository.findOne(1);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setSubjectCode("91");
paperSubjectType.setPaperSetting(paperSettingInDb);

paperSubjectTypeRepository.save(paperSubjectType);

error:detached entity passed to persist:PaperSetting.
it seems hibernate take PaperSetting as detached when cascade

2 if I want to create both PaperSubjectType and PaperSetting together,do I need to do this:

PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSetting  paperSettingInDbNew = paperSettingRepository.save(paperSetting);
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);

or I should use bidirectional in this situation?
thank you！

Body:
I tried it Hibernate 5.2 and it works like a charm.

Assuming you have these entities:

@Entity(name = "Person")
public static class Person  {

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    public Person() {}

    public Person(String registrationNumber) {
        this.registrationNumber = registrationNumber;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRegistrationNumber() {
        return registrationNumber;
    }
}

@Entity(name = "PersonDetails")
public static class PersonDetails  {

    @Id
    private Long id;

    private String nickName;

    @OneToOne
    @MapsId
    private Person person;

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}

And this data access logic:

Person _person = doInJPA( this::entityManagerFactory, entityManager -> {
    Person person = new Person( "ABC-123" );
    entityManager.persist( person );

    return person;
} );

doInJPA( this::entityManagerFactory, entityManager -> {
    Person person = entityManager.find( Person.class, _person.getId() );

    PersonDetails personDetails = new PersonDetails();
    personDetails.setNickName( "John Doe" );
    personDetails.setPerson( person );

    entityManager.persist( personDetails );
} );

The test passes just fine in Hibernate ORM.

Maybe it was a bug in 5.0 that got fixed, so you are better of upgrading.


问:
How to access only the related model with eager loading
I have these models in my project:

```<code>class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}
</code>```

-

```<code>class Product {

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

}
</code>```

-

```<code>class Favorite {

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

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

}
</code>```

When I try to get the user's favorites i will do like this:-

```<code>$user = User::find(1);
return $user->favorites;
</code>```

Or with the products in his favorites:-

```<code>return $user->favorites->load('product');
</code>```

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

```<code>public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}
</code>```

Thank you in advance.

答:
This seems like this could be a belongsToMany between User and Product to make a 'favorites', as the pivot table.

Your current setup is missing the inverse relationship from Product to Favorite, so you can't use the relationship in that direction. Which is the direction I would use to get the result you want.

If you had the relationship setup, you could potentially do this to just get the Products for a User's favorites.

```<code>Product::whereHas('favorites.user', function ($q) use ($user_id) {
    $q->where('id', $user_id);
})->get();
</code>```

Get all products that have a favorite that is for user with id == $user_id.

If this was setup for a belongsToMany you could potentially just do this instead:

```<code>User::find($id)->favorites;
</code>```

With what you currently have, you could "fetch" the children records out of the result you have on the PHP side.

Body:
I have these models in my project:

class User {

    public function favorites()
    {
        return $this->hasMany('App\Favorite');
    }

}

-

class Product {

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

}

-

class Favorite {

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

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

}

When I try to get the user's favorites i will do like this:-

$user = User::find(1);
return $user->favorites;

Or with the products in his favorites:-

return $user->favorites->load('product');

But It returns the results from both (products and favorites).

How do I get  the results only from Product model through the Favorite?

Like I want to retrieve only the products that the user added to his favorites?

I already tried to  make this in the User class and it doesn't work:-

public function favproducts()
{
    return this->hasManyThrough('App\Product', 'App\Favorite');
}

Thank you in advance.

Body:
This seems like this could be a belongsToMany between User and Product to make a 'favorites', as the pivot table.

Your current setup is missing the inverse relationship from Product to Favorite, so you can't use the relationship in that direction. Which is the direction I would use to get the result you want.

If you had the relationship setup, you could potentially do this to just get the Products for a User's favorites.

Product::whereHas('favorites.user', function ($q) use ($user_id) {
    $q->where('id', $user_id);
})->get();

Get all products that have a favorite that is for user with id == $user_id.

If this was setup for a belongsToMany you could potentially just do this instead:

User::find($id)->favorites;

With what you currently have, you could "fetch" the children records out of the result you have on the PHP side.


问:
set created input text selected using jquery
I have the following label:

```<code><div id="email">
  <label>
    myemail@gmail.com
  </label>
  <i class="fa fa-edit"></i>
</div>

<div id="phone">
  <label>
    1234567890
  </label>
  <i class="fa fa-edit"></i>
</div>
</code>```

When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:

```<code>$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
  .focus(function(){
     //alert(this);
     this.select();
  });
// some code ..
</code>```

the problem is that I can not set the input text as selected (ready to be replaced).
What should I do?

答:
Create the input element and set the focus & select on it after you replace the label.

Please check the below code:

$("#editBtn").click(function(){
   var label = $(this).parent().find('label');
   var curr_value = label.text().trim();

   var newInput = $('<input class="edit_input" type="text" value="'+curr_value+'" />')

   label.replaceWith(newInput)
   newInput.focus().select()

})```
<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 id="email">
  <label>
    myemail@gmail.com
  </label>
  <button id="editBtn">EDIT</button>
</div></code>```

Body:
I have the following label:

    myemail@gmail.com

    1234567890

When I click on the edit button I want to replace the label with an input and set the label value as selected. Below is what i have tried so far:

$('.fa-edit').click(function(){
var info = $(this).closest('div');
var label = info.find('label');
var curr_value = label.text();
label.replaceWith('<input class="edit_input" type="text" value="'+curr_value+'" />')
  .focus(function(){
     //alert(this);
     this.select();
  });
// some code ..

the problem is that I can not set the input text as selected (ready to be replaced).
What should I do?

Body:
Create the input element and set the focus & select on it after you replace the label.

Please check the below code:

$("#editBtn").click(function(){
   var label = $(this).parent().find('label');
   var curr_value = label.text().trim();

   var newInput = $('<input class="edit_input" type="text" value="'+curr_value+'" />')

   label.replaceWith(newInput)
   newInput.focus().select()

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="email">
  <label>
    myemail@gmail.com
  </label>
  <button id="editBtn">EDIT</button>
</div>


问:
Wordpress file upload media_handle_upload fatal error
I wrote a PHP script to process files sent to it via POST.

On the frontend js script, I create a Formdata object, and append images to it...like:

```<code>formdata.append('image0', image0);
formdata.append('image1', image1);
</code>```

etc

This is my PHP code, the code is in the wordpress root directory

```<code><?php
header("Access-Control-Allow-Origin: *");

require_once('wp-admin/includes/image.php' );
require_once('wp-admin/includes/file.php' );
require_once('wp-admin/includes/media.php' );

$id_array = array();

$c = 0;

foreach ($_FILES as $file) {

$id_array[] = media_handle_upload('image' . $c, 0);
$c++;
}

echo implode(',', $id_array);
</code>```

However when I run this code, I get the following error:

Fatal error:  Call to undefined function __() in /home/website/public_html/wp-admin/includes/file.php on line 16

Am i missing to include additional files in the script? I used the documentation on wordpress and it said:

These files need to be included as dependencies when on the front end.

```<code>require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
</code>```

I would appreciate any help!

答:
I'm also facing same issue.
Adding this in functions.php will fix the error.
Some time it will show as "http error"</p>

```<code>add_filter( 'wp_image_editors', 'raj_change_graphic_library' );
function raj_change_graphic_library($array) {
 return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}
</code>```

Body:
I wrote a PHP script to process files sent to it via POST.

On the frontend js script, I create a Formdata object, and append images to it...like:

formdata.append('image0', image0);
formdata.append('image1', image1);

etc

This is my PHP code, the code is in the wordpress root directory

<?php
header("Access-Control-Allow-Origin: *");

require_once('wp-admin/includes/image.php' );
require_once('wp-admin/includes/file.php' );
require_once('wp-admin/includes/media.php' );

$id_array = array();

$c = 0;

foreach ($_FILES as $file) {

$id_array[] = media_handle_upload('image' . $c, 0);
$c++;
}

echo implode(',', $id_array);

However when I run this code, I get the following error:

Fatal error:  Call to undefined function __() in /home/website/public_html/wp-admin/includes/file.php on line 16

Am i missing to include additional files in the script? I used the documentation on wordpress and it said:

These files need to be included as dependencies when on the front end.

require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );

I would appreciate any help!

Body:
I'm also facing same issue.
Adding this in functions.php will fix the error.
Some time it will show as "http error"

add_filter( 'wp_image_editors', 'raj_change_graphic_library' );
function raj_change_graphic_library($array) {
 return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}


问:
Replace a keyword in href with an input value
I am trying to replace a particular keyword in a href attribute which is taken from an input field. The code is as follows.

// Script

```<code>$('#fileName').blur(function() {
var saveName = $('#fileName').val();
var appendName = $('#exportFilename').attr("href").replace(/\DEFAULTNAME/g, saveName);
$('#exportFilename').attr("href", appendName);
});
</code>```

//  HTML

```<code><input type="text" id="fileName" />
<a id="exportFilename" href="http://127.0.0.1/DEFAULT/REPORTER/typDatabaase.FileName=DEFAULTNAME&typDataase.SelectId-1,2">Download File</a>
</code>```

Thanks in advance

JsFiddle Link

答:
The code you have seems to be working for me using the latest version of jQuery.

  The only thing I can suggest is to ensure your jQuery is encapsulated between either $(document).ready(function() {}) or $(function() {}).  Also, you may want to check to make sure you have the most up-to-date version of jQuery.

Body:
I am trying to replace a particular keyword in a href attribute which is taken from an input field. The code is as follows.

// Script

$('#fileName').blur(function() {
var saveName = $('#fileName').val();
var appendName = $('#exportFilename').attr("href").replace(/\DEFAULTNAME/g, saveName);
$('#exportFilename').attr("href", appendName);
});

//  HTML

<input type="text" id="fileName" />
Download File

Thanks in advance

JsFiddle Link


问:
how to open excel using javascript
I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.

```<code><html>
<body>
<form name="form1">
  <input type=button onClick="test()" value="Open File">
  <br><br>
</form>
<script type="text/javascript">
  function test() {
    var Excel = new ActiveXObject("Excel.Application");
    Excel.Visible = true;
    Excel.Workbooks.Open("teste.xlsx");
  }
</script>
</body>
</html>
</code>```

Thanks in Advance!

答:
ActiveXObject is only supported by IE, other browsers don't support it.

```<code>Excel.Workbooks.Open("teste.xlsx");
</code>```

There is no path specified for teste.xlsx, provide appropriate file path. The file should be accessed by the browser in the client system, so path should be set accordingly like C:\\Temp\\teste.xlsx (something similar with appropriate system drive).

Title: how to open excel using javascript

Body:
I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.

<form name="form1">
  <input type=button onClick="test()" value="Open File">

</form>

Thanks in Advance!

Body:
ActiveXObject is only supported by IE, other browsers don't support it.

Excel.Workbooks.Open("teste.xlsx");

There is no path specified for teste.xlsx, provide appropriate file path. The file should be accessed by the browser in the client system, so path should be set accordingly like C:\\Temp\\teste.xlsx (something similar with appropriate system drive).


问:
Getting "Could not find an implementation of the query pattern for source type 'ExcelQueryable<T>'. " Error
I am using LinqToExcel Nuget package to read excel file.

Below is my code

```<code>            var excelFile = new ExcelQueryFactory("DeployQueues");

        var tableData = from z in excelFile.Worksheet<AllQueues>("Data")
                        select z;
</code>```

But I am getting below compiler error.

```<code>Could not find an implementation of the query pattern for source type
'ExcelQueryable<AllQueues>

class for AllQueues

 public class AllQueues
 {
    [ExcelColumn("Company Title")]
    public string Name { get; set; }

    [ExcelColumn("Providence")]
    public string State { get; set; }

    [ExcelColumn("Employee Count")]
    public string Employees { get; set; }

 }
</code>```

答:
I think the documentation for using LINQToExcel is not good.

I have used below code.

```<code>        string fileName = @"YouPath";
        string conn = string.Empty;
        DataTable dtexcel = new DataTable();
        conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName
        + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel
        2007

        using (OleDbConnection con = new OleDbConnection(conn))
        {
            con.Open();
            DataTable Sheets =
            con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            try
            {
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select *
                from [WorksheetName$]", con); //here we read data from
                sheet1
                oleAdpt.Fill(dtexcel); //fill excel data into dataTable
            }
            catch (Exception ex)
            {
            }
        }
        return dtexcel;
</code>```

Body:
I am using LinqToExcel Nuget package to read excel file.

Below is my code

            var excelFile = new ExcelQueryFactory("DeployQueues");

        var tableData = from z in excelFile.Worksheet<AllQueues>("Data")
                        select z;

But I am getting below compiler error.

Could not find an implementation of the query pattern for source type
'ExcelQueryable<AllQueues>

class for AllQueues

 public class AllQueues
 {
    [ExcelColumn("Company Title")]
    public string Name { get; set; }

    [ExcelColumn("Providence")]
    public string State { get; set; }

    [ExcelColumn("Employee Count")]
    public string Employees { get; set; }

 }

Body:
I think the documentation for using LINQToExcel is not good.

I have used below code.

        string fileName = @"YouPath";
        string conn = string.Empty;
        DataTable dtexcel = new DataTable();
        conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName
        + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel
        2007

        using (OleDbConnection con = new OleDbConnection(conn))
        {
            con.Open();
            DataTable Sheets =
            con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            try
            {
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select *
                from [WorksheetName$]", con); //here we read data from
                sheet1
                oleAdpt.Fill(dtexcel); //fill excel data into dataTable
            }
            catch (Exception ex)
            {
            }
        }
        return dtexcel;


问:
CardView shadow not rendered when converted to bitmap
THE PROBLEM

I'm try to save a view group (which has a CardView as one of its childern) as a PNG file. To achieve this,

I inflate the view group and populate the views with required information

Load an image to an image view via Glide

Add a ViewTreeObserver.OnGlobalLayoutListener to the ViewTreeObserver of the image view and pass the entire (parent) view that is going to be shared to a method that converts the view to a bitmap when image view's bottom is greater than zero (image view's height attribute is set to wrap_content, thus its bottom will be zero until image is loaded).

By doing this, I'm able to convert the view to a bitmap, however, with one caveat: the CardView's show is not rendered on the bitmap.

FAILED ATTEMPTS

So far I've tried:

Switching between layerType attribute from "software" to "hardware".

Setting on and off cardUseCompatPadding attribute of the CardView.

Tried setting the image drawable without using Glide.

Tried without loading an image drawable at all.

THE CODE

Here are code snippets that might help you guys identify the problem:

The method used to convert a view to a bitmap

```<code>public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(b);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return b;
}
</code>```

XML layout file of the view that's being inflated and passed to the getBitmapFromView() above.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="16dp">

    <com.devspark.robototextview.widget.RobotoTextView
        android:id="@+id/title"
        style="@style/text_subhead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_marginBottom="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginLeft="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginRight="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginTop="@dimen/lessons_horizontal_margin_narrow"
        android:gravity="left"
        app:typeface="roboto_medium" />

    <com.devspark.robototextview.widget.RobotoTextView
        android:id="@+id/text"
        style="@style/text_subhead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginRight="@dimen/lessons_horizontal_margin_narrow"
        android:gravity="left"
        android:textColor="@color/text"
        app:typeface="roboto_regular" />

    <android.support.v7.widget.CardView
        android:id="@+id/image_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/lessons_horizontal_margin_narrow"
        app:cardCornerRadius="@dimen/lessons_image_card_corner_radius"
        app:cardElevation="3dp"
        app:cardPreventCornerOverlap="false"
        app:cardUseCompatPadding="true">

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

            <com.makeramen.roundedimageview.RoundedImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@null"
                app:riv_corner_radius_top_left="@dimen/lessons_image_card_corner_radius"
                app:riv_corner_radius_top_right="@dimen/lessons_image_card_corner_radius" />

            <com.devspark.robototextview.widget.RobotoTextView
                android:id="@+id/caption"
                style="@style/text_caption"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/lessons_image_card_caption_margin"
                android:gravity="left"
                app:typeface="roboto_condensed_regular" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <!-- Some other views that aren't particularly interesting -->

</LinearLayout>
</code>```

答:
just change cardview to view, and set

android:background="@android:drawable/dialog_holo_light_frame"

ofcause you need to deal the padding yourself

Body:
THE PROBLEM

I'm try to save a view group (which has a CardView as one of its childern) as a PNG file. To achieve this,

I inflate the view group and populate the views with required information

Load an image to an image view via Glide

Add a ViewTreeObserver.OnGlobalLayoutListener to the ViewTreeObserver of the image view and pass the entire (parent) view that is going to be shared to a method that converts the view to a bitmap when image view's bottom is greater than zero (image view's height attribute is set to wrap_content, thus its bottom will be zero until image is loaded).

By doing this, I'm able to convert the view to a bitmap, however, with one caveat: the CardView's show is not rendered on the bitmap.

FAILED ATTEMPTS

So far I've tried:

Switching between layerType attribute from "software" to "hardware".

Setting on and off cardUseCompatPadding attribute of the CardView.

Tried setting the image drawable without using Glide.

Tried without loading an image drawable at all.

THE CODE

Here are code snippets that might help you guys identify the problem:

The method used to convert a view to a bitmap

public static Bitmap getBitmapFromView(View view) {
    //Define a bitmap with the same size as the view
    Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
    //Bind a canvas to it
    Canvas canvas = new Canvas(b);
    //Get the view's background
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        //has background drawable, then draw it on the canvas
        bgDrawable.draw(canvas);
    else
        //does not have background drawable, then draw white background on the canvas
        canvas.drawColor(Color.WHITE);
    // draw the view on the canvas
    view.draw(canvas);
    //return the bitmap
    return b;
}

XML layout file of the view that's being inflated and passed to the getBitmapFromView() above.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="16dp">

    <com.devspark.robototextview.widget.RobotoTextView
        android:id="@+id/title"
        style="@style/text_subhead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:layout_marginBottom="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginLeft="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginRight="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginTop="@dimen/lessons_horizontal_margin_narrow"
        android:gravity="left"
        app:typeface="roboto_medium" />

    <com.devspark.robototextview.widget.RobotoTextView
        android:id="@+id/text"
        style="@style/text_subhead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/lessons_horizontal_margin_narrow"
        android:layout_marginRight="@dimen/lessons_horizontal_margin_narrow"
        android:gravity="left"
        android:textColor="@color/text"
        app:typeface="roboto_regular" />

    <android.support.v7.widget.CardView
        android:id="@+id/image_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/lessons_horizontal_margin_narrow"
        app:cardCornerRadius="@dimen/lessons_image_card_corner_radius"
        app:cardElevation="3dp"
        app:cardPreventCornerOverlap="false"
        app:cardUseCompatPadding="true">

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

            <com.makeramen.roundedimageview.RoundedImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:contentDescription="@null"
                app:riv_corner_radius_top_left="@dimen/lessons_image_card_corner_radius"
                app:riv_corner_radius_top_right="@dimen/lessons_image_card_corner_radius" />

            <com.devspark.robototextview.widget.RobotoTextView
                android:id="@+id/caption"
                style="@style/text_caption"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="@dimen/lessons_image_card_caption_margin"
                android:gravity="left"
                app:typeface="roboto_condensed_regular" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>


答:
1) Add cascading option:

```<code>@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@MapsId
private PaperSetting paperSetting;
</code>```

2) Having that in place, you can save only PaperSubjectType while creating both entities anew:

```<code>PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);
</code>```

Title: Persisting a @OneToOne child entity with @MapsId throws "error:detached entity passed to persist" in Hibernate

Body:
1) Add cascading option:

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@MapsId
private PaperSetting paperSetting;

2) Having that in place, you can save only PaperSubjectType while creating both entities anew:

PaperSetting paperSetting = new PaperSetting();
paperSetting.setxx;
PaperSubjectType paperSubjectType = new PaperSubjectType();
paperSubjectType.setPaperSetting(paperSettingInDbNew);
paperSubjectTypeRepository.save(paperSubjectType);


问:
Mongodb aggregate arguments to $lookup must be strings
```<code>        db.absences.insert([
           { "_id" : 1, "student" : "Ann Aardvark", sickdays: [ new Date ("2018-05-01"),new Date ("2018-08-23") ] },
           { "_id" : 2, "student" : "Zoe Zebra", sickdays: [ new Date ("2018-02-01"),new Date ("2018-05-23") ] },
        ])

    db.holidays.insert([
       { "_id" : 1, year: 2018, name: "New Years", date: new Date("2018-01-01") },
       { "_id" : 2, year: 2018, name: "Pi Day", date: new Date("2018-03-14") },
       { "_id" : 3, year: 2018, name: "Ice Cream Day", date: new Date("2018-07-15") },
       { "_id" : 4, year: 2017, name: "New Years", date: new Date("2017-01-01") },
       { "_id" : 5, year: 2017, name: "Ice Cream Day", date: new Date("2017-07-16") }
    ])

db.absences.aggregate([
   {
      $lookup:
         {
           from: "holidays",
           pipeline: [
              { $match: { year: 2018 } },
              { $project: { _id: 0, date: { name: "$name", date: "$date" } } },
              { $replaceRoot: { newRoot: "$date" } }
           ],
           as: "holidays"
         }
    }
])
</code>```

I'm trying to use pipeline in lookup for aggregation query. Having this as same as from the Mongodb documentation, it still gives an error

```<code>Unable to execute the selected commands

Mongo Server error (MongoCommandException): Command failed with error 4570: 'arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: "$name", date: "$date" } } }, { $replaceRoot: { newRoot: "$date" } } ] is type array' on server localhost:27017.

The full response is:
{
    "ok" : 0.0,
    "errmsg" : "arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: \"$name\", date: \"$date\" } } }, { $replaceRoot: { newRoot: \"$date\" } } ] is type array",
    "code" : NumberInt(4570),
    "codeName" : "Location4570"
}
</code>```

I'm using mongodb v3.4.

答:
Because you are trying to use the $lookup features (syntax) from MongoDB v3.6 on MongoDB v3.4

The MongoDB v3.4 $lookup syntax:

```<code>{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}
</code>```

The MongoDB v3.6 $lookup syntax:

```<code>{
   $lookup:
     {
       from: <collection to join>,
       let: { <var_1>: <expression>, …, <var_n>: <expression> },
       pipeline: [ <pipeline to execute on the collection to join> ],
       as: <output array field>
     }
}
</code>```

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Body:
        db.absences.insert([
           { "_id" : 1, "student" : "Ann Aardvark", sickdays: [ new Date ("2018-05-01"),new Date ("2018-08-23") ] },
           { "_id" : 2, "student" : "Zoe Zebra", sickdays: [ new Date ("2018-02-01"),new Date ("2018-05-23") ] },
        ])

    db.holidays.insert([
       { "_id" : 1, year: 2018, name: "New Years", date: new Date("2018-01-01") },
       { "_id" : 2, year: 2018, name: "Pi Day", date: new Date("2018-03-14") },
       { "_id" : 3, year: 2018, name: "Ice Cream Day", date: new Date("2018-07-15") },
       { "_id" : 4, year: 2017, name: "New Years", date: new Date("2017-01-01") },
       { "_id" : 5, year: 2017, name: "Ice Cream Day", date: new Date("2017-07-16") }
    ])

db.absences.aggregate([
   {
      $lookup:
         {
           from: "holidays",
           pipeline: [
              { $match: { year: 2018 } },
              { $project: { _id: 0, date: { name: "$name", date: "$date" } } },
              { $replaceRoot: { newRoot: "$date" } }
           ],
           as: "holidays"
         }
    }
])

I'm trying to use pipeline in lookup for aggregation query. Having this as same as from the Mongodb documentation, it still gives an error

Unable to execute the selected commands

Mongo Server error (MongoCommandException): Command failed with error 4570: 'arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: "$name", date: "$date" } } }, { $replaceRoot: { newRoot: "$date" } } ] is type array' on server localhost:27017.

The full response is:
{
    "ok" : 0.0,
    "errmsg" : "arguments to $lookup must be strings, pipeline: [ { $match: { year: 2018.0 } }, { $project: { _id: 0.0, date: { name: \"$name\", date: \"$date\" } } }, { $replaceRoot: { newRoot: \"$date\" } } ] is type array",
    "code" : NumberInt(4570),
    "codeName" : "Location4570"
}

I'm using mongodb v3.4.

Body:
Because you are trying to use the $lookup features (syntax) from MongoDB v3.6 on MongoDB v3.4

The MongoDB v3.4 $lookup syntax:

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

The MongoDB v3.6 $lookup syntax:

{
   $lookup:
     {
       from: <collection to join>,
       let: { <var_1>: <expression>, …, <var_n>: <expression> },
       pipeline: [ <pipeline to execute on the collection to join> ],
       as: <output array field>
     }
}

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/