问:
Extract ONLY THE FIRST match from Word doc using RegEx lunched from Excel VBA
There is a document like this one. I process 20 documents like this every day and they all look the same (structure, I mean, is very consistent).

The goal of this macro is to extract ONLY THE FIRST match of the RegEx pattern from the .ActiveDocument.Content. In the whole doc there is many more matches, but I need only the first one. The document being processed will be manually opened before the macro would run.

I'm just a VBA beginner so if there is a possibility to write it without using arrays, collections or some dictionaries I'd much appreciate. There is just one item to extract, so it's best to load it inside repNmbr string variable and from there just ws.Range("G30").Value = repNmbr. The simpler the better.

I used these resources Excel Regex Tutorial (Regular Expressions) which is very helpful but I still don't know how to load the FIRST MATCH alone into my repNmbr string variable. I'd like to do this without using any loop, because I just want to load a single string into this repNmbr variable.

Currently I have code like this:

```<code>Sub ExtractRepertor03()
    'Application.ScreenUpdating = False
    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim ExcelApp As Excel.Application
    Dim rng As Word.Range
    Dim ws As Worksheet
    Dim regEx As Object
    Dim matches As MatchCollection
    Dim match As String
    Dim repNmbr As String

    'Assigning object variables
    Set WordApp = GetObject(, "Word.Application")      'ActiveX can't create object is when
    Set ExcelApp = GetObject(, "Excel.Application")    'there is no Word document open;
    Set regEx = CreateObject("VBScript.RegExp")
    Set WordDoc = WordApp.ActiveDocument
    Set rng = WordApp.ActiveDocument.Content

    'Create the regular expression object
    regEx.Global = False    'because I need only the first match instead of all occurences;
    regEx.IgnoreCase = True
    regEx.Pattern = "([0-9]{1,5})([ ]{0,4})([/])([0-9]{4})"
    'regEx.Pattern = "([0-9]{1,5})([\s]{0,4})(/[0-9]{4})"

    repNmbr = regEx.Execute(rng.text)      'here is something wrong but I don't know what;
                            'I'm trying to assign the first RegEx match to repNmbr variable;
    Debug.Print repNmbr
    repNmbr = Replace(repNmbr, " ", "")
'    Set matches = regEx.Execute(rng.text)
'    Debug.Print regEx.Test(rng)
'    'Debug.Print regEx.Value
'        For Each match In matches    'I just want this macro run without the loop
'           Debug.Print match.Value   'Result: 9042 /2019
'           repNmbr = match.Value
'        Next match

    ExcelApp.Application.Visible = True
    ws.Range("G30").Value = repNmbr
End Sub
</code>```

And an error like this:

Can someone explain to me why Set matches = regEx.Execute(rng.text) works fine but
repNmbr = regEx.Execute(rng.text) returns the error: "Wrong number of arguments or invalid property assignment"??

After regEx.Global = False is set, the RegEx finds only a single value, so why VBA refuses to assign this string into the repNmbr string variable??

答:
As I said in your other question, you don't need the RegEx library for this. Stick to Word's wildcards! Try:

```<code>Sub Demo()
Application.ScreenUpdating = False
Dim WordApp As Word.Application
Set WordApp = GetObject(, "Word.Application")
With WordApp.ActiveDocument.Range
  With .Find
    .Text = "<[0-9 ]{1,7}/[0-9]{4}>"
    .MatchWildcards = True
    .Wrap = wdFindStop
    .Forward = True
    .Execute
  End With
  If .Find.Found = True Then ActiveSheet.Range("G30").Value = Replace(.Text, " ", "")
End With
Application.ScreenUpdating = True
End Sub
</code>```

Note: I haven't bothered with any of:

```<code>Dim ExcelApp As Excel.Application
Dim rng As Word.Range
Dim ws As Worksheet
Dim regEx As Object
Dim matches As MatchCollection
Dim match As String
Dim repNmbr As String
</code>```

as it's all superfluous - even your own code never assigns anything to ws.

Body:
There is a document like this one. I process 20 documents like this every day and they all look the same (structure, I mean, is very consistent).

The goal of this macro is to extract ONLY THE FIRST match of the RegEx pattern from the .ActiveDocument.Content. In the whole doc there is many more matches, but I need only the first one. The document being processed will be manually opened before the macro would run.

I'm just a VBA beginner so if there is a possibility to write it without using arrays, collections or some dictionaries I'd much appreciate. There is just one item to extract, so it's best to load it inside repNmbr string variable and from there just ws.Range("G30").Value = repNmbr. The simpler the better.

I used these resources Excel Regex Tutorial (Regular Expressions) which is very helpful but I still don't know how to load the FIRST MATCH alone into my repNmbr string variable. I'd like to do this without using any loop, because I just want to load a single string into this repNmbr variable.

Currently I have code like this:

Sub ExtractRepertor03()
    'Application.ScreenUpdating = False
    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document
    Dim ExcelApp As Excel.Application
    Dim rng As Word.Range
    Dim ws As Worksheet
    Dim regEx As Object
    Dim matches As MatchCollection
    Dim match As String
    Dim repNmbr As String

    'Assigning object variables
    Set WordApp = GetObject(, "Word.Application")      'ActiveX can't create object is when
    Set ExcelApp = GetObject(, "Excel.Application")    'there is no Word document open;
    Set regEx = CreateObject("VBScript.RegExp")
    Set WordDoc = WordApp.ActiveDocument
    Set rng = WordApp.ActiveDocument.Content

    'Create the regular expression object
    regEx.Global = False    'because I need only the first match instead of all occurences;
    regEx.IgnoreCase = True
    regEx.Pattern = "([0-9]{1,5})([ ]{0,4})([/])([0-9]{4})"
    'regEx.Pattern = "([0-9]{1,5})([\s]{0,4})(/[0-9]{4})"

    repNmbr = regEx.Execute(rng.text)      'here is something wrong but I don't know what;
                            'I'm trying to assign the first RegEx match to repNmbr variable;
    Debug.Print repNmbr
    repNmbr = Replace(repNmbr, " ", "")
'    Set matches = regEx.Execute(rng.text)
'    Debug.Print regEx.Test(rng)
'    'Debug.Print regEx.Value
'        For Each match In matches    'I just want this macro run without the loop
'           Debug.Print match.Value   'Result: 9042 /2019
'           repNmbr = match.Value
'        Next match

    ExcelApp.Application.Visible = True
    ws.Range("G30").Value = repNmbr
End Sub

And an error like this:

Can someone explain to me why Set matches = regEx.Execute(rng.text) works fine but
repNmbr = regEx.Execute(rng.text) returns the error: "Wrong number of arguments or invalid property assignment"??

After regEx.Global = False is set, the RegEx finds only a single value, so why VBA refuses to assign this string into the repNmbr string variable??

Body:
As I said in your other question, you don't need the RegEx library for this. Stick to Word's wildcards! Try:

Sub Demo()
Application.ScreenUpdating = False
Dim WordApp As Word.Application
Set WordApp = GetObject(, "Word.Application")
With WordApp.ActiveDocument.Range
  With .Find
    .Text = "<[0-9 ]{1,7}/[0-9]{4}>"
    .MatchWildcards = True
    .Wrap = wdFindStop
    .Forward = True
    .Execute
  End With
  If .Find.Found = True Then ActiveSheet.Range("G30").Value = Replace(.Text, " ", "")
End With
Application.ScreenUpdating = True
End Sub

Note: I haven't bothered with any of:

Dim ExcelApp As Excel.Application
Dim rng As Word.Range
Dim ws As Worksheet
Dim regEx As Object
Dim matches As MatchCollection
Dim match As String
Dim repNmbr As String

