问:
Flutter text output not throwing paragraph line when comes from Firebase
I have a Text widget, with \n\n in it to throw a blank line when the paragraph changes:

```<code>Text('Sibling Rivalry \n\n some more text\n\n> and even more text')
</code>```

This works fine and prints blank lines where the \n\n are defined. However when I try to output the exact same text, but retrieved from Cloud Firestore, the blank lines are not thrown.

Here's the loading code:

```<code>final extracted = await _firestore
    .collection('items')
    .where("active", isEqualTo: true)
    .orderBy("playCount", descending: true)
    .getDocuments();

extracted.documents.forEach(
  (mediaData) {

    if (mediaData['itemType'] == 'V') {
      loadedMedia.add(
        MediaItem(
          // load fields for VIDEO,
          title: mediaData['title'],
          description: mediaData['description'],
          itemCatCode: mediaData['itemCatCode'],
          imageUrl: mediaData['imageUrl'],
          itemUrl: mediaData['itemUrl'],
          itemType: mediaData['itemType'],
        ),
      );
    }
</code>```

And then I try to output it to screen via the same Text widget:

```<code>Text(mediaItem.description),
</code>```

Btw I am typing the text directly into Firestore and the description field is defined as String in Firestore. I have no idea why the /n/n is not being recognized as the string coming from Firestore looks exactly the same as the hardcoded string above.

Any help with this would really be greatly appreciated as in the final app, there is a lot of text with quite a few paragraphs.

答:
Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it. If you need to store something special, you may want to encode and decode that yourself.

just do mediaItem.description replace  "\n" with: "\n" again (if you have created string using \n)

One more thing you can try  mediaItem.description replace  "\\n" with: "\n" (if it was automatically created using some textarea etc)

Body:
I have a Text widget, with \n\n in it to throw a blank line when the paragraph changes:

Text('Sibling Rivalry \n\n some more text\n\n> and even more text')

This works fine and prints blank lines where the \n\n are defined. However when I try to output the exact same text, but retrieved from Cloud Firestore, the blank lines are not thrown.

Here's the loading code:

final extracted = await _firestore
    .collection('items')
    .where("active", isEqualTo: true)
    .orderBy("playCount", descending: true)
    .getDocuments();

