问:
How to Save io.BytesIO pdfrw PDF into Django FileField
What I am trying to do is basically:

Get PDF from URL

Modify it via pdfrw

Store it in memory as
a BytesIO obj

Upload it into a Django FileField via
Model.objects.create(form=pdf_file, name="Some name")

My issue is that when the create() method runs, it saves all of the fields except for the form.

helpers.py

```<code>import io
import tempfile
from contextlib import contextmanager

import requests
import pdfrw

@contextmanager
def as_file(url):
    with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile:
        tfile.write(requests.get(url).content)
        tfile.flush()
        yield tfile.name

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)

    ## PDF is modified here

    buf = io.BytesIO()
    print(buf.getbuffer().nbytes). # Prints "0"!
    pdfrw.PdfWriter().write(buf, template_pdf)
    buf.seek(0)
    return buf
</code>```

views.py

```<code>from django.core.files import File

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            print(submitted_form.getbuffer().nbytes).  # Prints "994782"!
            FilledPDF.objects.create(form=File(submitted_form), name="Test PDF")
        return render(request, 'index.html', {})
</code>```

As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? Also, if anyone knows a more efficient way to do this, please let me know!

答:
Here's the documentation on how to save a file to an object.</p>

```<code>from django.core.files import File

filled_pdf = FilledPDF()
filled_pdf.form.save('test_pdf.pdf', File(submitted_form.getvalue()), save=True)
</code>```

Body:
What I am trying to do is basically:

Get PDF from URL

Modify it via pdfrw

Store it in memory as
a BytesIO obj

Upload it into a Django FileField via
Model.objects.create(form=pdf_file, name="Some name")

My issue is that when the create() method runs, it saves all of the fields except for the form.

helpers.py

import io
import tempfile
from contextlib import contextmanager

import requests
import pdfrw

@contextmanager
def as_file(url):
    with tempfile.NamedTemporaryFile(suffix='.pdf') as tfile:
        tfile.write(requests.get(url).content)
        tfile.flush()
        yield tfile.name

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)

    ## PDF is modified here

    buf = io.BytesIO()
    print(buf.getbuffer().nbytes). # Prints "0"!
    pdfrw.PdfWriter().write(buf, template_pdf)
    buf.seek(0)
    return buf

views.py

from django.core.files import File

class FormView(View):
    def get(self, request, *args, **kwargs):
        form_url = 'http://some-pdf-url.com'

        with as_file(form_url) as temp_form_path:
            submitted_form = write_fillable_pdf(temp_form_path, temp_form_path, {"name": "John Doe"})
            print(submitted_form.getbuffer().nbytes).  # Prints "994782"!
            FilledPDF.objects.create(form=File(submitted_form), name="Test PDF")
        return render(request, 'index.html', {})

As you can see, print() gives out two different values as the BytesIO is populated, leading me to believe the increase in size means there is actually data in it. Is there a reason it is not saving properly into my django model instance? Also, if anyone knows a more efficient way to do this, please let me know!

Body:
Here's the documentation on how to save a file to an object.

from django.core.files import File

filled_pdf = FilledPDF()
filled_pdf.form.save('test_pdf.pdf', File(submitted_form.getvalue()), save=True)


来源: stackexchange

问:
Clearing the screen for text based rpg in python
I am trying to make a text based rpg game in python. I just started and this is what my code looks so far:

```<code>class Game:
    def __init__(self):
        self.map = [[" " for i in range(50)]for i in range(30)]

    def draw_map(self):
        for i in range(len(self.map)):
            print(self.map[i])

    def add_stuff(self, thing, x, y):
        self.map[y][x] = thing

game = Game()

class Player:
    def __init__(self):
        self.x = 1
        self.y = 1
        self.player = "ME"

    def draw(self):
        game.add_stuff(self.player, self.x, self.y)

    def move(self):
        pass

player = Player()
player.draw()
game.draw_map()
</code>```

I was trying to find a way to implement a game loop in some way. To do this i was thinking of running the draw_map() and clearing the screen right away and printing the map again, a bit like real game loops. However i am having problems doing this. Based on other answers to other similar questions, i managed to produce the following code(it just shows the main loop and subprocess is imported as sp).

```<code>while True:
    game.draw_map()
    sp.call("cls", shell = True)
</code>```

However this is not working for me. It simply dosent do anything. I also tried using clear function from clear_screen` module in a similar way and i cant figure out why this wouldnt work. Thanks for any help

答:
so based on your previous comments you want to clear the screen in a Python interpreter. There is no "command" to clear the screen just like this. But you can use a loop to print some new lines until your screen is blank again.

```<code>def clear(lines):
    for l in range(lines):
        print()

while True:
    game.draw_map()
    clear(35)
    time.sleep(0.05)
</code>```

You may need to increase or decrease the amount of lines cleared. I hope this works for you. P.S.: I would use a normal console.

https://en.wikipedia.org/wiki/Interpreter_(computing)#Efficiency:

Efficiency:
  The main disadvantage of interpreters is that an interpreted program typically runs slower than if it had been compiled. The difference in speeds could be tiny or great; often an order of magnitude and sometimes more. It generally takes longer to run a program under an interpreter than to run the compiled code but it can take less time to interpret it than the total time required to compile and run it. This is especially important when prototyping and testing code when an edit-interpret-debug cycle can often be much shorter than an edit-compile-run-debug cycle.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a text based rpg game in python. I just started and this is what my code looks so far:

class Game:
    def __init__(self):
        self.map = [[" " for i in range(50)]for i in range(30)]

    def draw_map(self):
        for i in range(len(self.map)):
            print(self.map[i])

    def add_stuff(self, thing, x, y):
        self.map[y][x] = thing

game = Game()

class Player:
    def __init__(self):
        self.x = 1
        self.y = 1
        self.player = "ME"

    def draw(self):
        game.add_stuff(self.player, self.x, self.y)

    def move(self):
        pass

player = Player()
player.draw()
game.draw_map()

I was trying to find a way to implement a game loop in some way. To do this i was thinking of running the draw_map() and clearing the screen right away and printing the map again, a bit like real game loops. However i am having problems doing this. Based on other answers to other similar questions, i managed to produce the following code(it just shows the main loop and subprocess is imported as sp).

while True:
    game.draw_map()
    sp.call("cls", shell = True)

However this is not working for me. It simply dosent do anything. I also tried using clear function from clear_screen` module in a similar way and i cant figure out why this wouldnt work. Thanks for any help

Body:
so based on your previous comments you want to clear the screen in a Python interpreter. There is no "command" to clear the screen just like this. But you can use a loop to print some new lines until your screen is blank again.

def clear(lines):
    for l in range(lines):
        print()

while True:
    game.draw_map()
    clear(35)
    time.sleep(0.05)

You may need to increase or decrease the amount of lines cleared. I hope this works for you. P.S.: I would use a normal console.

https://en.wikipedia.org/wiki/Interpreter_(computing)#Efficiency:

Efficiency:
  The main disadvantage of interpreters is that an interpreted program typically runs slower than if it had been compiled. The difference in speeds could be tiny or great; often an order of magnitude and sometimes more. It generally takes longer to run a program under an interpreter than to run the compiled code but it can take less time to interpret it than the total time required to compile and run it. This is especially important when prototyping and testing code when an edit-interpret-debug cycle can often be much shorter than an edit-compile-run-debug cycle.


问:
Can a CSS overflow scrollbar be controlled in Javascript?
I have a div with a class overflow: auto;  Is there a way to control this scrollbar when it appears?

I have a ajax photo gallery (no page refresh) where some caption text is in a div, but the content is of varying length.  If you scroll down in this div and then advance to the next slide, the scrollbar does not go back to the top.  So, I was wondering if there was a way to control this scrollbar.  Thanks.

答:
With jQuery, you can set the top of the scroll area like so:

```<code>$('#contents').scrollTop(0);
</code>```

Here's a demo showing this in action->

Note that this is also possible without jQuery:

```<code>document.getElementById('contents').scrollTop = 0;
</code>```