as it's all superfluous - even your own code never assigns anything to ws.


来源: stackexchange

问:
Finding the minimal k that 2^k begins with n
Given a positive integer n ≤ 107, I need to find the least positive integer k such that the decimal representation of 2k starts with the decimal representation of n.

So, for example, if n = 12, then k = 7 (because 27 = 128); if n = 134, then k = 27 (because 227 = 134,217,728); and if n = 82, then k = 209 (because 2209 ≈ 8.23×1062).

(If no such k exists, I need to return −1.)

I didn't even attempt to solve it with the formula (I have NO idea how), and decided to solve by calculating all powers of 2 up to 1000, putting them in a list, and then finding the index of the number that begins with n. The code works, but... It doesn't even pass the first test in the system. I have no clue why, because it works correctly for the above examples. Anyway, here is the code.

```<code>def find_all():
    arr = []
    n = 1
    for i in range(1000):
        arr.append(str(n))
        n = n << 1
    return arr

n = str(n)
NOT_FOUND = True
#n = input()
arr = find_all()
for i in arr:
    if i.startswith(n):
        print(arr.index(i), n)
        NOT_FOUND = False
        break
if NOT_FOUND:
    print(-1, n)
</code>```

What could be wrong?

答:
Suppose you want to find a power of 2 that starts with 123.

This is equivalent to finding a multiple of log10(2) whose mantissa lies between 0.089905111439398 and 0.093421685162235 (because log10(123) = 2.089905111439398 and log10(124) = 2.093421685162235).

If you frame the question in this way, there's no need to calculate huge powers of 2. All you need is a bit of floating point arithmetic.

The following code works fairly well, but takes a good few seconds to produce answers when n is close to 107:

```<code>def power_of_2_with_prefix(n):
    # Find the minimum integer k such that the digits of 2^k
    # start with the digits of n
    from math import log10
    #
    # First deal with trivial cases
    assert type(n) is int
    if n == 1:
        return 0
    if n < 1:
        return -1
    #
    # Calculate mantissa range
    logmin = log10(n)
    logmax = log10(n+1)
    logmin -= int(logmin)
    logmax -= int(logmax)
    if logmax < logmin:
        logmax += 1
    #
    # Now find a power of 2 whose log10 mantissa lies in this range
    log2 = log10(2)
    # Make sure k is large enough to include all trailing zeros of n
    mink = log10(n) / log10(2)
    x = 1
    k = 0
    while not (logmin <= x < logmax and k >= mink):
        x += log2
        if x >= 1:
            x -= 1
        k += 1
    return k

assert power_of_2_with_prefix(0) == -1
assert power_of_2_with_prefix(1) == 0
assert power_of_2_with_prefix(2) == 1
assert power_of_2_with_prefix(4) == 2
assert power_of_2_with_prefix(40) == 12
assert power_of_2_with_prefix(28584) == 74715
assert power_of_2_with_prefix(28723) == 110057
assert power_of_2_with_prefix(9999999) == 38267831
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given a positive integer n ≤ 107, I need to find the least positive integer k such that the decimal representation of 2k starts with the decimal representation of n.

So, for example, if n = 12, then k = 7 (because 27 = 128); if n = 134, then k = 27 (because 227 = 134,217,728); and if n = 82, then k = 209 (because 2209 ≈ 8.23×1062).

(If no such k exists, I need to return −1.)

I didn't even attempt to solve it with the formula (I have NO idea how), and decided to solve by calculating all powers of 2 up to 1000, putting them in a list, and then finding the index of the number that begins with n. The code works, but... It doesn't even pass the first test in the system. I have no clue why, because it works correctly for the above examples. Anyway, here is the code.

def find_all():
    arr = []
    n = 1
    for i in range(1000):
        arr.append(str(n))
        n = n << 1
    return arr

n = str(n)
NOT_FOUND = True
#n = input()
arr = find_all()
for i in arr:
    if i.startswith(n):
        print(arr.index(i), n)
        NOT_FOUND = False
        break
if NOT_FOUND:
    print(-1, n)

What could be wrong?

Body:
Suppose you want to find a power of 2 that starts with 123.

This is equivalent to finding a multiple of log10(2) whose mantissa lies between 0.089905111439398 and 0.093421685162235 (because log10(123) = 2.089905111439398 and log10(124) = 2.093421685162235).

If you frame the question in this way, there's no need to calculate huge powers of 2. All you need is a bit of floating point arithmetic.

The following code works fairly well, but takes a good few seconds to produce answers when n is close to 107:

def power_of_2_with_prefix(n):
    # Find the minimum integer k such that the digits of 2^k
    # start with the digits of n
    from math import log10
    #
    # First deal with trivial cases
    assert type(n) is int
    if n == 1:
        return 0
    if n < 1:
        return -1
    #
    # Calculate mantissa range
    logmin = log10(n)
    logmax = log10(n+1)
    logmin -= int(logmin)
    logmax -= int(logmax)
    if logmax < logmin:
        logmax += 1
    #
    # Now find a power of 2 whose log10 mantissa lies in this range
    log2 = log10(2)
    # Make sure k is large enough to include all trailing zeros of n
    mink = log10(n) / log10(2)
    x = 1
    k = 0
    while not (logmin <= x < logmax and k >= mink):
        x += log2
        if x >= 1:
            x -= 1
        k += 1
    return k

assert power_of_2_with_prefix(0) == -1
assert power_of_2_with_prefix(1) == 0
assert power_of_2_with_prefix(2) == 1
assert power_of_2_with_prefix(4) == 2
assert power_of_2_with_prefix(40) == 12
assert power_of_2_with_prefix(28584) == 74715
assert power_of_2_with_prefix(28723) == 110057
assert power_of_2_with_prefix(9999999) == 38267831


问:
How to dynamically add new instance (of say a text-field or a checkbox) in Wordpress widgets?
I am creating a Wordpress widget. I want users to enter their phone numbers. By default, the widget should show only one textbox and a link below it that says "Add New". When the user clicks the link, a the second text-box should appear below the first one with a small (X) beside it, that will be used to remove it.

This functionality is there in the post editing screen in Wordpress. Users can dynamically "Add new category" there. Can this me implemented inside Widgets?

答:
Sure. Start with this HTML at the bottom of your widget:

```<code><h2><a href="#" id="addNew">Add New</a></h2>
<div id="numbers">
    <p>
        <label for="numbers"><input type="text" id="p_number" size="20" name="p_number" value="" placeholder="Input Number" /></label>
    </p>