extracted.documents.forEach(
  (mediaData) {

    if (mediaData['itemType'] == 'V') {
      loadedMedia.add(
        MediaItem(
          // load fields for VIDEO,
          title: mediaData['title'],
          description: mediaData['description'],
          itemCatCode: mediaData['itemCatCode'],
          imageUrl: mediaData['imageUrl'],
          itemUrl: mediaData['itemUrl'],
          itemType: mediaData['itemType'],
        ),
      );
    }

And then I try to output it to screen via the same Text widget:

Text(mediaItem.description),

Btw I am typing the text directly into Firestore and the description field is defined as String in Firestore. I have no idea why the /n/n is not being recognized as the string coming from Firestore looks exactly the same as the hardcoded string above.

Any help with this would really be greatly appreciated as in the final app, there is a lot of text with quite a few paragraphs.


来源: stackexchange

问:
Generating report in Node JS
I want to generate a report(i.e pdf or any format that can be print) from the data in system. Its like i need to generate weekly report. Format of report will be the same but data will be change with time. Is there any way to perform this task in Node JS ? I m using Mongo DB. And React JS in front end. Thank you so much.

答: You can use jsPDF as it is a big library having more than 18k github star. if you want to make report from frontend only </p>

ContentLicense: CC BY-SA 4.0

Title: Generating report in Node JS


问:
how to hide the modal?
I'm already stuck for almost a day but still unable to fix this issue. I already search in web and the common recommendation in using this code $('#Modal').modal('hide'). This is working in my other function that are using modal but there is an specific function that unable to close. Here is the sample where I able to close the modal.

```<code>$(document).on('click', '#btnProcedureAccessSave', function (event) {
    HideAllInModal();
    $('#divLoadingInModal').show();
    $.ajax({
        async: false,
        type: 'POST',
        url: '/admin/AddProcedureAccess',
        data: {
            UserID: $('#txtNewUserID').val(),
            ProcedureID: $('#txtSelectedProcedureID').val(),
            __RequestVerificationToken: gettoken(),
        },
        success: function (response) {
            if (response['success'] == true) {
                $('#Modal').modal('hide');
                ProcedureAccessMarkUpUpdate(response['data']);
            }
            else {
                $('#divLoadingInModal').hide();
                $('#divProcedureAccessInModal').show();
                ValidationError(response['error']);
            }
        },
        error: function (jqXHR, exception) {
            $('#divLoadingInModal').hide();
            $('#divProcedureAccessInModal').show();
            JavaScriptError(jqXHR, exception);
        }
    });
});
</code>```

here the code that I unable to close the modal

```<code>function DeleteUserProcedureAccess(ID) {
    HideAllInModal();
    $('#divLoadingInModal').show();
    $.ajax({
        async: false,
        type: 'POST',
        url: '/admin/DeleteUserProcedureAccess',
        data: {
            UserProcedureID: ID,
            __RequestVerificationToken: gettoken()
        },
        success: function () {
            $('#' + ID).remove();
            $('#Modal').modal('hide');
        },
        error: function (jqXHR, exception) {
            $('#Modal').modal('hide');
            JavaScriptError(jqXHR, exception);
        }
    });
}
</code>```

my HTML Code

```<code><div class="modal fade show" tabindex="-1" role="dialog" id="Modal" style="padding-right: 17px;" aria-modal="true">

    @*Loading Modal*@
    <div id="divLoadingInModal" class="modal-dialog modal-md modal-dialog-centered" role="document" style="display:none; width:110px;">
        <div class="modal-content" style="text-align:center">
            <img src="~/Content/Assets/img/5.gif"  style="width:100px; height:100px; margin:5px;"/>
            <h5>Loading...</h5>
        </div>
    </div>

    @*Procedure Access Modal*@
    <div id="divProcedureAccessInModal" class="modal-dialog modal-md modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><label id="lblProcedureAccessModalHeader"></label></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body needs-validation">
                <input id="txtProcedureAccessID" type="hidden" />
                <div class="form-Group">
                    <label>Name</label>
                    <input id="txtNewUserID" type="hidden" />
                    <div class="input-group">
                        <input id="txtProcedureAccessname" type="text" class="form-control form-control-sm" />
                    </div>
                    <label id="err_ProcedureAccessUserID"></label>
                </div>
                <div class="modal-footer bg-whitesmoke">
                    <button class="btn btn-primary btn-shadow" id="btnProcedureAccessSave">Save</button>
                </div>
            </div>
        </div>
    </div>

</div>
</code>```

答:
you need to find the right id of modal div
for example if you using this $('#Modal').modal('hide'); that means your modal id is "Modal". you are using a correct way of hiding the model but your jquery selector is wrong id. use a correct jquery selector id for example if your modal when you are showing it you are calling -     $('#divLoadingInModal').show(); same wat  to hide you need to call
    $('#divLoadingInModal').hide(); or     $('#divLoadingInModal').modal('hide');
**** Make sure you are using a correct jquery selector in $ function .</p>

Title: how to hide the modal?

Body:
I'm already stuck for almost a day but still unable to fix this issue. I already search in web and the common recommendation in using this code $('#Modal').modal('hide'). This is working in my other function that are using modal but there is an specific function that unable to close. Here is the sample where I able to close the modal.

$(document).on('click', '#btnProcedureAccessSave', function (event) {
    HideAllInModal();
    $('#divLoadingInModal').show();
    $.ajax({
        async: false,
        type: 'POST',
        url: '/admin/AddProcedureAccess',
        data: {
            UserID: $('#txtNewUserID').val(),
            ProcedureID: $('#txtSelectedProcedureID').val(),
            __RequestVerificationToken: gettoken(),
        },
        success: function (response) {
            if (response['success'] == true) {
                $('#Modal').modal('hide');
                ProcedureAccessMarkUpUpdate(response['data']);
            }
            else {
                $('#divLoadingInModal').hide();
                $('#divProcedureAccessInModal').show();
                ValidationError(response['error']);
            }
        },
        error: function (jqXHR, exception) {
            $('#divLoadingInModal').hide();
            $('#divProcedureAccessInModal').show();
            JavaScriptError(jqXHR, exception);
        }
    });
});

here the code that I unable to close the modal

function DeleteUserProcedureAccess(ID) {
    HideAllInModal();
    $('#divLoadingInModal').show();
    $.ajax({
        async: false,
        type: 'POST',
        url: '/admin/DeleteUserProcedureAccess',
        data: {
            UserProcedureID: ID,
            __RequestVerificationToken: gettoken()
        },
        success: function () {
            $('#' + ID).remove();
            $('#Modal').modal('hide');
        },
        error: function (jqXHR, exception) {
            $('#Modal').modal('hide');
            JavaScriptError(jqXHR, exception);
        }
    });
}

my HTML Code

    @*Loading Modal*@

Loading...

    @*Procedure Access Modal*@

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <input id="txtProcedureAccessID" type="hidden" />

                    Name
                    <input id="txtNewUserID" type="hidden" />

                        <input id="txtProcedureAccessname" type="text" class="form-control form-control-sm" />

                    <button class="btn btn-primary btn-shadow" id="btnProcedureAccessSave">Save</button>


问:
why ssh connection timed out in vscode?
I  installed git instead of openssl to use Remote-SSH in VSCode.However,after I completed the config document and tried to connect to the remote host.I failed. The error info is showed in the below pic.error info

error info:

```<code>[11:27:12.631] remote-ssh@0.48.0
[11:27:12.632] win32 x64
[11:27:12.656] SSH Resolver called for "ssh-remote+23321", attempt 1
[11:27:12.659] SSH Resolver called for host: 23321
[11:27:12.659] Setting up SSH remote "23321"
[11:27:12.790] Using commit id "26076a4de974ead31f97692a0d32f90d735645c0" and quality "stable" for server
[11:27:12.798] Testing ssh with ssh -V
[11:27:13.099] ssh exited with code: 0
[11:27:13.100] Got stderr from ssh: OpenSSH_8.1p1, OpenSSL 1.1.1d  10 Sep 2019
[11:27:13.128] Running script with connection command: ssh -T -D 49485 23321 bash
[11:27:13.132] Install and start server if needed
[11:27:13.151] Terminal shell path: C:\Windows\System32\cmd.exe
[11:27:30.151] Resolver error: Connecting with SSH timed out
[11:27:30.178] ------
</code>```

答: I had the same problem before, I solved this by deleting  "terminal.integrated.inheritEnv": false inside ~/.config/Code/User/setting.json

Title: why ssh connection timed out in vscode?

Body:
I  installed git instead of openssl to use Remote-SSH in VSCode.However,after I completed the config document and tried to connect to the remote host.I failed. The error info is showed in the below pic.error info

error info:

[11:27:12.631] remote-ssh@0.48.0
[11:27:12.632] win32 x64
[11:27:12.656] SSH Resolver called for "ssh-remote+23321", attempt 1
[11:27:12.659] SSH Resolver called for host: 23321
[11:27:12.659] Setting up SSH remote "23321"
[11:27:12.790] Using commit id "26076a4de974ead31f97692a0d32f90d735645c0" and quality "stable" for server
[11:27:12.798] Testing ssh with ssh -V
[11:27:13.099] ssh exited with code: 0
[11:27:13.100] Got stderr from ssh: OpenSSH_8.1p1, OpenSSL 1.1.1d  10 Sep 2019
[11:27:13.128] Running script with connection command: ssh -T -D 49485 23321 bash
[11:27:13.132] Install and start server if needed
[11:27:13.151] Terminal shell path: C:\Windows\System32\cmd.exe
[11:27:30.151] Resolver error: Connecting with SSH timed out
[11:27:30.178] ------


问:
Hide Mouse Pointer
I am attempting to hide the mouse pointer when there has been a few seconds of inactivity and then re-show the pointer again when the user moves the mouse.  I have been able to get the mouse pointer to hide and re-show as I require it, however when I execute grid.Children.Clear() and grid.Children.Add() the mouse pointer re-appears (but again hides after a few seconds of inactivity).

My code is as below:

```<code>Private Sub Window1_MouseMoved(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
  'MsgBox("Mouse Has Moved", MsgBoxStyle.Critical, "Mouse Moved")
  LastMouseMove = DateTime.Now
  If IsHidden Then
    Cursor = Cursors.Arrow
    IsHidden = False
  End If
End Sub

Private Sub MouseHide_Tick(ByVal sender As Object, ByVal e As EventArgs)
  Dim elaped As TimeSpan = DateTime.Now - LastMouseMove
  If elaped >= TimeoutToHide AndAlso Not IsHidden Then
    Cursor = Cursors.None
    IsHidden = True
    'System.Console.SetCursorPosition(0, 0)
  End If
End Sub

Private Sub setupMouseHide()
  Try
    'Dim timer As New System.Timers.Timer(1000)
    Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer()
    AddHandler dispatcherTimer.Tick, AddressOf MouseHide_Tick
    dispatcherTimer.Interval = New TimeSpan(0, 0, 3)
    dispatcherTimer.Start()
    Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Critical, "Setup Display Message: error encountered")
  End Try
End Sub
</code>```

I was wondering if this is a known issue or is there a better way of achieving what I am seeking to do?

Thanks,

Matt

答:
It might be a bug, but its not uncommon for layout changes to cause a mouse move event to be raised.

I'd say your best bet might be to check and store the actual coordinates of the mouse in that mouse move event. That way you can ignore the errant mouse move events.

Not ideal, but I think it would work.

ContentLicense: CC BY-SA 3.0

Title: Hide Mouse Pointer

Body:
I am attempting to hide the mouse pointer when there has been a few seconds of inactivity and then re-show the pointer again when the user moves the mouse.  I have been able to get the mouse pointer to hide and re-show as I require it, however when I execute grid.Children.Clear() and grid.Children.Add() the mouse pointer re-appears (but again hides after a few seconds of inactivity).

My code is as below:

Private Sub Window1_MouseMoved(ByVal sender As Object, ByVal e As MouseEventArgs) Handles MyBase.MouseMove
  'MsgBox("Mouse Has Moved", MsgBoxStyle.Critical, "Mouse Moved")
  LastMouseMove = DateTime.Now
  If IsHidden Then
    Cursor = Cursors.Arrow
    IsHidden = False
  End If
End Sub

Private Sub MouseHide_Tick(ByVal sender As Object, ByVal e As EventArgs)
  Dim elaped As TimeSpan = DateTime.Now - LastMouseMove
  If elaped >= TimeoutToHide AndAlso Not IsHidden Then
    Cursor = Cursors.None
    IsHidden = True
    'System.Console.SetCursorPosition(0, 0)
  End If
End Sub

Private Sub setupMouseHide()
  Try
    'Dim timer As New System.Timers.Timer(1000)
    Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer()
    AddHandler dispatcherTimer.Tick, AddressOf MouseHide_Tick
    dispatcherTimer.Interval = New TimeSpan(0, 0, 3)
    dispatcherTimer.Start()
    Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Critical, "Setup Display Message: error encountered")
  End Try
End Sub

I was wondering if this is a known issue or is there a better way of achieving what I am seeking to do?

Thanks,

Matt


问:
python how download all file image,css, js from web url?
How can I list all file of a URL website in Python and download them in folder?

```<code>import uuid
rnd_str = uuid.uuid4().hex
main_name="download_"+rnd_str
main_folder=main_name+"/"
dir = main_folder
if os.path.exists(dir):
    shutil.rmtree(dir)
os.mkdir(main_folder)

site = 'http://digipaz.com/'
response = requests.get(site)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]
for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png|css))$', url)
    with open( '/home/danesh20016/public_html/ts/'+main_folder+filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)
</code>```

i can download image but not file  js,css

答:
```<code>from bs4 import BeautifulSoup
from pip._vendor import requests
import os
import shutil
import re
from bs4 import BeautifulSoup
import uuid

rnd_str = uuid.uuid4().hex
main_name="download_"+rnd_str
main_folder= main_name+"/"
dir = main_folder

if os.path.exists(dir):
    shutil.rmtree(dir)
os.mkdir(main_folder)

site = 'http://digipaz.com/'
response = requests.get(site)
soup = BeautifulSoup(response.text, 'html.parser')
#find all jpg,png,gif
img_tags = soup.find_all('img')
urls = [img['src'] for img in img_tags]
#print (urls)
for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
   #with open( '/home/danesh20016/public_html/ts/'+main_folder+filename.group(1), 'wb') as f:
    print (url)
    with open( '/home/danesh20016/public_html/ts/'+main_folder+filename.group(1), 'wb') as f:
    #with open(main_folder+filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

 #find all css
 for link in soup.findAll('link', href=True):
    #print ("Found the URL:", link['href'])
    if re.search(".css", link['href']):
       print (link['href'])
       with open('/home/danesh20016/public_html/ts/'+main_folder+ filename.group(1), 'wb') as f:
           # with open(main_folder+filename.group(1), 'wb') as f:
           if 'http' not in url:
               # sometimes an image source can be relative
               # if it is provide the base url which also happens
               # to be the site variable atm.
               url = '{}{}'.format(site, link['href'])
           response = requests.get(url)
           f.write(response.content)
#find all js
link_js = [sc["src"] for sc in soup.find_all("script",src=True)]
for link in link_js:
    print ("Found the URL:", link)
    with open('/home/danesh20016/public_html/ts/'+main_folder+ filename.group(1), 'wb') as f:
        # with open(main_folder+filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            url = '{}{}'.format(site, link)
        response = requests.get(url)
        f.write(response.content)
</code>```

Body:
How can I list all file of a URL website in Python and download them in folder?

import uuid
rnd_str = uuid.uuid4().hex
main_name="download_"+rnd_str
main_folder=main_name+"/"
dir = main_folder
if os.path.exists(dir):
    shutil.rmtree(dir)
os.mkdir(main_folder)

site = 'http://digipaz.com/'
response = requests.get(site)
soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]
for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png|css))$', url)
    with open( '/home/danesh20016/public_html/ts/'+main_folder+filename.group(1), 'wb') as f:
        if 'http' not in url:
            # sometimes an image source can be relative
            # if it is provide the base url which also happens
            # to be the site variable atm.
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

i can download image but not file  js,css


问:
Create general exception class when implement retry in Python
As the title explains, I want to create a general exception class to inherit from built-in exception classes that would be caught later in other class(es).

Here is my code:

