问:
how to style HTML when using react-native-print
So what I am trying to print out html but with little styling i tried everything that i know of but I was't able to get it done.Every thing is working fine thought can't style the Html.I even tried to bind it with the style tag properties but still it didn't worked.

My code is

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  Button,
  StyleSheet,
  NativeModules,
  Platform,
  Text,
  View
} from 'react-native';

import RNPrint from 'react-native-print';

export default class RNPrintExample extends Component {
  state = {
    selectedPrinter: null
  }

  // @NOTE iOS Only
  selectPrinter = async () => {
    const selectedPrinter = await RNPrint.selectPrinter()
    this.setState({ selectedPrinter })
  }

  // @NOTE iOS Only
  silentPrint = async () => {
    if (!this.state.selectedPrinter) {
      alert('Must Select Printer First')
    }

    const jobName = await RNPrint.print({
      printerURL: this.state.selectedPrinter.url,
      html: '<h1>Silent Print</h1>'
    })

  }
    //trying to style this HTML
  async printHTML() {
    await RNPrint.print({
      html: '<h1>Heading 1</h1><h2>Heading 2</h2><h3>Heading 3</h3>'
    })
  }

  async printRemotePDF() {
    await RNPrint.print({ filePath: 'https://graduateland.com/api/v2/users/jesper/cv' })
  }

  customOptions = () => {
    return (
      <View>
        {this.state.selectedPrinter &&
          <View>
            <Text>{`Selected Printer Name: ${this.state.selectedPrinter.name}`}</Text>
            <Text>{`Selected Printer URI: ${this.state.selectedPrinter.url}`}</Text>
          </View>
        }
      <Button onPress={this.selectPrinter} title="Select Printer" />
      <Button onPress={this.silentPrint} title="Silent Print" />
    </View>

    )
  }

  render() {
    return (
      <View style={styles.container}>
        {Platform.OS === 'ios' && this.customOptions()}
        <Button onPress={this.printHTML} title="Print HTML" />
        <Button onPress={this.printPDF} title="Print PDF" />
        <Button onPress={this.printRemotePDF} title="Print Remote PDF" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});
</code>```

Any help Would be Appreciated.

答:
```<code><html>
<head>
    <style>
        .heading{
        background-color: red;
        }
        .block {
        background-color: black;
        height: 30;
        }
        .text{
        color: white;
        }
    </style>
</head>
<body>
    <h1 class='heading'>Title</h1>
    <div class='block'>
        <span class='text'>Hello, World !</span>
    </div>
</body>
</code>```

I was able to style it by storing the above HTML inside back-ticks (``) and using it like

```<code>RNPrint.print({
  html: `<html>... ....</html>`
})
</code>```

Body:
So what I am trying to print out html but with little styling i tried everything that i know of but I was't able to get it done.Every thing is working fine thought can't style the Html.I even tried to bind it with the style tag properties but still it didn't worked.

My code is

import React, { Component } from 'react';
import {
  AppRegistry,
  Button,
  StyleSheet,
  NativeModules,
  Platform,
  Text,
  View
} from 'react-native';

import RNPrint from 'react-native-print';

export default class RNPrintExample extends Component {
  state = {
    selectedPrinter: null
  }

  // @NOTE iOS Only
  selectPrinter = async () => {
    const selectedPrinter = await RNPrint.selectPrinter()
    this.setState({ selectedPrinter })
  }

  // @NOTE iOS Only
  silentPrint = async () => {
    if (!this.state.selectedPrinter) {
      alert('Must Select Printer First')
    }

    const jobName = await RNPrint.print({
      printerURL: this.state.selectedPrinter.url,
      html: '
Silent Print
'
    })

  }
    //trying to style this HTML
  async printHTML() {
    await RNPrint.print({
      html: '
Heading 1

Heading 2

Heading 3
'
    })
  }

  async printRemotePDF() {
    await RNPrint.print({ filePath: 'https://graduateland.com/api/v2/users/jesper/cv' })
  }

  customOptions = () => {
    return (
      <View>
        {this.state.selectedPrinter &&
          <View>
            <Text>{`Selected Printer Name: ${this.state.selectedPrinter.name}`}</Text>
            <Text>{`Selected Printer URI: ${this.state.selectedPrinter.url}`}</Text>
          </View>
        }
      <Button onPress={this.selectPrinter} title="Select Printer" />
      <Button onPress={this.silentPrint} title="Silent Print" />
    </View>

    )
  }

  render() {
    return (
      <View style={styles.container}>
        {Platform.OS === 'ios' && this.customOptions()}
        <Button onPress={this.printHTML} title="Print HTML" />
        <Button onPress={this.printPDF} title="Print PDF" />
        <Button onPress={this.printRemotePDF} title="Print Remote PDF" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

Any help Would be Appreciated.

Body:
<html>
<head>
    <style>
        .heading{
        background-color: red;
        }
        .block {
        background-color: black;
        height: 30;
        }
        .text{
        color: white;
        }
    </style>
</head>
<body>
    <h1 class='heading'>Title</h1>
    <div class='block'>
        <span class='text'>Hello, World !</span>
    </div>
</body>

I was able to style it by storing the above HTML inside back-ticks (``) and using it like

RNPrint.print({
  html: `<html>... ....</html>`
})


来源: stackexchange

问:
I just installed visual studio and ran into some errors specifically The WindowsSDKDir property is not defined. Some build tools may not be found
Just installed visual studio 2019 on windows 10, was using visual studio for the first time and ran into the following error, It's a basic hello world console program that I tried to run.

error C1083:  Cannot open include file: 'corecrt.h': No such file or directory

1>Done building project "ConsoleApplication2.vcxproj" -- FAILED.

Severity   Code    Description Project File    Line    Suppression State
Warning MSB8003 The WindowsSDKDir property is not defined. Some build tools may not be found.   ConsoleApplication2 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppBuild.targets  434

I tried searching for this error over YouTube and of course here, and also Microsoft's offical forum but couldn't find anything.

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!\n";
}
```

the code looks just fine.

答: I was just having thesame issue so I figured maybe the headers were in a different directory than where the program is searching.  When I went looking for tge header files none existed. So the problem is probably with iostream not existing. </p>

ContentLicense: CC BY-SA 4.0

Body:
Just installed visual studio 2019 on windows 10, was using visual studio for the first time and ran into the following error, It's a basic hello world console program that I tried to run.

error C1083:  Cannot open include file: 'corecrt.h': No such file or directory

1>Done building project "ConsoleApplication2.vcxproj" -- FAILED.

Severity   Code    Description Project File    Line    Suppression State
Warning MSB8003 The WindowsSDKDir property is not defined. Some build tools may not be found.   ConsoleApplication2 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Microsoft\VC\v160\Microsoft.CppBuild.targets  434

I tried searching for this error over YouTube and of course here, and also Microsoft's offical forum but couldn't find anything.

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!\n";
}

the code looks just fine.


问:
Azure Function TimerTrigger Singleton Lock - Can It Be File Storage?
Can I configure an Azure Function TimerTrigger Singleton lock to use Cloud File Storage instead of Cloud Blob Storage and if so, how? i.e. to take a "lease"/lock on a Cloud File instead of a Blob ?

And if that is not possible, can I turn off the Singleton lock altogether somehow ? i.e. to get the TimerTrigger to have no lock at all.

Unfortunately our Azure Storage has not been created with any Blob Storage, only File Storage.

Alternative suggestions to using a TimerTrigger also welcome.

Thanks.

答:
I afraid that you can't disable Singletone lock for TimerTrigger.

Please see implementation of TimerListener here:
https://github.com/Azure/azure-webjobs-sdk-extensions/blob/dev/src/WebJobs.Extensions/Extensions/Timers/Listener/TimerListener.cs

```<code>[Singleton(Mode = SingletonMode.Listener)]
    internal sealed partial class TimerListener : IListener
    {
</code>```

Body:
I afraid that you can't disable Singletone lock for TimerTrigger.

Please see implementation of TimerListener here:
https://github.com/Azure/azure-webjobs-sdk-extensions/blob/dev/src/WebJobs.Extensions/Extensions/Timers/Listener/TimerListener.cs