</div>
</code>```

Now a little jQuery:

```<code>$(function() {
        var nmbrsDiv = $('#numbers');
        var i = $('#numbers p').size() + 1;

        $('#addNew').live('click', function() {
                $('<p><label for="numbers"><input type="text" id="p_number_' + i +'" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Number" /></label> <a href="#" id="remNew">Remove</a></p>').appendTo(nmbrsDiv);
                i++;
                return false;
        });

        $('#remNew').live('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sure. Start with this HTML at the bottom of your widget:

<h2><a href="#" id="addNew">Add New</a></h2>
<div id="numbers">
    <p>
        <label for="numbers"><input type="text" id="p_number" size="20" name="p_number" value="" placeholder="Input Number" /></label>
    </p>
</div>

Now a little jQuery:

$(function() {
        var nmbrsDiv = $('#numbers');
        var i = $('#numbers p').size() + 1;

        $('#addNew').live('click', function() {
                $('<p><label for="numbers"><input type="text" id="p_number_' + i +'" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Number" /></label> <a href="#" id="remNew">Remove</a></p>').appendTo(nmbrsDiv);
                i++;
                return false;
        });

        $('#remNew').live('click', function() {
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});


问:
How do I make my bootstrap carousel appear only when hovering over a piece of text?
Please help! I have tried to find this seemingly straightforward function for days and can only find information related to the hidden display of bootstrap controls. How can I apply the hidden display to the entire bootstrap carousel with either css or java? I'd like for the carousel to only appear when the mouse hovers over a piece of text. Please let me know! Thank you.</p>

答:
Doing some assumptions based on your question. You are using Bootstrap. So I assume you are also using jQuery as it is a dependency. Why don't use jQuery to remove the no-display class when hovering the text.

```<code><script>
    $( "#text-container" )
        .on( "mouseenter", function() {
            $( "#carrousel" ).removeClass( "no-display" );
        })
        .on( "mouseleave", function() {
            $( "#carrousel" ).addClass( "no-display" );
        });
</script>
</code>```

text-container should be used to target the text container.
carrousel should be used to target the carousel container.

Check this page for more information https://api.jquery.com/mouseout/

Tip: next time, tell us more about the tech you are using.

Body:
Doing some assumptions based on your question. You are using Bootstrap. So I assume you are also using jQuery as it is a dependency. Why don't use jQuery to remove the no-display class when hovering the text.

<script>
    $( "#text-container" )
        .on( "mouseenter", function() {
            $( "#carrousel" ).removeClass( "no-display" );
        })
        .on( "mouseleave", function() {
            $( "#carrousel" ).addClass( "no-display" );
        });
</script>

text-container should be used to target the text container.
carrousel should be used to target the carousel container.

Check this page for more information https://api.jquery.com/mouseout/

Tip: next time, tell us more about the tech you are using.


问:
Cannot add a wireguard wg0 interface to an Openvswitch OVS switch
I have a working wireguard wg10 interface. I want to add it to a OVS bridge using the following simple commands, as root:

```<code>root@raspberrypi:~# ovs-vsctl add-br sw1
root@raspberrypi:~# ovs-vsctl add-port sw1 wg10
ovs-vsctl: Error detected while setting up 'wg10'.  See ovs-vswitchd log for details.
</code>```

======> ovs-vswitchd relevant log:

```<code>2020-02-15T21:40:43.791Z|00029|dpif|WARN|system@ovs-system: failed to add wg10 as port: Invalid argument
</code>```

Does anyone know if a wireguard interface can be used on an OVS switch?
Is there a need to anything special (other than what I'm doing)?

Thank you very much.

答:
The problem was that I was using an old raspbian. I completely reinstalled my raspberry pi - this time using Ubuntu Server - and all is good: I can add wg interfaces to OVS switches.
Thanks!

DC.

Body:
I have a working wireguard wg10 interface. I want to add it to a OVS bridge using the following simple commands, as root:

root@raspberrypi:~# ovs-vsctl add-br sw1
root@raspberrypi:~# ovs-vsctl add-port sw1 wg10
ovs-vsctl: Error detected while setting up 'wg10'.  See ovs-vswitchd log for details.

======> ovs-vswitchd relevant log:

2020-02-15T21:40:43.791Z|00029|dpif|WARN|system@ovs-system: failed to add wg10 as port: Invalid argument

Does anyone know if a wireguard interface can be used on an OVS switch?
Is there a need to anything special (other than what I'm doing)?

Thank you very much.


问:
Intercept *all* requests from Android WebView
The title says it all. I would like to know about everything what the WebView is asking for. Some weird limitations like not knowing about XHR POST are not acceptable. In other words, something like iOS have in NSURLProtocol. That one is application-wide hook. I don't need such level of control, WebView-instance-specific hook would be good enough. Now, i know that nothing like that exists on Android out of the box. I know about shouldOverrideUrlLoading and shouldInterceptRequest, but it's largely unusable. I need to know about requests (method, HTTP version, headers, you know) not just merely the URL strings. Moreover the intercepting is awkwardly synchronous. What happens if shouldInterceptRequest call is blocked because i need to ask a different server for related resource? It appears to me being designed just for a local resource caching.

On the other hand, i am willing to throw anything at the problem. Some kind of native library, hooking into low level internals? Extending Chromium interfaces with help of an existing project (pwnall, mogoweb)? Reflecting into the existing webkit class privates? Application-specific proxy? Any insights appreciated. I have read through two dozens of existing SO questions. They all either suggest a partial hack (like working around XHR POST deficiency with JavaScript) or it goes unresponded altogether, very often.

答:
If I understand your goal - try:

WebView.setWebContentsDebuggingEnabled(true);

Open Chrome and go to url chrome://inspect/#devices

for details:

https://developers.google.com/web/tools/chrome-devtools/remote-debugging

https://developers.google.com/web/tools/chrome-devtools/remote-debugging/webviews


问:
Bootstrap navbar goes into next section in mobile view
I have been trying to figure out why my navbar doesn't expand itself when in mobile view, rather the menu ends up occupying the following section. I have tried playing around with static/fixed navbars, adding padding to the body, to no avail.

I'm also not sure about where I should be including my container-fluid. I've seen examples of it wrapping the entire navbar, while others only wrap the brand.

```<code><html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Coins 4 Clothes</title>
    <!-- Stylesheets and libraries -->
    <link href="https://fonts.googleapis.com/css?family=Ubuntu&display=swap" rel="stylesheet">
    <!-- CSS stylesheets-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="stylesheet.css">
    <!-- Bootstrap scripts -->
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  </head>
  <body>
    <div class="container-fluid">
    <!-- Nav Bar -->
    <nav class="navbar navbar-expand-lg navbar-light">
      <a class="navbar-md-brand" href="">
        <img class="img-fluid c4clogo" src="images/output-onlinepngtools.png" alt="Coins 4 Clothes logo">
      </a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarTogglerDemo02">

        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="#footer">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#pricing">Contact</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#cta">FAQ</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#cta">Register</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#cta">Log in</a>
          </li>
        </ul>
      </div>
    </Nav>
    <hr class="hr-nav"></hr>

    <!-- Carousel section -->

    <div id="carouselExampleIndicators" class="carousel" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <div class= "headings-slide1">
        <h2 class="headings-slides">De-clutter your closet.</h3>
        <h3 class="headings-slides">Help the needy.</h3>
        <h3 class="headings-slides">Earn Bitcoins.</h3>
        <hr class="hr-slides"></hr>
      </div>
      <img class="d-block w-10" src="..." alt="First slide">
    </div>
    <div class="carousel-item">
      <div class= "headings-slide2">
        <h3 class="headings-slides">De-clutter your closet.</h3>
        <h2 class="headings-slides">Help the needy.</h2>
        <h3 class="headings-slides">Earn Bitcoins.</h3>
        <hr class="hr-slides"></hr>
      </div>
      <img class="d-block w-10" src="..." alt="Second slide">
    </div>
    <div class="carousel-item">
      <div class= "headings-slide3">
        <h3 class="headings-slides">De-clutter your closet.</h3>
        <h3 class="headings-slides">Help the needy.</h3>
        <h2 class="headings-slides">Earn Bitcoins.</h2>
        <hr class="hr-slides"></hr>
      </div>
      <img class="d-block w-10" src="..." alt="Third slide">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</div>
    hello world
  </body> ```

and here is the CSS

```

<p>Below is the CSS:</p>

```  font-size: 30px;
  margin-right: auto;
  margin-left: auto;
  padding-left: 15px;
  padding-right: 15px;
}

/* Navigation Bar */

.navbar {
  background-color: #FFFFFF;
  text-align: center;
  height: 70px;
}

.navbar-md-brand {
  height: 70px;
  width: 276px;
padding-top: 10px;
}

.nav-item {
  padding: 18px;
}

.nav-link {
  font-family: "ubuntu",sans-serif;
  font-weight: 500;
  font-size: 1.2rem;
}

.navbar-light .navbar-nav .nav-link .navbar-toggler-icon {
  color: #21bf73;
}

/* Carousel */

.carousel-control-prev {
  margin-left: -100px;
}

.carousel-control-next {
  margin-right: -100px;
}

/* Download Buttons*/
.download-button {
  margin: 5% 3% 5% 0;
}

.headings-slides{
  padding-left: 20px;

}

.hr-slides{
margin-top: 20px;
margin-left: 30px;
}

.hr-nav{
margin-top: inherit;
border-top: 3px solid black;
}

h2{
  color: #478559;
  font-family: "ubuntu",sans-serif;
}

```

答:
There are a couple of ways to fix this. Since you are using a custom .navbar-md-brand, the simplest way is to set it like this:

.navbar-md-brand {
  height: 70px;
  max-width: 276px;
  flex-grow: 1; /* let it "spread" until max-width */
  padding-top: 10px;
}
```

For an ideal scenario, you need to check these breakpoints and "rewrite" .navbar-md-brand for corner cases, if you need
https://getbootstrap.com/docs/4.4/layout/overview/#responsive-breakpoints

Or you can stay with the "official" way of doing things and use some of the existing classes like class="navbar-brand mb-0" https://getbootstrap.com/docs/4.4/components/navbar/#brand

Either way, hope these tips help you.

Body:
I have been trying to figure out why my navbar doesn't expand itself when in mobile view, rather the menu ends up occupying the following section. I have tried playing around with static/fixed navbars, adding padding to the body, to no avail.

I'm also not sure about where I should be including my container-fluid. I've seen examples of it wrapping the entire navbar, while others only wrap the brand.

    <meta charset="utf-8">
    <title>Coins 4 Clothes</title>

    <link href="https://fonts.googleapis.com/css?family=Ubuntu&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="stylesheet.css">

      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            About

            Contact

            FAQ

            Register

            Log in

De-clutter your closet.

Help the needy.

Earn Bitcoins.

De-clutter your closet.

Help the needy.

Earn Bitcoins.

De-clutter your closet.

Help the needy.

Earn Bitcoins.

    Previous

    Next

    hello world
   ```

and here is the CSS

Below is the CSS:

  font-size: 30px;
  margin-right: auto;
  margin-left: auto;
  padding-left: 15px;
  padding-right: 15px;
}

/* Navigation Bar */

.navbar {
  background-color: #FFFFFF;
  text-align: center;
  height: 70px;
}

.navbar-md-brand {
  height: 70px;
  width: 276px;
padding-top: 10px;
}

.nav-item {
  padding: 18px;
}

.nav-link {
  font-family: "ubuntu",sans-serif;
  font-weight: 500;
  font-size: 1.2rem;
}

.navbar-light .navbar-nav .nav-link .navbar-toggler-icon {
  color: #21bf73;
}

/* Carousel */

.carousel-control-prev {
  margin-left: -100px;
}

.carousel-control-next {
  margin-right: -100px;
}

/* Download Buttons*/
.download-button {
  margin: 5% 3% 5% 0;
}

.headings-slides{
  padding-left: 20px;

}

.hr-slides{
margin-top: 20px;
margin-left: 30px;
}

.hr-nav{
margin-top: inherit;
border-top: 3px solid black;
}

h2{
  color: #478559;
  font-family: "ubuntu",sans-serif;
}

Body:
There are a couple of ways to fix this. Since you are using a custom .navbar-md-brand, the simplest way is to set it like this:

.navbar-md-brand {
  height: 70px;
  max-width: 276px;
  flex-grow: 1; /* let it "spread" until max-width */
  padding-top: 10px;
}

For an ideal scenario, you need to check these breakpoints and "rewrite" .navbar-md-brand for corner cases, if you need
https://getbootstrap.com/docs/4.4/layout/overview/#responsive-breakpoints

Or you can stay with the "official" way of doing things and use some of the existing classes like class="navbar-brand mb-0" https://getbootstrap.com/docs/4.4/components/navbar/#brand

Either way, hope these tips help you.


问:
Android Adapter only fetching the last entered data
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

```<code>import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

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

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}
</code>```

Contact Adapter

```<code>import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}
</code>```

Contact Database

```<code>import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}
</code>```

contacts

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

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

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

contact_list (Cardview)

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>
</code>```

答:
There are some issues in your code.
I would start from the Cursor that remains open while the recyclerview is recycling views. That's not good, and moreover, you're doing it in UI Thread, and this will slow down your UI a lot.

I would suggest you read all the data and pass it to your adapter. That's what adapters are for: they are a way to access your data, but they do not have to know anything about how your data is accessed. So the first thing is changing the db helper, adding a method that will loop through all the data in your db and returns a list:

```<code>public List<Contact> readAllContacts() {
    List<Contact> contacts = new ArrayList();
    Cursor cursor = this.getContactDatabase();
    if (cursor.moveToFirst()){
       do {
          contacts.add(new Contact(cursor.getString(0), cursor.getString(1), cursor.getString(2)));
       } while(cursor.moveToNext());
    }
    cursor.close();
}
</code>```

You will also need to create a Contact class, with a public constructor.

Then, I would modify the adapter, to receive a List of Contacts, instead of the cursor:

```<code>public ContactAdapter(Context context,List<Contact> contacts) {
    mContext = context;
    this.contacts = contacts;
}
</code>```

You won't need the db helper in the adapter anymore, since you already have the whole list and the cursor, now, is already closed, improving performance for the whole UI. Also, you'll need a class attribute named contacts, of type List.

Now you can access the value for the single row by position, so in your onBindViewHolder you will have:

```<code>public void onBindViewHolder(MyHolder holder, final int position) {
    holder.contact_name.setText(this.contacts.get(position).getName());
    holder.contact_number.setText(this.contacts.get(position).getNumber());
    holder.contact_relation.setText(this.contacts.get(position).getContactRelation());

}
</code>```

This will already work. On top of all of this, I warmly suggest you to start using Room instead of writing your own db helper.

Body:
I tried looking around but cant seem to find an answer that could resolve it.
Here is the process of what I'm doing:

1: Users enter data in a alert dialog

2: Data get sent into sql.

3: Adapter runs, takes data and put into a cardview.

4: Cardview is displayed(Stacks according to number of inputs made).

What that is not working to plan, the data that is being outputted overrides all previous inputs,and updates all cardviews with the latest information.

EG: Input 1: Test 1, Input 2: Test 2. Output will be 2 cardviews of Test 2.

Contact Activity

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.sp.R;

public class Contacts extends AppCompatActivity {

    private Button newContact;
    private AlertDialog.Builder builder;
    private AlertDialog dialog;
    private RecyclerView recyclerView;

    private ContactDatabaseHelper helper;
    private ContactAdapter mAdapter;

    private EditText new_contact_name;
    private EditText new_contact_number;
    private EditText new_contact_relation;
    private Button button_create_contact;
    private Button button_cancel_create;

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

        helper = new ContactDatabaseHelper(this);

        recyclerView = findViewById(R.id.contact_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new ContactAdapter(this,getAllItems());
        recyclerView.setAdapter(mAdapter);

        newContact = findViewById(R.id.contact_button);
        // New Contact Button
        newContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                builder = new AlertDialog.Builder(Contacts.this);
                builder.setTitle("Create New Contact");
                builder.setCancelable(false);
                View view = LayoutInflater.from(Contacts.this).inflate(R.layout.new_contact_dialog,null,false);
                CreateDialog(view);
                builder.setView(view);
                dialog = builder.create();
                dialog.show();
            }
        });

    }

    private void CreateDialog(View view) {

        // ContactDialog ID's
        new_contact_name = view.findViewById(R.id.new_contact_name);
        new_contact_number = view.findViewById(R.id.new_contact_number);
        new_contact_relation = view.findViewById(R.id.new_contact_relation);
        button_create_contact = view.findViewById(R.id.button_create_contact);
        button_cancel_create = view.findViewById(R.id.button_cancel_create);

        button_create_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                        // Get String of Name, Number, Relationship
                        String contactNameStr = new_contact_name.getText().toString();
                        String contactNumberStr = new_contact_number.getText().toString();
                        String contactRelationStr = new_contact_relation.getText().toString();

                        // Insert into ContactTable
                        helper.insertContactDatabase(contactNameStr,contactNumberStr,contactRelationStr);
                        mAdapter.swapCursor(getAllItems());

                        // Outputs a Toast
                        Toast.makeText(Contacts.this, "Contact Created", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
            }
        });

        button_cancel_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    private Cursor getAllItems(){
        return helper.getContactDatabase();
    }

}