```<code>from functools import wraps

class ControlledException(TypeError, AttributeError):
    """A generic exception on the program's domain."""

class WithRetry:
    def __init__(self, retries_limit=3, allowed_exceptions=None):
        self.retries_limit = retries_limit
        self.allowed_exceptions = allowed_exceptions or (ControlledException,)

    def __call__(self, operation):
        @wraps(operation)
        def wrapped(*args, **kwargs):
            last_raised = None

            for _ in range(self.retries_limit):
                try:
                    return operation(*args, **kwargs)
                except self.allowed_exceptions as e:
                    print(f'retrying {operation.__qualname__} due to {e}')
                    last_raised = e
            raise last_raised

        return wrapped

@WithRetry()
def test(x):
    x = x + 1
    print(x)

test('a')
</code>```

ControlledException class inherits two exceptions, TypeError and AttributeError which I want to catch. In this case, the program will catch the TypeError.

And I have no idea why the parameter self.allowed_exceptions has no effect on (ControlledException,)...
However, if I change (ControlledException,) to Exception or TypeError the error is caught.

答:
When you define custom exceptions like that, either you have to raise them directly or you have to catch the original exceptions and then raise the custom exceptions.

Here, I've caught the original exception, suppressed their traceback and raised your custom exception.

from functools import wraps

class ControlledException(TypeError, AttributeError):
    """A generic exception on the program's domain."""

class WithRetry:
    def __init__(self, retries_limit=3, allowed_exceptions=None):
        self.retries_limit = retries_limit
        self.allowed_exceptions = allowed_exceptions or (ControlledException,)

    def __call__(self, operation):
        @wraps(operation)
        def wrapped(*args, **kwargs):

            for _ in range(self.retries_limit):
                try:
                    return operation(*args, **kwargs)

                # if you want to catch the error, you have to catch the original
                # exceptions as opposed to custom exceptions
                except (TypeError, AttributeError) as exc:
                    print(f"retrying {operation.__qualname__} due to {exc}")

                    # this suppresses the original error message and raises your
                    # custom exception
                    raise ControlledException("Here is your error message!!") from None

        return wrapped

@WithRetry()
def test(x):
    x = x + 1
    print(x)

test("a")
```

<p>This prints out:</p>

<pre class="lang-py prettyprint-override"><code>retrying test due to can only concatenate str (not "int") to str
---------------------------------------------------------------------------
ControlledException                       Traceback (most recent call last)
<ipython-input-364-2a7d6eb73e92> in <module>
     38
     39
---> 40 test('a')

<ipython-input-364-2a7d6eb73e92> in wrapped(*args, **kwargs)
     27                     # this suppresses the original error message and raises your
     28                     # custom exception
---> 29                     raise ControlledException('Here is your error message!!') from None
     30
     31         return wrapped

ControlledException: Here is your error message!!
</code>```

Body:
As the title explains, I want to create a general exception class to inherit from built-in exception classes that would be caught later in other class(es).

Here is my code:

from functools import wraps

class ControlledException(TypeError, AttributeError):
    """A generic exception on the program's domain."""

class WithRetry:
    def __init__(self, retries_limit=3, allowed_exceptions=None):
        self.retries_limit = retries_limit
        self.allowed_exceptions = allowed_exceptions or (ControlledException,)

    def __call__(self, operation):
        @wraps(operation)
        def wrapped(*args, **kwargs):
            last_raised = None

            for _ in range(self.retries_limit):
                try:
                    return operation(*args, **kwargs)
                except self.allowed_exceptions as e:
                    print(f'retrying {operation.__qualname__} due to {e}')
                    last_raised = e
            raise last_raised

        return wrapped

@WithRetry()
def test(x):
    x = x + 1
    print(x)

test('a')

ControlledException class inherits two exceptions, TypeError and AttributeError which I want to catch. In this case, the program will catch the TypeError.

And I have no idea why the parameter self.allowed_exceptions has no effect on (ControlledException,)...
However, if I change (ControlledException,) to Exception or TypeError the error is caught.

Body:
When you define custom exceptions like that, either you have to raise them directly or you have to catch the original exceptions and then raise the custom exceptions.

Here, I've caught the original exception, suppressed their traceback and raised your custom exception.

from functools import wraps

class ControlledException(TypeError, AttributeError):
    """A generic exception on the program's domain."""

class WithRetry:
    def __init__(self, retries_limit=3, allowed_exceptions=None):
        self.retries_limit = retries_limit
        self.allowed_exceptions = allowed_exceptions or (ControlledException,)

    def __call__(self, operation):
        @wraps(operation)
        def wrapped(*args, **kwargs):

            for _ in range(self.retries_limit):
                try:
                    return operation(*args, **kwargs)

                # if you want to catch the error, you have to catch the original
                # exceptions as opposed to custom exceptions
                except (TypeError, AttributeError) as exc:
                    print(f"retrying {operation.__qualname__} due to {exc}")

                    # this suppresses the original error message and raises your
                    # custom exception
                    raise ControlledException("Here is your error message!!") from None

        return wrapped

@WithRetry()
def test(x):
    x = x + 1
    print(x)

test("a")

This prints out:

retrying test due to can only concatenate str (not "int") to str
---------------------------------------------------------------------------
ControlledException                       Traceback (most recent call last)
<ipython-input-364-2a7d6eb73e92> in <module>
     38
     39
---> 40 test('a')

<ipython-input-364-2a7d6eb73e92> in wrapped(*args, **kwargs)
     27                     # this suppresses the original error message and raises your
     28                     # custom exception
---> 29                     raise ControlledException('Here is your error message!!') from None
     30
     31         return wrapped

ControlledException: Here is your error message!!


问:
Role is not authorized to perform DescribeStream on KinesisStream
I have 2 policies each for S3 and Kinesis stream which includes DescribeStream. The S3 policy works well but I am getting this error with KinesisPolicy.

Resources:

S3

KinesisStream

Firehose

Role:

FirehoseRole

Policies:

S3 policy with the following permissions:

```<code>      - 's3:AbortMultipartUpload'
      - 's3:GetBucketLocation'
      - 's3:GetObject'
      - 's3:ListBucket'
      - 's3:ListBucketMultipartUploads'
      - 's3:PutObject'
</code>```

Kinesis Policy with the following permissions:

```<code>      - 'kinesis:PutRecord'
      - 'kinesis:DescribeStreamSummary'
      - 'kinesis:PutRecords'
      - 'kinesis:GetShardIterator'
      - 'kinesis:GetRecords'
      - 'kinesis:DescribeStream'
</code>```

Error:

The role (firehoseRole) is not authorized to perform DescribeStream on MyKinesisStream.

Cloud formation template

```<code>Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      VersioningConfiguration:
        Status: Enabled

 firehoseRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: ''
            Effect: Allow
            Principal:
              Service: firehose.amazonaws.com
            Action: 'sts:AssumeRole'
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref 'AWS::AccountId'

  DeliveryPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: firehose_delivery_policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - 's3:AbortMultipartUpload'
              - 's3:GetBucketLocation'
              - 's3:GetObject'
              - 's3:ListBucket'
              - 's3:ListBucketMultipartUploads'
              - 's3:PutObject'
            Resource:
              - !Sub 'arn:aws:s3:::${S3Bucket}'
              - !Sub 'arn:aws:s3:::${S3Bucket}*'
      Roles:
        - !Ref firehoseRole

  KinesisPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: kinesis_policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - 'kinesis:PutRecord'
              - 'kinesis:DescribeStreamSummary'
              - 'kinesis:PutRecords'
              - 'kinesis:GetShardIterator'
              - 'kinesis:GetRecords'
              - 'kinesis:DescribeStream'
            Resource:
              - !GetAtt MyKinesisStream.Arn
      Roles:
        - !Ref firehoseRole

  MyKinesisStream:
    Type: AWS::Kinesis::Stream
    Properties:
      ShardCount: 1

  DeliveryStream:
    Type: AWS::KinesisFirehose::DeliveryStream
    Properties:
      DeliveryStreamType: KinesisStreamAsSource
      KinesisStreamSourceConfiguration:
        KinesisStreamARN: !GetAtt MyKinesisStream.Arn
        RoleARN: !GetAtt firehoseRole.Arn
      S3DestinationConfiguration:
        BucketARN: !GetAtt S3Bucket.Arn
        BufferingHints:
          IntervalInSeconds: 60
          SizeInMBs: 50
        CompressionFormat: UNCOMPRESSED
        Prefix: firehose/
        RoleARN: !GetAtt firehoseRole.Arn
</code>```

答: I was able to resolve the error. I had to add DependsOn To DeliveryStream and include both the policies. </p>

Body:
I have 2 policies each for S3 and Kinesis stream which includes DescribeStream. The S3 policy works well but I am getting this error with KinesisPolicy.

Resources:

S3

KinesisStream

Firehose

Role:

FirehoseRole

Policies:

S3 policy with the following permissions:

      - 's3:AbortMultipartUpload'
      - 's3:GetBucketLocation'
      - 's3:GetObject'
      - 's3:ListBucket'
      - 's3:ListBucketMultipartUploads'
      - 's3:PutObject'

Kinesis Policy with the following permissions:

      - 'kinesis:PutRecord'
      - 'kinesis:DescribeStreamSummary'
      - 'kinesis:PutRecords'
      - 'kinesis:GetShardIterator'
      - 'kinesis:GetRecords'
      - 'kinesis:DescribeStream'

Error:

The role (firehoseRole) is not authorized to perform DescribeStream on MyKinesisStream.