[Singleton(Mode = SingletonMode.Listener)]
    internal sealed partial class TimerListener : IListener
    {


问:
How can I extract URL of image from a list of Amazon web pages?
```<code>import pandas as pd

listt=[list of web pages]

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

imgss = []
for i in range(len(listt)):
    print(i)
    html = urlopen(listt[i])
    bs = BeautifulSoup(html, 'html.parser')
    images = bs.find_all('img', {'src':re.compile('PATTERN.jpg')})
    for image in images:
        imgss.append(image['src'])

</code>```

There are about 1100 URLs of Amazon web pages in the listt. It works for some initial web pages but after that, it throws error : HTTP Error 503: Service Unavailable .

答:
Try this, to acces element attributes</p>

```<code>imgss.append(image.attrs['src'])
</code>```

Body:
import pandas as pd

listt=[list of web pages]

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

imgss = []
for i in range(len(listt)):
    print(i)
    html = urlopen(listt[i])
    bs = BeautifulSoup(html, 'html.parser')
    images = bs.find_all('img', {'src':re.compile('PATTERN.jpg')})
    for image in images:
        imgss.append(image['src'])

There are about 1100 URLs of Amazon web pages in the listt. It works for some initial web pages but after that, it throws error : HTTP Error 503: Service Unavailable .

Body:
Try this, to acces element attributes

imgss.append(image.attrs['src'])


问:
postgres Like query performance for single word columns
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';
```

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.

答:
I think you have a fundamental (but kind of common) misunderstanding here:

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words

No, that is what Full Text Search is for, which is very different than pg_trgm.

pg_trgm is fairly bad at long text with many words (not as bad since 9.6 as it was before that, but still not its strongest point), but it is good at this very thing you want.

The problem is that you need to have trigrams to start with.  If your query was changed to like '%ab%' then pg_trgm would probably be worse than not having the index at all.  So it might be worthwhile to validate the query in the app or client side to reject attempts to specify such patterns.

Body:
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.


问:
How can i make first letter of all words in a string uppercase recursively?
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

```<code>define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }
</code>```

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

答:
the main problem is that you're using index and recursion at the same time, simple recursive solution would be:

```<code>void capitalize(char* str, bool start){
    if (!*str) return; // end as soon as \0 is met
    if (start)
        if (*str >= 'a' && *str <= 'z') *str = (*str - 'a') + 'A'; // capitalize latin letters
    capitalize(str + 1, *str == ' '); // work with next symbol
}
</code>```

should be called as capitalize(str, true)

Body:
I wonder how can i make this. I don't want any iteration or isalpha() and toupper() functions. We want to use our own code to read input. We assume that user enters all characters lowercase. This is what i've tried so far:

define MAX_LENGTH 100

int read_line(char str[],int);
void capitalize(char[]);

int main (void){
    char A[MAX_LENGTH];
printf("Enter a text \n");
read_line(A, MAX_LENGTH);

capitalize(A);
puts(A);

}

int read_line(char str[],int n){
    int ch,i=0;

    while ((ch = getchar()) != '\n'){
        if(i<MAX_LENGTH)
            str[i++] = ch;
    }
    str[i] = '\0';
    return i;
}

void capitalize(char str[]){
 int x = strlen(str);
 static int i = 0;
    if(str[i]=='\0')
    return;
    if(str[i-1]==' '|| i == 0)
      str[i] -= 32;
      i++;
      return capitalize(&str[i]);
 }

Output is like this:

Enter a text:

asdf sdf df

Asdf sdf df

What is wrong with my code?

Body:
the main problem is that you're using index and recursion at the same time, simple recursive solution would be:

void capitalize(char* str, bool start){
    if (!*str) return; // end as soon as \0 is met
    if (start)
        if (*str >= 'a' && *str <= 'z') *str = (*str - 'a') + 'A'; // capitalize latin letters
    capitalize(str + 1, *str == ' '); // work with next symbol
}

should be called as capitalize(str, true)


问:
How do I centre a block of text but keep the alignment to the left HTML?
I want to centralise the below text but keep the text alignment to the left. i.e. I want to keep the left margin the same size for each line of text:</p>

```<code><li>Stainless steel capacity: 0.5mm<br />
<li>Aluminum, copper, zinc, steel capacity: 0.8mm<br />
<li>Steel, Plastisol capacity: 0.8mm<br />
<li>Length: 310mm<br />
<li>Width: 320 - 610mm<br />
<li>Closing length: 210mm<br />
<li>Weight: 3.3kg<br /></li>
</code>```

答:
Please try and do some research - I promise it is super easy.

ul{
  max-width:700px;
  margin:auto;
  list-style: inside;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul></code>```

The margin:auto property centres items, providing you have a width.

Body:
I want to centralise the below text but keep the text alignment to the left. i.e. I want to keep the left margin the same size for each line of text:

Stainless steel capacity: 0.5mm

Aluminum, copper, zinc, steel capacity: 0.8mm

Steel, Plastisol capacity: 0.8mm

Length: 310mm

Width: 320 - 610mm

Closing length: 210mm

Weight: 3.3kg

Body:
Please try and do some research - I promise it is super easy.

ul{
  max-width:700px;
  margin:auto;
  list-style: inside;
}

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>

The margin:auto property centres items, providing you have a width.


问:
Flask static file content type is text/html after redirect
I have run into a problem with static files after a redirect in Flask.
The web app I am writing will redirect users after logging in for the first time to a site where they need to change the default password they've been provided. On this site my custom stylesheets are entirely broken and images won't display either.
A quick inspection in the Chrome dev tools showed that after the redirect the content type for the all files from the static folder is set to text/html. I suspect that this is the issue.

In my template html the stylesheet is linked in the following way:

```<code><link rel="stylesheet" href="{{ url_for('static', filename='css/colorVariables.css') }}">
</code>```

The stylesheets and images work fine on every other page of the app and also if you go to the exact same page without the redirect.

The redirecting part looks like this:

```<code>if user.first_login:
    return redirect(url_for("change_password"))
</code>```

答: I have found the issue. The redirect was happening in a function run with app.before_request. Wrapping the routes with the function manually solved the problem.

Body:
I have run into a problem with static files after a redirect in Flask.
The web app I am writing will redirect users after logging in for the first time to a site where they need to change the default password they've been provided. On this site my custom stylesheets are entirely broken and images won't display either.
A quick inspection in the Chrome dev tools showed that after the redirect the content type for the all files from the static folder is set to text/html. I suspect that this is the issue.

In my template html the stylesheet is linked in the following way:

<link rel="stylesheet" href="{{ url_for('static', filename='css/colorVariables.css') }}">

The stylesheets and images work fine on every other page of the app and also if you go to the exact same page without the redirect.

The redirecting part looks like this:

if user.first_login:
    return redirect(url_for("change_password"))


问:
JavaScript Debugging
I am using Visual Studio 2010 Express Developer edition. Developing a Website. I'm using JavaScript in my .aspx pages. How to put breakpoints in Javascript.

Any help is highly appreciated.

Thank You

答:
If you're debugging IE, use the following links:

http://aspnetlive.blogspot.com/2010/02/debugging-java-script-in-visual-studio.html

http://msdn.microsoft.com/en-us/library/7seh8d72.aspx

For Firefox, I recommend Firebug.

http://getfirebug.com/

For Chrome, you can use the Developer's Tools debugger.

Update

Here's a comprehensive list of debugging JavaScript in each browser:

http://siliconforks.com/doc/debugging-javascript/

ContentLicense: CC BY-SA 3.0

Title: JavaScript Debugging


问:
VBA AutoShapeType Ignored When Macro Runs
I have the following vba code:

```<code>Dim targetChart As Chart
Dim labelRange As Range

Set targetChart = Worksheets("Graph").ChartObjects("Chart 2").Chart
Set labelRange = Worksheets("Graph").Range("H3", "H" & lastrow)

With targetChart.SeriesCollection(4)
        .ApplyDataLabels
        With .DataLabels
            .Format.AutoShapeType = msoShapeRoundedRectangle
            .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
            .ShowCategoryName = False
            .ShowRange = True
            .ShowSeriesName = False
            .ShowValue = False
        End With
    End With
</code>```

I want to format my data labels as rounded rectangles, but when I run the macro the .Format.AutoShapeType = msoShapeRoundedRectangle seems to not execute. When I step through the macro it doesn't throw an error so I am not sure what I am doing wrong. Everything else within the with statement works as intended.

The reason I have .ShowValue = False is because I am setting the data label values from a range.

答:
Try this:</p>

```<code>targetChart.FullSeriesCollection(1).ApplyDataLabels
    With targetChart.FullSeriesCollection(1).DataLabels
    .ShowRange = True
    .ShowValue = False
    .Format.AutoShapeType = msoShapeRoundedRectangle
    .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
    .Format.Fill.Visible = msoTrue
    .Format.Fill.ForeColor.ObjectThemeColor = msoThemeColorAccent2
    .Format.Fill.ForeColor.TintAndShade = 0.5
    .Format.Fill.ForeColor.Brightness = 0
    .Format.Fill.Solid
End With
</code>```

Body:
I have the following vba code:

Dim targetChart As Chart
Dim labelRange As Range