Contact Adapter

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.sp.R;

public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyHolder>{

    private Context mContext;
    private Cursor c;
    private ContactDatabaseHelper helper;

    public ContactAdapter(Context context,Cursor cursor) {

        mContext = context;
        c = cursor;
        helper = new ContactDatabaseHelper(mContext);
    }

    public static class MyHolder extends RecyclerView.ViewHolder{

        private TextView contact_name;
        private TextView contact_number;
        private TextView contact_relation;

        public MyHolder(View itemView) {
            super(itemView);

            contact_name = itemView.findViewById(R.id.contact_list_name_item);
            contact_number = itemView.findViewById(R.id.contact_list_number_item);
            contact_relation = itemView.findViewById(R.id.contact_list_relation_item);
        }
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.contact_list,parent,false);

        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, final int position) {

        c.moveToFirst();

        holder.contact_name.setText(helper.getContactName(c));
        holder.contact_number.setText(helper.getContactNumber(c));
        holder.contact_relation.setText(helper.getContactRelation(c));

    }

    @Override
    public int getItemCount() {

        return c.getCount();
    }

    public void swapCursor(Cursor newCursor){
        if (c != null){
            c.close();
        }

        c = newCursor;

        if (newCursor != null){
            notifyDataSetChanged();
        }
    }

}