Cloud formation template

Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      VersioningConfiguration:
        Status: Enabled

 firehoseRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: ''
            Effect: Allow
            Principal:
              Service: firehose.amazonaws.com
            Action: 'sts:AssumeRole'
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref 'AWS::AccountId'

  DeliveryPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: firehose_delivery_policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - 's3:AbortMultipartUpload'
              - 's3:GetBucketLocation'
              - 's3:GetObject'
              - 's3:ListBucket'
              - 's3:ListBucketMultipartUploads'
              - 's3:PutObject'
            Resource:
              - !Sub 'arn:aws:s3:::${S3Bucket}'
              - !Sub 'arn:aws:s3:::${S3Bucket}*'
      Roles:
        - !Ref firehoseRole

  KinesisPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: kinesis_policy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - 'kinesis:PutRecord'
              - 'kinesis:DescribeStreamSummary'
              - 'kinesis:PutRecords'
              - 'kinesis:GetShardIterator'
              - 'kinesis:GetRecords'
              - 'kinesis:DescribeStream'
            Resource:
              - !GetAtt MyKinesisStream.Arn
      Roles:
        - !Ref firehoseRole

  MyKinesisStream:
    Type: AWS::Kinesis::Stream
    Properties:
      ShardCount: 1

  DeliveryStream:
    Type: AWS::KinesisFirehose::DeliveryStream
    Properties:
      DeliveryStreamType: KinesisStreamAsSource
      KinesisStreamSourceConfiguration:
        KinesisStreamARN: !GetAtt MyKinesisStream.Arn
        RoleARN: !GetAtt firehoseRole.Arn
      S3DestinationConfiguration:
        BucketARN: !GetAtt S3Bucket.Arn
        BufferingHints:
          IntervalInSeconds: 60
          SizeInMBs: 50
        CompressionFormat: UNCOMPRESSED
        Prefix: firehose/
        RoleARN: !GetAtt firehoseRole.Arn


问:
Camel Rest-DSL required param ignored
I have a Rest API, created with Camel Rest-DSL. There is a rest, that consumes GET with a list of params, some of which are mandatory.

Route config:

```<code>    rest().get("/{{camel.rest.version}}/myget")
            .param()
                .name("accountNumber")
                .dataType("string")
                .type(RestParamType.query)
                .required(true)
            .endParam()
            .param()
                .name("someId")
                .dataType("string")
                .type(RestParamType.query)
                .required(false)
            .endParam()
            .produces(REST_PR_CN_TYPE)
            .responseMessage().code("200").message("OK").endResponseMessage()
            .responseMessage().code("500").endResponseMessage()
            .route().routeId("rst_cardsInfo")
            .log(LoggingLevel.INFO, "ApiRq Recieved http request")
            .log(LoggingLevel.DEBUG, "AccountNumber: ${header.accountNumber}, SomeId: ${header.someId}")
            .id("rst_rst_info_recieved")
            .to("direct:drt_rst_info")
            .endRest();
</code>```

When I open swagger-ui generated page, my API is looks fine.  Param accountNumber is marked as required, someId - as not required.

Using any other tool I can send a request without any params and receive HTTP.200 as a response. I expected, that if a param is required, but not present in request, the request would fail. Spring Rest for example makes sure that all mandatory params are present.

Is there any mandatory params presence validation in Camel? May be I misconfigured something?

答:
Thank you, @Claus Ibsen.

From Camel 2.22 version onwards, now we can validate incoming client request.

The validation is turned off by default. In order to configure it, we need to use clientRequestValidation as follow :

```<code>restConfiguration()
    .component("restlet").host("localhost").port("port")
    .clientRequestValidation(true);
</code>```

For more details visit : Client Request Validation - Apache Camel Manual

Title: Camel Rest-DSL required param ignored

Body:
I have a Rest API, created with Camel Rest-DSL. There is a rest, that consumes GET with a list of params, some of which are mandatory.

Route config:

    rest().get("/{{camel.rest.version}}/myget")
            .param()
                .name("accountNumber")
                .dataType("string")
                .type(RestParamType.query)
                .required(true)
            .endParam()
            .param()
                .name("someId")
                .dataType("string")
                .type(RestParamType.query)
                .required(false)
            .endParam()
            .produces(REST_PR_CN_TYPE)
            .responseMessage().code("200").message("OK").endResponseMessage()
            .responseMessage().code("500").endResponseMessage()
            .route().routeId("rst_cardsInfo")
            .log(LoggingLevel.INFO, "ApiRq Recieved http request")
            .log(LoggingLevel.DEBUG, "AccountNumber: ${header.accountNumber}, SomeId: ${header.someId}")
            .id("rst_rst_info_recieved")
            .to("direct:drt_rst_info")
            .endRest();

When I open swagger-ui generated page, my API is looks fine.  Param accountNumber is marked as required, someId - as not required.

Using any other tool I can send a request without any params and receive HTTP.200 as a response. I expected, that if a param is required, but not present in request, the request would fail. Spring Rest for example makes sure that all mandatory params are present.

Is there any mandatory params presence validation in Camel? May be I misconfigured something?

Body:
Thank you, @Claus Ibsen.

From Camel 2.22 version onwards, now we can validate incoming client request.

The validation is turned off by default. In order to configure it, we need to use clientRequestValidation as follow :

restConfiguration()
    .component("restlet").host("localhost").port("port")
    .clientRequestValidation(true);

For more details visit : Client Request Validation - Apache Camel Manual


问:
Do i need to first request a real Ad to get the Device ID from the logcat so i can add a testdevice?
In the documentation it says you should add a test device this way.

But to get this ID from the logcat do i have to first Request a real ad? Isn't that against their own policy to request real ads?

Add your test device

Load your ads-integrated app and make an ad request. Check the logcat
output for a message that looks like the one
below, which shows you your device ID and how to add it as a test
device:

I/Ads: Use
AdRequest.Builder.addTestDevice("33BE2250B43518CCDA7DE426D04EE231") to
get test ads on this device."

答:
There are a) test ad units, which one can use and b) it knows when it is running in debug mode.

This message likely shows in the log before showing any ad unit, but when instancing the client.


问:
String value coming with two double quoted to .ts
If I given the normal value say hello in input field, it is coming like "hello", And if I have given the value like "hello", it is storing like ""hello"" . How to identify this two double quoted string and make it to one double quote .? </p>

答:
Without code, it is impossible to predict why the input field is adding double quotes to the value.

However, if you are using typescript or javascript, you can use the following to rectify the 2-double quotes issue:

```<code>let str = '""hello""';
if(str.startsWith("\"\"") && str.endsWith("\"\"")){
    str = str.substr(1,str.length-2);
  // str = str.replace(/\"\"/g, "\""); //Alternatively you can use this, if there will not be 2-double quotes in between your string
}
store(str);
</code>```

Body:
Without code, it is impossible to predict why the input field is adding double quotes to the value.

However, if you are using typescript or javascript, you can use the following to rectify the 2-double quotes issue:

let str = '""hello""';
if(str.startsWith("\"\"") && str.endsWith("\"\"")){
    str = str.substr(1,str.length-2);
  // str = str.replace(/\"\"/g, "\""); //Alternatively you can use this, if there will not be 2-double quotes in between your string
}
store(str);


问:
MERGE command results in gaps in sequence numbers
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

```<code>-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

```<code>INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);
</code>```

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.

答:
From the documentation, Snowflake does not guarantee generating sequence numbers with no gaps. Sequences will wrap around after reaching the maximum positive integer value for the data type.

You could try to use row_number() as a workaround
https://docs.snowflake.net/manuals/sql-reference/functions/row_number.html

Body:
I was trying to make use of the MERGE command for populating dimensions in Snowflake. To implement surrogate keys, I created a column defaulted to a sequence number that auto increments whenever a new row gets inserted. I tried a similar approach in other data warehousing platforms and it never caused any issues. However, I noticed that whenever I use the MERGE command in Snowflake, the sequence number increments for every single row processed by the MERGE command, regardless of whether it results in an UPDATE or INSERT operation.

The following is a simple example of what I'm referring to:

-- Sequence
CREATE OR REPLACE SEQUENCE seq1 START=1 INCREMENT=1;

-- Source table
CREATE OR REPLACE TABLE source_table
(
row_key int,
row_value string
);

-- Target table: Column ID uses the sequence
CREATE OR REPLACE TABLE target_table
(
id int DEFAULT seq1.nextval,
row_key int,
row_value string
);

-- Initial data
INSERT INTO source_table VALUES
(1,'One'),
(2,'Two'),
(3,'Three');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

After running these commands, the output table would contain these rows:

ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

Now, let's insert a new row and run the same merge command again:

INSERT INTO source_table VALUES
(4,'Four');

MERGE INTO target_table D
USING source_table s
ON D.row_key=s.row_key
WHEN MATCHED AND D.row_value!=s.row_value THEN UPDATE SET row_value=s.row_value
WHEN NOT MATCHED THEN INSERT(row_key,row_value) VALUES (s.row_key,s.row_value);

This time, the output of the table looks like this:
ID,ROW_KEY,ROW_VALUE

1,1,One

2,2,Two

3,3,Three

7,4,Four

If I insert another row, the next MERGE command will insert the new row with its ID set to 12 and the same goes on and on. It looks as if the MERGE command increments the sequence number for each row it reads from the source table, even if they don't end up being inserted into the target table at all.

Is this intentional behaviour? I tried the IDENTITY functionality instead of the sequence and it didn't change the output.

The workaround I came with was to replace the MERGE command with multiple UPDATE and INSERT statements instead, but I'm still keen to know the reason behind this behaviour.


问:
HTML a href alignment
Currently, this is my code:

```<code>@media (max-width: 500px) {
  a {
    text-align: left;
    font-size: 90%;
    float: left;
  }
}
</code>```

How do I align my hyperlink to the right side?

Currently, if I am using float:left, it will be stacked with my other element.

Example

Fixed with the code > "clear: both" .

答:
wish you had explained your problem better along with your HTML code. Anyway, you can use display flex that is much better than float. Or you can use text-align: right.
if you want them on one row, delete flex-direction.

.container{
  display: flex;
  align-items: flex-end;
  flex-direction: column;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  click

  click

  click
</div></code>```