And a demo of that->

For both demos, press the Reset button to set the scroll bar back to the top.

ContentLicense: CC BY-SA 3.0

Body:
With jQuery, you can set the top of the scroll area like so:

$('#contents').scrollTop(0);

Here's a demo showing this in action->

Note that this is also possible without jQuery:

document.getElementById('contents').scrollTop = 0;

And a demo of that->

For both demos, press the Reset button to set the scroll bar back to the top.


问:
When compile llvm 3.1, why get error: expected primary-expression before ‘>’ token
For some reason, I need to install llvm 3.1 or llvm 3.0, but I'm getting this error when during make.

```<code>[  5%] Building CXX object utils/TableGen/CMakeFiles/llvm-tblgen.dir/AsmMatcherEmitter.cpp.o
In file included from /home/ubuntu/llvm/utils/TableGen/AsmMatcherEmitter.cpp:103:0:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h: In member function ‘int llvm::PointerUnion3<PT1, PT2, PT3>::is() const’:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:266:26: error: expected primary-expression before ‘>’ token
       return Ty(Val).is<T>();
                          ^
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:266:28: error: expected primary-expression before ‘)’ token
       return Ty(Val).is<T>();
                            ^
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h: In member function ‘T llvm::PointerUnion3<PT1, PT2, PT3>::get() const’:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:279:27: error: expected primary-expression before ‘>’ token
       return Ty(Val).get<T>();
                           ^'
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:279:29: error: expected primary-expression before ‘)’ token
       return Ty(Val).get<T>();
                             ^
</code>```

I guess there might be a compatibility issue between llvm 3.0 and gcc 7.0.0, so I installed gcc-4.6.3, and use this cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/home/ubuntu/install -DCMAKE_CXX_LINK_FLAGS="-Wl,-rpath,$HOME/gcc463/install -L$HOME/gcc463/install" -G "Unix Makefiles" ../llvm to configure. But the same error still occurs. Anybody knows why and how to fix it? Thanks!!

答:
Try passing -std=c++98 or if that does not work then -std=c++11. I'm afraid this maybe because of incompatibilities in different C++ versions.

Additionally, you may have to remove -std=c++14 from the CXXFLAGS if it is there. This is the default for g++7.

So I installed gcc-4.6.3, and use this

Did you change the CMAKE_C_COMPILER and CMAKE_CXX_COMPILER flag so that cmake can use the gcc-4.6 instead?

hth,

Body:
For some reason, I need to install llvm 3.1 or llvm 3.0, but I'm getting this error when during make.

[  5%] Building CXX object utils/TableGen/CMakeFiles/llvm-tblgen.dir/AsmMatcherEmitter.cpp.o
In file included from /home/ubuntu/llvm/utils/TableGen/AsmMatcherEmitter.cpp:103:0:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h: In member function ‘int llvm::PointerUnion3<PT1, PT2, PT3>::is() const’:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:266:26: error: expected primary-expression before ‘>’ token
       return Ty(Val).is<T>();
                          ^
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:266:28: error: expected primary-expression before ‘)’ token
       return Ty(Val).is<T>();
                            ^
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h: In member function ‘T llvm::PointerUnion3<PT1, PT2, PT3>::get() const’:
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:279:27: error: expected primary-expression before ‘>’ token
       return Ty(Val).get<T>();
                           ^'
/home/ubuntu/llvm/include/llvm/ADT/PointerUnion.h:279:29: error: expected primary-expression before ‘)’ token
       return Ty(Val).get<T>();
                             ^

I guess there might be a compatibility issue between llvm 3.0 and gcc 7.0.0, so I installed gcc-4.6.3, and use this cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/home/ubuntu/install -DCMAKE_CXX_LINK_FLAGS="-Wl,-rpath,$HOME/gcc463/install -L$HOME/gcc463/install" -G "Unix Makefiles" ../llvm to configure. But the same error still occurs. Anybody knows why and how to fix it? Thanks!!


问:
How to keep observable chain going after http error in one observable
I've got a chain of observables. Here is the piece of code:

```<code>        //get dynamic tree
      flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
      tap(res => this.dynamicTree = res),
        //get dynamic report
      flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),
</code>```

However when I got 500 API error from the first request(get dynamic tree), the chain stops and never enters the second flatMap(dynamic report).

Here is the function this.reportService.getDynamicTree():

```<code> get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.apiBaseUrl}${path}`, {headers: this.setHeaders(true), params: params}).pipe(
      catchError(error => this.processError(path, error)),
      map((res: Response) => res));
  }
</code>```

where this.processError returns observableThrowError(res);

What should I return in case of error to continue the chain? Or is the reason in other things?

答:
First of - continuing the chain kind of defeats the whole concept of a chain. However, I think this issue should be resolveable by having some fairly simple chain iterator and handling errors thrown by HttpClient and service.

I created a StackBlitz example with my solution: https://stackblitz.com/edit/chain. For simplycity, the chain returns data in { result: any, error: any }[]. Of course you will be able to do pretty much anything in terms of piping operators to adjust the result.

Ideally, the observableChain functionality would be separate and handling the empty results as you need it to - in your case instead of returning { result: any, error: any }[] it would return {} on error response and log the error.

Body:
I've got a chain of observables. Here is the piece of code:

        //get dynamic tree
      flatMap(res => this.dynamicReportId !== null ? this.reportService.getDynamicTree(this.dynamicReportId) : of({})),
      tap(res => this.dynamicTree = res),
        //get dynamic report
      flatMap((res) => this.dynamicReportId !== null ? this.reportService.getDynamicReport(this.dynamicReportId) : of({})),

However when I got 500 API error from the first request(get dynamic tree), the chain stops and never enters the second flatMap(dynamic report).

Here is the function this.reportService.getDynamicTree():

 get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
    return this.http.get(`${environment.apiBaseUrl}${path}`, {headers: this.setHeaders(true), params: params}).pipe(
      catchError(error => this.processError(path, error)),
      map((res: Response) => res));
  }

where this.processError returns observableThrowError(res);

What should I return in case of error to continue the chain? Or is the reason in other things?


问:
How to forcefully close an async generator?
Let's say I have an async generator like this:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            event = await queue.get()
            yield event
        else:
            return
```

<p>I consume it like this:</p>

<pre class="lang-py prettyprint-override"><code>published_events = event_publisher(connection, queue)
async for event in published_events:
    # do event processing here
</code>```

It works just fine, however when the connection is disconnected and there is no new event published the async for will just wait forever, so ideally I would like to close the generator forcefully like this:

if connection.is_disconnected():
    await published_events.aclose()
```

But I get the following error:

RuntimeError: aclose(): asynchronous generator is already running

Is there a way to stop processing of an already running generator?

答:
You can use a timeout on the queue so is_connected() is polled regularly if there is no item to pop:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            try:
                event = await asyncio.wait_for(queue.get(), timeout=10.0)
            except asyncio.TimeoutError:
                continue
            yield event
        else:
            return
```

Alternatively, it is possible to use Queue.get_nowait().

Body:
Let's say I have an async generator like this:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            event = await queue.get()
            yield event
        else:
            return

I consume it like this:

published_events = event_publisher(connection, queue)
async for event in published_events:
    # do event processing here

It works just fine, however when the connection is disconnected and there is no new event published the async for will just wait forever, so ideally I would like to close the generator forcefully like this:

if connection.is_disconnected():
    await published_events.aclose()

But I get the following error:

RuntimeError: aclose(): asynchronous generator is already running

Is there a way to stop processing of an already running generator?

Body:
You can use a timeout on the queue so is_connected() is polled regularly if there is no item to pop:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            try:
                event = await asyncio.wait_for(queue.get(), timeout=10.0)
            except asyncio.TimeoutError:
                continue
            yield event
        else:
            return

Alternatively, it is possible to use Queue.get_nowait().


问:
How to fix "java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions"
I am trying to migrate a REST API (Java-made, using Maven, in Eclipse) from own server to a partner's server. They have installed Tomcat 9 and Mongo 3.6.17 for us there (I have little control over it, but if really needed I can see for a installing newer/other versions). I have had many incompatibility problems, but can't find a fix for the following.

When calling any endpoint on the remote server, I get the following error (you can see I'm using Jersey):

```<code>javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