Contact Database

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ContactDatabaseHelper extends SQLiteOpenHelper {

    public static String DATABASE_NAME = "contactlist.db";
    private static final int SCHEMA_VERSION = 1;

    public ContactDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, SCHEMA_VERSION); }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE contact_table( name TEXT, number TEXT , relation TEXT);");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    // Adds data into Contact database
    public void insertContactDatabase (String contact_name, String contact_number, String contact_relation) {
        ContentValues cv = new ContentValues();

        cv.put("name", contact_name);
        cv.put("number", contact_number);
        cv.put("relation", contact_relation);

        getWritableDatabase().insert("contact_table", "name", cv);
    }

    // Read Contact database
    public Cursor getContactDatabase() {
        return  (getReadableDatabase().rawQuery(
                "SELECT name, number, relation  FROM contact_table ORDER BY  + name", null));
    }

    // Delete Contact database
    public Integer deleteContactDatabase () {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete("contact_table",null,null);

    }

    public String getContactName (Cursor c){ return (c.getString(0)); }

    public String getContactNumber (Cursor c){ return (c.getString(1)); }

    public String getContactRelation (Cursor c){ return (c.getString(2)); }
}

contacts

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/contact_background"
    tools:context=".Contact.Contacts">

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

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

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

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/contact_recycler_view"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_above="@id/contact_button"
                    android:layout_marginTop="10dp"
                    android:scrollbars="vertical">

                </androidx.recyclerview.widget.RecyclerView>

                <Button
                    android:id="@+id/contact_button"
                    android:layout_width="150dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="10sp"
                    android:layout_marginBottom="10sp"
                    android:background="#43464B"
                    android:text="New Contact"
                    android:textAlignment="center"
                    android:textColor="#FFFFFF"
                    android:textSize="18sp" />
            </LinearLayout>
        </ScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

contact_list (Cardview)

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/list_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#FFEAB8"
    app:cardCornerRadius="15dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#00ACEE"
        app:cardCornerRadius="5dp"
        app:cardElevation="15dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:id="@+id/contact_layout_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="Name"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_name_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="Name"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_number"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="35dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_number_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:text="Number"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/contact_layout_relation"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="60dp"
            android:layout_marginBottom="15dp"
            android:orientation="horizontal">

            <TextView
                android:layout_width="120dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textAlignment="center"
                android:textColor="#E6E6E6"
                android:textSize="20sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text=":"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/contact_list_relation_item"
                android:layout_width="190dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:text="Relationship"
                android:textColor="#FFFF00"
                android:textSize="20sp" />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</androidx.cardview.widget.CardView>

Body:
There are some issues in your code.
I would start from the Cursor that remains open while the recyclerview is recycling views. That's not good, and moreover, you're doing it in UI Thread, and this will slow down your UI a lot.

I would suggest you read all the data and pass it to your adapter. That's what adapters are for: they are a way to access your data, but they do not have to know anything about how your data is accessed. So the first thing is changing the db helper, adding a method that will loop through all the data in your db and returns a list:

public List<Contact> readAllContacts() {
    List<Contact> contacts = new ArrayList();
    Cursor cursor = this.getContactDatabase();
    if (cursor.moveToFirst()){
       do {
          contacts.add(new Contact(cursor.getString(0), cursor.getString(1), cursor.getString(2)));
       } while(cursor.moveToNext());
    }
    cursor.close();
}

You will also need to create a Contact class, with a public constructor.

Then, I would modify the adapter, to receive a List of Contacts, instead of the cursor:

public ContactAdapter(Context context,List<Contact> contacts) {
    mContext = context;
    this.contacts = contacts;
}

You won't need the db helper in the adapter anymore, since you already have the whole list and the cursor, now, is already closed, improving performance for the whole UI. Also, you'll need a class attribute named contacts, of type List.

Now you can access the value for the single row by position, so in your onBindViewHolder you will have:

public void onBindViewHolder(MyHolder holder, final int position) {
    holder.contact_name.setText(this.contacts.get(position).getName());
    holder.contact_number.setText(this.contacts.get(position).getNumber());
    holder.contact_relation.setText(this.contacts.get(position).getContactRelation());

}

This will already work. On top of all of this, I warmly suggest you to start using Room instead of writing your own db helper.


问:
If I have vim open in two terminals, how can I share the copy/paste buffer?
I want to yy a line from one instance of vim running in one terminal emulator, and p that line into another instance of vim running in another terminal emulator. Possible? Is there a special setting to use?

答:
You can instead:
Esc for canceling all modes
:r! cat file.txt all content of file.txt pasts in your file, but if you want paste for example from 5 to 11 lines of file then
:r! sed -n 5,11p file.txt


问:
How to Decompose and Visualise Slope Component in Tensorflow Probability
I'm running tensorflow 2.1 and tensorflow_probability 0.9.  I have fit a Structural Time Series Model with a seasonal component.  I am using code from the Tensorflow Probability Structural Time Series Probability example:
Tensorflow Github.