Set targetChart = Worksheets("Graph").ChartObjects("Chart 2").Chart
Set labelRange = Worksheets("Graph").Range("H3", "H" & lastrow)

With targetChart.SeriesCollection(4)
        .ApplyDataLabels
        With .DataLabels
            .Format.AutoShapeType = msoShapeRoundedRectangle
            .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
            .ShowCategoryName = False
            .ShowRange = True
            .ShowSeriesName = False
            .ShowValue = False
        End With
    End With

I want to format my data labels as rounded rectangles, but when I run the macro the .Format.AutoShapeType = msoShapeRoundedRectangle seems to not execute. When I step through the macro it doesn't throw an error so I am not sure what I am doing wrong. Everything else within the with statement works as intended.

The reason I have .ShowValue = False is because I am setting the data label values from a range.

Body:
Try this:

targetChart.FullSeriesCollection(1).ApplyDataLabels
    With targetChart.FullSeriesCollection(1).DataLabels
    .ShowRange = True
    .ShowValue = False
    .Format.AutoShapeType = msoShapeRoundedRectangle
    .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, labelRange.Address(External:=True), 0
    .Format.Fill.Visible = msoTrue
    .Format.Fill.ForeColor.ObjectThemeColor = msoThemeColorAccent2
    .Format.Fill.ForeColor.TintAndShade = 0.5
    .Format.Fill.ForeColor.Brightness = 0
    .Format.Fill.Solid
End With


问:
Count number of ways to reach a score
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

```<code>Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6
</code>```

2nd Example:

```<code>Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)
</code>```

I have come up with below code with help of this link:

```<code>static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}
</code>```

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

答:
Here you go,

For input 0 or 1, result should be 0, because no way to reach the score using 2, 3 or 6.

I consider all the tiny numbers ( <= 6 ) first and then find all other numbers with a straight loop (no more if statements).

The returned type is long just to handle large inputs.

```<code>  if (n == 0 || n == 1)
     return 0L;

  if (n == 2 || n == 3 || n == 4)
     return 1L;

  if (n == 5)
     return 2L;

  if (n == 6)
     return 3L;

  // Otherwise, n>6

  long[] table = new long[n + 1];
  table[0] = 1; // Base case
  table[1] = 0L; //
  table[2] = 1L; // 2
  table[3] = 1L; // 3
  table[4] = 1L; // 2+2
  table[5] = 2L; // 2+3, 3+2
  table[6] = 3L; // 2+2+2, 3+3, 6

  for (int i = 7; i <= n; i++)
     table[i] = table[i - 2] + table[i - 3] + table[i - 6];

  return table[n];
</code>```

Title: Count number of ways to reach a score

Body:
I am working on a task where I have a number now I want to know how many ways to reach to this number using 2,3,6 using additions and I can use a number as many number of times as possible.

1st Example:

Given number is 6
There are 3 ways to reach to this number:
2 +2 + 2 = 2*3
3 + 3 = 3*2
6

2nd Example:

Given number is 5
There are 2 ways to reach to this number:
2+3
3+2 (order matters here)

I have come up with below code with help of this link:

static int count(int n) {
    // table[i] will store count of solutions for
    // value i.
    int table[] = new int[n + 1], i;

    // Base case (If given value is 0)
    table[0] = 1;

    // One by one consider given 3
    // moves and update the table[]
    // values after the index greater
    // than or equal to the value of
    // the picked move
    for (i = 2; i <= n; i++)
        table[i] += table[i - 2];
    for (i = 3; i <= n; i++)
        table[i] += table[i - 3];
    for (i = 6; i <= n; i++)
        table[i] += table[i - 6];

    return table[n];
}

This code is working only for 1st example, but not working for 2nd example because the program is returning 1 instead of 2.

How to fix this issue?

Body:
Here you go,

For input 0 or 1, result should be 0, because no way to reach the score using 2, 3 or 6.

I consider all the tiny numbers ( <= 6 ) first and then find all other numbers with a straight loop (no more if statements).

The returned type is long just to handle large inputs.

  if (n == 0 || n == 1)
     return 0L;

  if (n == 2 || n == 3 || n == 4)
     return 1L;

  if (n == 5)
     return 2L;

  if (n == 6)
     return 3L;

  // Otherwise, n>6

  long[] table = new long[n + 1];
  table[0] = 1; // Base case
  table[1] = 0L; //
  table[2] = 1L; // 2
  table[3] = 1L; // 3
  table[4] = 1L; // 2+2
  table[5] = 2L; // 2+3, 3+2
  table[6] = 3L; // 2+2+2, 3+3, 6

  for (int i = 7; i <= n; i++)
     table[i] = table[i - 2] + table[i - 3] + table[i - 6];

  return table[n];


问:
Swift Firebase Facebook Login - Gets Name, but email returns nil
Recently my facebook login hasn't been working. It doesn't save into my database but in Firebase authentication it shows someone signed in with facebook but the email is blank. It doesn't save any data to my database which it should. The email is returning nil. My google sign in works. I've checked all the connections and they all seem to be fine. (I could have missed something) anyone have any suggestions on what connections I should check? Not sure what to do...

More Info

I printed my graph request... not sure if this helps to debug

```<code>let loginManager: FBSDKLoginManager = FBSDKLoginManager()
        loginManager.logIn(withReadPermissions: self.facebookPermissions, from: self, handler: { (result, error) in
            if error != nil {
                loginManager.logOut()
                let message: String = "An error has occured. \(String(describing: error))"
                let alertView = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
                alertView.addAction(UIAlertAction(title: "Ok ", style: UIAlertActionStyle.default, handler: nil))
                self.present(alertView, animated: true, completion: nil)
            } else if (result?.isCancelled)! {
                // user cancelled login
                loginManager.logOut()
            } else {
                let accessToken = FBSDKAccessToken.current()
                guard let accessTokenString = accessToken?.tokenString else { return }
                let credential = FacebookAuthProvider.credential(withAccessToken: accessTokenString)

                Auth.auth().signIn(with: credential) { (user, error) in
                    if (error != nil) {
                        // handle error
                        print(error ?? "Error")
                    } else {
                        let ref = Database.database().reference()

                        // guard for user id
                        guard let uid = user?.uid else {
                            return
                        }
                        let usersReference = ref.child("user_profiles").child(uid)

                        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
                        graphRequest.start(completionHandler: { (connection, result, error) -> Void in
                            if error != nil {
                                // Process error
                                print("Error: \(String(describing: error))")
                            } else {
                                guard let data: [String:AnyObject] = result  as? [String:AnyObject] else {
                                    print("Can't pull data from JSON")
                                    return
                                }
                                guard let userName: String = data["name"] as? String else {
                                    print("Can't pull username from JSON")
                                    return
                                }
                                guard let userID: String = data["id"] as? String else {
                                    print("Can't pull ID from JSON")
                                    return
                                }
                                let imgURLString = "http://graph.facebook.com/\(userID)/picture?type=large" as String
                                guard let userEmail: String = data["email"] as? String else {
                                    print("Can't pull email from JSON")
                                    print("Error: \(String(describing: error))")
                                    return
                                }

                                // initial # posts = 0
                                let values = ["name": userName, "email": userEmail, "facebookID": userID, "profPicString": imgURLString] as [String : Any]

                                // update database with new user
                                usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                                    // error in database save
                                    if err != nil {
                                        print(err ?? "Error saving user to database")
                                        return
                                    }
                                })
                            }
                        })
                        self.dismiss(animated: false, completion: nil)
                        // Present the main view
                        if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Customer Profile") {
                            UIApplication.shared.keyWindow?.rootViewController = viewController
                            self.dismiss(animated: true, completion: nil)
                        }
                    }
                }
            }
        })
</code>```

答:
Using Swift 5 I found the email inside providerData which is an array of FIRUserInfo:

```<code>if AccessToken.current != nil {
    let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
    Auth.auth().signIn(with: credential) { (res, err) in
        if err != nil || res == nil {
            //...
            return
        }
        guard let providerData = res?.user.providerData else {
            //...
            return
        }
        for firUserInfo in providerData {
            print(firUserInfo.providerID)
            print(firUserInfo.email ?? "Email not found")
        }
    }
}
</code>```

Body:
Recently my facebook login hasn't been working. It doesn't save into my database but in Firebase authentication it shows someone signed in with facebook but the email is blank. It doesn't save any data to my database which it should. The email is returning nil. My google sign in works. I've checked all the connections and they all seem to be fine. (I could have missed something) anyone have any suggestions on what connections I should check? Not sure what to do...

More Info

I printed my graph request... not sure if this helps to debug