I understand from what I read online that there is an incompatibility problem with the mongo Java driver. I have done many changes to the Mongo driver version, based on the compatibility tables I've found, but no luck. Currently it is set to:

```<code><dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.6.2</version>
</dependency>
</code>```

in my project's pom.

For reference, we use Tomcat 9 and Mongo v4.0.9 - but even with changing the driver version in our build, the services still run smoothly (e.g. when using v3.6.2 above), both on our server (Linux, don't know specs, I can update tomorrow) and when I run the service through eclipse on my local machine (Windows). The remote server runs on CentOS 7.6.1810 and has OpenJDK v1.8.0_242 installed. Conversely, we have the Oracle JDK 8 (slightly different versions on local machine and server - locally, I run 1.8.0_91).

Any ideas?

答: I couldn't resolve it based on the java driver versions. Instead, I asked for Mongo to be updated (4.0.9) and it worked. </p>

Body:
I am trying to migrate a REST API (Java-made, using Maven, in Eclipse) from own server to a partner's server. They have installed Tomcat 9 and Mongo 3.6.17 for us there (I have little control over it, but if really needed I can see for a installing newer/other versions). I have had many incompatibility problems, but can't find a fix for the following.

When calling any endpoint on the remote server, I get the following error (you can see I'm using Jersey):

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class com.mongodb.MongoClientOptions
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

I understand from what I read online that there is an incompatibility problem with the mongo Java driver. I have done many changes to the Mongo driver version, based on the compatibility tables I've found, but no luck. Currently it is set to:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.6.2</version>
</dependency>

in my project's pom.

For reference, we use Tomcat 9 and Mongo v4.0.9 - but even with changing the driver version in our build, the services still run smoothly (e.g. when using v3.6.2 above), both on our server (Linux, don't know specs, I can update tomorrow) and when I run the service through eclipse on my local machine (Windows). The remote server runs on CentOS 7.6.1810 and has OpenJDK v1.8.0_242 installed. Conversely, we have the Oracle JDK 8 (slightly different versions on local machine and server - locally, I run 1.8.0_91).

Any ideas?


问:
Unable to run app in emulator with API 29 android studio
I have an app run normally in the emulator with API 28. But when I run the app in the emulator with API 29 it shows

It does not only show keeps stopping in the emulator. I tried to install it on mobile and it also shows the same error.

The log shows this error like this:

```<code>2020-02-14 19:48:12.922 20370-20370/? E/stickerappmake: Unknown bits set in runtime_flags: 0x8000
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.138 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.139 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.059 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.063 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:22.727 20370-20370/com.testdev.appname E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.testdev.appname, PID: 20370
    java.lang.NullPointerException: Attempt to get length of null array
        at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)
        at com.testdev.appname.activities.CreateFragment.onCreateView(CreateFragment.java:88)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
        at android.app.Activity.performStart(Activity.java:7825)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

I see there some problems with the java code in CreateFragment.java. And the java code is like below:
The CreateFragment.java code:

package com.devname.appname.activities;

```<code>import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.devname.appname.helpers.Admob;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter;
import com.sangcomz.fishbun.define.Define;
import com.devname.appname.R;
import com.devname.appname.backgroundRemover.CutOut;
import com.devname.appname.helpers.Constants;
import com.devname.appname.utils.FileUtils;
import com.devname.appname.utils.StickerPacksManager;

import java.io.File;
import java.util.ArrayList;

public class CreateFragment extends Fragment {
    ImagesGridAdapter imagesGridAdapter;
    View view;

    public CreateFragment() {
        // Required empty public constructor
    }

    public static ArrayList<Uri> loadStickersCreated() {
        String directoryPath = Constants.STICKERS_CREATED_DIRECTORY_PATH;
        File directory = new File(directoryPath);
        ArrayList<Uri> images = new ArrayList<>();
        if (directory.exists()) {
            File[] stickersImages = directory.listFiles();
            for (File f : stickersImages) {
                if (f.isFile() && (f.getName().contains(".png") || f.getName().contains(".PNG"))) {
                    images.add(Uri.fromFile((f)));
                }
            }
        } else {
            directory.mkdir();
        }
       // verifyStickersCount();
        return images;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_create, container, false);
        Admob.createLoadBanner(getContext(), view);
        view.findViewById(R.id.create_sticker).setOnClickListener(v -> FishBun.with(getActivity())
                .setImageAdapter(new GlideAdapter())
                .setMaxCount(1)
                .exceptGif(true)
                .setMinCount(1)
                .setActionBarColor(getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorPrimary), false)
                .setActionBarTitleColor(Color.parseColor("#ffffff"))
                .startAlbum());

        RecyclerView gridview = view.findViewById(R.id.stickers_created_grid);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(view.getContext(), 3);
        gridview.setLayoutManager(gridLayoutManager);
        imagesGridAdapter = new ImagesGridAdapter(view.getContext(), loadStickersCreated());
        gridview.setAdapter(imagesGridAdapter);
        verifyStickersCount();
        return view;
    }

    public void verifyStickersCount() {
        View linearLayout = view.findViewById(R.id.no_stickers_icon);
        if (imagesGridAdapter == null || imagesGridAdapter.getItemCount() == 0) {
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }
    }

    public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TESTTTTTT",requestCode+"");
        if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
            Log.d("TESTTTTTT :::::",requestCode+"");
            switch (resultCode) {
                case Activity.RESULT_OK:
                    String imagePath_intent = data.getStringExtra("imagePath");
                    Uri imageUri = Uri.fromFile(new File(imagePath_intent));

                    Log.d("TESTTTTTT ::::: He",imageUri+"");
                    String stickerName = FileUtils.generateRandomIdentifier();
                    Uri imagePath = Uri.parse(Constants.STICKERS_CREATED_DIRECTORY_PATH + stickerName + ".PNG");
                    StickerPacksManager.createStickerImageFile(imageUri, imagePath, getActivity(), Bitmap.CompressFormat.PNG);
                    addImageToGallery(imagePath.getPath(), getActivity());
                    imagesGridAdapter.uries = loadStickersCreated();
                    imagesGridAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "Sticker created", Toast.LENGTH_LONG).show();
                    verifyStickersCount();
                    break;
                case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                    Exception ex = CutOut.getError(data);
                    Log.d("TESTTTTTT :::::",ex+"::DDD");
                    break;
                default:
                    System.out.print("User cancelled the CutOut screen");
            }
        } else if (requestCode == Define.ALBUM_REQUEST_CODE) {
            ArrayList<Uri> uries;
            if (resultCode == Activity.RESULT_OK) {
                uries = data.getParcelableArrayListExtra(Define.INTENT_PATH);
                CutOut.activity().src(uries.get(0)).intro().start(getActivity());
            }
        }
    }

    public class ImagesGridAdapter extends RecyclerView.Adapter<ImageViewHolder> {
        public ArrayList<Uri> uries = new ArrayList<>();
        Context context;

        public ImagesGridAdapter(Context context, ArrayList<Uri> uries) {
            this.uries = uries;
            this.context = context;
        }

        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            final Context context = viewGroup.getContext();
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            final View view = layoutInflater.inflate(R.layout.sticker_created_item, viewGroup, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder imageAdapter, int index) {
            imageAdapter.imageView.setImageURI(uries.get(index));
            imageAdapter.imageView.setPadding(8, 8, 8, 8);
            imageAdapter.imageView.setOnLongClickListener(v -> {
                PopupMenu popupMenu = new PopupMenu(context, imageAdapter.imageView);
                popupMenu.inflate(R.menu.sticker_menu);
                popupMenu.setOnMenuItemClickListener(item -> {
                    switch (item.getItemId()) {
                     /*  case R.id.add_to_exist_stickerpack:
                            addToStickerPack(index);
                            break;*/
                        case R.id.delete_sticker:
                            this.deleteSticker(index);
                            break;
                        default:
                            break;
                    }
                    return false;
                });
                popupMenu.show();
                return false;
            });
        }

        void deleteSticker(int index) {
            new AlertDialog.Builder(context)
                    .setTitle("Deleting")
                    .setMessage("Are you sure you want to delete this sticker?")
                    .setPositiveButton("Yes", (dialog, which) -> {
                        Uri uri = uries.get(index);
                        FileUtils.deleteFile(uri.getPath(),context);
                        uries.remove(index);
                        notifyItemRemoved(index);
                        notifyDataSetChanged();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                        verifyStickersCount();
                    })
                    .setNegativeButton("No", null)
                    .show();
        }

         void addToStickerPack(int index) {
            Intent intent = new Intent(context, AddToStickerPackActivity.class);
            intent.setData(uries.get(index));
            startActivity(intent);
        }

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

    class ImageViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.sticker_created_image);
        }

    }
}
</code>```

答:
Let's read your error message:

java.lang.NullPointerException: Attempt to get length of null array

some array of you is null and you still try to get the length of it.

at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)

and it even tells you, in which line you will find the error

```<code>File[] stickersImages = directory.listFiles();
</code>```

stickerImages seems to be null.

```<code>for (File f : stickersImages) {/*...*/}
</code>```

it tries to read from stickerImages, which is null and therefore this Exception is thrown.

Body:
I have an app run normally in the emulator with API 28. But when I run the app in the emulator with API 29 it shows

It does not only show keeps stopping in the emulator. I tried to install it on mobile and it also shows the same error.

The log shows this error like this:

2020-02-14 19:48:12.922 20370-20370/? E/stickerappmake: Unknown bits set in runtime_flags: 0x8000
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.326 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:15.385 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.138 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.139 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:17.243 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:19.984 20370-20464/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.048 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.059 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:20.063 20370-20454/com.testdev.appname E/eglCodecCommon: glUtilsParamSize: unknow param 0x000088ef
2020-02-14 19:48:22.727 20370-20370/com.testdev.appname E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.testdev.appname, PID: 20370
    java.lang.NullPointerException: Attempt to get length of null array
        at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)
        at com.testdev.appname.activities.CreateFragment.onCreateView(CreateFragment.java:88)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3273)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
        at android.app.Activity.performStart(Activity.java:7825)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I see there some problems with the java code in CreateFragment.java. And the java code is like below:
The CreateFragment.java code:

package com.devname.appname.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.devname.appname.helpers.Admob;
import com.sangcomz.fishbun.FishBun;
import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter;
import com.sangcomz.fishbun.define.Define;
import com.devname.appname.R;
import com.devname.appname.backgroundRemover.CutOut;
import com.devname.appname.helpers.Constants;
import com.devname.appname.utils.FileUtils;
import com.devname.appname.utils.StickerPacksManager;

import java.io.File;
import java.util.ArrayList;

public class CreateFragment extends Fragment {
    ImagesGridAdapter imagesGridAdapter;
    View view;

    public CreateFragment() {
        // Required empty public constructor
    }

    public static ArrayList<Uri> loadStickersCreated() {
        String directoryPath = Constants.STICKERS_CREATED_DIRECTORY_PATH;
        File directory = new File(directoryPath);
        ArrayList<Uri> images = new ArrayList<>();
        if (directory.exists()) {
            File[] stickersImages = directory.listFiles();
            for (File f : stickersImages) {
                if (f.isFile() && (f.getName().contains(".png") || f.getName().contains(".PNG"))) {
                    images.add(Uri.fromFile((f)));
                }
            }
        } else {
            directory.mkdir();
        }
       // verifyStickersCount();
        return images;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_create, container, false);
        Admob.createLoadBanner(getContext(), view);
        view.findViewById(R.id.create_sticker).setOnClickListener(v -> FishBun.with(getActivity())
                .setImageAdapter(new GlideAdapter())
                .setMaxCount(1)
                .exceptGif(true)
                .setMinCount(1)
                .setActionBarColor(getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorPrimary), false)
                .setActionBarTitleColor(Color.parseColor("#ffffff"))
                .startAlbum());

        RecyclerView gridview = view.findViewById(R.id.stickers_created_grid);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(view.getContext(), 3);
        gridview.setLayoutManager(gridLayoutManager);
        imagesGridAdapter = new ImagesGridAdapter(view.getContext(), loadStickersCreated());
        gridview.setAdapter(imagesGridAdapter);
        verifyStickersCount();
        return view;
    }

    public void verifyStickersCount() {
        View linearLayout = view.findViewById(R.id.no_stickers_icon);
        if (imagesGridAdapter == null || imagesGridAdapter.getItemCount() == 0) {
            linearLayout.setVisibility(View.VISIBLE);
        } else {
            linearLayout.setVisibility(View.GONE);
        }
    }

    public static void addImageToGallery(final String filePath, final Context context) {

        ContentValues values = new ContentValues();

        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.MediaColumns.DATA, filePath);

        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("TESTTTTTT",requestCode+"");
        if (requestCode == CutOut.CUTOUT_ACTIVITY_REQUEST_CODE) {
            Log.d("TESTTTTTT :::::",requestCode+"");
            switch (resultCode) {
                case Activity.RESULT_OK:
                    String imagePath_intent = data.getStringExtra("imagePath");
                    Uri imageUri = Uri.fromFile(new File(imagePath_intent));

                    Log.d("TESTTTTTT ::::: He",imageUri+"");
                    String stickerName = FileUtils.generateRandomIdentifier();
                    Uri imagePath = Uri.parse(Constants.STICKERS_CREATED_DIRECTORY_PATH + stickerName + ".PNG");
                    StickerPacksManager.createStickerImageFile(imageUri, imagePath, getActivity(), Bitmap.CompressFormat.PNG);
                    addImageToGallery(imagePath.getPath(), getActivity());
                    imagesGridAdapter.uries = loadStickersCreated();
                    imagesGridAdapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "Sticker created", Toast.LENGTH_LONG).show();
                    verifyStickersCount();
                    break;
                case CutOut.CUTOUT_ACTIVITY_RESULT_ERROR_CODE:
                    Exception ex = CutOut.getError(data);
                    Log.d("TESTTTTTT :::::",ex+"::DDD");
                    break;
                default:
                    System.out.print("User cancelled the CutOut screen");
            }
        } else if (requestCode == Define.ALBUM_REQUEST_CODE) {
            ArrayList<Uri> uries;
            if (resultCode == Activity.RESULT_OK) {
                uries = data.getParcelableArrayListExtra(Define.INTENT_PATH);
                CutOut.activity().src(uries.get(0)).intro().start(getActivity());
            }
        }
    }

    public class ImagesGridAdapter extends RecyclerView.Adapter<ImageViewHolder> {
        public ArrayList<Uri> uries = new ArrayList<>();
        Context context;

        public ImagesGridAdapter(Context context, ArrayList<Uri> uries) {
            this.uries = uries;
            this.context = context;
        }

        @NonNull
        @Override
        public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            final Context context = viewGroup.getContext();
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            final View view = layoutInflater.inflate(R.layout.sticker_created_item, viewGroup, false);
            return new ImageViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageViewHolder imageAdapter, int index) {
            imageAdapter.imageView.setImageURI(uries.get(index));
            imageAdapter.imageView.setPadding(8, 8, 8, 8);
            imageAdapter.imageView.setOnLongClickListener(v -> {
                PopupMenu popupMenu = new PopupMenu(context, imageAdapter.imageView);
                popupMenu.inflate(R.menu.sticker_menu);
                popupMenu.setOnMenuItemClickListener(item -> {
                    switch (item.getItemId()) {
                     /*  case R.id.add_to_exist_stickerpack:
                            addToStickerPack(index);
                            break;*/
                        case R.id.delete_sticker:
                            this.deleteSticker(index);
                            break;
                        default:
                            break;
                    }
                    return false;
                });
                popupMenu.show();
                return false;
            });
        }

        void deleteSticker(int index) {
            new AlertDialog.Builder(context)
                    .setTitle("Deleting")
                    .setMessage("Are you sure you want to delete this sticker?")
                    .setPositiveButton("Yes", (dialog, which) -> {
                        Uri uri = uries.get(index);
                        FileUtils.deleteFile(uri.getPath(),context);
                        uries.remove(index);
                        notifyItemRemoved(index);
                        notifyDataSetChanged();
                        Toast.makeText(context, "Deleted", Toast.LENGTH_SHORT).show();
                        verifyStickersCount();
                    })
                    .setNegativeButton("No", null)
                    .show();
        }

         void addToStickerPack(int index) {
            Intent intent = new Intent(context, AddToStickerPackActivity.class);
            intent.setData(uries.get(index));
            startActivity(intent);
        }

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

    class ImageViewHolder extends RecyclerView.ViewHolder {
        SimpleDraweeView imageView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            this.imageView = itemView.findViewById(R.id.sticker_created_image);
        }

    }
}

Body:
Let's read your error message:

java.lang.NullPointerException: Attempt to get length of null array

some array of you is null and you still try to get the length of it.

at com.testdev.appname.activities.CreateFragment.loadStickersCreated(CreateFragment.java:52)

and it even tells you, in which line you will find the error

File[] stickersImages = directory.listFiles();

stickerImages seems to be null.

for (File f : stickersImages) {/*...*/}

it tries to read from stickerImages, which is null and therefore this Exception is thrown.


问:
How to use JMS Message Transformation in ActiveMQ with Stomp/JSON
I am sending messages in JSON format to an ActiveMQ server. I am trying to use JMS Transformation to transform the JSON encoded object into a true Java Object in hopes of being able to use selectors on the data inside.

Here is a link to the documentation on Stomp and Message Transformation.
Here is a link to a discussion on the patch where someone shows an example of a legal JSON object

The format of the JSON objects I am sending (in pretty print) are similar to this:

```
{
   "msg": {
      "flag1" : "value1",
      "flag2" : "value2"
   }
}
```

The messages arrive in the message queue, but with the transformation-error property set to 'msg : msg'.

答: It should be mentioned that ActiveMQ version must at least 5.8, because with 5.6 version I had problem when transformation just did not work.</p>

OwnerDisplayName: Phillip Whelan

ContentLicense: CC BY-SA 2.5

Body:
I am sending messages in JSON format to an ActiveMQ server. I am trying to use JMS Transformation to transform the JSON encoded object into a true Java Object in hopes of being able to use selectors on the data inside.

Here is a link to the documentation on Stomp and Message Transformation.
Here is a link to a discussion on the patch where someone shows an example of a legal JSON object

The format of the JSON objects I am sending (in pretty print) are similar to this:

{
   "msg": {
      "flag1" : "value1",
      "flag2" : "value2"
   }
}

The messages arrive in the message queue, but with the transformation-error property set to 'msg : msg'.

LastEditorDisplayName: Phillip Whelan


问:
C# to Postman Convert example
```<code>reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dictData, Formatting.Indented));
resByte = wc.UploadData(ServiceAuthorization.URL + @"api/main/setTransactionDetail", "PUT", reqString);
</code>```

How can convert reqString Postman Request and which tab use in postman?
I want to Put this operation in Postman. But I have get error every time.

答:
First (get the url and JSON body):

var body = JsonConvert.SerializeObject(dictData, Formatting.Indented);
var ulr = ServiceAuthorization.URL + @"api/main/setTransactionDetail";

Console.WriteLine(body);

Console.WriteLine(url);

Then go to Postman:

Hope that helps?

Title: C# to Postman Convert example

Body:
reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dictData, Formatting.Indented));
resByte = wc.UploadData(ServiceAuthorization.URL + @"api/main/setTransactionDetail", "PUT", reqString);

How can convert reqString Postman Request and which tab use in postman?
I want to Put this operation in Postman. But I have get error every time.


问:
Drupal: Display a list of contribution (posted content) for each user
I’m searching for a way to display on a member profile page, the number of contributions in some content types. Basically it has to display something like this:

Blog(10)

Articles(10)

Questions(19)

Comments(30)

Tips(3)

I’ve installed some different modules (like “user stats”) that I though could help me but haven’t been successful.

I’m wondering if it would be easiest just to hard-code it into my template file by starting taking the uid and just run some queries with the content types I want to display but I’m not sure on how to do that either.

Any help og suggestions would be very much appreciated.

Sincere
- Mestika

Edit:

I found a solution to do it manually with a query for each content type but I'm still very interested in a solution that's more elegant and smoother.

I use this code:

```<code>global $user;
$userid = $user->uid;
$blog_count  = db_result(db_query("SELECT COUNT(0) AS num FROM {node} n where n.type = 'blog' AND status = 1 AND n.uid = {$userid}"));
</code>```

答:
If you are using the core Profile module, you could use something like below.  It will show the nodes created by the user whose profile is being viewed.  As an added benefit, it only needs to execute one custom database query.

Insert this snippet into template.php in your theme's folder and change "THEMENAME" to the name of your theme:

```<code>function THEMENAME_preprocess_user_profile(&$variables) {
  // Information about user profile being viewed
  $account = $variables['account'];

  // Get info on all content types
  $content_types = node_get_types('names');

  // Get node counts for all content types for current user
  $stats = array();
  $node_counts = db_query('SELECT type, COUNT(type) AS num FROM {node} WHERE status = 1 AND uid = %d GROUP BY type', $account->uid);
  while ($row = db_fetch_array($node_counts)) {
    $stats[] = array(
      'name' => $content_types[$row['type']],
      'type' => $row['type'],
      'num' => $row['num'],
    );
  }
  $variables['node_stats'] = $stats;
}
</code>```

Now, in user-profile.tpl.php can add something similar to:

```<code>// If user has created content, display stats
<?php if (count($node_stats) > 0): ?>

  // For each content type, display a DIV with name and number of nodes
  <?php foreach ($node_stats as $value): ?>
    <div><?php print $value['name']; ?> (<?php print $value['num']; ?>)</div>
  <?php endforeach; ?>