In the example there is a great plot where the decomposition is visualised:

```<code>
# Get the distributions over component outputs from the posterior marginals on
# training data, and from the forecast model.
component_dists = sts.decompose_by_component(
    demand_model,
    observed_time_series=demand_training_data,
    parameter_samples=q_samples_demand_)

forecast_component_dists = sts.decompose_forecast_by_component(
    demand_model,
    forecast_dist=demand_forecast_dist,
    parameter_samples=q_samples_demand_)

demand_component_means_, demand_component_stddevs_ = (
    {k.name: c.mean() for k, c in component_dists.items()},
    {k.name: c.stddev() for k, c in component_dists.items()})

(
    demand_forecast_component_means_,
    demand_forecast_component_stddevs_
) = (
    {k.name: c.mean() for k, c in forecast_component_dists.items()},
    {k.name: c.stddev() for k, c in forecast_component_dists.items()}
    )
</code>```

When using a trend component, is it possible to decompose and visualise both:

trend/_level_scale & trend/_slope_scale

I have tried many permutations to extract the nested element of the trend component with no luck.

Thanks for your time in advance.

答:
We didn't write a separate STS interface for this, but you can access the posterior on latent states (in this case, both the level and slope) by directly querying the underlying state-space model for its marginal means and covariances:

ssm = model.make_state_space_model(
        num_timesteps=num_timesteps,
        param_vals=parameter_samples)
posterior_means, posterior_covs = (
  ssm.posterior_marginals(observed_time_series))
```

You should also be able to draw samples from the joint posterior by running ssm.posterior_sample(observed_time_series, num_samples).

It looks like there's currently a glitch when drawing posterior samples from a model with no batch shape (Could not find valid device for node. Node:{{node Reshape}}): while we fix that, it should work to add an artificial batch dimension as a workaround:
ssm.posterior_sample(observed_time_series[tf.newaxis, ...], num_samples).

Body:
I'm running tensorflow 2.1 and tensorflow_probability 0.9.  I have fit a Structural Time Series Model with a seasonal component.  I am using code from the Tensorflow Probability Structural Time Series Probability example:
Tensorflow Github.

In the example there is a great plot where the decomposition is visualised:

# Get the distributions over component outputs from the posterior marginals on
# training data, and from the forecast model.
component_dists = sts.decompose_by_component(
    demand_model,
    observed_time_series=demand_training_data,
    parameter_samples=q_samples_demand_)

forecast_component_dists = sts.decompose_forecast_by_component(
    demand_model,
    forecast_dist=demand_forecast_dist,
    parameter_samples=q_samples_demand_)

demand_component_means_, demand_component_stddevs_ = (
    {k.name: c.mean() for k, c in component_dists.items()},
    {k.name: c.stddev() for k, c in component_dists.items()})

(
    demand_forecast_component_means_,
    demand_forecast_component_stddevs_
) = (
    {k.name: c.mean() for k, c in forecast_component_dists.items()},
    {k.name: c.stddev() for k, c in forecast_component_dists.items()}
    )

When using a trend component, is it possible to decompose and visualise both:

trend/_level_scale & trend/_slope_scale

I have tried many permutations to extract the nested element of the trend component with no luck.

Thanks for your time in advance.

Body:
We didn't write a separate STS interface for this, but you can access the posterior on latent states (in this case, both the level and slope) by directly querying the underlying state-space model for its marginal means and covariances:

ssm = model.make_state_space_model(
        num_timesteps=num_timesteps,
        param_vals=parameter_samples)
posterior_means, posterior_covs = (
  ssm.posterior_marginals(observed_time_series))

You should also be able to draw samples from the joint posterior by running ssm.posterior_sample(observed_time_series, num_samples).

It looks like there's currently a glitch when drawing posterior samples from a model with no batch shape (Could not find valid device for node. Node:{{node Reshape}}): while we fix that, it should work to add an artificial batch dimension as a workaround:
ssm.posterior_sample(observed_time_series[tf.newaxis, ...], num_samples).


问:
actionBarDrawerToggle.setDrawerIndicatorEnabled(false) back arrow has no action
I use a navigation drawer, which I want to disable for inner Fragments.
I used following code to setup the drawer:

```<code>private void initSideMenu() {
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.Open, R.string.Close);

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        binding.nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menuData:
                        selectPersonalDataFragment();
                        break;
                    case R.id.menuBlogPosts:
                        closeDrawerAndNavigateTo(new BlogPostFragment(), true);
                        break;
                    case R.id.menuSettings:
                        closeDrawerAndNavigateTo(new BackgroundImageFragment(), true);
                        break;
                }
                return true;
            }
        });
    }
</code>```

To disable the navigation drawer I use following code:

```<code>@Override
    public void setDrawerEnabled(boolean enabled) {
        Log.d(TAG, "setDrawerEnabled: " + enabled);
        if(enabled) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
        } else {
            actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
            actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }
</code>```

The burger icon changes to a back arrow, but this arrow does not have any functionality. So why is my listener not listening?

答:
After a lot of trying I found out, that I did not have to set a toolbar navigation click Listener, but had to override onSupportNavigateUp():

Changed setDrawerEnabled():

```<code>@Override
    public void setDrawerEnabled(boolean enabled) {
        Log.d(TAG, "setDrawerEnabled: " + enabled);
        if(enabled) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
        } else {
            actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
        }
    }
</code>```

New overriden onSupportNavigateUp():

```<code>@Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
</code>```

Body:
I use a navigation drawer, which I want to disable for inner Fragments.
I used following code to setup the drawer:

private void initSideMenu() {
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.Open, R.string.Close);

        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        binding.nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menuData:
                        selectPersonalDataFragment();
                        break;
                    case R.id.menuBlogPosts:
                        closeDrawerAndNavigateTo(new BlogPostFragment(), true);
                        break;
                    case R.id.menuSettings:
                        closeDrawerAndNavigateTo(new BackgroundImageFragment(), true);
                        break;
                }
                return true;
            }
        });
    }

To disable the navigation drawer I use following code:

@Override
    public void setDrawerEnabled(boolean enabled) {
        Log.d(TAG, "setDrawerEnabled: " + enabled);
        if(enabled) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
        } else {
            actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
            actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

The burger icon changes to a back arrow, but this arrow does not have any functionality. So why is my listener not listening?

Body:
After a lot of trying I found out, that I did not have to set a toolbar navigation click Listener, but had to override onSupportNavigateUp():

Changed setDrawerEnabled():

@Override
    public void setDrawerEnabled(boolean enabled) {
        Log.d(TAG, "setDrawerEnabled: " + enabled);
        if(enabled) {
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
        } else {
            actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
        }
    }

New overriden onSupportNavigateUp():

@Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }


问:
TypeError: 'float' object is not iterable when attempting to choose specific objects from a float list
Good morning everyone, I'm sorry if this question is a duplicate, but I tried to search for this question and can't find any good answer so I'm asking one myself.

Basically,

```<code>    AccessoriesPrice = (0.00, 50.00, 19.99, 15.99)

    for count,(case) in enumerate((AccessoriesPrice[1])):
        print(count,"|",case,">>")
</code>```

I'm currently programming a test app that uses lists as a way to store lists of available phones and accessories and their prices, and then outputs them in a menu, which then prompts them to choose a number, which eventually goes to use the numbers in the lists with stored input numbers in variables. Kind of like AccessoriesPrice[1] This code above is part of it.

For some reason, when I run the code to the terminal, it says TypeError: 'float' object is not iterable, and I kinda understand what does the error mean, but I wanted to know if there could be a way where I can grab a specific number from the list with its index number without dealing with this error. Thank you for answering this question

答:
Remove the [1] from it.</p>

```<code>AccessoriesPrice = (0.00, 50.00, 19.99, 15.99)

    for count,(case) in enumerate((AccessoriesPrice)):
        print(count,"|",case,">>")