let loginManager: FBSDKLoginManager = FBSDKLoginManager()
        loginManager.logIn(withReadPermissions: self.facebookPermissions, from: self, handler: { (result, error) in
            if error != nil {
                loginManager.logOut()
                let message: String = "An error has occured. \(String(describing: error))"
                let alertView = UIAlertController(title: "Alert", message: message, preferredStyle: UIAlertControllerStyle.alert)
                alertView.addAction(UIAlertAction(title: "Ok ", style: UIAlertActionStyle.default, handler: nil))
                self.present(alertView, animated: true, completion: nil)
            } else if (result?.isCancelled)! {
                // user cancelled login
                loginManager.logOut()
            } else {
                let accessToken = FBSDKAccessToken.current()
                guard let accessTokenString = accessToken?.tokenString else { return }
                let credential = FacebookAuthProvider.credential(withAccessToken: accessTokenString)

                Auth.auth().signIn(with: credential) { (user, error) in
                    if (error != nil) {
                        // handle error
                        print(error ?? "Error")
                    } else {
                        let ref = Database.database().reference()

                        // guard for user id
                        guard let uid = user?.uid else {
                            return
                        }
                        let usersReference = ref.child("user_profiles").child(uid)

                        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email"])
                        graphRequest.start(completionHandler: { (connection, result, error) -> Void in
                            if error != nil {
                                // Process error
                                print("Error: \(String(describing: error))")
                            } else {
                                guard let data: [String:AnyObject] = result  as? [String:AnyObject] else {
                                    print("Can't pull data from JSON")
                                    return
                                }
                                guard let userName: String = data["name"] as? String else {
                                    print("Can't pull username from JSON")
                                    return
                                }
                                guard let userID: String = data["id"] as? String else {
                                    print("Can't pull ID from JSON")
                                    return
                                }
                                let imgURLString = "http://graph.facebook.com/\(userID)/picture?type=large" as String
                                guard let userEmail: String = data["email"] as? String else {
                                    print("Can't pull email from JSON")
                                    print("Error: \(String(describing: error))")
                                    return
                                }

                                // initial # posts = 0
                                let values = ["name": userName, "email": userEmail, "facebookID": userID, "profPicString": imgURLString] as [String : Any]

                                // update database with new user
                                usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
                                    // error in database save
                                    if err != nil {
                                        print(err ?? "Error saving user to database")
                                        return
                                    }
                                })
                            }
                        })
                        self.dismiss(animated: false, completion: nil)
                        // Present the main view
                        if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Customer Profile") {
                            UIApplication.shared.keyWindow?.rootViewController = viewController
                            self.dismiss(animated: true, completion: nil)
                        }
                    }
                }
            }
        })

Body:
Using Swift 5 I found the email inside providerData which is an array of FIRUserInfo:

if AccessToken.current != nil {
    let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
    Auth.auth().signIn(with: credential) { (res, err) in
        if err != nil || res == nil {
            //...
            return
        }
        guard let providerData = res?.user.providerData else {
            //...
            return
        }
        for firUserInfo in providerData {
            print(firUserInfo.providerID)
            print(firUserInfo.email ?? "Email not found")
        }
    }
}


问:
How to migrate existing java based cucumber test framework to Karate
Karate recently released GUI Automation feature. I always liked the karate way of writing script. I'm thinking to implement Karate's unified framework for Rest + GUI at larger scale in my org.

Problem statement: The existing teams uses purely cucumber based framework and have automated significant number of tests. In order to migrate Karate framework we will need to re write automated tests with Karate's standards. It would take huge efforts to migrate existing tests considering volume of work. I am just looking for best possible ways to migrate with minimum efforts.

Is there a way I can add Karate to my existing cucumber based framework so that I can keep existing tests running while writing new tests with karate guidelines.

答:
It should be possible (in theory) to mix Karate and Cucumber in the same Maven (or Gradle) project. Unfortunately I don't know of too many people who have done this.

Please refer to this discussion for more: https://github.com/intuit/karate/issues/444#issuecomment-419852761

Sorry I can't provide a more clearer answer, you may need to experiment a bit.


答:
You could place it in a
 container which is centered using margin:0; and its parent set to display:flex;

Let me know if that works or paste your code.

Your list items
 needed to have their own closing tags each
 even these little errors can cause an entire web page to not work also it's just

Code

Stainless steel capacity: 0.5mm

Aluminum, copper, zinc, steel capacity: 0.8mm

Steel, Plastisol capacity: 0.8mm

Length: 310mm

Width: 320 - 610mm

Closing length: 210mm

Weight: 3.3kg

 then in your head you will need to add this style...

```<code><style>
        .list-container {
            display: flex;
            width: 100%;
        }

        .list-container ul {
            margin: auto;
        }
    </style>
</code>```

If you are still having issues you can email me at lexar5657@gmail.com

Title: How do I centre a block of text but keep the alignment to the left HTML?

Body:
You could place it in a <div> container which is centered using margin:0; and its parent set to display:flex;

Let me know if that works or paste your code.

Your list items <li> needed to have their own closing tags each </li> even these little errors can cause an entire web page to not work also it's just <br>

Code

    <div class="list-container">
        <ul>
            <li>Stainless steel capacity: 0.5mm</li><br>
            <li>Aluminum, copper, zinc, steel capacity: 0.8mm</li><br>
            <li>Steel, Plastisol capacity: 0.8mm</li><br>
            <li>Length: 310mm</li><br>
            <li>Width: 320 - 610mm</li><br>
            <li>Closing length: 210mm</li><br>
            <li>Weight: 3.3kg</li><br>
        </ul>
    </div>

 then in your head you will need to add this style...

<style>
        .list-container {
            display: flex;
            width: 100%;
        }

        .list-container ul {
            margin: auto;
        }
    </style>

If you are still having issues you can email me at lexar5657@gmail.com


问:
Try to filter ListView.builder inside StreamBuilder in Flutter
i'm newbie in Flutter and I'm  trying to develop an app, so nom have a trouble with how to show a filtered ListView.builder

This is the widget code:

```<code>@override
Widget build(BuildContext context) {

print('Favorites');
return Container(
  color: AppColors.hexToColor('F0F4F5'),
  alignment: Alignment.topCenter,
  child: Column(
    children: <Widget>[
      HeaderCity(),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0),
          child: Container(
            child: StreamBuilder<CoworkingState>(
                stream: Provider.coworkingBlocOf(context).streamCoworkingState,
                initialData: CoworkingState(),
                builder: (BuildContext context, AsyncSnapshot<CoworkingState> snapshot) {
                  return (snapshot.data.isLoading)
                      ? CustomCircularLoader()
                      : ListView.builder(
                          padding: EdgeInsets.all(0.0),
                          itemBuilder: (BuildContext context, int index) {
                            if (snapshot.data.coworking.any((isFavorite) => true)){
                              return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
                            } return null;
                          },
                          itemCount: snapshot.data.coworking.length,
                        );
                }),
          ),
        ),
      ),
    ],
  ),
);
</code>```

}

So now this  are returning a complete list and I only want to show items with isFavorite = true

答:
You are not if condition is not working correctly.

You are returning true for each and every case that’s why it is adding all the items.

Try Following one:

```<code>...
if (snapshot.data.coworking.any((isFavorite) => isFavorite)){ //here it return true if isFavorite is true and if isFavorite is false then it will return false.
....
</code>```

Body:
i'm newbie in Flutter and I'm  trying to develop an app, so nom have a trouble with how to show a filtered ListView.builder

This is the widget code:

@override
Widget build(BuildContext context) {

print('Favorites');
return Container(
  color: AppColors.hexToColor('F0F4F5'),
  alignment: Alignment.topCenter,
  child: Column(
    children: <Widget>[
      HeaderCity(),
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 16.0, right: 16.0),
          child: Container(
            child: StreamBuilder<CoworkingState>(
                stream: Provider.coworkingBlocOf(context).streamCoworkingState,
                initialData: CoworkingState(),
                builder: (BuildContext context, AsyncSnapshot<CoworkingState> snapshot) {
                  return (snapshot.data.isLoading)
                      ? CustomCircularLoader()
                      : ListView.builder(
                          padding: EdgeInsets.all(0.0),
                          itemBuilder: (BuildContext context, int index) {
                            if (snapshot.data.coworking.any((isFavorite) => true)){
                              return CoworkingCellDetail(
                                onTap: () {
                                  Provider.coworkingBlocOf(context)
                                      .selectCoworking(coworking: snapshot.data.coworking[index]);
                                  Future.delayed(Duration.zero, () {
                                    changeRoute(context, Routes.coworkDetail, false);
                                  });
                                },
                                isFavorite: snapshot.data.coworking[index].isFavorite,
                                name: snapshot.data.coworking[index].name,
                                adress: snapshot.data.coworking[index].address,
                                phone: snapshot.data.coworking[index].phone,
                                hour: snapshot.data.coworking[index].openingHours,
                                urlImages: snapshot.data.coworking[index].imagesUrl,
                                onFavoriteTap: () {
                                  Provider.coworkingBlocOf(context).removeFavorite(snapshot.data.coworking[index].id);
                                }
                              );
                            } return null;
                          },
                          itemCount: snapshot.data.coworking.length,
                        );
                }),
          ),
        ),
      ),
    ],
  ),
);

}