Title: HTML a href alignment

Body:
Currently, this is my code:

@media (max-width: 500px) {
  a {
    text-align: left;
    font-size: 90%;
    float: left;
  }
}

How do I align my hyperlink to the right side?

Currently, if I am using float:left, it will be stacked with my other element.

Example

Fixed with the code > "clear: both" .

Body:
wish you had explained your problem better along with your HTML code. Anyway, you can use display flex that is much better than float. Or you can use text-align: right.
if you want them on one row, delete flex-direction.

.container{
  display: flex;
  align-items: flex-end;
  flex-direction: column;
}

<div class="container">
  <a href="#">click</a>

  <a href="#">click</a>

  <a href="#">click</a>
</div>


问:
What configuration do I need to get a Windows Service project to read and write from a SQLite database?
I previously had a working console application project that will read and write settings to a local SQLite database file.

Based on this project, I converted it to a windows service project by porting over the classes and use the ServiceBase class to create the the service.
However, each time I run the service, I keep getting an SqliteException with the Message SQLite Error 1: 'no such table: Settings'.

Using DB Browser for SQLite, I do see the table present in the database file so I am not sure what is going on.

I have tried testing with my own account using Windows Service, I have tried giving Local System access to my build folder for testing.

I am not sure if this helps but I have also included part of the DbContext file:

```<code>public class CDIContext : DbContext
{
    public DbSet<Setting> Settings { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlite("Data Source=ApplicationData.db");
    }
}

public class Setting
{
    [Key]
    public Int32 Id { get; set; }
    [Required]
    public Int64 LastUpdateEpochUTC { get; set; }
}
</code>```

答:
Found out that the Windows Service Working directory is located in either:
C:\Windows\System32 or C:\Windows\SysWOW64 and not my application directory

What directory does a Windows Service run in?

As such, my database files were being searched in those directories instead of the application directory.

Will take @ErikEJ advice and change to a full path.

Body:
I previously had a working console application project that will read and write settings to a local SQLite database file.

Based on this project, I converted it to a windows service project by porting over the classes and use the ServiceBase class to create the the service.
However, each time I run the service, I keep getting an SqliteException with the Message SQLite Error 1: 'no such table: Settings'.

Using DB Browser for SQLite, I do see the table present in the database file so I am not sure what is going on.

I have tried testing with my own account using Windows Service, I have tried giving Local System access to my build folder for testing.

I am not sure if this helps but I have also included part of the DbContext file:

public class CDIContext : DbContext
{
    public DbSet<Setting> Settings { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlite("Data Source=ApplicationData.db");
    }
}

public class Setting
{
    [Key]
    public Int32 Id { get; set; }
    [Required]
    public Int64 LastUpdateEpochUTC { get; set; }
}


问:
React - Display loading screen while DOM is rendering?
This is an example from the Google AdSense application page. The loading screen is displayed before the main page is shown.

I am not sure how to achieve the same effect with React because if I render the loading screen as a React component, it will not be displayed while the page is loading as it needs to wait for the DOM to be rendered first.

Updated:

As a solution, I tried an approach where I placed the screen loader in index.html file and removed it in the componentDidMount() lifecycle method of React component.

Example and react-loading-screen.

答:
I also used @Ori Drori's answer and managed to get it to work. As your React code grows, so will the bundles compiled that the client browser will have to download on first time access. This imposes a user experience issue if you don't handle it well.

What I added to @Ori answer was to add and execute the onload function in the index.html on onload attribute of the body tag, so that the loader disappear after everything has been fully loaded in the browse, see the snippet below:

```<code><html>
  <head>
     <style>
       .loader:empty {
          position: absolute;
          top: calc(50% - 4em);
          left: calc(50% - 4em);
          width: 6em;
          height: 6em;
          border: 1.1em solid rgba(0, 0, 0, 0.2);
          border-left: 1.1em solid #000000;
          border-radius: 50%;
          animation: load8 1.1s infinite linear;
        }
        @keyframes load8 {
          0% {
           transform: rotate(0deg);
          }
          100% {
           transform: rotate(360deg);
          }
        }
     </style>
     <script>
       function onLoad() {
         var loader = document.getElementById("cpay_loader");loader.className = "";}
     </script>
   </head>
   <body onload="onLoad();">
     more html here.....
   </body>
</html>
</code>```

Body:
I also used @Ori Drori's answer and managed to get it to work. As your React code grows, so will the bundles compiled that the client browser will have to download on first time access. This imposes a user experience issue if you don't handle it well.

What I added to @Ori answer was to add and execute the onload function in the index.html on onload attribute of the body tag, so that the loader disappear after everything has been fully loaded in the browse, see the snippet below:

<html>
  <head>
     <style>
       .loader:empty {
          position: absolute;
          top: calc(50% - 4em);
          left: calc(50% - 4em);
          width: 6em;
          height: 6em;
          border: 1.1em solid rgba(0, 0, 0, 0.2);
          border-left: 1.1em solid #000000;
          border-radius: 50%;
          animation: load8 1.1s infinite linear;
        }
        @keyframes load8 {
          0% {
           transform: rotate(0deg);
          }
          100% {
           transform: rotate(360deg);
          }
        }
     </style>
     <script>
       function onLoad() {
         var loader = document.getElementById("cpay_loader");loader.className = "";}
     </script>
   </head>
   <body onload="onLoad();">
     more html here.....
   </body>
</html>


问:
Python selecting closest negative and positive values to zero from a list
I have many lists. Each list constains three floats. I need to select a negative and positive closest to zero from each list.
Here is the example:

```<code>list1= [-18.987536121749894, 9.154936510174036, -4.626424654409895]
list2= [-4.626424654409895, 9.154936510174036, 2.355498340416582]
list3= [-0.5, 0.1, 0.005]
</code>```

My expected output:

```<code>list1_op= [-4.626424654409895, 9.154936510174036]
list2_op= [-4.626424654409895, 2.355498340416582]
list3_op= [-0.5, 0.005]
</code>```

My code:

```<code>while loop:
     ...
     ...
    pdif = fun(mf1,mf2,mf3)   # mf1 and mf2 are extreme points, mf3 is middle point between them
    asign = np.sign(pdif) # check for sign change in Pdif list
    signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
    print(pdif)
    if abs(pdif[2])<0.01:
        print("Optimal point reached")
        break
    else:
        if signchange.sum()>0: # If yes then there is a merging point
            if (pdif[2]<abs(pdif[0]))&(signchange[1]==1):
                mf1 = mf3
            elif (pdif[2]<abs(pdif[1]))&(signchange[2]==1):
                mf2 = mf3
            mf3 = np.array([mf1,mf2]).mean()
</code>```

I have no idea how to start.

答:
```<code>output_list = [None]*len(lists)

for i in len(lists):
    list = lists[i]
    smallest_positive = list[list>0].min()
    biggest_negative = list[list<0].max()
    output_list[i] = (smallest_positive, biggest_negative)
return output_list
</code>```

Body:
I have many lists. Each list constains three floats. I need to select a negative and positive closest to zero from each list.
Here is the example:

list1= [-18.987536121749894, 9.154936510174036, -4.626424654409895]
list2= [-4.626424654409895, 9.154936510174036, 2.355498340416582]
list3= [-0.5, 0.1, 0.005]

My expected output:

list1_op= [-4.626424654409895, 9.154936510174036]
list2_op= [-4.626424654409895, 2.355498340416582]
list3_op= [-0.5, 0.005]

My code:

while loop:
     ...
     ...
    pdif = fun(mf1,mf2,mf3)   # mf1 and mf2 are extreme points, mf3 is middle point between them
    asign = np.sign(pdif) # check for sign change in Pdif list
    signchange = ((np.roll(asign, 1) - asign) != 0).astype(int)
    print(pdif)
    if abs(pdif[2])<0.01:
        print("Optimal point reached")
        break
    else:
        if signchange.sum()>0: # If yes then there is a merging point
            if (pdif[2]<abs(pdif[0]))&(signchange[1]==1):
                mf1 = mf3
            elif (pdif[2]<abs(pdif[1]))&(signchange[2]==1):
                mf2 = mf3
            mf3 = np.array([mf1,mf2]).mean()

I have no idea how to start.


问:
Is there replacement for cat on Windows
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

答:
Shameless PowerShell plug (because I think the learning curve is a pain, so teaching something at any opportunity can help)

```<code>Get-Content file1,file2
</code>```

Note that type is an alias for Get-Content, so if you like it better, you can write:

```<code>type file1,file2
</code>```

OwnerDisplayName: Artem Tikhomirov

Title: Is there replacement for cat on Windows

LastEditorDisplayName: Greg Hewgill

Body:
Shameless PowerShell plug (because I think the learning curve is a pain, so teaching something at any opportunity can help)