// Message to show for user that hasn't created any content
<?php else: ?>
  <?php print $account->name; ?> has not created any content.
<?php endif; ?>
</code>```

This is just a general idea of what you can do.  You can also add restrictions to the content types you look for/display, check permissions for users to see these stats, use CSS to change the look of the stats, etc.

If you are using Content Profile, you could use THEMENAME_preprocess_node() and check that the node is a profile node before executing this code.

Body:
I’m searching for a way to display on a member profile page, the number of contributions in some content types. Basically it has to display something like this:

Blog(10)

Articles(10)

Questions(19)

Comments(30)

Tips(3)

I’ve installed some different modules (like “user stats”) that I though could help me but haven’t been successful.

I’m wondering if it would be easiest just to hard-code it into my template file by starting taking the uid and just run some queries with the content types I want to display but I’m not sure on how to do that either.

Any help og suggestions would be very much appreciated.

Sincere
- Mestika

Edit:

I found a solution to do it manually with a query for each content type but I'm still very interested in a solution that's more elegant and smoother.

I use this code:

global $user;
$userid = $user->uid;
$blog_count  = db_result(db_query("SELECT COUNT(0) AS num FROM {node} n where n.type = 'blog' AND status = 1 AND n.uid = {$userid}"));

Body:
If you are using the core Profile module, you could use something like below.  It will show the nodes created by the user whose profile is being viewed.  As an added benefit, it only needs to execute one custom database query.

Insert this snippet into template.php in your theme's folder and change "THEMENAME" to the name of your theme:

function THEMENAME_preprocess_user_profile(&$variables) {
  // Information about user profile being viewed
  $account = $variables['account'];

  // Get info on all content types
  $content_types = node_get_types('names');

  // Get node counts for all content types for current user
  $stats = array();
  $node_counts = db_query('SELECT type, COUNT(type) AS num FROM {node} WHERE status = 1 AND uid = %d GROUP BY type', $account->uid);
  while ($row = db_fetch_array($node_counts)) {
    $stats[] = array(
      'name' => $content_types[$row['type']],
      'type' => $row['type'],
      'num' => $row['num'],
    );
  }
  $variables['node_stats'] = $stats;
}

Now, in user-profile.tpl.php can add something similar to:

// If user has created content, display stats
<?php if (count($node_stats) > 0): ?>

  // For each content type, display a DIV with name and number of nodes
  <?php foreach ($node_stats as $value): ?>
    <div><?php print $value['name']; ?> (<?php print $value['num']; ?>)</div>
  <?php endforeach; ?>

// Message to show for user that hasn't created any content
<?php else: ?>
  <?php print $account->name; ?> has not created any content.
<?php endif; ?>

This is just a general idea of what you can do.  You can also add restrictions to the content types you look for/display, check permissions for users to see these stats, use CSS to change the look of the stats, etc.

If you are using Content Profile, you could use THEMENAME_preprocess_node() and check that the node is a profile node before executing this code.


问:
Is Try-Catch More or Less Expensive Than Try-With-Resources

Question

I've just started getting back into Java recently and never had an opportunity to use try-with-resources. On the surface it looks great as it can cut down on code, but under the hood is it more or less expensive of an operation than the traditional try-catch? I know try-catch already is an expensive operation, hence my curiosity.

I gave both types a simple test and didn't notice much of a difference at all:

Test Examples

Try-With-Resources Test

```<code>long startTime = System.currentTimeMillis();
ArrayList<String> list = null;