So now this  are returning a complete list and I only want to show items with isFavorite = true

Body:
You are not if condition is not working correctly.

You are returning true for each and every case that’s why it is adding all the items.

Try Following one:

...
if (snapshot.data.coworking.any((isFavorite) => isFavorite)){ //here it return true if isFavorite is true and if isFavorite is false then it will return false.
....


问:
Alternative to declaring const in google sheets script
I understand that google sheets does not support const declaration

I currently use var at the global level. This of course allows duplicate declarations of the same name to take place.
One may define the following global statements in two different scripts files, within the same project.

```<code>var name = "Jhon";
var name = "Sam";
</code>```

Only the last to be loaded will be actually take place.

What is the best practice to avoid that, if any at all?

答: You can upgrade to the modern faster V8 engine to use const

Body:
I understand that google sheets does not support const declaration

I currently use var at the global level. This of course allows duplicate declarations of the same name to take place.
One may define the following global statements in two different scripts files, within the same project.

var name = "Jhon";
var name = "Sam";

Only the last to be loaded will be actually take place.

What is the best practice to avoid that, if any at all?


问:
java.time.temporal.ValueRange bug when constructing
I am working with some time stuff in a project, and as I was implementing unit testing, I am not sure if I have found a bug, or if I have have just misunderstood the documentation.  The javadocs for ValueRange.of(long min, long maxSmallest, long maxLargest) state:

```<code> * @return the ValueRange for min, smallest max, largest max, not null
 * @throws IllegalArgumentException if
 *     the minimum is greater than the smallest maximum,
 *  or the smallest maximum is greater than the largest maximum
</code>```

The way I read that is if the value passed for min is larger than the value for maxSmallest, it should throw an exception.  However, the following code works:

ValueRange vr = ValueRange.of(5, 2, 10);

I think this should fail.  The value for min is larger than the value for smallest maximum, but no exception is thrown.  In addition, when printing the resulting ValueRange, it looks very strange:  5 - 2/10

Is this a bug?  Or am I just not understanding the javadocs?

答:
It is a bug JDK-8239520 and it has been fixed in JDK 15 Build 12.

I have created unit tests based on ValueRange.of() API for different value ranges:

package org.mycompany.mavenproject1;

import java.time.temporal.ValueRange;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

public class ValueRangeTest {

    @ParameterizedTest
    @CsvSource({
        "5, 2" // the minimum is greater than the maximum
    })
    public void testFixedValueRange(long min, long max) {
        Executable when = () -> ValueRange.of(min, max);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", max: " + max);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 2, 10", // the minimum is greater than the smallest maximum - THIS FAILS!
        "2, 10, 2" // the smallest maximum is greater than the largest maximum
    })
    public void testVariableValueRange(long min, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(min, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 1, 2, 10", // the smallest minimum is greater than the smallest maximum
        "1, 2, 10, 2", // the smallest maximum is greater than the largest maximum
        "1, 11, 2, 10" // the largest minimum is greater than the largest maximum
    })
    public void testFullyVariableValueRange(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(minSmallest, minLargest, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "minSmallest: " + minSmallest + ", minLargest: " + minLargest + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

}
```

<p>All scenarios pass but one - <code>if the minimum is greater than the smallest maximum</code></p>

```Tests run: 6, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.087 s <<< FAILURE! - in org.mycompany.mavenproject1.ValueRangeTest
testVariableValueRange{long, long, long}[1]  Time elapsed: 0.034 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: min: 5, maxSmallest: 2, maxLargest: 10 ==> Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
    at org.mycompany.mavenproject1.ValueRangeTest.testVariableValueRange(ValueRangeTest.java:30)
```

This makes me believe that this is a bug in the ValueRange.

Body:
I am working with some time stuff in a project, and as I was implementing unit testing, I am not sure if I have found a bug, or if I have have just misunderstood the documentation.  The javadocs for ValueRange.of(long min, long maxSmallest, long maxLargest) state:

 * @return the ValueRange for min, smallest max, largest max, not null
 * @throws IllegalArgumentException if
 *     the minimum is greater than the smallest maximum,
 *  or the smallest maximum is greater than the largest maximum

The way I read that is if the value passed for min is larger than the value for maxSmallest, it should throw an exception.  However, the following code works:

ValueRange vr = ValueRange.of(5, 2, 10);

I think this should fail.  The value for min is larger than the value for smallest maximum, but no exception is thrown.  In addition, when printing the resulting ValueRange, it looks very strange:  5 - 2/10

Is this a bug?  Or am I just not understanding the javadocs?

Body:
It is a bug JDK-8239520 and it has been fixed in JDK 15 Build 12.

I have created unit tests based on ValueRange.of() API for different value ranges:

package org.mycompany.mavenproject1;

import java.time.temporal.ValueRange;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

public class ValueRangeTest {

    @ParameterizedTest
    @CsvSource({
        "5, 2" // the minimum is greater than the maximum
    })
    public void testFixedValueRange(long min, long max) {
        Executable when = () -> ValueRange.of(min, max);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", max: " + max);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 2, 10", // the minimum is greater than the smallest maximum - THIS FAILS!
        "2, 10, 2" // the smallest maximum is greater than the largest maximum
    })
    public void testVariableValueRange(long min, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(min, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "min: " + min + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

    @ParameterizedTest
    @CsvSource({
        "5, 1, 2, 10", // the smallest minimum is greater than the smallest maximum
        "1, 2, 10, 2", // the smallest maximum is greater than the largest maximum
        "1, 11, 2, 10" // the largest minimum is greater than the largest maximum
    })
    public void testFullyVariableValueRange(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {
        Executable when = () -> ValueRange.of(minSmallest, minLargest, maxSmallest, maxLargest);

        assertThrows(IllegalArgumentException.class, when,
                () -> "minSmallest: " + minSmallest + ", minLargest: " + minLargest + ", maxSmallest: " + maxSmallest + ", maxLargest: " + maxLargest);
    }

}

All scenarios pass but one - if the minimum is greater than the smallest maximum

Tests run: 6, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.087 s <<< FAILURE! - in org.mycompany.mavenproject1.ValueRangeTest
testVariableValueRange{long, long, long}[1]  Time elapsed: 0.034 s  <<< FAILURE!
org.opentest4j.AssertionFailedError: min: 5, maxSmallest: 2, maxLargest: 10 ==> Expected java.lang.IllegalArgumentException to be thrown, but nothing was thrown.
    at org.mycompany.mavenproject1.ValueRangeTest.testVariableValueRange(ValueRangeTest.java:30)

This makes me believe that this is a bug in the ValueRange.


问:
UITableView: the proper way to display a separator for the last cell
The question is what's the right-most way to display a separator in the last cell in a table/section.

Basically this is what I am after.

This is from the native music app, which makes me think that it should be possible to achieve just by means of UITableView, they would not be using some private API for cell separators, right?

I know you can get away without using actual separators, but adding one pixel line in the bottom of the cell. But I'm not a fan of this approach because

When a cell is selected/highlighted its separator and the separator of the previous cell are automatically hidden (see the second screenshot with "You've got to be crazy" selected). And this is
something I want UITableView to handle instead of doing myself if I use one-pixel line
(which is especially handy when cell separators do not extend all
the way to the edge of the table view, separators and selected cell background do not look nice together).

I would like to keep my cells as flat as possible for scrolling performance.

Also there is something in UITableView reference that makes me think that there is an easy way to get what I want:

In iOS 7 and later, cell separators do not extend all the way to the
  edge of the table view. This property sets the default inset for all
  cells in the table, much like rowHeight sets the default height for
  cells. It is also used for managing the “extra” separators drawn at
  the bottom of plain style tables.

Does somebody know how exactly to use these “extra” separators drawn at the bottom of plain style tables? Because this is exactly what I need.
I thought assigning separatorInsetto the UITableView, not UITableViewCell would do the trick, but it does not, the last cell is still missing its separator.

Right now I only see one option: to have a custom section footer to mimic the separator for the last cell. And this is not good, especially if you want to have an actual section footer using tableView:titleForFooterInSection: method.

答:
I used the table view style "grouped" to add this line:

And furthermore it avoids sticking the last separator line to stick on the screen when scrolling out!


问:
How to display Last week Sunday and last week Saturday in SSRS?
How to display Last week Sunday and last week Saturday from current date in SSRS  ?

In sql server we can find the last week Sunday and last week Saturday  from todays date(CurrentDate='19-02-2020') as

select DATEADD(wk, -1, DATEADD(wk, DATEDIFF(wk, 0,getdate()), -1))-- for sunday

select DATEADD(wk, DATEDIFF(wk, 0, getdate()), -2) --for saturday

So how we can write an default expression in the SSRS Parameters?

答:
This assumes that the first day of the week is a Sunday, if you configuration is not like this then you will need to adjust the expressions to correct the offset

For Last Saturday use:

```<code>=DATEADD(DateInterval.Day, Weekday(Today()) * -1, Today())
</code>```

For Last Sunday use:

```<code>=DATEADD(DateInterval.Day, (Weekday(Today()) -1) * -1, Today())
</code>```

Body:
This assumes that the first day of the week is a Sunday, if you configuration is not like this then you will need to adjust the expressions to correct the offset

For Last Saturday use:

=DATEADD(DateInterval.Day, Weekday(Today()) * -1, Today())

For Last Sunday use:

=DATEADD(DateInterval.Day, (Weekday(Today()) -1) * -1, Today())


问:
get previous row id using stored procedure
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

```<code>select * from table b where ID = 4
</code>```

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.

答: How about selecting all ID's less than 5 and sorting them by ID.  The first result then would be the one you want.</p>

Body:
My requirement like this:

I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like

select * from table b where ID = 4

Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?

Please give me some sql stored procedure to get previous id record from table.


问:
How to do split NSToolbarItem
I'm wondering what the best way is to do a split NSToolbarItem like Xcode does. I've read the documentation, but can't figure out a way to do this. Any ideas?

答:
It's a custom control. Basically it's a custom NSView, drawing a background the same as a button/popup, draws the "selection" on both sides, handles mouse events and displays one of two menus based on which side was clicked. It's not difficult, but it's not a trivial amount of code to whip up and share either. Just look at any examples of making any kind of clickable custom view and you'll be on your way.

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaViewsGuide/SubclassingNSView/SubclassingNSView.html

Title: How to do split NSToolbarItem


问:
How to use stack navigation, drawer navigation and tab navigation simultaneously in react navigation v5
I'm looking to render the drawer navigation, tab navigation and stack navigation simultaneously in my app.
but I'm getting this error:

This is my root.js file content:

```<code>import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import {Like, Home, Search, Media, Profile, Direct, HeaderProfile, CustomDrawer } from './components/index';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createStackNavigator } from '@react-navigation/stack';
import { createDrawerNavigator } from '@react-navigation/drawer';
</code>```

This the tab navigation code:

```<code>const Tab =createMaterialTopTabNavigator();