Get-Content file1,file2

Note that type is an alias for Get-Content, so if you like it better, you can write:

type file1,file2

OwnerDisplayName: Jay Bazuzi

ContentLicense: CC BY-SA 2.5


问:
ThreadAbortException vs graceful event handle exit in C#
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

```<code>int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();
</code>```

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

```<code>try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}
</code>```

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

答:
If I can I try to avoid using Thread.Abort.
The problem with Thread.Abort is that it could happen in (almost) any line of the executing code and might cause some "interesting" behavior (read: bugs).
Intead I prefer to have a point of exit on my code that checks for an event or variable to see if it the thread should stop running and gracefully exit.</p>

OwnerDisplayName: Jorge Córdoba

Body:
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

OwnerDisplayName: Dror Helper


问:
Releasing variables but app still leaking memory and crashing
When my app loads for the first time, it loads data from several text files into a SQLite database. There is a lot of data so I have slit the file up into several smaller files and I load the data in a loop using the code below. I release each variable on each pass and write to NSLog to record the memory state at the time. Even though I am releasing the variables the memory is reducing and I receive memory warning, level 1 & 2 and then the app shuts down. Could it be that adding data to the SQLite table is causing the memory to reduce or have I missed something in my code?</p>

```<code>while (filePathNo != @"7") {
  NSString *filePath;
  NSString *GenericName = nil;
      .
      .
      // Nineteen Other Variables
      .
      .
  if (filePathNo == @"1") {
        filePath = [[NSBundle mainBundle] pathForResource:@"FileLoad1" ofType:@"txt"];
        filePathNo = @"2";
  }
      else if (filePathNo == @"2") {
        filePath = [[NSBundle mainBundle] pathForResource:@"FileLoad2" ofType:@"txt"];
        filePathNo = @"3";
  }
      .
      .
      // Five Other Files declared
  .
      .

  NSString *textFromFile = [NSString stringWithContentsOfFile:filePath];

  NSString *cellString = textFromFile;
  NSRange range2 = [cellString rangeOfString:@"<string>"];
  range2 = [cellString rangeOfString:@"<string>"];
  if (range2.location != NSNotFound ) {
      eof = @"N";
      cellString = [cellString substringFromIndex:range2.location + 8];
  }

  while (eof != @"Y") {
    NSLog(@"Drug is - %@ , Memory free is  %d", GenericName, [self get_freemem]);
    progVal = progval + 1;
    [self performSelectorOnMainThread:@selector(updateMyProgressBar) withObject:nil waitUntilDone:NO];
    NSRange range1 = [cellString rangeOfString:@"#"];
    if (range1.location != NSNotFound )
        GenericName = [cellString substringToIndex:range1.location];
    cellString = [cellString substringFromIndex:range1.location + 1];
            .
            .
            //  Find and load nineteen other variables
            .
            .
            range2 = [cellString rangeOfString:@"</string>"];
        if (range2.location != NSNotFound )
        Doses = [cellString substringToIndex:range2.location];
    cellString = [cellString substringFromIndex:range2.location + 9];
    range2 = [cellString rangeOfString:@"<string>"];
    if (range2.location != 0 ) {
        eof = @"N";
        @try {
            cellString = [cellString substringFromIndex:range2.location + 8];
        }
        @catch (NSException *exception) {
            eof = @"Y";
        }
    }
    else {
        eof = @"Y";
    }
    if (cellString == nil) {
        eof = @"Y";
    }

    NSString *spkrs = @"";
    char *errorMsg;
    char *update = "INSERT OR REPLACE INTO DRUGTABLE (FullDrugName, GenericName, OtherNames, TradeName, PrescriptionStatus, Formulations, DrugAction, DrugUse, SafetyAndHandling, Contraindications, AdverseReactions, DrugInteractions, Therapeuticgroup, GeneralAction, SpecificAction, ChemicalGroup, DrugReferences, Furtherreading, Doses) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
    //int errVal = sqlite3_prepare_v2(database, update, -1, &stmt, nil);
    if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK);
    {

        sqlite3_bind_text(stmt, 1, [FullDrugName  UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [GenericName UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [OtherNames UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [TradeName UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5, [PrescriptionStatus UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 6, [Formulations UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 7, [DrugAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 8, [DrugUse UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 9, [SafetyAndHandling UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 10, [Contraindications UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 11, [AdverseReactions UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 12, [DrugInteractions UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 13, [Therapeuticgroup UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 14, [GeneralAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 15, [SpecificAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 16, [ChemicalGroup UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 17, [References UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 18, [FurtherReading UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 19, [Doses UTF8String], -1, NULL);
    }
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        NSString *err = errorMsg;
    }
    sqlite3_finalize(stmt);
    [spkrs release];
  }
  [GenericName release];
  .
      .
      // Release all nineteen other variables
      .
      .
}
</code>```

答:
Try to use Instruments to track how your allocations are accumulating while doing the import.  I agree with Anders K. about utilizing the autorelease pool and then draining it periodically.

Also agree with Mr. Berna, create the database and then add it to your project, making sure that it is added to your Target and app bundle.

There is a good snippet of code in here that you can adapt that shows how to make the database available to your app at launch time.  It looks for the database in the default location, if it can't find it, it will copy it from your bundle.

Body:
When my app loads for the first time, it loads data from several text files into a SQLite database. There is a lot of data so I have slit the file up into several smaller files and I load the data in a loop using the code below. I release each variable on each pass and write to NSLog to record the memory state at the time. Even though I am releasing the variables the memory is reducing and I receive memory warning, level 1 & 2 and then the app shuts down. Could it be that adding data to the SQLite table is causing the memory to reduce or have I missed something in my code?