try (Scanner sc = new Scanner(new File("file.txt"))) {
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
</code>```

Traditional Try-Catch Test

```<code>long startTime = System.currentTimeMillis();
ArrayList<String> list = null;
Scanner sc = null;

try {
    sc = new Scanner(new File("file.txt"));
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    sc.close();
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}
</code>```

Results

Both resulted in a time of 15-16ms - no real noticeable difference at all. But admittedly this is a very small test example.

My question again: Under the hood is try-with-resources more or less expensive than a traditional try-catch?

答:
Traditional Try-catch: In the try block, your code may have a exception, and this exception will be throw and then catch by the catch-block. Then the catch block will deal with the exception. And if you open a source, like a file or other things before a try, and you need to close them in finally then the close() executes in the finally may also throw a exception, and this will replace the exception which are throw in try This sitiution is solved by a nested try-catch before SE 7 like this

try
{
   try
  {
      code with exception;
  }
   finally
 {
      close();
 }

}
catch(Exception e)
{
  Deal the exception
}
```

this is really complex, so After SE 7 we use try-with-resource to solve this problem when you finish the try block, the resource in try(Here) will all be closed.

reference "Core Java" Edition:9 based on SE 7

Body:
Question

I've just started getting back into Java recently and never had an opportunity to use try-with-resources. On the surface it looks great as it can cut down on code, but under the hood is it more or less expensive of an operation than the traditional try-catch? I know try-catch already is an expensive operation, hence my curiosity.

I gave both types a simple test and didn't notice much of a difference at all:

Test Examples

Try-With-Resources Test

long startTime = System.currentTimeMillis();
ArrayList<String> list = null;

try (Scanner sc = new Scanner(new File("file.txt"))) {
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}

Traditional Try-Catch Test

long startTime = System.currentTimeMillis();
ArrayList<String> list = null;
Scanner sc = null;

try {
    sc = new Scanner(new File("file.txt"));
    list = new ArrayList();
    while (sc.hasNext()) {
        list.add(sc.next());
    }
} catch (Exception ex) {
    System.err.println("Error: " + ex.getMessage());
} finally {
    sc.close();
    long endTime = System.currentTimeMillis();
    System.out.println("The program completed in " + (endTime - startTime) + " ms");
}

Results

Both resulted in a time of 15-16ms - no real noticeable difference at all. But admittedly this is a very small test example.

My question again: Under the hood is try-with-resources more or less expensive than a traditional try-catch?

Body:
Traditional Try-catch: In the try block, your code may have a exception, and this exception will be throw and then catch by the catch-block. Then the catch block will deal with the exception. And if you open a source, like a file or other things before a try, and you need to close them in finally then the close() executes in the finally may also throw a exception, and this will replace the exception which are throw in try This sitiution is solved by a nested try-catch before SE 7 like this

try
{
   try
  {
      code with exception;
  }
   finally
 {
      close();
 }

}
catch(Exception e)
{
  Deal the exception
}

this is really complex, so After SE 7 we use try-with-resource to solve this problem when you finish the try block, the resource in try(Here) will all be closed.

reference "Core Java" Edition:9 based on SE 7


问:
HTTP request is not working, setting Authorization using setRequestProperty method
I am trying to make a get request in Java. However, when I run this code,

```<code>URL urlForGetRequest = new URL("my_url");
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");

String username = "user";
String password = "pass";

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
System.out.println(basicAuth);

conection.setRequestProperty("Authorization", "Basic "+basicAuth);

int responseCode = conection.getResponseCode();

System.out.println(responseCode);
</code>```

It always returns a 403. I can type the url into the address bar and it returns what I need it to. Similarly, the credentials are correct. Am I missing a setRequestProperty beyond Authorization?

答:
I guess the urlForGetRequest for your site and url for login are different. When you open a site, it's one url, and when you click the login button, you request another url, that's should be your urlForGetRequest.

Just try to login by correct hardcoded url for a start. And use POST method. And then you can either hardcode this url in your code or parse HTML response with jsoup, selenium maybe. I didn't solve such problems honestly. If you can control the code of this site, you can integrate some other auth options (0Auth, tokens) I'm not savvy with that, maybe someone can help you with it, it's another topic

Body:
I am trying to make a get request in Java. However, when I run this code,

URL urlForGetRequest = new URL("my_url");
String readLine = null;
HttpURLConnection conection = (HttpURLConnection) urlForGetRequest.openConnection();
conection.setRequestMethod("GET");

String username = "user";
String password = "pass";

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
System.out.println(basicAuth);

conection.setRequestProperty("Authorization", "Basic "+basicAuth);

int responseCode = conection.getResponseCode();

System.out.println(responseCode);

It always returns a 403. I can type the url into the address bar and it returns what I need it to. Similarly, the credentials are correct. Am I missing a setRequestProperty beyond Authorization?


问:
Creating a table in MS ACCESS 2007 without a primary key
Can I do this?

The reason I want to do this is, I am importing data from a csv file to access, and during the import process it creates a lot of problems with the autonumber in access.

The tables are not going to be linked in anyway

答: Yes, but consider adding it back when you're done importing.  Otherwise you may run into issues when trying to do edits, deletes, etc.  If you want to be able to edit or delete the records after you've imported, then you'll want a primary key.  If you just need read-only access to the data after import, then you should be fine without a primary key.</p>


问:
Getting all documents from one collection in cloud Firestore?
I'm starting to learn Android and try to solve this problem for hours. Maybe someone will explain to me how to get all documents from collection -> document from Firestore?

```<code>package com.aak.daywork.Activities.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aak.daywork.Adapters.PostAdapter;
import com.aak.daywork.Models.Post;
import com.aak.daywork.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    RecyclerView postRecyclerView;
    PostAdapter postAdapter;
    FirebaseFirestore firestore;
    DocumentReference documentReference;

    FirebaseAuth mAuth;
    FirebaseUser currentUser;

    List<Post> postList;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        String id = currentUser.getUid();

        documentReference = firestore.collection("Post").document(id);
         //Я пытался это
       // Я получаю только через id

        return root;
    }
    @Override
    public void onStart(){
        super.onStart();
        documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                postList = new ArrayList<>();
                Post post = documentSnapshot.toObject(Post.class);
                postList.add(post);
                postAdapter = new PostAdapter(getActivity(), postList);
                postRecyclerView.setAdapter(postAdapter);
            }
        });
    }
}
</code>```

Often, it is very useful to read the official documentation, in which everything is well-written.

```<code>firestore.collection("Post")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });
</code>```

This code was advised to me. I did not understand how to embed it in my code.

enter image description here

答:
Use addSnapshotListener() method to get all the documents in one collection

```<code>firestore.collection("Post")
         .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                    if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {

                        List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                        for (DocumentSnapshot value : documents) {

                            Map<String, Object> mapInfo = value.getData();
                            if (mapInfo != null) {

                                String path = value.getReference().getPath();
                                switch (path) {

                                    case "Post" + "/" + "2E3eQpxe....9Y12":
                                        JSONObject info1 = new JSONObject(mapInfo);
                                        info1.optString("city", "");
                                        info1.optString("date", "");
                                        break;

                                    case "Post" + "/" + "D7RP0KLv....fwCh2":
                                        JSONObject info2 = new JSONObject(mapInfo);
                                        info2.optString("city", "");
                                        break;
                                }
                            }
                        }
                    }
                }
            });
</code>```

CODE:

```<code>public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private RecyclerView postRecyclerView;
    private PostAdapter postAdapter;
    private FirebaseFirestore firestore;
    private DocumentReference documentReference;

    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;

    private List<Post> postList;
    private String userId;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        return root;
    }

    @Override
    public void onStart(){
        super.onStart();

        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        userId = currentUser.getUid();

        firestore.collection("Post")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                        if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {
                            postList = new ArrayList<>();
                            List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                            for (DocumentSnapshot value : documents) {
                                Post post = value.toObject(Post.class);
                                postList.add(post);
                            }
                            postAdapter = new PostAdapter(getActivity(), postList);
                            postRecyclerView.setAdapter(postAdapter);
                        }
                    }
                });
    }
}
</code>```

and let me know if this not works.

Body:
I'm starting to learn Android and try to solve this problem for hours. Maybe someone will explain to me how to get all documents from collection -> document from Firestore?

package com.aak.daywork.Activities.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aak.daywork.Adapters.PostAdapter;
import com.aak.daywork.Models.Post;
import com.aak.daywork.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    RecyclerView postRecyclerView;
    PostAdapter postAdapter;
    FirebaseFirestore firestore;
    DocumentReference documentReference;

    FirebaseAuth mAuth;
    FirebaseUser currentUser;

    List<Post> postList;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        String id = currentUser.getUid();

        documentReference = firestore.collection("Post").document(id);
         //Я пытался это
       // Я получаю только через id

        return root;
    }
    @Override
    public void onStart(){
        super.onStart();
        documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                postList = new ArrayList<>();
                Post post = documentSnapshot.toObject(Post.class);
                postList.add(post);
                postAdapter = new PostAdapter(getActivity(), postList);
                postRecyclerView.setAdapter(postAdapter);
            }
        });
    }
}