const MyTabs=()=>{

return(

    <Tab.Navigator>
    <Tab.Screen name="Home" component={Home}/>
    <Tab.Screen name="Search" component={Search} />
    <Tab.Screen name="Media" component={Media} />
    <Tab.Screen name="Like" component={Like} />
    <Tab.Screen name="Profile" component={Profile} />

  </Tab.Navigator>
)}
</code>```

This the drawer navigation code:

```<code>
onst Drawer = createDrawerNavigator();

const MyDrawer=()=> {
  return (

      <Drawer.Navigator>

        <Drawer.Screen name="Home" component={Home} />

      </Drawer.Navigator>

  );}

</code>```

And this stack navigation code: (I've imported two above components into stack navigation)

```<code>
        const Stack= createStackNavigator();

        const MainStack=()=>{

        return(

        <NavigationContainer>
        <Stack.Navigator>

        <Stack.Screen name="MyTabs" component={MyTabs} options={{headerShown:false}}  />
        <Stack.Screen name="MyDrawer" component={MyDrawer}   />
        <Stack.Screen name="Direct" component={Direct} />

        </Stack.Navigator>
        </NavigationContainer>

        )}

</code>```

I should say when i remove drawer navigation, everything works without any problem

This the code i implemented to open drawer in profile.js :

```<code>const HeaderProfile = (props) => {

const {navigation}=props;

    return (

            <View >

                <TouchableWithoutFeedback
                onPress={()=>navigation.openDrawer()}

                />
           </View >
                    )}

</code>```

How can i fix this?

答: I have been struggling with this same problem for a whole week. Yes, I am a beginner, but this youtube video helped me. (React Native #21: React Navigation(New Version) Mix Tabs + Drawer + Stack) https://www.youtube.com/watch?v=z7wZSA176kE</p>

Body:
I'm looking to render the drawer navigation, tab navigation and stack navigation simultaneously in my app.
but I'm getting this error:

This is my root.js file content:

import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import {Like, Home, Search, Media, Profile, Direct, HeaderProfile, CustomDrawer } from './components/index';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createStackNavigator } from '@react-navigation/stack';
import { createDrawerNavigator } from '@react-navigation/drawer';

This the tab navigation code:

const Tab =createMaterialTopTabNavigator();

const MyTabs=()=>{

return(

    <Tab.Navigator>
    <Tab.Screen name="Home" component={Home}/>
    <Tab.Screen name="Search" component={Search} />
    <Tab.Screen name="Media" component={Media} />
    <Tab.Screen name="Like" component={Like} />
    <Tab.Screen name="Profile" component={Profile} />

  </Tab.Navigator>
)}

This the drawer navigation code:

onst Drawer = createDrawerNavigator();

const MyDrawer=()=> {
  return (

      <Drawer.Navigator>

        <Drawer.Screen name="Home" component={Home} />

      </Drawer.Navigator>

  );}

And this stack navigation code: (I've imported two above components into stack navigation)

        const Stack= createStackNavigator();

        const MainStack=()=>{

        return(

        <NavigationContainer>
        <Stack.Navigator>

        <Stack.Screen name="MyTabs" component={MyTabs} options={{headerShown:false}}  />
        <Stack.Screen name="MyDrawer" component={MyDrawer}   />
        <Stack.Screen name="Direct" component={Direct} />

        </Stack.Navigator>
        </NavigationContainer>

        )}

I should say when i remove drawer navigation, everything works without any problem

This the code i implemented to open drawer in profile.js :

const HeaderProfile = (props) => {

const {navigation}=props;

    return (

            <View >

                <TouchableWithoutFeedback
                onPress={()=>navigation.openDrawer()}

                />
           </View >
                    )}

How can i fix this?


问:
Is there a REST API Reference available for AWS?
As far as I understand, there are only three ways to access AWS resources:

Management Console (browser)

AWS CLI

AWS SDK (in various programming languages)

However, why did not AWS provide REST APIs and their reference document so that we can interact with AWS resources directly using a REST client like Postman?

I think they are using REST APIs behind the scenes (All the above three interactions actively use REST API I guess).

Thanks in advance.

答:
There is REST API documentation available as well. Its just that AWS officially encourages the use of more abstract methods such as using CLI and SDK since its easier to use as well as they are maintained by AWS.

Also using the sdk or cli is encouraged because they are perfectly interfaced with the aws rest api with extensive testing and covering all cases. And you don't need to focus on stuff like what headers you need to attach or what should be the request body format. Users can focus on writing their own business logic.

The only source I could find for documentation of rest api are the official docs which I have linked below. Since the direct use of rest api is not preferred hence no commonly available tutorials. I don't think there is anything extra which can be accomplished using the rest api which the cli or sdk doesn't already offer.

A more practical example would be aws s3 cli. It has a lot of underlying implementation which speeds up the process of uploading and downloading, like establishing 10 network connections in parallel to utilize the complete network bandwidth etc. This you would have to implement yourself if you are directly using the api.

Some Examples:
S3 REST API
EC2 REST API

Similarly there is API documentation available for every service.


问:
Android Fragment no view found for ID?
I have a fragment I am trying to add into a view.

```<code>FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)fragMgr
                                    .findFragmentById(R.id.feedContentContainer);
FragmentTransaction xaction=fragMgr.beginTransaction();