while (filePathNo != @"7") {
  NSString *filePath;
  NSString *GenericName = nil;
      .
      .
      // Nineteen Other Variables
      .
      .
  if (filePathNo == @"1") {
        filePath = [[NSBundle mainBundle] pathForResource:@"FileLoad1" ofType:@"txt"];
        filePathNo = @"2";
  }
      else if (filePathNo == @"2") {
        filePath = [[NSBundle mainBundle] pathForResource:@"FileLoad2" ofType:@"txt"];
        filePathNo = @"3";
  }
      .
      .
      // Five Other Files declared
  .
      .

  NSString *textFromFile = [NSString stringWithContentsOfFile:filePath];

  NSString *cellString = textFromFile;
  NSRange range2 = [cellString rangeOfString:@"<string>"];
  range2 = [cellString rangeOfString:@"<string>"];
  if (range2.location != NSNotFound ) {
      eof = @"N";
      cellString = [cellString substringFromIndex:range2.location + 8];
  }

  while (eof != @"Y") {
    NSLog(@"Drug is - %@ , Memory free is  %d", GenericName, [self get_freemem]);
    progVal = progval + 1;
    [self performSelectorOnMainThread:@selector(updateMyProgressBar) withObject:nil waitUntilDone:NO];
    NSRange range1 = [cellString rangeOfString:@"#"];
    if (range1.location != NSNotFound )
        GenericName = [cellString substringToIndex:range1.location];
    cellString = [cellString substringFromIndex:range1.location + 1];
            .
            .
            //  Find and load nineteen other variables
            .
            .
            range2 = [cellString rangeOfString:@"</string>"];
        if (range2.location != NSNotFound )
        Doses = [cellString substringToIndex:range2.location];
    cellString = [cellString substringFromIndex:range2.location + 9];
    range2 = [cellString rangeOfString:@"<string>"];
    if (range2.location != 0 ) {
        eof = @"N";
        @try {
            cellString = [cellString substringFromIndex:range2.location + 8];
        }
        @catch (NSException *exception) {
            eof = @"Y";
        }
    }
    else {
        eof = @"Y";
    }
    if (cellString == nil) {
        eof = @"Y";
    }

    NSString *spkrs = @"";
    char *errorMsg;
    char *update = "INSERT OR REPLACE INTO DRUGTABLE (FullDrugName, GenericName, OtherNames, TradeName, PrescriptionStatus, Formulations, DrugAction, DrugUse, SafetyAndHandling, Contraindications, AdverseReactions, DrugInteractions, Therapeuticgroup, GeneralAction, SpecificAction, ChemicalGroup, DrugReferences, Furtherreading, Doses) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
    //int errVal = sqlite3_prepare_v2(database, update, -1, &stmt, nil);
    if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK);
    {

        sqlite3_bind_text(stmt, 1, [FullDrugName  UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [GenericName UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [OtherNames UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [TradeName UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5, [PrescriptionStatus UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 6, [Formulations UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 7, [DrugAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 8, [DrugUse UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 9, [SafetyAndHandling UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 10, [Contraindications UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 11, [AdverseReactions UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 12, [DrugInteractions UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 13, [Therapeuticgroup UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 14, [GeneralAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 15, [SpecificAction UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 16, [ChemicalGroup UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 17, [References UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 18, [FurtherReading UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 19, [Doses UTF8String], -1, NULL);
    }
    if (sqlite3_step(stmt) != SQLITE_DONE)
    {
        NSString *err = errorMsg;
    }
    sqlite3_finalize(stmt);
    [spkrs release];
  }
  [GenericName release];
  .
      .
      // Release all nineteen other variables
      .
      .
}


问:
Find partial key and their value from Map<String, String> in java
I've this map key value pair as :

```<code>{$skip=28, $landingPageURL=https://www.example.com, $gtmCount=gtmMPCL, $url=mpclProd, $trackingJson=mpclNonAmpTracking.json, $portalCD=portal_CD_MPCL}
</code>```

and I need to findout the key as  $landingPageURL?utm_medium=lp_automation from the above map. So, my final output should be for **$landingPageURL?utm_medium=lp_automation** as https://www.example.com?utm_medium=lp_automation (because $landingPageURL is replaced with above map).

How do I achieve this with condition something like

```<code>if(map.partialcontainskey(keyname) so, as example, it should conditionally check if
$landingPageURL.partialcontainskey($landingPageURL?utm_medium=lp_automation).
</code>```

how do i achieve this. Your help is appreciated.

答:
If your input is following

```<code>String input = landingPageURL?utm_medium=lp_automation;
</code>```

You can split the input string and get the required key as follows:

```<code>String[] urlComponents = input.split("?");
String key = urlComponents[0];
String queryString = urlComponents[1];
</code>```

And finally you can generate your output as follows:

```<code>String output = map.get(key)+"?"+queryString;
</code>```

Body:
I've this map key value pair as :

{$skip=28, $landingPageURL=https://www.example.com, $gtmCount=gtmMPCL, $url=mpclProd, $trackingJson=mpclNonAmpTracking.json, $portalCD=portal_CD_MPCL}

and I need to findout the key as  $landingPageURL?utm_medium=lp_automation from the above map. So, my final output should be for **$landingPageURL?utm_medium=lp_automation** as https://www.example.com?utm_medium=lp_automation (because $landingPageURL is replaced with above map).

How do I achieve this with condition something like

if(map.partialcontainskey(keyname) so, as example, it should conditionally check if
$landingPageURL.partialcontainskey($landingPageURL?utm_medium=lp_automation).

how do i achieve this. Your help is appreciated.

Body:
If your input is following

String input = landingPageURL?utm_medium=lp_automation;

You can split the input string and get the required key as follows:

String[] urlComponents = input.split("?");
String key = urlComponents[0];
String queryString = urlComponents[1];

And finally you can generate your output as follows:

String output = map.get(key)+"?"+queryString;


问:
Flutter - Handler != null is not true
Can anyone explain me this error log

```<code>Another exception was thrown: 'package:flutter/src/semantics/semantics.dart': Failed assertion: line 2847 pos 12: 'handler != null': is not true
</code>```

It does not affect in any screen but this does keep coming when I change child of a certain controller through setState((){}).

Thanks for your help,

答: You need to pass a String to the Text constructor</p>

Title: Flutter - Handler != null is not true

Body:
Can anyone explain me this error log

Another exception was thrown: 'package:flutter/src/semantics/semantics.dart': Failed assertion: line 2847 pos 12: 'handler != null': is not true

It does not affect in any screen but this does keep coming when I change child of a certain controller through setState((){}).

Thanks for your help,


问:
Heroku Deployment Continues to Fail at "Pruning devDependencies" Step
I continue to have issues deploying to Heroku and I can't find out what is going wrong for the life of me. The Heroku error log tells me this after it successfully builds my react app:

```<code>-----> Caching build
       - node_modules

-----> Pruning devDependencies
       npm ERR! Cannot read property 'match' of undefined
</code>```

Here is my package.json

```<code>{
  "name": "test",
  "version": "1.0.0",
  "homepage": "./",
  "description": "test",
  "main": "server.js",
  "node": "v12.13.1",
  "npm": "6.13.7",
  "scripts": {
    "heroku": "node server.js",
    "client-install": "npm install --prefix client",
    "build": "cd client && react-scripts build",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "author": "John Doe",
  "license": "MIT",
  "dependencies": {
    "@material-ui/core": "^4.8.0",
    "axios": "^0.19.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.18.3",
    "classnames": "^2.2.6",
    "concurrently": "^5.1.0",
    "date-fns": "^2.8.1",
    "debug": "^4.1.1",
    "depcheck": "^0.9.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "express": "^4.16.4",
    "fibers": "^4.0.2",
    "growl": "^1.10.5",
    "heroku": "^7.35.1",
    "history": "^4.10.1",
    "is-empty": "^1.2.0",
    "jquery": "^3.4.1",
    "jsonwebtoken": "^8.3.0",
    "jwt-decode": "^2.2.0",
    "material-table": "^1.54.2",
    "material-ui": "^0.20.2",
    "minimatch": "^3.0.4",
    "moment": "^2.23.0",
    "mongodb": "^3.5.3",
    "mongoose": "^5.8.9",
    "mongoose-global": "^1.0.1",
    "morgan": "^1.9.1",
    "node-sass": "^4.13.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "plaid": "^4.6.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-ga": "^2.7.0",
    "react-plaid-link-button": "0.0.4",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^3.3.0",
    "react-slick": "^0.25.2",
    "react-stripe-elements": "^6.0.1",
    "react-vis": "^1.11.7",
    "redux-thunk": "^2.3.0",
    "sass": "^1.24.0",
    "slick": "^1.12.2",
    "slick-carousel": "^1.8.1",
    "typescript": "^3.7.4",
    "update-mongo": "0.0.4",
    "validator": "^12.2.0",
    "vis": "^4.21.0-EOL"
  },
  "devDependencies": {},
  "engines": {
    "node": "12.x"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

What is perhaps most frustrating, is that I was able to deploy successfully once the other day but I am not sure what changed. Going back through my git I can't see anything that would have made any difference.

Things I have tried:

removing package.json

adding "devDependencies": {} to my    package.json (although I
deployed successfully without it)

updating node and adding the engines section to my package.json to
match.

running npm prune locally

ensuring that all packages are updated and referenced appropriately in package.json

Things that I suspect could be the issue:

Maybe somehow the current version of my app that is actively deployed on heroku is interfering with my new deployment? That being said i have tried scaling down dynos and deploying. Additionally the npm ERR! Cannot read property 'match' of undefined seems to indicate something else?

答:
In the scripts section in package.json, only keep the start key and remove others.

Your scripts in the package.json should be,

```<code>"scripts": {
    "start": "node server.js"
  },
</code>```

Also before deployment, build the react app manually.

Heroku messed up with all these build scripts.

Body:
I continue to have issues deploying to Heroku and I can't find out what is going wrong for the life of me. The Heroku error log tells me this after it successfully builds my react app:

-----> Caching build
       - node_modules

-----> Pruning devDependencies
       npm ERR! Cannot read property 'match' of undefined

Here is my package.json

{
  "name": "test",
  "version": "1.0.0",
  "homepage": "./",
  "description": "test",
  "main": "server.js",
  "node": "v12.13.1",
  "npm": "6.13.7",
  "scripts": {
    "heroku": "node server.js",
    "client-install": "npm install --prefix client",
    "build": "cd client && react-scripts build",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "author": "John Doe",
  "license": "MIT",
  "dependencies": {
    "@material-ui/core": "^4.8.0",
    "axios": "^0.19.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.18.3",
    "classnames": "^2.2.6",
    "concurrently": "^5.1.0",
    "date-fns": "^2.8.1",
    "debug": "^4.1.1",
    "depcheck": "^0.9.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "express": "^4.16.4",
    "fibers": "^4.0.2",
    "growl": "^1.10.5",
    "heroku": "^7.35.1",
    "history": "^4.10.1",
    "is-empty": "^1.2.0",
    "jquery": "^3.4.1",
    "jsonwebtoken": "^8.3.0",
    "jwt-decode": "^2.2.0",
    "material-table": "^1.54.2",
    "material-ui": "^0.20.2",
    "minimatch": "^3.0.4",
    "moment": "^2.23.0",
    "mongodb": "^3.5.3",
    "mongoose": "^5.8.9",
    "mongoose-global": "^1.0.1",
    "morgan": "^1.9.1",
    "node-sass": "^4.13.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "plaid": "^4.6.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-ga": "^2.7.0",
    "react-plaid-link-button": "0.0.4",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^3.3.0",
    "react-slick": "^0.25.2",
    "react-stripe-elements": "^6.0.1",
    "react-vis": "^1.11.7",
    "redux-thunk": "^2.3.0",
    "sass": "^1.24.0",
    "slick": "^1.12.2",
    "slick-carousel": "^1.8.1",
    "typescript": "^3.7.4",
    "update-mongo": "0.0.4",
    "validator": "^12.2.0",
    "vis": "^4.21.0-EOL"
  },
  "devDependencies": {},
  "engines": {
    "node": "12.x"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

What is perhaps most frustrating, is that I was able to deploy successfully once the other day but I am not sure what changed. Going back through my git I can't see anything that would have made any difference.

Things I have tried:

removing package.json

adding "devDependencies": {} to my    package.json (although I
deployed successfully without it)

updating node and adding the engines section to my package.json to
match.

running npm prune locally

ensuring that all packages are updated and referenced appropriately in package.json

Things that I suspect could be the issue:

Maybe somehow the current version of my app that is actively deployed on heroku is interfering with my new deployment? That being said i have tried scaling down dynos and deploying. Additionally the npm ERR! Cannot read property 'match' of undefined seems to indicate something else?

Body:
In the scripts section in package.json, only keep the start key and remove others.

Your scripts in the package.json should be,

"scripts": {
    "start": "node server.js"
  },

Also before deployment, build the react app manually.

Heroku messed up with all these build scripts.


问:
Oracle 12c - RMAN report unrecoverable
I am having trouble checking my Oracle backups with RMAN.
The "report need backup" command does not display anything, which means that there is no problem ; but the command "report unrecoverable" asks me to do another backup :

```<code>RMAN> report need backup;

RMAN retention policy will be applied to the command
RMAN retention policy is set to recovery window of 7 days
Report of files that must be backed up to satisfy 7 days recovery window
File Days  Name
---- ----- -----------------------------------------------------
</code>```

and

```<code>RMAN> report unrecoverable;

Report of files that need backup due to unrecoverable operations
File Type of Backup Required Name
---- ----------------------- -----------------------------------
45   full or incremental     /u01/app/oracle/oradata/orcl/data_ts3_01.dbf
</code>```

How can I solve this problem ?

Thank you in advance

答:
According to Oracle doc "report unrecoverable;" will list: "Lists all data files for which an unrecoverable operation has been performed against an object in the data file since the last backup of the data file."
In other word, the instance doesn't have enough redo log to recover datafile. There are some missing redo and most of them take place when a non-logging operation has been specified (to speed up operation) using nologging clause.

The solution is to enable force-logging at database level.

Title: Oracle 12c - RMAN report unrecoverable

Body:
I am having trouble checking my Oracle backups with RMAN.
The "report need backup" command does not display anything, which means that there is no problem ; but the command "report unrecoverable" asks me to do another backup :

RMAN> report need backup;

RMAN retention policy will be applied to the command
RMAN retention policy is set to recovery window of 7 days
Report of files that must be backed up to satisfy 7 days recovery window
File Days  Name
---- ----- -----------------------------------------------------

and

RMAN> report unrecoverable;

Report of files that need backup due to unrecoverable operations
File Type of Backup Required Name
---- ----------------------- -----------------------------------
45   full or incremental     /u01/app/oracle/oradata/orcl/data_ts3_01.dbf

How can I solve this problem ?

Thank you in advance


问:
Show view when toolbar collapses
I have an activity with a CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout and Toolbar. So, basically, a view that collapses when scrolling a RecyclerView.

What I need to do is to show a custom view when the view of the expanded layout is hidden due to collapsing.

This is my layout:

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="192dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="#2196F3"
            app:expandedTitleMarginBottom="32dp"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <include
                android:id="@+id/header"
                layout="@layout/header_big_first_screen"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.CollapsingToolbarLayout
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

                <TextView

                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="Hello!"/>

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

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/categories_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

In the end, when the toolbar is expanded the view loaded with the  element is shown. When it is collapsed it doesn't . When it disappears the TextView inside Toolbarshould be shown. Currently it shows all the time.

I've been looking in the events of CollapsingToolbarLayout to add a listener when it changes size so I can check if that is smaller than a value and show that view.

This can be kind of tricky to explain but I believe I made myself clear. I've been googling around and cannot find anyone trying to do the same.

答:
Instead of trying to replicate when the scrim is supposed to show (collapsed) or not (expanded), a better way is to override the setScrimsShown method, which is called every time inside the CollapsingToolbarLayout's onOffsetChanged, and add a listener to it like this:

```<code>public class CollapsingToolbarLayoutWithScrimListener extends CollapsingToolbarLayout {

    public CollapsingToolbarLayoutWithScrimListener(Context context) {
        super(context);
    }

    public CollapsingToolbarLayoutWithScrimListener(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CollapsingToolbarLayoutWithScrimListener(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context,attrs,defStyleAttr);
    }

    private ScrimListener scrimListener = null;

    @Override
    public void setScrimsShown(boolean shown, boolean animate) {
        super.setScrimsShown(shown, animate);
        if (scrimListener != null)
            scrimListener.onScrimShown(shown);
    }

    public void setScrimListener(ScrimListener listener) {
        scrimListener = listener;
    }

    public interface ScrimListener {

        void onScrimShown(boolean shown);
    }
}
</code>```

Title: Show view when toolbar collapses

Body:
I have an activity with a CoordinatorLayout, AppBarLayout, CollapsingToolbarLayout and Toolbar. So, basically, a view that collapses when scrolling a RecyclerView.

What I need to do is to show a custom view when the view of the expanded layout is hidden due to collapsing.

This is my layout:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="192dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            app:contentScrim="#2196F3"
            app:expandedTitleMarginBottom="32dp"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <include
                android:id="@+id/header"
                layout="@layout/header_big_first_screen"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"/>

            <android.support.v7.widget.CollapsingToolbarLayout
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

                <TextView

                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="Hello!"/>

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

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/categories_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

In the end, when the toolbar is expanded the view loaded with the  element is shown. When it is collapsed it doesn't . When it disappears the TextView inside Toolbarshould be shown. Currently it shows all the time.

I've been looking in the events of CollapsingToolbarLayout to add a listener when it changes size so I can check if that is smaller than a value and show that view.

This can be kind of tricky to explain but I believe I made myself clear. I've been googling around and cannot find anyone trying to do the same.

Body:
Instead of trying to replicate when the scrim is supposed to show (collapsed) or not (expanded), a better way is to override the setScrimsShown method, which is called every time inside the CollapsingToolbarLayout's onOffsetChanged, and add a listener to it like this:

public class CollapsingToolbarLayoutWithScrimListener extends CollapsingToolbarLayout {

    public CollapsingToolbarLayoutWithScrimListener(Context context) {
        super(context);
    }

    public CollapsingToolbarLayoutWithScrimListener(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CollapsingToolbarLayoutWithScrimListener(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context,attrs,defStyleAttr);
    }

    private ScrimListener scrimListener = null;

    @Override
    public void setScrimsShown(boolean shown, boolean animate) {
        super.setScrimsShown(shown, animate);
        if (scrimListener != null)
            scrimListener.onScrimShown(shown);
    }

    public void setScrimListener(ScrimListener listener) {
        scrimListener = listener;
    }

    public interface ScrimListener {

        void onScrimShown(boolean shown);
    }
}


问:
Differing state in select input and dynamic url in React
I have a select input pulling JSON data of Japanese prefectures using React.  Users select prefectures by name.

The select input value is set as state.prefecture, which calls "Tokyo", for example. I'm mapping this data to the select options from a local JSON file.

In the dynamic URL JSON fetch call ${state.prefecture}, I need the prefectural code instead of the name, "13" in the case of Tokyo.

Is there a good way of doing this?

答:
Once you map your data to the select options from a local JSON file, at that point you can store prefectural code for that particular value into some other variable using {this.state.prefecture.id} as per your API data.

Then use that data for the fetch call lets say by ${this.state.prefecture.id}.


问:
How to display radio buttons as

I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

```<code><div class="radio-toolbar">
    <table>
        <tr>
            <td><input type="radio" id="radioone" name="product" value="first">
                <label for="radioone">50</label></td>

            <td><input type="radio" id="radiotwo" name="product" value="second">
                <label for="radiotwo">100</label></td>

            <td><input type="radio" id="radiothree" name="product" value="third">
                <label for="radiothree">500</label></td>
</div>
</code>```

CSS

```<code>.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}
</code>```

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

答:
You need to hide the radio buttons and the left over label is still "clickable"

```<code>.radio-toolbar input[type="radio"] {
  display: none;
}
</code>```

I put all the working code on codepen here: https://codepen.io/stormingorman-the-vuer/pen/ExjKRvz

Title: How to display radio buttons as <div>

Body:
I want to display my radio buttons as  so that i can give style sheet and make div clickable.

here are my radio buttons.

and I want to show them like this.

div as radio

This is what I have tried but did not work.

HTML

            <input type="radio" id="radioone" name="product" value="first">
                50

            <input type="radio" id="radiotwo" name="product" value="second">
                100

            <input type="radio" id="radiothree" name="product" value="third">
                500

CSS

.radio-toolbar input[type='radio']:focus + label {
  border: 2px thin blue;
}
.radio-toolbar input[type='radio']:checked + label {
  background-color: #86b1f7;
  border-color: #4c4;
  color: white;
}

So how can I achive this
Small help will be appreciated.
Thanks in advance :)

Body:
You need to hide the radio buttons and the left over label is still "clickable"

.radio-toolbar input[type="radio"] {
  display: none;
}

I put all the working code on codepen here: https://codepen.io/stormingorman-the-vuer/pen/ExjKRvz


问:
how to add duration time on google map draw path?
I able to draw path from source to destination it's working fine. but now I looking add to duration on path like google or ubar. tried but my duration marker little  bit away from drawer path.

```<code>let path = GMSPath(fromEncodedPath:objMapModel.arrayMapPath[0].routes.first?.overviewPolyline.points ?? "")
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 5.0
marker.map = mapView
rectangle.map = mapView
</code>```

I am looking something like this image. I want to add marker on path with duration time(ex 27h)

here is image more details

答:
The duration time is also given by google API response and the parameter is like this and it's call  estimated time.

```<code>       "duration" : {
          "text" : "27 mins",
          "value" : 1615
         },
</code>```

Body:
I able to draw path from source to destination it's working fine. but now I looking add to duration on path like google or ubar. tried but my duration marker little  bit away from drawer path.

let path = GMSPath(fromEncodedPath:objMapModel.arrayMapPath[0].routes.first?.overviewPolyline.points ?? "")
let rectangle = GMSPolyline(path: path)
rectangle.strokeWidth = 5.0
marker.map = mapView
rectangle.map = mapView

I am looking something like this image. I want to add marker on path with duration time(ex 27h)

here is image more details

Body:
The duration time is also given by google API response and the parameter is like this and it's call  estimated time.

       "duration" : {
          "text" : "27 mins",
          "value" : 1615
         },