Often, it is very useful to read the official documentation, in which everything is well-written.

firestore.collection("Post")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    Log.d(TAG, document.getId() + " => " + document.getData());
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

This code was advised to me. I did not understand how to embed it in my code.

enter image description here

Body:
Use addSnapshotListener() method to get all the documents in one collection

firestore.collection("Post")
         .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                    if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {

                        List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                        for (DocumentSnapshot value : documents) {

                            Map<String, Object> mapInfo = value.getData();
                            if (mapInfo != null) {

                                String path = value.getReference().getPath();
                                switch (path) {

                                    case "Post" + "/" + "2E3eQpxe....9Y12":
                                        JSONObject info1 = new JSONObject(mapInfo);
                                        info1.optString("city", "");
                                        info1.optString("date", "");
                                        break;

                                    case "Post" + "/" + "D7RP0KLv....fwCh2":
                                        JSONObject info2 = new JSONObject(mapInfo);
                                        info2.optString("city", "");
                                        break;
                                }
                            }
                        }
                    }
                }
            });

CODE:

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private RecyclerView postRecyclerView;
    private PostAdapter postAdapter;
    private FirebaseFirestore firestore;
    private DocumentReference documentReference;

    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;

    private List<Post> postList;
    private String userId;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        return root;
    }

    @Override
    public void onStart(){
        super.onStart();

        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        userId = currentUser.getUid();

        firestore.collection("Post")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                        if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {
                            postList = new ArrayList<>();
                            List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                            for (DocumentSnapshot value : documents) {
                                Post post = value.toObject(Post.class);
                                postList.add(post);
                            }
                            postAdapter = new PostAdapter(getActivity(), postList);
                            postRecyclerView.setAdapter(postAdapter);
                        }
                    }
                });
    }
}