if (content == null || content.isRemoving()) {
    content=new feed_parser_activity(item.getLink().toString());
    xaction
        .add(R.id.feedContentContainer, content)
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .addToBackStack(null)
        .commit();
    Log.e("Abstract", "DONE");
}
</code>```

When this code is executed I get the following error in debug..

```<code>java.lang.IllegalArgumentException: No view found for id 0x7f080011
   for fragment feed_parser_activity{41882f50 #2 id=0x7f080011}
</code>```

feed_parser_activity is a Fragment that is set to Fragment layout in xml.

I am using a FragmentActivity to host the Fragment Layout holding the feed_parser_layout.

Am I coding this correctly above?

答:
In our case we have purged/corrupted class.dex file along with gradle compiled outputs. Due to cache recompile weren't tried hence no error, but apk was not having the required file causing this confusing error. A gradle resync and fresh build cleared us from all errors.

// Happy coding

Title: Android Fragment no view found for ID?

Body:
I have a fragment I am trying to add into a view.

FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)fragMgr
                                    .findFragmentById(R.id.feedContentContainer);
FragmentTransaction xaction=fragMgr.beginTransaction();

if (content == null || content.isRemoving()) {
    content=new feed_parser_activity(item.getLink().toString());
    xaction
        .add(R.id.feedContentContainer, content)
        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        .addToBackStack(null)
        .commit();
    Log.e("Abstract", "DONE");
}

When this code is executed I get the following error in debug..

java.lang.IllegalArgumentException: No view found for id 0x7f080011
   for fragment feed_parser_activity{41882f50 #2 id=0x7f080011}

feed_parser_activity is a Fragment that is set to Fragment layout in xml.

I am using a FragmentActivity to host the Fragment Layout holding the feed_parser_layout.

Am I coding this correctly above?


问:
SCNkit: Issues with unhidden nodes
I am creating a 3-D game with a cave as the main environment. The cave is made of a large number of ring segments, one attached to the other, thus creating a currently small tunnel system.

If the Player is inside the cave, only a small part of the segments are visible. I am figuring that actually hiding the not-visible segments could save a lot of gpu time, which I need for other objects like  buildings or enemies.

So what I try to do first is hiding the entire cave and then unhiding the visible segments by turning ‚node.isHidden’ true and false.
The particular nodes are being found and accessed by their names: ‚Node.childnode (withName: „XYZ003“, recursively: false).isHidden = true‘ (or false).

It works to the point where the segments are unhidden, but once I am trying to hide a previously unhidden segment, the renderer crashes with an EXC_BAD_ACCESS.

Doing the hiding on a hidden object (of course useless, but helping to understand the problem) is fine, so is unhiding unhidden segments.

Following the hint of another thread, I moved the routine into the renderer delegate so not doing the switching during the wrong time, but instead during the phase in which such changes are supposed to happen, but this did not help.
As an alternative, I did the hiding (and unhiding) by SCNActions, but I received the same result, which really puzzles me, as this would be kind of the ‚official way‘ to do it...

I also played around with the ‚recursively’ boolean, getting the same outcome (works for unhide, crashes on isHidden = true).

Then I tried to change opacity or other properties of the nodes - which worked perfectly. On the other hand, trying to remove the nodes from the parent resulted in the mentioned crash as well.

I need this to work, because older hardware could never cope with several thousand nodes (trying this, the frame rate dropped to 10fps, even without enemies around). And newer hardware might break down once the enemies appear...

My thinking is that the pointer is somehow messed up by the first unhiding (and hence the BAD_ACCESS error), so maybe an additional bonding (often seen with spritekit-routines) or another way to get the node-pointer could be the solution. On the other hand, if the pointer is broken, why can I still access all other properties? Maybe it‘s the subnodes that cause the problem - everyone of the nodes has 20 subnodes, which are supposed to change visibility, too.

Did anyone come across this behavior before me? I could not find anything during my google-research...

答:
Hiding and unhiding nodes frequently is typically not a problem by itself.  You can hide a main node and any sub-nodes of the main node will automatically hide themselves, so you shouldn't have to loop them individually.

I'm not an expert debugger and don't know your skill level, but BAD_ACCESS can mean that you tried to send a msg to a block of memory that can't execute the message or whenever the app tried to deference a corrupt pointer.  Search "What Is EXC_BAD_ACCESS and How to Debug It" for a decent tutorial on some options for dealing with it.

I do my changes in the render delegate as well, but depending on the number of changes and how long they take, I sometimes use timers to control the amount of changes that can be made in a certain amount of time.  That way, and after some adjustments, I'm pretty sure that I'm not bogging it down to a point where it just spirals out of control.

Structure can matter - personal preference, but I try to setup an array of classes that create individual nodes (and sub-nodes) and therefore have direct access to them.  That way I'm not iterating through the whole node structure or finding nodes by name.  Sometimes a lot is going on before I really have to make a modification to the node itself and so I can loop through my array of classes, check values, compare, etc. before taking action that involves the display.  That also gives me a chance to remove particle systems, remove actions, set geometry = nil and update logic counters when I need to remove a node.

I'm sure opinions vary, but this has worked well for me.  Once I standardized the structure, I just keep repeating the pattern.

Hope that helps

Title: SCNkit: Issues with unhidden nodes


问:
InsertAfter long block of HTML using Javascript
I'm attempting to insert a long block of HTML after a div element using javascript. I've tried a few methods, but none seem to work. This is what I have now. How do you insert a long block of HTML after a div container using Javascript?

Injection Javascript

```<code><script>
  $(function() {
$( "<p class="" style="white-space:pre-wrap;" id="yui_3_17_2_1_1582132982979_54">Sabine the Queen<br>
<strong data-shrink-original-size="75">A Global Real Estate & Lifestyle Brand<br></strong>
<a href="/properties" target="">Our Properties</a></p>" ).insertAfter( ".sqs-gallery" );
    });
</script>
</code>```

Container

```<code><div class="sqs-gallery">
This is a slideshow.
</div>
</code>```

答:
It looks like you've got unescaped quotation marks that may be fouling up the HTML markup.  Swap out your outer quotation marks for single marks or escape the inner quoation marks

Swapping quotation marks:

```<code><script>
  $(function() {
$( '<p class="" style="white-space:pre-wrap;" id="yui_3_17_2_1_1582132982979_54">Sabine the Queen<br>
<strong data-shrink-original-size="75">A Global Real Estate & Lifestyle Brand<br></strong>
<a href="/properties" target="">Our Properties</a></p>' ).insertAfter( ".sqs-gallery" );
    });
</script>
</code>```

Note the single quote I've put at the start and end of your HTML string

Escaping:

```<code><script>
  $(function() {
$( "<p class=\"\" style=\"white-space:pre-wrap;\" id=\"yui_3_17_2_1_1582132982979_54\">Sabine the Queen<br>
<strong data-shrink-original-size=\"75\">A Global Real Estate & Lifestyle Brand<br></strong>
<a href=\"/properties\" target=\"\">Our Properties</a></p>" ).insertAfter( ".sqs-gallery" );
    });
</script>
</code>```

To escape the double quotation mark within you string, it should be preceded by a backslash.  This tells the browser that this quotation mark is not the partner for the first one and to keep going.  If it's unescaped then it thinks the string is a lot shorter than you meant and breaks

Body:
I'm attempting to insert a long block of HTML after a div element using javascript. I've tried a few methods, but none seem to work. This is what I have now. How do you insert a long block of HTML after a div container using Javascript?

Injection Javascript

Container

This is a slideshow.

Body:
It looks like you've got unescaped quotation marks that may be fouling up the HTML markup.  Swap out your outer quotation marks for single marks or escape the inner quoation marks

Swapping quotation marks:

<script>
  $(function() {
$( '<p class="" style="white-space:pre-wrap;" id="yui_3_17_2_1_1582132982979_54">Sabine the Queen<br>
<strong data-shrink-original-size="75">A Global Real Estate &amp; Lifestyle Brand<br></strong>
<a href="/properties" target="">Our Properties</a></p>' ).insertAfter( ".sqs-gallery" );
    });
</script>

Note the single quote I've put at the start and end of your HTML string

Escaping:

<script>
  $(function() {
$( "<p class=\"\" style=\"white-space:pre-wrap;\" id=\"yui_3_17_2_1_1582132982979_54\">Sabine the Queen<br>
<strong data-shrink-original-size=\"75\">A Global Real Estate &amp; Lifestyle Brand<br></strong>
<a href=\"/properties\" target=\"\">Our Properties</a></p>" ).insertAfter( ".sqs-gallery" );
    });
</script>

To escape the double quotation mark within you string, it should be preceded by a backslash.  This tells the browser that this quotation mark is not the partner for the first one and to keep going.  If it's unescaped then it thinks the string is a lot shorter than you meant and breaks


问:
mySQL SELECT based on its result
I have a table like this:

```<code>| id | parentID | columnName        |
|----|----------|-------------------|
| 1  | 2        | John              |
| 2  | 0        | Task name         |
| 3  | 4        | John              |
| 4  | 0        | Task another name |
</code>```

I want to get John task, but also with its name so I'm wondering if it is any way to do it in single MySQL query?

```<code>SELECT id, parentID, person FROM table WHERE columnName = "John"
</code>```

will result in user task, but I want to know how this task is named.

答:
You seem to be looking for a self-join:</p>

```<code>select
    t.id,
    t.parentid,
    t.columnname person,
    t1.columnname task
from mytable t
left join mytable t1 on t1.id = t.parentid
where t.person = 'John'
</code>```

Title: mySQL SELECT based on its result

Body:
I have a table like this:

| id | parentID | columnName        |
|----|----------|-------------------|
| 1  | 2        | John              |
| 2  | 0        | Task name         |
| 3  | 4        | John              |
| 4  | 0        | Task another name |

I want to get John task, but also with its name so I'm wondering if it is any way to do it in single MySQL query?

SELECT id, parentID, person FROM table WHERE columnName = "John"

will result in user task, but I want to know how this task is named.

Body:
You seem to be looking for a self-join:

select
    t.id,
    t.parentid,
    t.columnname person,
    t1.columnname task
from mytable t
left join mytable t1 on t1.id = t.parentid
where t.person = 'John'


问:
Problem displaying and saving the data from one recycle view to another
I am new to Android and I can't understand why when I send data from one activity to another it doesn't remember the values that I saved previously and it's not able to show me more than one item inside the shopping cart.

Example :

I have a shopping list and a cart list

Inside the shopping list, I have a recycleview and I have items that I can add to the shopping cart when I press the add button, the item is added to the shopping cart by sending the data to the cart activity and it shows me the data inside the recycle view(this recycleview is inside the Cart activity) but now if I go back using the back button of the phone and I select another item from the shopping list when I go to the cart list the previous item added it's gone and I don't understand why since I created an ArrayList and I save the data inside it. Can anyone explain to me what I'm doing wrong?

I will add 3 photos to explain myself better.

In the second picture, if I go back from shopping cart to the shopping list and click on C, A from Shopping cart will disappear and I will have just C.

This is my code:

Shopping list:

```<code>public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;

String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
}

private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery =
   mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
    FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cart_count++;
                Context context = v.getContext();
                Intent intent = new Intent(context, CartActivity.class);
                intent.putExtra("Name",nome);
                intent.putExtra("Surname",surname);
                intent.putExtra("Prezzo",Long.toString(prezzo));
                context.startActivity(intent);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

    }
}
}enter code here
</code>```

Shopping CART :

```<code>public class CartActivity extends AppCompatActivity {
private RecyclerView cities;
private RecyclerView.Adapter adapter;
String nome,cognome;
Long prezzo;
int totalPrice=0;
TextView campoPrezzo;
int position=0;

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

    campoPrezzo=findViewById(R.id.TotalPrice);

    //Receive the data from the previous activity
    String passedArg = getIntent().getExtras().getString("Name");
    nome=passedArg;
    String passedArg2 = getIntent().getExtras().getString("Surname");
    cognome=passedArg2;

    Intent intent = getIntent();
    String str = intent.getStringExtra("Prezzo");

    ArrayList<Users> cities = initCities(nome,cognome,Long. parseLong(str));

    this.cities = (RecyclerView) findViewById(R.id.cartList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    this.cities.setLayoutManager(mLayoutManager);

    adapter = new ProductAdapter(cities);
    this.cities.setAdapter(adapter);
    System.out.println("Prezzo"+returnTotalPrice());
}

private ArrayList<Users> initCities(String nome,String cognome,Long price) {
    ArrayList<Users> list = new ArrayList<>();
    list.add(position,new Users(nome,cognome,price));
    position++;
    getTotalPrice(price);
    return list;
}

public void getTotalPrice(Long price){
    totalPrice+=price;
}

public int returnTotalPrice(){
    return totalPrice;
}
}
</code>```

enter code here

答: You must save in the database which elements you clicked (sent to the shopping cart) in order for them not to load again or to be shown every time you enter the shopping cart. You are just populating the RecyclerView with all the options and you're not saving the ones you have in the ShoppingCartActivity. When you start the shopping cart activity it will load the extras from the Intent, if you didn't click any item the intent won't have extras, therefore the shopping cart won't have any items to show if you start it again. If you need help setting up the database just ask. Also you should add firebase tag to the post.</p>

Body:
I am new to Android and I can't understand why when I send data from one activity to another it doesn't remember the values that I saved previously and it's not able to show me more than one item inside the shopping cart.

Example :

I have a shopping list and a cart list

Inside the shopping list, I have a recycleview and I have items that I can add to the shopping cart when I press the add button, the item is added to the shopping cart by sending the data to the cart activity and it shows me the data inside the recycle view(this recycleview is inside the Cart activity) but now if I go back using the back button of the phone and I select another item from the shopping list when I go to the cart list the previous item added it's gone and I don't understand why since I created an ArrayList and I save the data inside it. Can anyone explain to me what I'm doing wrong?

I will add 3 photos to explain myself better.

In the second picture, if I go back from shopping cart to the shopping list and click on C, A from Shopping cart will disappear and I will have just C.

This is my code:

Shopping list:

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;

String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;

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

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
}

private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery =
   mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
    FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cart_count++;
                Context context = v.getContext();
                Intent intent = new Intent(context, CartActivity.class);
                intent.putExtra("Name",nome);
                intent.putExtra("Surname",surname);
                intent.putExtra("Prezzo",Long.toString(prezzo));
                context.startActivity(intent);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

    }
}
}enter code here

Shopping CART :

public class CartActivity extends AppCompatActivity {
private RecyclerView cities;
private RecyclerView.Adapter adapter;
String nome,cognome;
Long prezzo;
int totalPrice=0;
TextView campoPrezzo;
int position=0;

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

    campoPrezzo=findViewById(R.id.TotalPrice);

    //Receive the data from the previous activity
    String passedArg = getIntent().getExtras().getString("Name");
    nome=passedArg;
    String passedArg2 = getIntent().getExtras().getString("Surname");
    cognome=passedArg2;

    Intent intent = getIntent();
    String str = intent.getStringExtra("Prezzo");

    ArrayList<Users> cities = initCities(nome,cognome,Long. parseLong(str));

    this.cities = (RecyclerView) findViewById(R.id.cartList);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    this.cities.setLayoutManager(mLayoutManager);

    adapter = new ProductAdapter(cities);
    this.cities.setAdapter(adapter);
    System.out.println("Prezzo"+returnTotalPrice());
}

private ArrayList<Users> initCities(String nome,String cognome,Long price) {
    ArrayList<Users> list = new ArrayList<>();
    list.add(position,new Users(nome,cognome,price));
    position++;
    getTotalPrice(price);
    return list;
}

public void getTotalPrice(Long price){
    totalPrice+=price;
}

public int returnTotalPrice(){
    return totalPrice;
}
}

enter code here


问:
Dumping a java object's properties
Is there a library that will recursively dump/print an objects properties?  I'm looking for something similar to the console.dir() function in Firebug.

I'm aware of the commons-lang ReflectionToStringBuilder but it does not recurse into an object. I.e., if I run the following:

```<code>public class ToString {

    public static void main(String [] args) {
        System.out.println(ReflectionToStringBuilder.toString(new Outer(), ToStringStyle.MULTI_LINE_STYLE));
    }

    private static class Outer {
        private int intValue = 5;
        private Inner innerValue = new Inner();
    }

    private static class Inner {
        private String stringValue = "foo";
    }
}
</code>```

I receive:

ToString$Outer@1b67f74[
  intValue=5

  innerValue=ToString$Inner@530daa
  ]

I realize that in my example, I could have overriden the toString() method for Inner but in the real world, I'm dealing with external objects that I can't modify.

答: Maybe you could use an XML binding framework like XStream, Digester or JAXB for that.</p>

OwnerDisplayName: Kevin

Title: Dumping a java object's properties

Body:
Is there a library that will recursively dump/print an objects properties?  I'm looking for something similar to the console.dir() function in Firebug.

I'm aware of the commons-lang ReflectionToStringBuilder but it does not recurse into an object. I.e., if I run the following:

public class ToString {

    public static void main(String [] args) {
        System.out.println(ReflectionToStringBuilder.toString(new Outer(), ToStringStyle.MULTI_LINE_STYLE));
    }

    private static class Outer {
        private int intValue = 5;
        private Inner innerValue = new Inner();
    }

    private static class Inner {
        private String stringValue = "foo";
    }
}

I receive:

ToString$Outer@1b67f74[
  intValue=5

  innerValue=ToString$Inner@530daa
  ]

I realize that in my example, I could have overriden the toString() method for Inner but in the real world, I'm dealing with external objects that I can't modify.

OwnerDisplayName: Fabian Steeg