</code>```

Body:
Good morning everyone, I'm sorry if this question is a duplicate, but I tried to search for this question and can't find any good answer so I'm asking one myself.

Basically,

    AccessoriesPrice = (0.00, 50.00, 19.99, 15.99)

    for count,(case) in enumerate((AccessoriesPrice[1])):
        print(count,"|",case,">>")

I'm currently programming a test app that uses lists as a way to store lists of available phones and accessories and their prices, and then outputs them in a menu, which then prompts them to choose a number, which eventually goes to use the numbers in the lists with stored input numbers in variables. Kind of like AccessoriesPrice[1] This code above is part of it.

For some reason, when I run the code to the terminal, it says TypeError: 'float' object is not iterable, and I kinda understand what does the error mean, but I wanted to know if there could be a way where I can grab a specific number from the list with its index number without dealing with this error. Thank you for answering this question

Body:
Remove the [1] from it.

AccessoriesPrice = (0.00, 50.00, 19.99, 15.99)

    for count,(case) in enumerate((AccessoriesPrice)):
        print(count,"|",case,">>")


问:
Retrieving and displaying data on android studio using Firebase
I have sent data to my firebase database underneath the key "Bench" and i am trying to retrieve the data onto android studio by creating a arrayadapter :

```<code>    public class ScoreInfoAdapter extends ArrayAdapter<ScoreProfile> {

    private Activity context;
    private List<ScoreProfile> scoreList;

    public ScoreInfoAdapter(Activity context, List<ScoreProfile>scoreList){

    super(context,R.layout.list_view,scoreList);
    this.context =context;
    this.scoreList = scoreList;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = context.getLayoutInflater();
    View listview = inflater.inflate(R.layout.list_view, null, true);

    TextView Scorename = (TextView)listview.findViewById(R.id.Name_bench);
    TextView Scorelevel = (TextView)listview.findViewById(R.id.Score_of_bench);
    ScoreProfile scoreProfile = scoreList.get(position);

    Scorename.setText(scoreProfile.getUserName());
    Scorelevel.setText(scoreProfile.getUserScore());

    return listview;
    }
    }

</code>```

I have created a layout resource file with a list view with two textviews. "Name", "Score". I have created a class with an xml layout to display the information with a list view and on the class for this activity i have used this code to retrieve data:

```<code>    private FirebaseAuth firebaseAuth;
    private ListView listView;
    DatabaseReference databaseReference;
    private FirebaseDatabase firebaseDatabase;
    List<ScoreProfile> scoreList;

    @Override
    protected void onStart() {
    super.onStart();
    databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

    for(DataSnapshot scoreSnapshot : dataSnapshot.getChildren()){

    ScoreProfile scoreProfile = scoreSnapshot.getValue(ScoreProfile.class);
    scoreList.add(scoreProfile);

    }
    ScoreInfoAdapter scoreInfoAdapter = new ScoreInfoAdapter(RankT.this, scoreList);
    listView.setAdapter(scoreInfoAdapter);

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
    });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rank_t);
    Toolbar toolbar = findViewById(R.id.toolbarMain);
    toolbar.setTitle("GymTastic Rank Table");

    listView = findViewById(R.id.listview);

    firebaseDatabase = FirebaseDatabase.getInstance();

    databaseReference = firebaseDatabase.getReference("Bench");

    scoreList = new ArrayList<>();

    firebaseAuth = FirebaseAuth.getInstance();

</code>```

However, when i run the app i get this error :

```<code>    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.gymtastic, PID: 14505
    com.google.firebase.database.DatabaseException: Class com.example.gymtastic.ScoreProfile does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.0:569)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.0:562)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.2.0:432)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.0:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.2.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.2.0:203)
        at com.example.gymtastic.RankT$1.onDataChange(RankT.java:52)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.0:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

What can I do to prevent this error and successfully present data pulled from the Database.

答: sir this eror shows you have no default constructor in ScoreProfile class. you need to initialize default constructor in scoreProfile=file class like. public ScoreProfile(){} because for mapping data like this ScoreProfile scoreProfile = scoreSnapshot.getValue(ScoreProfile.class); firebase demand a defualt constructor in modal class

Body:
I have sent data to my firebase database underneath the key "Bench" and i am trying to retrieve the data onto android studio by creating a arrayadapter :

    public class ScoreInfoAdapter extends ArrayAdapter<ScoreProfile> {

    private Activity context;
    private List<ScoreProfile> scoreList;

    public ScoreInfoAdapter(Activity context, List<ScoreProfile>scoreList){

    super(context,R.layout.list_view,scoreList);
    this.context =context;
    this.scoreList = scoreList;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = context.getLayoutInflater();
    View listview = inflater.inflate(R.layout.list_view, null, true);

    TextView Scorename = (TextView)listview.findViewById(R.id.Name_bench);
    TextView Scorelevel = (TextView)listview.findViewById(R.id.Score_of_bench);
    ScoreProfile scoreProfile = scoreList.get(position);

    Scorename.setText(scoreProfile.getUserName());
    Scorelevel.setText(scoreProfile.getUserScore());

    return listview;
    }
    }

I have created a layout resource file with a list view with two textviews. "Name", "Score". I have created a class with an xml layout to display the information with a list view and on the class for this activity i have used this code to retrieve data:

    private FirebaseAuth firebaseAuth;
    private ListView listView;
    DatabaseReference databaseReference;
    private FirebaseDatabase firebaseDatabase;
    List<ScoreProfile> scoreList;

    @Override
    protected void onStart() {
    super.onStart();
    databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

    for(DataSnapshot scoreSnapshot : dataSnapshot.getChildren()){

    ScoreProfile scoreProfile = scoreSnapshot.getValue(ScoreProfile.class);
    scoreList.add(scoreProfile);

    }
    ScoreInfoAdapter scoreInfoAdapter = new ScoreInfoAdapter(RankT.this, scoreList);
    listView.setAdapter(scoreInfoAdapter);

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
    });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rank_t);
    Toolbar toolbar = findViewById(R.id.toolbarMain);
    toolbar.setTitle("GymTastic Rank Table");

    listView = findViewById(R.id.listview);

    firebaseDatabase = FirebaseDatabase.getInstance();

    databaseReference = firebaseDatabase.getReference("Bench");

    scoreList = new ArrayList<>();

    firebaseAuth = FirebaseAuth.getInstance();

However, when i run the app i get this error :

    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.gymtastic, PID: 14505
    com.google.firebase.database.DatabaseException: Class com.example.gymtastic.ScoreProfile does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.0:569)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.0:562)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.2.0:432)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.0:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.2.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.2.0:203)
        at com.example.gymtastic.RankT$1.onDataChange(RankT.java:52)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.0:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

What can I do to prevent this error and successfully present data pulled from the Database.


问:
applications shares same BDE
I encouter problem with my application when it turn in PC running other application using same BDE as my application , my application can't store record in database in this case, is thre any configuration to make in BDE resolving this problem .</p>

答:
If you operating system is XP or Win7 try editing the BDE settings in BDE administrator in the control panel (backup you idapi.cfg first, of course!). Under configuration|system|init change the sharedmemlocation to 6BDE. Restart your computer.

This will allow BDE to be called by mulitple programs. It may allow the two programs to use the BDE.

ContentLicense: CC BY-SA 2.5