and let me know if this not works.


问:
How to redirect to another component after checking conditions in angular 8?
I am new to Angular 8 and i am making a login component and after entering username password i want to redirect to another component using route thats my code i have done this much :

my login component.ts:

```<code>       import { Component, OnInit } from '@angular/core';
       import{FormGroup,FormBuilder,Validators} from '@angular/forms'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  myForm:FormGroup
  submitted=false;
  _baseURL : string;
  formvalid: boolean;
   user:string;
   pwd:string;
  constructor(private formbuilder:FormBuilder){}

  ngOnInit(){
    this.myForm = this.formbuilder.group({
    username:['',Validators.required],
    password:['',[Validators.required,Validators.pattern("^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$")]]
    });
    this._baseURL="";
    this.formvalid=false;
  }

  Submitme(){
    this.submitted = true;

    if (this.myForm.invalid) {
      this.formvalid=false;
        return;
    }
    if (this.myForm.valid) {
      this.formvalid=true;
    this._baseURL= 'Welcome'+" "+ this.myForm.controls.username.value;
  }
  this.user=this.myForm.controls.username.value;
  this.pwd=this.myForm.controls.password.value;
}
rest(){
  this.myForm.reset();
  this.submitted = false;
}
}
</code>```

my login component html is:

```<code>        <h1 class="text-center" [hidden]="formvalid">Login</h1>
          <form [formGroup]="myForm" (ngSubmit)="Submitme()" class="text-center">
           <div class="container bg-dark" [hidden]="formvalid" style="border: 1px solid black;">
         <div class="row mt-3">
           <div class="col-lg-5">
         <label for="name" class="text-white">Username :</label>
         </div>
         <input type="text" formControlName="username" class="col-lg-4 form-control"
           [ngClass]="{ 'is-invalid': submitted && myForm.controls.username.errors }">
          <div *ngIf="submitted && myForm.controls.username.errors" class="text-danger">
            <div *ngIf="myForm.controls.username.errors.required">First Name is required</div>
        </div>
       </div>
     <div class="row mt-2">
           <div class="col-lg-5">
       <label for="pwd" class="text-white">Password :</label>
         </div>
      <input type="password" formControlName="password" class="col-lg-4 form-control"
      [ngClass]="{ 'is-invalid': submitted && myForm.controls.password.errors }">
       <div *ngIf="submitted && myForm.controls.password.errors" class="text-danger">
     <div *ngIf="myForm.controls.password.errors.required">password is required</div>
      <div *ngIf="myForm.controls.password.errors.pattern">Pwd must contain atleast one upper and
    lower case character one special character one digit and 8 characters in length  </div>
   </div>
    </div>
     <button class="btn btn-primary mt-2 mb-3" type="submit"
   [routerLink]="'/afterlog'">Submit</button>
     <input type="button" (click)="rest()" value="Reset" class="btn btn-primary mt-2 mb-3">
 </div>
      </form>
</code>```

After login i want to redirect to another component with welcome message using routing in angular 8:
Thanks in advance!!!!

答:
i think you you want to navigate to the new component and sending the new data to show the welcome message there, you can navigate with sending queryParams, send your username as a queryParam to welcome component, You can store the loggedin user in localstorage too if you want and avoid sending it as query parameter

```<code>this.router.navigate(['/welcome'], { queryParams: { username: this.myForm.controls.username.value} });
</code>```

and you can construct the message in your welcome.component.ts

```<code>username: string;
constructor(private route: ActivatedRoute) {
    this.username= this.route.snapshot.paramMap.get('username');
}
</code>```

and in your welcome.component.html

```<code><div>Welcome {{username}}!</div>
</code>```

Body:
I am new to Angular 8 and i am making a login component and after entering username password i want to redirect to another component using route thats my code i have done this much :

my login component.ts:

       import { Component, OnInit } from '@angular/core';
       import{FormGroup,FormBuilder,Validators} from '@angular/forms'

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  myForm:FormGroup
  submitted=false;
  _baseURL : string;
  formvalid: boolean;
   user:string;
   pwd:string;
  constructor(private formbuilder:FormBuilder){}

  ngOnInit(){
    this.myForm = this.formbuilder.group({
    username:['',Validators.required],
    password:['',[Validators.required,Validators.pattern("^(?=.*?[a-z])(.{13,}|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,12})$")]]
    });
    this._baseURL="";
    this.formvalid=false;
  }

  Submitme(){
    this.submitted = true;

    if (this.myForm.invalid) {
      this.formvalid=false;
        return;
    }
    if (this.myForm.valid) {
      this.formvalid=true;
    this._baseURL= 'Welcome'+" "+ this.myForm.controls.username.value;
  }
  this.user=this.myForm.controls.username.value;
  this.pwd=this.myForm.controls.password.value;
}
rest(){
  this.myForm.reset();
  this.submitted = false;
}
}

my login component html is:

Login

          <form [formGroup]="myForm" (ngSubmit)="Submitme()" class="text-center">

         Username :

         <input type="text" formControlName="username" class="col-lg-4 form-control"
           [ngClass]="{ 'is-invalid': submitted && myForm.controls.username.errors }">

First Name is required

       Password :

      <input type="password" formControlName="password" class="col-lg-4 form-control"
      [ngClass]="{ 'is-invalid': submitted && myForm.controls.password.errors }">

password is required

Pwd must contain atleast one upper and
    lower case character one special character one digit and 8 characters in length

     <button class="btn btn-primary mt-2 mb-3" type="submit"
   [routerLink]="'/afterlog'">Submit</button>
     <input type="button" (click)="rest()" value="Reset" class="btn btn-primary mt-2 mb-3">

      </form>

After login i want to redirect to another component with welcome message using routing in angular 8:
Thanks in advance!!!!

Body:
i think you you want to navigate to the new component and sending the new data to show the welcome message there, you can navigate with sending queryParams, send your username as a queryParam to welcome component, You can store the loggedin user in localstorage too if you want and avoid sending it as query parameter

this.router.navigate(['/welcome'], { queryParams: { username: this.myForm.controls.username.value} });

and you can construct the message in your welcome.component.ts

username: string;
constructor(private route: ActivatedRoute) {
    this.username= this.route.snapshot.paramMap.get('username');
}

and in your welcome.component.html

<div>Welcome {{username}}!</div>


问:
Why doesn't it print Armstrong numbers up to 1000?
It was working without the nested loop just to check if the input number was Armstrong number.</p>

```<code>c=0
for y in range(1000):
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)
</code>```

答:
Because Armstrong numbers are numbers such that the sum of the cubes of each digit of the number is equal to the original number. Your code seems to be raising each digit to the nth power, where n is equal to the number of digits in the number. The below code will print Armstrong numbers less than 1000:

```<code>for y in range(1000):
    if sum(int(x)**3 for x in str(y)) == y:
        print(y)
</code>```

Output:

```<code>0
1
153
370
371
407
</code>```

From the comments, it seems there are multiple definitions of Armstrong numbers; if you seek the other definition then see @Mandy007's answer below.

Body:
It was working without the nested loop just to check if the input number was Armstrong number.

c=0
for y in range(1000):
    for x in str(y):
        c += int(x) ** len(str(y))
        if c == y:
            print(c)

Body:
Because Armstrong numbers are numbers such that the sum of the cubes of each digit of the number is equal to the original number. Your code seems to be raising each digit to the nth power, where n is equal to the number of digits in the number. The below code will print Armstrong numbers less than 1000:

for y in range(1000):
    if sum(int(x)**3 for x in str(y)) == y:
        print(y)

Output:

0
1
153
370
371
407

From the comments, it seems there are multiple definitions of Armstrong numbers; if you seek the other definition then see @Mandy007's answer below.


问:
SharpSVN - Is there a way to get a current working copy directly to a memory stream?
I am using the latest version of SharpSVN.  I would like to retrieve the latest working copy of a repository, but I would like to load it into a memory stream instead of saving it to disk.  Is there a way to do this?

Thanks.

答:
I assume you want one file in memory?
(It is hard to stream directories in a memoryStream).

But with SvnClient.Write() you can just copy a Subversion url to a stream.


问:
.net Core : How to pass parameters and run Azure data factory pipeline from C# Code?
I am using Microsoft.Azure.Management.DataFactories .net core package.

I am using following code to get the required token for accessing azure data factory pipeline in C# .net core :

```<code>public static void RunDataFactoryPipeline()
    {
        try
        {
            var context = new AuthenticationContext("" + "");
            var credentials = new ClientCredential(clientId: "", clientSecret: "");
            AuthenticationResult result = context.AcquireTokenAsync("", credentials).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to acquire Token");
            }

            var token = result.AccessToken;
            var serviceClientCredentials = new TokenCloudCredentials("",result.AccessToken);
            var client = new DataFactoryManagementClient(serviceClientCredentials);

            StartPipeline("name", "name", "name", client);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
public static void StartPipeline(string resourceGroup, string dataFactory, string pipeLineName, DataFactoryManagementClient client, )
        {
            var pipeLine = client.Pipelines.Get(resourceGroup, dataFactory, pipeLineName);
}
</code>```

But i don't find any method using which i can run the pipeline in
  factory.

答:
Seems you are using incorrect nuget package, use this one and you should have methods available to run pipelines on the IPipelineOperations instance

Install-Package Microsoft.Azure.Management.DataFactory -Version 4.7.0

```<code>public static void StartPipeline(string resourceGroup, string dataFactory, string pipeLineName, DataFactoryManagementClient client )
{
   var pipeLine = client.Pipelines.Get(resourceGroup, dataFactory, pipeLineName);
   client.Pipelines.CreateRun(resourceGroup, dataFactory, pipeLineName);
}
</code>```

Body:
I am using Microsoft.Azure.Management.DataFactories .net core package.

I am using following code to get the required token for accessing azure data factory pipeline in C# .net core :

public static void RunDataFactoryPipeline()
    {
        try
        {
            var context = new AuthenticationContext("" + "");
            var credentials = new ClientCredential(clientId: "", clientSecret: "");
            AuthenticationResult result = context.AcquireTokenAsync("", credentials).Result;

            if (result == null)
            {
                throw new InvalidOperationException("Failed to acquire Token");
            }

            var token = result.AccessToken;
            var serviceClientCredentials = new TokenCloudCredentials("",result.AccessToken);
            var client = new DataFactoryManagementClient(serviceClientCredentials);

            StartPipeline("name", "name", "name", client);
        }
        catch (Exception ex)
        {
            throw;
        }
    }
public static void StartPipeline(string resourceGroup, string dataFactory, string pipeLineName, DataFactoryManagementClient client, )
        {
            var pipeLine = client.Pipelines.Get(resourceGroup, dataFactory, pipeLineName);
}

But i don't find any method using which i can run the pipeline in
  factory.

Body:
Seems you are using incorrect nuget package, use this one and you should have methods available to run pipelines on the IPipelineOperations instance

Install-Package Microsoft.Azure.Management.DataFactory -Version 4.7.0

public static void StartPipeline(string resourceGroup, string dataFactory, string pipeLineName, DataFactoryManagementClient client )
{
   var pipeLine = client.Pipelines.Get(resourceGroup, dataFactory, pipeLineName);
   client.Pipelines.CreateRun(resourceGroup, dataFactory, pipeLineName);
}