Title: applications shares same BDE


问:
Spring Boot - how make different resources for different users
I am writing a spring boot application and have encountered the problem of sharing resources for different users. Simplified by example, it looks like this: there is one variable. You can assign a value to it through the form on the page. If the first user assigns the value hello java from one browser, then the second user will see the same value through another browser. I dont know how to make each user work with their own variable and their values do not overlap?

Controller:

```<code>@Controller
public class MessageController {
    private String message;

    @GetMapping(value = "/show_message")
    public String showMessage(Model model){
        model.addAttribute("message", message);
        return "message";
    }

    @PostMapping(value = "set_message")
    public String setMessage(@RequestParam(name = "newMessage") String newMessage){
        message = newMessage;
        return "redirect:/show_message";
    }
}
</code>```

html page:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">

</head>
<body>
<p>Message value: <th:block th:utext="${message}"/></p>

<p>Enter a new message value</p>
<form method="POST" th:action="@{/set_message}">
    <input type="text" name="newMessage"/>
    <input type="submit" value="Send"/>
</form>
</body>
</html>
</code>```

答:
The rule of thumb is that controllers as well as services are not designed to maintain a state, particularly the client state.

Besides, Spring beans are by default singletons : they are shared among clients/requests.   That explains the behavior that you notice.

To solve that issue you may use the in-memory HttpSession (old practice) but that is not advised  any longer because it sticks the client/user to a specific server instance that has first served his request.

You should preferably either resend the data at each request (which may be cumbersome to do) or better store the data in an in-memory database such as Redis.

That is fast and it doesn't stick the client to a specific instance of your spring boot application.

With Spring, a good association with the in-memory database usage to handle the user state is using HttpSession but Spring Session backed to a database (Redis or another).

For how to use the Session with Spring MVC, you have that good post.

Body:
I am writing a spring boot application and have encountered the problem of sharing resources for different users. Simplified by example, it looks like this: there is one variable. You can assign a value to it through the form on the page. If the first user assigns the value hello java from one browser, then the second user will see the same value through another browser. I dont know how to make each user work with their own variable and their values do not overlap?

Controller:

@Controller
public class MessageController {
    private String message;

    @GetMapping(value = "/show_message")
    public String showMessage(Model model){
        model.addAttribute("message", message);
        return "message";
    }

    @PostMapping(value = "set_message")
    public String setMessage(@RequestParam(name = "newMessage") String newMessage){
        message = newMessage;
        return "redirect:/show_message";
    }
}

html page:

<!DOCTYPE html>

    <meta charset="UTF-8">

Message value:

Enter a new message value

<form method="POST" th:action="@{/set_message}">
    <input type="text" name="newMessage"/>
    <input type="submit" value="Send"/>
</form>


问:
Python write files process crashed before closing
If I have a process that is writing large number of lines on a file and the process got killed in the middle before the file handler is closed. Do I get the content of the lines written successfully?</p>

答:
It depends on what you mean by "got killed" and "successfully". If its a python-raised exception then the file is closed (which flushes it to the operating system) because it exited a with clause or because the final reference to the object was removed and its __del__ method was called. This last bit isn't always guaranteed, which is why with clauses are usually used.

If the program was killed by an external unhandled exception or crashed because some c library has a bug, then the file isn't closed and whatever data was still in the local process cache is lost. Whatever had already been flushed to the operating system by clib will be there, but not the latest data. And it may be truncated on a memory block boundary. You can call flush often to reduce the amount of lost data. Or perhaps use a memory mapped file and direct io.

Now to the question of success. Depending on what you're doing, a partially written file may be the worst choice. In fact, I'd wager that's the case more often than not. I'm guilty of this as much as anybody but it makes sense to write to a temporary file and move it on success. Or alternately, deleting the file on failure. Parially written faulty data is a curse.


问:
Problem with declaring a protected pointer to a vector
I'm trying to declare a pointer to a std::vector<int> in a derived class in C++. That class is a base class for other classes again.

My attempt was as follows

```<code>protected:
   std::vector<CustomClass> *mypointer;
</code>```

However, when I compile it, I get the following error:

```<code>error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)
</code>```

and some other operands are missing.

I'm pretty clueless, where the problem lies at all. Do I have to implement all those functions in the current class? If so, why do I have to do so?

For anyone needing more context, I want to implement that pointer in the class CbmStsSensor (found here), which derives from CbmStsElement.

Edit: Some relevant classes can be found here CbmStsElement.h and here enter link description here.

Edit2: The whole compilation error log can be found here.

答:
The error messages are enough clear. For example somewhere in the code you are trying to assign a pointer to an object of the type std::vector<int> * to an object of the type std::vector<int>.

Here is a demonstrative program that shows how this error message can be generated.

```<code>#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1;
    std::vector<int> v2;

    v1 = &v2;

    return 0;
}
</code>```

The compilation error is

```<code>prog.cpp: In function ‘int main()’:
prog.cpp:9:8: error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
  v1 = &v2;
        ^~
</code>```

Or (relative to the second error message) there is no unary operator * for objects of the type std::vector<int>.

Here is another demonstrative program

```<code>#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;

    *v;

    return 0;
}
</code>```

the error message is

```<code>prog.cpp: In function ‘int main()’:
prog.cpp:8:2: error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)
  *v;
  ^~
</code>```

Maybe you should declare the data member as having the type std::vector<int> instead of the pointer type.

Body:
I'm trying to declare a pointer to a std::vector<int> in a derived class in C++. That class is a base class for other classes again.

My attempt was as follows

protected:
   std::vector<CustomClass> *mypointer;

However, when I compile it, I get the following error:

error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)

and some other operands are missing.

I'm pretty clueless, where the problem lies at all. Do I have to implement all those functions in the current class? If so, why do I have to do so?

For anyone needing more context, I want to implement that pointer in the class CbmStsSensor (found here), which derives from CbmStsElement.

Edit: Some relevant classes can be found here CbmStsElement.h and here enter link description here.

Edit2: The whole compilation error log can be found here.

Body:
The error messages are enough clear. For example somewhere in the code you are trying to assign a pointer to an object of the type std::vector<int> * to an object of the type std::vector<int>.

Here is a demonstrative program that shows how this error message can be generated.

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1;
    std::vector<int> v2;

    v1 = &v2;

    return 0;
}

The compilation error is

prog.cpp: In function ‘int main()’:
prog.cpp:9:8: error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
  v1 = &v2;
        ^~

Or (relative to the second error message) there is no unary operator * for objects of the type std::vector<int>.

Here is another demonstrative program

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v;

    *v;

    return 0;
}

the error message is

prog.cpp: In function ‘int main()’:
prog.cpp:8:2: error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)
  *v;
  ^~

Maybe you should declare the data member as having the type std::vector<int> instead of the pointer type.


问:
Xcode 10 Build Location -> Per-configuration Build Products Path
I'm just trying to implement react-native code push on my react-native application but I just can't find Build Location -> Per-configuration Build Products Path on Xcode 10.

Here's the guide I'm following: https://learn.microsoft.com/en-us/appcenter/distribution/codepush/react-native#multi-deployment-testing

Where did that change go to?

答:
Xcode 11 has removed this setting moving to the new build settings found in the Workspace Settings.

For CodePush, you want to create another user-defined section named CONFIGURATION_BUILD_DIR, using the same per-configuration settings.

NOTE: I found that Xcode would crash anytime I set the section name to CONFIGURATION_BUILD_DIR after creating it (most likely due to the empty values). To avoid this issue, create the section without renaming, set the configuration specific build folders, and then change the name.

Best of luck!