问:
What is the significance of class data type in java?
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

```<code>Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}
</code>```

What does Node next = null; mean? I can understand the effort to create an object with

```<code>Node next = new Node();
</code>```

and then try to manipulate the next object.

答:
This code:

```<code>Node next = null;
</code>```

declares a variable of type Node. As Node is a class, the value of next is always a reference - either to an object of type Node or a subclass, or the null reference which doesn't refer to any object at all... and in this case the variable starts off with a value of null.

It's really important to understand that the value of next is never a Node object itself... it's only ever a reference. So suppose we have:

```<code>Node next = new Node(10);
Node foo = next;
</code>```

Here, next and foo are separate variables, each with independent values... but we've assigned the value of next as the initial value of foo, which means they both refer to the same object. So if we print out foo.data, it will be 10.

I like to think of variables as pieces of paper - and in the case of variables of reference types, what's written on the piece of paper is the address of a house, or the word "null". If two pieces of paper have the same address written on them, they refer to the same house - but the two pieces of paper themselves are independent. Changing the value of one variable (crossing out the current address and writing another one) doesn't change anything about the other variable... but changes to the house itself (e.g. painting a door red) are visible whichever piece of paper you use to get there.

Note that in your question, you've lumped String in with int, double and boolean... but whereas int, double and boolean are primitive types (where the value of a variable is simply the data itself - the number etc), String is a class, so it's a reference type. The value of a string variable isn't the text itself, but a reference.

Body:
Noob question.

I have been programming at basic level for quite a while but I have trouble understanding class data type.

when we say int a = 9;
it means a is of data type int meaning it can contain only integers.

like wise for String, boolean, double, float etc.

But consider the following code:

Class Node {

Node next = null;
int data;

public Node(int d){ data = d; }

void append(int d)
    {
        blah blah blah
        ..............
    }
}

What does Node next = null; mean? I can understand the effort to create an object with

Node next = new Node();

and then try to manipulate the next object.

Body:
This code:

Node next = null;

declares a variable of type Node. As Node is a class, the value of next is always a reference - either to an object of type Node or a subclass, or the null reference which doesn't refer to any object at all... and in this case the variable starts off with a value of null.

It's really important to understand that the value of next is never a Node object itself... it's only ever a reference. So suppose we have:

Node next = new Node(10);
Node foo = next;

Here, next and foo are separate variables, each with independent values... but we've assigned the value of next as the initial value of foo, which means they both refer to the same object. So if we print out foo.data, it will be 10.

I like to think of variables as pieces of paper - and in the case of variables of reference types, what's written on the piece of paper is the address of a house, or the word "null". If two pieces of paper have the same address written on them, they refer to the same house - but the two pieces of paper themselves are independent. Changing the value of one variable (crossing out the current address and writing another one) doesn't change anything about the other variable... but changes to the house itself (e.g. painting a door red) are visible whichever piece of paper you use to get there.

Note that in your question, you've lumped String in with int, double and boolean... but whereas int, double and boolean are primitive types (where the value of a variable is simply the data itself - the number etc), String is a class, so it's a reference type. The value of a string variable isn't the text itself, but a reference.


来源: stackexchange

问:
How is the Transaction ID generated in Hyperledger fabric?
How is the transaction ID generated in Hyperledger Fabric at the time of adding a block into the chain and how is it different from the block hash?

Also, is there an option to view the previous and current block hash for each block both in local fabric setup (first network setup in Ubuntu) as well as IBM Blockchain starter plan?

答:
This should probably be two separate questions. I can answer the first.

It's a hash of a Nonce and the user credentials creating the transaction. It is generated by the client creating the proposals that get send to peers to execute the transaction.

For example in fabric-sdk-go.

ContentLicense: CC BY-SA 4.0


问:
Find the mode across multiple columns for each row of a pandas DataFrame
I am new to Python and Pandas. I want to find the most common item for each row for columns Opt_1 to Opt_7. Note for some reason some of the blank cells appear to have NaN and in other cases it has None.

```<code>ID  Col_1   Col_2   Opt_1   Opt_2   Opt_3   Opt_4   Opt_5   Opt_6   Opt_7
1   Game 1  Team 1  13
2   Game 1  Team 2  -13
3   Game 1  Team 1
4   Game 1  Team 2
5   Game 2  Team 1  -7.5    -7.5    -7.5    -7.5
6   Game 2  Team 2  7.5     7.5     7.5     7.5
7   Game 2  Team 1          -2.5    -1.5
8   Game 2  Team 2          2.5     1.5
9   Game 3  Team 1          3.5     3.5
10  Game 3  Team 2          -3.5    -3.5
11  Game 3  Team 1  -1      -1.5    -1
12  Game 3  Team 2  1       1.5     1
</code>```

I already tried the following code, which worked as expected for most rows, but not all. And it was a bit slow.

```<code>def freq_value(series):
    return Counter(series).most_common()[0][0]

for row in df.iterrows():
     df['result'] = df.apply(lambda row: freq_value((row['Opt_1'], row['Opt_2'], row['Opt_3'], row['Opt_4'], row['Opt_5'], row['Opt_6'], row['Opt_7'])), axis=1)
</code>```

Below is the expected results and the actual results:

```<code>ID  Expected    Actual Result
1   NaN         NaN
2   NaN         NaN
3   NaN         NaN
4   NaN         NaN
5   -7.5            -7.5
6   7.5         7.5
7   NaN         NaN
8   NaN         NaN
9   3.5         3.5
10  -3.5           -3.5
11  -1          NaN
12  1           NaN
</code>```

Is there anyway of doing this so it is 100% correct, and perhaps done without iterating through each row one at a time? Thanks in advance for any suggestions.

答:
Use pandas.DataFrame.mode:

>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({
...     'ID': range(1, 13),
...     'Col_1': [*(['Game 1'] * 4), *(['Game 2'] * 4), *(['Game 3'] * 4)],
...     'Col_2': ['Team 1', 'Team 2'] * 6,
...     'Opt_1': [13, -13, np.nan, np.nan, -7.5, 7.5, np.nan, np.nan, np.nan, np.nan, -1, 1],
...     'Opt_2': [np.nan, np.nan, np.nan, np.nan, -7.5, 7.5, -2.5, 2.5, 3.5, -3.5, -1.5, 1.5],
...     'Opt_3': [np.nan, np.nan, np.nan, np.nan, -7.5, 7.5, -1.5, 1.5, 3.5, -3.5, -1, 1],
...     'Opt_4': [np.nan, np.nan, np.nan, np.nan, -7.5, 7.5, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
...     'Opt_5': [np.nan] * 12,
...     'Opt_6': [np.nan] * 12,
...     'Opt_7': [np.nan] * 12
... })
>>> df
    ID   Col_1   Col_2  Opt_1  Opt_2  Opt_3  Opt_4  Opt_5  Opt_6  Opt_7
0    1  Game 1  Team 1   13.0    NaN    NaN    NaN    NaN    NaN    NaN
1    2  Game 1  Team 2  -13.0    NaN    NaN    NaN    NaN    NaN    NaN
2    3  Game 1  Team 1    NaN    NaN    NaN    NaN    NaN    NaN    NaN
3    4  Game 1  Team 2    NaN    NaN    NaN    NaN    NaN    NaN    NaN
4    5  Game 2  Team 1   -7.5   -7.5   -7.5   -7.5    NaN    NaN    NaN
5    6  Game 2  Team 2    7.5    7.5    7.5    7.5    NaN    NaN    NaN
6    7  Game 2  Team 1    NaN   -2.5   -1.5    NaN    NaN    NaN    NaN
7    8  Game 2  Team 2    NaN    2.5    1.5    NaN    NaN    NaN    NaN
8    9  Game 3  Team 1    NaN    3.5    3.5    NaN    NaN    NaN    NaN
9   10  Game 3  Team 2    NaN   -3.5   -3.5    NaN    NaN    NaN    NaN
10  11  Game 3  Team 1   -1.0   -1.5   -1.0    NaN    NaN    NaN    NaN
11  12  Game 3  Team 2    1.0    1.5    1.0    NaN    NaN    NaN    NaN
>>> opts = ['Opt_{}'.format(i) for i in range(1, 8)]
>>> df[opts].mode(axis=1, dropna=False)
      0
0   NaN
1   NaN
2   NaN
3   NaN
4  -7.5
5   7.5
6   NaN
7   NaN
8   NaN
9   NaN
10  NaN
11  NaN
```

Body:
I am new to Python and Pandas. I want to find the most common item for each row for columns Opt_1 to Opt_7. Note for some reason some of the blank cells appear to have NaN and in other cases it has None.

ID  Col_1   Col_2   Opt_1   Opt_2   Opt_3   Opt_4   Opt_5   Opt_6   Opt_7
1   Game 1  Team 1  13
2   Game 1  Team 2  -13
3   Game 1  Team 1
4   Game 1  Team 2
5   Game 2  Team 1  -7.5    -7.5    -7.5    -7.5
6   Game 2  Team 2  7.5     7.5     7.5     7.5
7   Game 2  Team 1          -2.5    -1.5
8   Game 2  Team 2          2.5     1.5
9   Game 3  Team 1          3.5     3.5
10  Game 3  Team 2          -3.5    -3.5
11  Game 3  Team 1  -1      -1.5    -1
12  Game 3  Team 2  1       1.5     1

I already tried the following code, which worked as expected for most rows, but not all. And it was a bit slow.

def freq_value(series):
    return Counter(series).most_common()[0][0]

for row in df.iterrows():
     df['result'] = df.apply(lambda row: freq_value((row['Opt_1'], row['Opt_2'], row['Opt_3'], row['Opt_4'], row['Opt_5'], row['Opt_6'], row['Opt_7'])), axis=1)

Below is the expected results and the actual results:

ID  Expected    Actual Result
1   NaN         NaN
2   NaN         NaN
3   NaN         NaN
4   NaN         NaN
5   -7.5            -7.5
6   7.5         7.5
7   NaN         NaN
8   NaN         NaN
9   3.5         3.5
10  -3.5           -3.5
11  -1          NaN
12  1           NaN

Is there anyway of doing this so it is 100% correct, and perhaps done without iterating through each row one at a time? Thanks in advance for any suggestions.


问:
Unable to access UI for kubeflow
I have installed Kubeflow onto Ubuntu 18.04 running on microk8s.  To do this I followed the instructions on https://www.kubeflow.org/docs/started/getting-started/.

Everything seems to be running correctly:

```<code>steven@linux:~/my-kf$ microk8s.kubectl  -n kubeflow get all
NAME                                                          READY   STATUS             RESTARTS   AGE
pod/ambassador-b4d9cdb8-79km4                                 1/1     Running            3          4d20h
pod/ambassador-b4d9cdb8-drs95                                 1/1     Running            3          4d20h
pod/ambassador-b4d9cdb8-gkn6w                                 1/1     Running            3          4d20h
pod/argo-ui-6d6658d8f7-4kv7x                                  1/1     Running            2          4d20h
</code>```

I set up port-forwarding:

```<code>steven@linux:~/my-kf$ microk8s.kubectl port-forward svc/ambassador -n kubeflow 9999:80
Forwarding from 127.0.0.1:9999 -> 80
Forwarding from [::1]:9999 -> 80
</code>```

And then try to access the UI by pointing a web browser at

```<code>http://127.0.0.1:9999/
</code>```

however, I just get the following in the browser

```<code>no healthy upstream
</code>```

I get the log for the ambassador service using

```<code>steven@linux:~$ microk8s.kubectl -n kubeflow logs svc/ambassador
</code>```

and all I can see is

```<code> ACCESS [2019-02-07T06:39:38.623Z] "GET / HTTP/1.1" 503 UH 0 19 0 - "-" "Mozilla/5.0 (X11; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0" "3b346da8-be7b-43fa-9b62-6db0a449a8f3" "127.0.0.1:9999" "-"
</code>```

This is quite frustrating - any help in being able to access the Kubeflow cluster would be much appreciated.

答:
It's related to Ambassador issue: resourceVersion: Invalid value here

Upgrade Ambassador version to 0.50.0 can solve this.

microk8s.kubectl -n kubeflow edit deployment ambassador

Title: Unable to access UI for kubeflow

Body:
I have installed Kubeflow onto Ubuntu 18.04 running on microk8s.  To do this I followed the instructions on https://www.kubeflow.org/docs/started/getting-started/.

Everything seems to be running correctly:

steven@linux:~/my-kf$ microk8s.kubectl  -n kubeflow get all
NAME                                                          READY   STATUS             RESTARTS   AGE
pod/ambassador-b4d9cdb8-79km4                                 1/1     Running            3          4d20h
pod/ambassador-b4d9cdb8-drs95                                 1/1     Running            3          4d20h
pod/ambassador-b4d9cdb8-gkn6w                                 1/1     Running            3          4d20h
pod/argo-ui-6d6658d8f7-4kv7x                                  1/1     Running            2          4d20h

I set up port-forwarding:

steven@linux:~/my-kf$ microk8s.kubectl port-forward svc/ambassador -n kubeflow 9999:80
Forwarding from 127.0.0.1:9999 -> 80
Forwarding from [::1]:9999 -> 80

And then try to access the UI by pointing a web browser at

http://127.0.0.1:9999/

however, I just get the following in the browser

no healthy upstream

I get the log for the ambassador service using

steven@linux:~$ microk8s.kubectl -n kubeflow logs svc/ambassador

and all I can see is

 ACCESS [2019-02-07T06:39:38.623Z] "GET / HTTP/1.1" 503 UH 0 19 0 - "-" "Mozilla/5.0 (X11; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0" "3b346da8-be7b-43fa-9b62-6db0a449a8f3" "127.0.0.1:9999" "-"

This is quite frustrating - any help in being able to access the Kubeflow cluster would be much appreciated.


问:
Security warning in IE when using jScrollpane
I am using JSrollpane (a jquery plugin) on my page. use of source file for this plugin causing a security warning in IE- "this webpage contains content that will not be delivered using s secure HTTPS connection,which could compromise the security of entire webpage"

i checked for any media resources with is fetched using http nut it's not there.

my page is https://login.salesforce.com/?ec=302&startURL=/visualforce/session%3Furl%3Dhttps%253A%252F%252Faexp.ap1.visual.force.com%252Fapex%252Faexp__test_Offer&un=ashok_bommali%40amex.cms&pw=Infy@789

and source file i am using is http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.min.js

any help on this?

thanks,
Sushil

答:
@alex is right but you can also get URI scheme in JS see link
JavaScript URI class or from Server Side scriptings likes ASP/JSP</p>

ContentLicense: CC BY-SA 3.0


问:
How to get string value from Listbox as user selected?
I can't get string value from Listbox after selected one item.

In my Listbox I have the Image (blinding source) and TextBlock (blinding source).

My code at .xaml page:

```<code>        <ListBox Name="carListBox" Height="431" Canvas.Left="28" Canvas.Top="65" Width="446" SelectionChanged="ListBoxOnSelection">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Name="brandImage" Source="{Binding Image}" Width="100" Height="150"></Image>
                        <Image Name="carImage" Source="{Binding Image}" Width="150" Height="150"></Image>
                        <TextBlock Name="textDisplay" Text="{Binding ShowDetail}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</code>```

My code at .xaml.cs page (C#)

private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)

```<code>    {
       MessageBox.Show(carListBox.SelectedItem.ToString());
       string saveData = carListBox.SelectedItem.ToString();

    }
</code>```

MessageBox can't show string value and I can't get value after user selected.

MessageBox show [1]https://i.imgur.com/2VSjhgN.jpg

答:
You have to somehow get the Car object before you can have access to it's properties.

Something like this:

```<code>private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)
{
 Car myCar=carListBox.SelectedItem as Car;
 if(myCar != null)
   MessageBox.Show(myCar.ShowDetail); //or any property.
}
</code>```

Body:
I can't get string value from Listbox after selected one item.

In my Listbox I have the Image (blinding source) and TextBlock (blinding source).

My code at .xaml page:

        <ListBox Name="carListBox" Height="431" Canvas.Left="28" Canvas.Top="65" Width="446" SelectionChanged="ListBoxOnSelection">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Name="brandImage" Source="{Binding Image}" Width="100" Height="150"></Image>
                        <Image Name="carImage" Source="{Binding Image}" Width="150" Height="150"></Image>
                        <TextBlock Name="textDisplay" Text="{Binding ShowDetail}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

My code at .xaml.cs page (C#)

private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)

    {
       MessageBox.Show(carListBox.SelectedItem.ToString());
       string saveData = carListBox.SelectedItem.ToString();

    }

MessageBox can't show string value and I can't get value after user selected.

MessageBox show [1]https://i.imgur.com/2VSjhgN.jpg

Body:
You have to somehow get the Car object before you can have access to it's properties.

Something like this:

private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)
{
 Car myCar=carListBox.SelectedItem as Car;
 if(myCar != null)
   MessageBox.Show(myCar.ShowDetail); //or any property.
}


问:
What does "String[]::new" mean?
I'm learning how to use stream, and I get a problem with this method.

```<code>public static String[] inArray(String[] array1, String[] array2) {
   return Arrays.stream(array1)
  .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str)))
  .distinct().sorted().toArray(**String[]::new**);
}
</code>```

I'm so confused about String[]::new, could you give me a hint?

答:
This is a method reference expression see JLS 15.13.  The syntax for method references is:

```<code>MethodReference:
    ExpressionName :: [TypeArguments] Identifier
    Primary :: [TypeArguments] Identifier
    ReferenceType :: [TypeArguments] Identifier
    super :: [TypeArguments] Identifier
    TypeName . super :: [TypeArguments] Identifier
    ClassType :: [TypeArguments] new
    ArrayType :: new
</code>```

The particular case you are looking at is the last one.  In your example, String[] is an ArrayType which means that it consists of a type name followed by one or more [].

There shouldn't be a class named String[] which is very lame and I could not interpret what it is actually meant for.

See above: it is a type specification not a class name. From a syntactic / linguistic perspective, this usage is analogous to:

```<code>  Class<?> c = String[].class;
</code>```

or

```<code>  if (a instanceof String[])
</code>```

or even

```<code>  public void myMethod(String[] arg)
</code>```

(You wouldn't call those "lame" ... would you?)

Now you could have a valid case for saying that it is syntactically unexpected (especially to a pre-Java 8 programmer) to be able to use the new keyword like this.  But this unexpected syntax is a consequence of the strong imperative that the designers have to NOT break backwards compatibility when adding new language features to Java.  And it is not unintuitive.  (At least, I don't think so.  When I first saw this construct, is was obvious to me what it meant.)

Now, if they were starting with a clean slate in 2018, a lot of details of the Java language design would be simpler and cleaner.  But they don't have the luxury of doing that.

Title: What does "String[]::new" mean?

Body:
I'm learning how to use stream, and I get a problem with this method.

public static String[] inArray(String[] array1, String[] array2) {
   return Arrays.stream(array1)
  .filter(str -> Arrays.stream(array2).anyMatch(s -> s.contains(str)))
  .distinct().sorted().toArray(**String[]::new**);
}

I'm so confused about String[]::new, could you give me a hint?

Body:
This is a method reference expression see JLS 15.13.  The syntax for method references is:

MethodReference:
    ExpressionName :: [TypeArguments] Identifier
    Primary :: [TypeArguments] Identifier
    ReferenceType :: [TypeArguments] Identifier
    super :: [TypeArguments] Identifier
    TypeName . super :: [TypeArguments] Identifier
    ClassType :: [TypeArguments] new
    ArrayType :: new

The particular case you are looking at is the last one.  In your example, String[] is an ArrayType which means that it consists of a type name followed by one or more [].

There shouldn't be a class named String[] which is very lame and I could not interpret what it is actually meant for.

See above: it is a type specification not a class name. From a syntactic / linguistic perspective, this usage is analogous to:

  Class<?> c = String[].class;

or

  if (a instanceof String[])

or even

  public void myMethod(String[] arg)

(You wouldn't call those "lame" ... would you?)

Now you could have a valid case for saying that it is syntactically unexpected (especially to a pre-Java 8 programmer) to be able to use the new keyword like this.  But this unexpected syntax is a consequence of the strong imperative that the designers have to NOT break backwards compatibility when adding new language features to Java.  And it is not unintuitive.  (At least, I don't think so.  When I first saw this construct, is was obvious to me what it meant.)

Now, if they were starting with a clean slate in 2018, a lot of details of the Java language design would be simpler and cleaner.  But they don't have the luxury of doing that.


问:
Checking a string is palindromic using stacks
I want to check a string is palindromic using stacks implement in java. I have tried many ways but its not getting me the correct answer. Can someone help me with it?

I have implemented a Stack in my class which variable name is "stackArray".

Palindromic method :

```<code>Stack s1 = new Stack(5);

for (int i = 0; i < 5; i++) {
    s1.push(stackArray[i]);
}

String [] reverser = new String[5];

while (!s1.isEmpty()) {
    int count = 0;
    reverser[count] = s1.pop();
    count++;
}

if (s1.equals(reverser)){
    System.out.println("The input String is a palindrome.");
}
else
    System.out.println("The input String is not a palindrome.");
</code>```

Driver code :

```<code>public static void main(String[] args) throws Exception {

        Stack st = new Stack(5);

        st.push("l");
        st.push("e");
        st.push("v");
        st.push("e");
        st.push("l");
        System.out.println("");
        System.out.println("When Palindromic is starting; ");
        System.out.println("");
        st.palindromic();
}
</code>```

Its obvious that the word "level" is Palindromic but always it says "The input String is not a palindrome."

答:
```<code>public static void main(String[] args) {

    String str ="word";
    if(str.equals(reverse(str))) {
          System.out.println("Word is Palindromic ");
    }else {
          System.out.println("Word is Not Palindromic ");
    }
}

public static String reverse(String str) {
    char[] charArr = str.toCharArray();
    int size = charArr.length;
    Stack stack = new Stack(size);

    int i;
    for(i = 0; i < size; ++i) {
        stack.push(charArr[i]);
    }

    for(i = 0; i < size; ++i) {
        charArr[i] = stack.pop();
    }

    return String.valueOf(charArr);
}
</code>```

Body:
I want to check a string is palindromic using stacks implement in java. I have tried many ways but its not getting me the correct answer. Can someone help me with it?

I have implemented a Stack in my class which variable name is "stackArray".

Palindromic method :

Stack s1 = new Stack(5);

for (int i = 0; i < 5; i++) {
    s1.push(stackArray[i]);
}

String [] reverser = new String[5];

while (!s1.isEmpty()) {
    int count = 0;
    reverser[count] = s1.pop();
    count++;
}

if (s1.equals(reverser)){
    System.out.println("The input String is a palindrome.");
}
else
    System.out.println("The input String is not a palindrome.");

Driver code :

public static void main(String[] args) throws Exception {

        Stack st = new Stack(5);

        st.push("l");
        st.push("e");
        st.push("v");
        st.push("e");
        st.push("l");
        System.out.println("");
        System.out.println("When Palindromic is starting; ");
        System.out.println("");
        st.palindromic();
}

Its obvious that the word "level" is Palindromic but always it says "The input String is not a palindrome."


问:
Disable Scrolling in child Recyclerview android
I have a layout consists of a Parent RecyclerView with a sub Recyclerview in it

i know that it is not good to put a list inside another list but i have to so that i can use the sub list features like swiping and drag and drop

My issue is that the child Recyclerview gain focus and stops the parent from scrolling if the touch point was on it
simply i want if the touch was vertically on the child Recyclerview
the parent scrolls up and down and if the touch was horizontal or a click then the child Recyclerview list item swipes left and right.
Any help to achieve this?

答:
```<code> <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_marginTop="2dp"
        android:layout_marginLeft="2dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="2dp"
        android:nestedScrollingEnabled="false"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>
</code>```

put the code inside LinearLayout...no need to do anything pragmatically

Body:
 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_marginTop="2dp"
        android:layout_marginLeft="2dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="2dp"
        android:nestedScrollingEnabled="false"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

put the code inside LinearLayout...no need to do anything pragmatically


问:
Do I need to include css and js files in the lightbox page?
Do I need to load all the css and js files again in my lightbox html code?
The css seems to work fine. But the js functions do not work in the lightbox page. Those js files are included in the parent html page and triggered in the same file.

only the jquery code that I have written in the lightbox html code works in the lightbox page. The other js functions written in the included js files do not work.

Should I use any different methods to trigger the js functions which are included in the parent page in the lightbox page??

Edit

Lightbox html code:

```<code><div id="lightbox-holder">
    <div class="result">
         <p>Total Amount</p>
         <h3>1000</h3>
    </div>

    <div class="equal-sign"> </div>

    <div class="left-stepper">  //Stepper input
      <label class="steper-label">Left stepper</label>
      <input type="text" id="spinner1" class="ui-stepper" value="0" />
    </div>

    <div class="plus-sign"> </div>

    <div class="right-stepper"> //Stepper input
        <label class="steper-label">Right Stepper</label>
        <input type="text" id="spinner2" class="ui-stepper" value="0" />
    </div>
 </div>

 <script type="text/javascript">

  $(document).ready(function (){

        func.init();

        $('#cost_allocation').live('click', function() {
            $(this).hide();
            $('#help_icon').hide();
            $('#breakdown').show();

            $('#ok_button').hide();
            $('#save_button').show();
        });

        $('#save_button').live('click', function(){
            $("#jQLightboxContents").remove();
            $("#jQVeil").remove();

        });
});
</script>
</code>```

This jQuery inside the lightbox page works. But the js functions triggered through func.init() do not work.

The func.init() is for triggering all the js files required for this code to work. For example, the stepper input unit(numeric stepper) code is written in a file named stepper.js  and it is triggered using the init function. This works well in the parent page, but is not displayed in the lightbox page. Should I invoke the init() function in a different way?

答:
A code snippet would help.

In any case, the lightbox code is a part of the body tag in your html and is not a standalone html. So no, you do not need to include your js again.

Body:
Do I need to load all the css and js files again in my lightbox html code?
The css seems to work fine. But the js functions do not work in the lightbox page. Those js files are included in the parent html page and triggered in the same file.

only the jquery code that I have written in the lightbox html code works in the lightbox page. The other js functions written in the included js files do not work.

Should I use any different methods to trigger the js functions which are included in the parent page in the lightbox page??

Edit

Lightbox html code:

Total Amount

1000

  //Stepper input
      Left stepper
      <input type="text" id="spinner1" class="ui-stepper" value="0" />

 //Stepper input
        Right Stepper
        <input type="text" id="spinner2" class="ui-stepper" value="0" />

This jQuery inside the lightbox page works. But the js functions triggered through func.init() do not work.

The func.init() is for triggering all the js files required for this code to work. For example, the stepper input unit(numeric stepper) code is written in a file named stepper.js  and it is triggered using the init function. This works well in the parent page, but is not displayed in the lightbox page. Should I invoke the init() function in a different way?


答:
Use filter to select columns and mode + mask to find unique modes only:

```<code>(df.filter(like='Opt')
   .mode(axis=1)
   .set_axis(['a', 'b'], axis=1, inplace=False)
   .eval('a.mask(b.notna())', engine='python'))

0     13.0
1    -13.0
2      NaN
3      NaN
4     -7.5
5      7.5
6      NaN
7      NaN
8      3.5
9     -3.5
10    -1.0
11     1.0
Name: a, dtype: float64
</code>```

mode will return all modes for a given row. This means that if there are two values that are equally frequent, there will be two columns in the output. The solution above handles the case when there are at most two columns.

If the mode is unique, the solution can be simplified to

```<code>df.filter(like='Opt').mode(axis=1).iloc[:, 0]
</code>```

Another solution when there is no unique mode, this will generalise to any number of columns in the output.

```<code>u = df.filter(like='Opt').mode(axis=1)
if len(u.columns) > 1:
    u = u.iloc[:, 0].where(u.iloc[:, 1:].isna().all(axis=1))

u
0     13.0
1    -13.0
2      NaN
3      NaN
4     -7.5
5      7.5
6      NaN
7      NaN
8      3.5
9     -3.5
10    -1.0
11     1.0
Name: 0, dtype: float64
</code>```

Title: Find the mode across multiple columns for each row of a pandas DataFrame

Body:
Use filter to select columns and mode + mask to find unique modes only:

(df.filter(like='Opt')
   .mode(axis=1)
   .set_axis(['a', 'b'], axis=1, inplace=False)
   .eval('a.mask(b.notna())', engine='python'))

0     13.0
1    -13.0
2      NaN
3      NaN
4     -7.5
5      7.5
6      NaN
7      NaN
8      3.5
9     -3.5
10    -1.0
11     1.0
Name: a, dtype: float64

mode will return all modes for a given row. This means that if there are two values that are equally frequent, there will be two columns in the output. The solution above handles the case when there are at most two columns.

If the mode is unique, the solution can be simplified to

df.filter(like='Opt').mode(axis=1).iloc[:, 0]

Another solution when there is no unique mode, this will generalise to any number of columns in the output.

u = df.filter(like='Opt').mode(axis=1)
if len(u.columns) > 1:
    u = u.iloc[:, 0].where(u.iloc[:, 1:].isna().all(axis=1))

u
0     13.0
1    -13.0
2      NaN
3      NaN
4     -7.5
5      7.5
6      NaN
7      NaN
8      3.5
9     -3.5
10    -1.0
11     1.0
Name: 0, dtype: float64


问:
Two Inline Inputs Separated by Text
I want to place to inputs inline and separate them with some text. The reason for this is I want users to enter a start time and end time, and have the inputs relatively close each other so it looks visually pleasing.
I currently have tried to use rows and columns to achieve this, but the widths between the text are rather large due to the column. Below is some code to give an idea of my attempt. Are there any alternatives?</p>

```<code><div class = "w3-row">
   <div class="w3-col w3-container s3 m3 l3">
     <div style="text-align:right">
       <label for="hours-operation-s" class="register-labels">Hours of Operation:</label>
     </div>
   </div>
   <div class="w3-col w3-container s2 m2 l2" id="div-start-time">
     <input type="text" name="hours-operation-s" class="w3-input" required>
   </div>
   <div class="w3-col w3-container s2 m2 l2">
     <div class="" style="text-align:center; padding-top:5px;">
       <p><strong>to</strong></p>
     </div>
   </div>
   <div class="w3-col w3-container s2 m2 l2">
     <input type="text" class="w3-input" required>
   </div>
   <div class = "w3-col w3-container s3 m6 l3">
     <!-- Blank -->
   </div>
</div>
</code>```

答:
It is very simple with Flexbox.

There is a reason why Bootstrap re-did their entire platform from Bootstrap3 to Bootstrap4, primarily to change from using floats to flexbox.

Flexbox requires two things:

A parent container (e.g. DIV, section, aside, p, etc)

One or more child elements (e.g. div, p, img, etc)

You turn flexbox on on the parent: display:flex;

Then, there are various switches. Some are set on the parent (as in the case of justify-content) but others might be set on the items (as with flex-grow:1)

Demo:

.row{display:flex;}
.col-inline{flex:1;XXXborder:1px solid red;}
.col-left {max-width:45vw;text-align:right;}
.col-right{max-width:48vw;text-align:left;}
.col-to{max-width:5vw;text-align:center;}
.w3-input{width:80px;text-align:center;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
    <div id="div-start-time" class="col-left col-inline">
        <label for="hours-operation-s" class="register-labels">
            Hours of Operation:
            <input type="text" id="hours-operation-s" class="w3-input" placeholder="9AM" required>
        </label>
    </div>
    <div class="col-to col-inline">
        to
    </div>
    <div id="div-end-time" class="col-right col-inline">
            <input type="text" id="hours-operation-e" class="w3-input" placeholder="6PM" required>
    </div>
</div></code>```

References:

YouTube tutorial - fast-paced and best-of-breed

Here is a great cheatsheet for Flexbox.

Watch the tutorial and in 30 mins from now your problem will be solved -- and you'll know flexbox.

P.S. I have no connection to the video or its presenter - I was fortunate to discover it, and now pass it along.

Title: Two Inline Inputs Separated by Text

Body:
I want to place to inputs inline and separate them with some text. The reason for this is I want users to enter a start time and end time, and have the inputs relatively close each other so it looks visually pleasing.
I currently have tried to use rows and columns to achieve this, but the widths between the text are rather large due to the column. Below is some code to give an idea of my attempt. Are there any alternatives?

       Hours of Operation:

     <input type="text" name="hours-operation-s" class="w3-input" required>

to

     <input type="text" class="w3-input" required>

Body:
It is very simple with Flexbox.

There is a reason why Bootstrap re-did their entire platform from Bootstrap3 to Bootstrap4, primarily to change from using floats to flexbox.

Flexbox requires two things:

A parent container (e.g. DIV, section, aside, p, etc)

One or more child elements (e.g. div, p, img, etc)

You turn flexbox on on the parent: display:flex;

Then, there are various switches. Some are set on the parent (as in the case of justify-content) but others might be set on the items (as with flex-grow:1)

Demo:

.row{display:flex;}
.col-inline{flex:1;XXXborder:1px solid red;}
.col-left {max-width:45vw;text-align:right;}
.col-right{max-width:48vw;text-align:left;}
.col-to{max-width:5vw;text-align:center;}
.w3-input{width:80px;text-align:center;}

<div class="row">
    <div id="div-start-time" class="col-left col-inline">
        <label for="hours-operation-s" class="register-labels">
            Hours of Operation:
            <input type="text" id="hours-operation-s" class="w3-input" placeholder="9AM" required>
        </label>
    </div>
    <div class="col-to col-inline">
        to
    </div>
    <div id="div-end-time" class="col-right col-inline">
            <input type="text" id="hours-operation-e" class="w3-input" placeholder="6PM" required>
    </div>
</div>

References:

YouTube tutorial - fast-paced and best-of-breed

Here is a great cheatsheet for Flexbox.

Watch the tutorial and in 30 mins from now your problem will be solved -- and you'll know flexbox.

P.S. I have no connection to the video or its presenter - I was fortunate to discover it, and now pass it along.


问:
Split Array Clean up
Sorry about the Title. Couldn't think of anything else.

I have this formula written with the help I received here:

```<code>ARRAYFORMULA(TO_TEXT(UNIQUE(TRANSPOSE(SPLIT(JOIN("+",IFERROR(INDEX(TO_TEXT(SPLIT({D$3:D$50;L$3:L$50},"|")),,1)),""),"+")))))
</code>```

Which works fine. The only issue I have is when the range {D$3:D$50;L$3:L$50} is totally blank it returns a load of +++ and I can't work out what to wrap in an "if" statement to stop this, without causing the array results to offset. Any help would be greatly appreciated.

答:
Please try:

```<code>=if(and(isblank(D$3:D$50),isblank(L$3:L$50)),"",
ARRAYFORMULA(TO_TEXT(UNIQUE(TRANSPOSE(SPLIT(JOIN("+",IFERROR(INDEX(TO_TEXT(SPLIT({D$3:D$50;L$3:L$50},"|")),,1)),""),"+")))))
)
</code>```

The middle line is the same as you already have.

Title: Split Array Clean up

Body:
Sorry about the Title. Couldn't think of anything else.

I have this formula written with the help I received here:

ARRAYFORMULA(TO_TEXT(UNIQUE(TRANSPOSE(SPLIT(JOIN("+",IFERROR(INDEX(TO_TEXT(SPLIT({D$3:D$50;L$3:L$50},"|")),,1)),""),"+")))))

Which works fine. The only issue I have is when the range {D$3:D$50;L$3:L$50} is totally blank it returns a load of +++ and I can't work out what to wrap in an "if" statement to stop this, without causing the array results to offset. Any help would be greatly appreciated.

Body:
Please try:

=if(and(isblank(D$3:D$50),isblank(L$3:L$50)),"",
ARRAYFORMULA(TO_TEXT(UNIQUE(TRANSPOSE(SPLIT(JOIN("+",IFERROR(INDEX(TO_TEXT(SPLIT({D$3:D$50;L$3:L$50},"|")),,1)),""),"+")))))
)

The middle line is the same as you already have.


问:
spring boot logback not logging my application logs
Need help... what am I doing wrong here???
I believe it does read the path and file name from application.properties file. But  I don't think it reads the logback.xml or logback-spring.xml

I did some research and found many questions/answers. But I think everyone says to put the logback xml in resources and give the path and file name in application.properties. I know it is simple, but missing something somewhere...

Thanks in advance!!

application.properties

```<code># ===============================
# LOGGING
# ===============================
# log configuration -- update config location as needed
#logging.config=/logback-spring.xml
#logging.file=/logs/iqs-service.txt
logging.path=/logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
</code>```

Content of log file (log.log.0):

```<code>[2018-12-10 15:54:41.999] - 10828 INFO [main] --- org.apache.catalina.core.StandardService: Starting service Tomcat
[2018-12-10 15:54:42.002] - 10828 INFO [main] --- org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat/8.5.14
[2018-12-10 15:54:42.257] - 10828 INFO [localhost-startStop-1] --- org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]: Initializing Spring embedded WebApplicationContext
[2018-12-10 15:54:46.551] - 10828 INFO [http-nio-19917-exec-1] --- org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]: Initializing Spring FrameworkServlet 'dispatcherServlet
</code>```

Log statements in my java method - This never prints in the log

```<code>log.info("init(): [" + modelId + "]");
log.error("init(): [" + modelId + "]");
</code>```

答:
As far as I can tell the only thing I think that will kill it are these lines:

```<code>logging.path=/logs
logging.file=${logging.path}/log.log
</code>```

I believe that if you include both, Spring Boot will ignore both of them. So I'd try removing one of those, and seeing if that helps.

As another thing (but I don't think it contributes to this problem), Spring recommends that you have just a logback-spring.xml file, not logback.xml (and definitely not both).

Body:
Need help... what am I doing wrong here???
I believe it does read the path and file name from application.properties file. But  I don't think it reads the logback.xml or logback-spring.xml

I did some research and found many questions/answers. But I think everyone says to put the logback xml in resources and give the path and file name in application.properties. I know it is simple, but missing something somewhere...

Thanks in advance!!

application.properties

# ===============================
# LOGGING
# ===============================
# log configuration -- update config location as needed
#logging.config=/logback-spring.xml
#logging.file=/logs/iqs-service.txt
logging.path=/logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n

Content of log file (log.log.0):

[2018-12-10 15:54:41.999] - 10828 INFO [main] --- org.apache.catalina.core.StandardService: Starting service Tomcat
[2018-12-10 15:54:42.002] - 10828 INFO [main] --- org.apache.catalina.core.StandardEngine: Starting Servlet Engine: Apache Tomcat/8.5.14
[2018-12-10 15:54:42.257] - 10828 INFO [localhost-startStop-1] --- org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]: Initializing Spring embedded WebApplicationContext
[2018-12-10 15:54:46.551] - 10828 INFO [http-nio-19917-exec-1] --- org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/]: Initializing Spring FrameworkServlet 'dispatcherServlet

Log statements in my java method - This never prints in the log

log.info("init(): [" + modelId + "]");
log.error("init(): [" + modelId + "]");

Body:
As far as I can tell the only thing I think that will kill it are these lines:

logging.path=/logs
logging.file=${logging.path}/log.log

I believe that if you include both, Spring Boot will ignore both of them. So I'd try removing one of those, and seeing if that helps.

As another thing (but I don't think it contributes to this problem), Spring recommends that you have just a logback-spring.xml file, not logback.xml (and definitely not both).


问:
__attribute__((const)) vs __attribute__((pure)) in GNU C
What is the difference between __attribute__((const)) and __attribute__((pure)) in GNU C?

```<code>__attribute__((const)) int f() {
    /* ... */
    return 4;
}
</code>```

vs

```<code>__attribute__((pure)) int f() {
    /* ... */
    return 4;
}
</code>```

答:
Note that if a function is passed a pointer and examines the contexts of that pointer, it cannot be declared const, even if the passed pointer and the pointer contexts are const. This is a severe limitation to the usefulness of const.

You can return multiple values in C by using a struct, which makes it easier to use pure. (It is more typical to use pointer return operands, but this breaks use of pure).

Body:
What is the difference between __attribute__((const)) and __attribute__((pure)) in GNU C?

__attribute__((const)) int f() {
    /* ... */
    return 4;
}

vs

__attribute__((pure)) int f() {
    /* ... */
    return 4;
}


问:
BottomNavigationView does not hide on scroll - NestedScrollView in viewpager
I have bottom navigation bar and viewpager inside coordinator layout, every fragment inside viewpager has own collapsing toolbars,

but app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior" doesn't work for me.

Also I don't want to do bottomNav.setVisibility(View.GONE); by listening the my nested scrollviews (inside fragments), because it hasn't animation. this is my last option.

My Activity

```<code>   <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".market.MarketActivity">

    <com.example.x.custom.NonSwipeableViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="?android:attr/windowBackground"
            app:labelVisibilityMode="labeled"
            app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
            app:layout_insetEdge="bottom"
            app:itemIconTint="@drawable/bottom_navigation_selector"
            app:itemTextColor="@drawable/bottom_navigation_selector"
            app:menu="@menu/bottom_navigation_menu"
            android:theme="@style/Widget.BottomNavigationView"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

One of the fragments (In the content view there is an nested scrollview. I set its layout behavior)

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".testproject.ScrollingActivity">

    <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_height="140dp"
            android:minHeight="56dp"
            app:elevation="0dp"
            android:layout_width="match_parent">

        <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:toolbarId="@+id/toolbar"
                app:expandedTitleGravity="bottom|left"
                app:expandedTitleMarginStart="14dp"
                app:expandedTitleMarginBottom="60dp"
                app:collapsedTitleTextAppearance="@style/CollapsingToolbarTextStyleBlack"
                app:expandedTitleTextAppearance="@style/CollapsingToolbarTextStyleBlack"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                android:background="@color/white">

            <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_width="match_parent"
                    app:layout_collapseMode="pin"
                    app:titleMarginStart="0dp"
                    android:gravity="top"
                    android:layout_marginBottom="48dp"
                    app:popupTheme="@style/AppTheme.PopupOverlay">

            </androidx.appcompat.widget.Toolbar>

            <com.google.android.material.tabs.TabLayout
                    android:id="@+id/tabs"

                    android:background="@color/white"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabIndicatorFullWidth="false"
                    app:tabTextColor="@color/warm_grey"
                    app:tabMode="scrollable"
                    app:tabSelectedTextColor="@color/lipstick"
                    android:layout_gravity="bottom"
                    app:tabTextAppearance="@style/TabLayoutTextStyle"
                    android:paddingRight="6dp"
                    android:paddingLeft="6dp"
            >

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/main_market">

                </com.google.android.material.tabs.TabItem>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/high_yield"/>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/perpetuals"/>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem4"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/special_situations"/>

            </com.google.android.material.tabs.TabLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_market"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Those links didn't work
Hide/Show bottomNavigationView on Scroll

Show/hide BottomNavigationView on scroll in CoordinatorLayout with AppBarLayout

When scroll bottom navigation bar does not hide - BottomNavigationBehavior

BottomNavigationView does not hide on scrolling inside fragment, if fragment contains AppBarLayout

答:
it's too altho the

```<code>BottomNavigationView
</code>```

is in the Activity so it's will work only if you are scrolling in the Activity.

you can do something like this https://stackoverflow.com/a/44778453/7373745

Body:
I have bottom navigation bar and viewpager inside coordinator layout, every fragment inside viewpager has own collapsing toolbars,

but app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior" doesn't work for me.

Also I don't want to do bottomNav.setVisibility(View.GONE); by listening the my nested scrollviews (inside fragments), because it hasn't animation. this is my last option.

My Activity

   <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".market.MarketActivity">

    <com.example.x.custom.NonSwipeableViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="?android:attr/windowBackground"
            app:labelVisibilityMode="labeled"
            app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
            app:layout_insetEdge="bottom"
            app:itemIconTint="@drawable/bottom_navigation_selector"
            app:itemTextColor="@drawable/bottom_navigation_selector"
            app:menu="@menu/bottom_navigation_menu"
            android:theme="@style/Widget.BottomNavigationView"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

One of the fragments (In the content view there is an nested scrollview. I set its layout behavior)

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".testproject.ScrollingActivity">

    <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_height="140dp"
            android:minHeight="56dp"
            app:elevation="0dp"
            android:layout_width="match_parent">

        <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:toolbarId="@+id/toolbar"
                app:expandedTitleGravity="bottom|left"
                app:expandedTitleMarginStart="14dp"
                app:expandedTitleMarginBottom="60dp"
                app:collapsedTitleTextAppearance="@style/CollapsingToolbarTextStyleBlack"
                app:expandedTitleTextAppearance="@style/CollapsingToolbarTextStyleBlack"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                android:background="@color/white">

            <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_height="?attr/actionBarSize"
                    android:layout_width="match_parent"
                    app:layout_collapseMode="pin"
                    app:titleMarginStart="0dp"
                    android:gravity="top"
                    android:layout_marginBottom="48dp"
                    app:popupTheme="@style/AppTheme.PopupOverlay">

            </androidx.appcompat.widget.Toolbar>

            <com.google.android.material.tabs.TabLayout
                    android:id="@+id/tabs"

                    android:background="@color/white"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    app:tabIndicatorFullWidth="false"
                    app:tabTextColor="@color/warm_grey"
                    app:tabMode="scrollable"
                    app:tabSelectedTextColor="@color/lipstick"
                    android:layout_gravity="bottom"
                    app:tabTextAppearance="@style/TabLayoutTextStyle"
                    android:paddingRight="6dp"
                    android:paddingLeft="6dp"
            >

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/main_market">

                </com.google.android.material.tabs.TabItem>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/high_yield"/>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/perpetuals"/>

                <com.google.android.material.tabs.TabItem
                        android:id="@+id/tabItem4"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@string/special_situations"/>

            </com.google.android.material.tabs.TabLayout>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <include layout="@layout/content_market"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Those links didn't work
Hide/Show bottomNavigationView on Scroll

Show/hide BottomNavigationView on scroll in CoordinatorLayout with AppBarLayout

When scroll bottom navigation bar does not hide - BottomNavigationBehavior

BottomNavigationView does not hide on scrolling inside fragment, if fragment contains AppBarLayout

Body:
it's too altho the

BottomNavigationView

is in the Activity so it's will work only if you are scrolling in the Activity.

you can do something like this https://stackoverflow.com/a/44778453/7373745


问:
How can i make the style sheet rendering in expressjs/ejs common?
I am using ejs in node for creating an app. And in my ejs, when I navigate from one page to another I have to render the header also to have the styles.

How can I make this common for all pages?

```<code><title>Static Website </title>
<meta charset="utf-8">
<meta name="active-menu">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="./styles/abc.css">
<link rel="stylesheet" type="text/css" href="./styles/def.css"> ```

I don't want load styles on every routing. Render all the styles on first page itself
```

答: ejs will render the page every time you refresh the page, so you need to put every css you need. you can pass var that say if a css is needed ex: isDefNedded = true and make a if statement in your ejs header</p>

Body:
I am using ejs in node for creating an app. And in my ejs, when I navigate from one page to another I have to render the header also to have the styles.

How can I make this common for all pages?

<title>Static Website </title>
<meta charset="utf-8">
<meta name="active-menu">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="./styles/abc.css">
<link rel="stylesheet" type="text/css" href="./styles/def.css"> ```

I don't want load styles on every routing. Render all the styles on first page itself


问:
How to output DATEADD with a specific precision?
I have a procedure which is called from external application.
The procedure has a parameter time of bigint type. In the procedure I insert the time to my table to column of 'time' type. To convert bigint to time I use DATEADD:

```<code>DATEADD(S, @piHMSTime, '19700101')
</code>```

Everything works fine but I get time in my table like this 22:59:57.0000000.
How do I set a needed precision? I need only seconds or maybe 2 digits after point.

答:
Don't worry about it.  The value you are storing uses an internal format.

If you only want to see the time up to seconds, use convert():

```<code>convert(varchar(8), timecol, 114)
</code>```

If the column is defined as time, then the default is to have seven digits of precision for seconds (100 nanoseconds).  If you only want seconds, use time(0):

```<code>alter table t alter column timecol time(0);
</code>```

Body:
I have a procedure which is called from external application.
The procedure has a parameter time of bigint type. In the procedure I insert the time to my table to column of 'time' type. To convert bigint to time I use DATEADD:

DATEADD(S, @piHMSTime, '19700101')

Everything works fine but I get time in my table like this 22:59:57.0000000.
How do I set a needed precision? I need only seconds or maybe 2 digits after point.

Body:
Don't worry about it.  The value you are storing uses an internal format.

If you only want to see the time up to seconds, use convert():

convert(varchar(8), timecol, 114)

If the column is defined as time, then the default is to have seven digits of precision for seconds (100 nanoseconds).  If you only want seconds, use time(0):

alter table t alter column timecol time(0);


问:
What is the difference between psql and postgresql-client?
I have access to two postgres database servers on different hosts. On server A I access the client using:

```<code>psql -h localhost -U user -W db_name

db_name=>
</code>```

And on the second host B I access the client using (docker image):

docker run -it --rm  --network fiware_default jbergknoff/postgresql-client\
   postgresql://postgres:password@postgres-db:5432/postgres

postgres=#
```

<p>Now I need to dump database file copied from A (now on B) using:</p>

```psql -U postgres -d targetdb -f sourcedb.sql
```

However, the command psql isn´t recognised second host B. I mean I cannot run commands using psql B

what is then the difference between psqland postgres-clienthere please?

答:
The docker image postgresql-client has psql defined as an entrypoint. See https://github.com/jbergknoff/Dockerfile/blob/master/postgresql-client/Dockerfile#L3 .

So you basically ran psql psql and psql does not understand that. Just leave psql out and start straight with the args.

You can read up on CMD vs ENTRYPOINT here What is the difference between CMD and ENTRYPOINT in a Dockerfile? or here http://goinbigdata.com/docker-run-vs-cmd-vs-entrypoint/ .

Body:
I have access to two postgres database servers on different hosts. On server A I access the client using:

psql -h localhost -U user -W db_name

db_name=>

And on the second host B I access the client using (docker image):

docker run -it --rm  --network fiware_default jbergknoff/postgresql-client\
   postgresql://postgres:password@postgres-db:5432/postgres

postgres=#

Now I need to dump database file copied from A (now on B) using:

psql -U postgres -d targetdb -f sourcedb.sql

However, the command psql isn´t recognised second host B. I mean I cannot run commands using psql B

what is then the difference between psqland postgres-clienthere please?


问:
is there one way to turn on code assist in animation xml
Eclipse give me a good experience in code assistence.But when it comes to animation xml files and i enter alt+/,it pop up nothing.So it make me very easy to type a wrong attribute name because of my poor english.can you give me a hand?
thanks.</p>

答:
I am not sure what you mean by "animation xml file" (the CEGUI ones? Android ones?), but, as explained in "eclipse editor, ex: xml editor, code assistance. how it works?", any xml file with auto-completion needs a DTD or Schema informtion.

Sometime, the DOCTYPE at the beginning of the xml file can prevent the auto-completion to work.


问:
multiple openvpn connections for different browsers
I'm trying to use OpenVPN to establish multiple connections so that every browser has its own Ip. I'm trying to do it programatically using selenium but I'll adapt to any other if needed. I'm following this other thread which answers the question that I'm asking:

https://forums.linuxmint.com/viewtopic.php?f=42&t=175765

But I followed all the steps and the problem is that it's using my router Ip (it's not using any .ovpn provided although it's connecting properly "Initialization Sequence Completed").

Why is using my home router IP address when my IP gateway is ok, my username and interface too from the up.sh file?

Perhaps there's another easier way to do it...

答:
There are multiple ways to have different IPs per browser. The cheapest and most anonymous way is to use Tor.

Another way would be to change the IP on the browser level by using a proxy (such as Shadowsocks). For example, you could set something up with a proxy and SwitchyOmega (a browser extension which also allows you to switch between proxies based on URL).

Here is what it looks like from within Chrome.

Hope this helps!


问:
How do I get a button to run a function in a fragment?
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

<p>If needed, heres the whole fragment activity</p>

<p>When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.</p>

<p>Here's how I tried to set up my OnClickListener:</p>

```    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }
```

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.

答:
If you added fragment to activity by XML:
From activity class:

YourFragmentClass  fragment = (YourFragmentClass)(yourActivity.getSupportFragmentManager().findFragmentById(fragment_id));.

You also can find fragment inside an activity by tag (tag is a string that you assign to the fragment when you promatically add fragment to activity).

YourFragmentClass  fragment = (YourFragmentClass)(yourActivity.getSupportFragmentManager().findFragmentByTag(fragment_tag));.

After having gotten fragment, you now can call the fragment methods from activity by set OnClickListener for button.

```<code>btn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
       fragment.methodOfFragment();
    }
});
</code>```

Body:
I have a fragment and I want a button to run the function Calculate() when I press it. My fragment is also based from one of the templates.

I've tried the XML android:onClick thing, though I assume its looking inside MainActivity instead of the Fragment so it throws an error.
I've also followed trying to use an OnClickListener from another post, though setting it up (as in code inside OnCreateCiew) gave errors, though it might just be my amateur knowledge of how it works.

This is my calculate function (the function I'm trying to get to run when my button is clicked), which is inside the fragment activity:

    public void Calculate(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

If needed, heres the whole fragment activity

When using the XML onclick, my app just crashes when the button is pressed.
When using OnClickListener, I can't even compile because of errors.
I don't have much coding expertise to know what the template fragment code is doing, but I assume its conflicting with however I'm setting up the OnClickListener.

Here's how I tried to set up my OnClickListener:

    Button calculatebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View kinematicsCalculatorView = inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);
        calculatebutton = (Button) kinematicsCalculatorView.findViewById(R.id.calculateButton);
        calculatebutton.setOnClickListener(this);
        return kinematicsCalculatorView;
        // Inflate the layout for this fragment
       // return inflater.inflate(R.layout.fragment_fragment_calculator_kinematics, container, false);

    }

    public void onClick(View v) {
        EditText InitialVelocityInput = getView().findViewById(R.id.initialVelocityInput);
        EditText VelocityInput = getView().findViewById(R.id.velocityInput);
        EditText AccelerationInput = getView().findViewById(R.id.accelerationInput);
        EditText TimeInput = getView().findViewById(R.id.timeInput);

        Log.d("bing", "bing");
    }

However, the this in calculatebutton.setOnClickListener(this); shows up as an error, (setOnClickListener(android.view.View.OnClickListener) in View cannot be applied to (com.example.myApp.FragmentCalculatorKinematics)). onClick method is shown as never being used.

Body:
If you added fragment to activity by XML:
From activity class:

YourFragmentClass  fragment = (YourFragmentClass)(yourActivity.getSupportFragmentManager().findFragmentById(fragment_id));.

You also can find fragment inside an activity by tag (tag is a string that you assign to the fragment when you promatically add fragment to activity).

YourFragmentClass  fragment = (YourFragmentClass)(yourActivity.getSupportFragmentManager().findFragmentByTag(fragment_tag));.

After having gotten fragment, you now can call the fragment methods from activity by set OnClickListener for button.

btn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
       fragment.methodOfFragment();
    }
});


问:
Looking for right approach to saving data with Keychain and data encryption - Swift 5
 My app stores user's sensitive data and I wonder what is general/proper/the most secure way to secure the data.

My approach now is saving encoded data into Keychain, more specifically but simply :

I am encoding/decoding custom types in array with PropertyList

Then pass these to Keychain. I am using a wrapper called KeychainAccess thanks to Kishikawa Katsumi.

Retrieve data from Keychain then decode it to display on tableview.

Below is my code bits :

```<code>extension UserInformation {

    static let propertyListEncoder = PropertyListEncoder()
    static let propertyListDecoder = PropertyListDecoder()
    static let keychain = Keychain(service: "com.xxxxx.DataSaving-App")

    static func saveToKeychain(userInfo: [UserInformation]) {
        let data = try? propertyListEncoder.encode(userInfo)
        if let savingData = data {
            dump(userInfo)
            keychain[data: "encodedUserInfo"] = NSData(data: savingData) as Data
        }
    }

    static func loadFromKeychain() -> [UserInformation]? {
        guard let retrievedData = keychain[data: "encodedUserInfo"] else {
            return nil }
        let data = try? propertyListDecoder.decode(Array<UserInformation>.self, from: retrievedData)
        return data
    }

}
</code>```

Above works fine and no problem found so far. However, I am not sure to use PropertyListEncoder is right way to encode/decode. Please kindly see below specified questions and giving advice to me should be very grateful.

Would above approach be secure enough?

Is PropertyListEncoder/Decoder just doing ENCODING/DECODING, NOT SAVING DATA TO ANY, like plist or any storage where is vulnerable?

If any other measure is needed, is encrypting data with Common Swift then passing it to Keychain making sense?

I spent few weeks to find detail solution but no luck yet. Please help a new developer.

答: Property list encoding is not encryption. It's plain text (possibly in binary format); it is just a form of serialization. The "encryption" in your example consists of the fact that the information is hidden in the keychain. And the keychain is generally regarded as sufficiently secure.</p>

Body:
 My app stores user's sensitive data and I wonder what is general/proper/the most secure way to secure the data.

My approach now is saving encoded data into Keychain, more specifically but simply :

I am encoding/decoding custom types in array with PropertyList

Then pass these to Keychain. I am using a wrapper called KeychainAccess thanks to Kishikawa Katsumi.

Retrieve data from Keychain then decode it to display on tableview.

Below is my code bits :

extension UserInformation {

    static let propertyListEncoder = PropertyListEncoder()
    static let propertyListDecoder = PropertyListDecoder()
    static let keychain = Keychain(service: "com.xxxxx.DataSaving-App")

    static func saveToKeychain(userInfo: [UserInformation]) {
        let data = try? propertyListEncoder.encode(userInfo)
        if let savingData = data {
            dump(userInfo)
            keychain[data: "encodedUserInfo"] = NSData(data: savingData) as Data
        }
    }

    static func loadFromKeychain() -> [UserInformation]? {
        guard let retrievedData = keychain[data: "encodedUserInfo"] else {
            return nil }
        let data = try? propertyListDecoder.decode(Array<UserInformation>.self, from: retrievedData)
        return data
    }

}

Above works fine and no problem found so far. However, I am not sure to use PropertyListEncoder is right way to encode/decode. Please kindly see below specified questions and giving advice to me should be very grateful.

Would above approach be secure enough?

Is PropertyListEncoder/Decoder just doing ENCODING/DECODING, NOT SAVING DATA TO ANY, like plist or any storage where is vulnerable?

If any other measure is needed, is encrypting data with Common Swift then passing it to Keychain making sense?

I spent few weeks to find detail solution but no luck yet. Please help a new developer.


问:
sort sublists by matching elements
I have a list like below:

```<code>lst1 = [[5, 0], [5, 3], [6, 2], [6, 1], [4, 0], [4, 1], [4, 3], [7, 2], [7, 1], [7, 3], [0, 3], [2, 1], [3, 8]]
</code>```

I want to create a list like below:

```<code>lst2 = [[5, 0, 3, 8], [6, 2, 1], [4, 0, 3, 8], [7, 2, 1], [5, 3, 8]]
</code>```

[5, 0, 3, 8] is created from [5, 0], [0, 3], and [3, 8] because the last item of [5, 0] matched with the first item of [0, 3] and the last item of [0, 3] matched with the first element of [3, 8]. Similarly, [6, 2, 1] is from [6, 2] and [2, 1] and so on. The problem is how can I iterate lst1 and create lst2? I know how to iterate list/list of lists, extract items, etc. but the difficulty I have here is by iterating lst1 once how can I create lst2.

答:
Well, I can iterate over the top loop "once," but it's not really "once," in that each iteration waltzes over its sublist. O(n^2), if I'm not mistaken:

lst1 = [[5, 0], [5, 3], [6, 2], [6, 1], [4, 0], [4, 1], [4, 3], [7, 2], [7, 1], [7, 3], [0, 3], [2, 1], [3, 8]]

def accept(root, pair):
    if root[-1] == pair[0]:
        root.append(pair[1])

def longest_for_root(root, pairs):
    for i, pair in enumerate(pairs):
        accept(root, pairs[i])

def strings_for_list(pairs):
    for i, pair in enumerate(pairs):
        if i < len(pairs) - 1:
            lfr = pairs[i].copy()
            longest_for_root(lfr, pairs[i + 1:])
            if len(lfr) > 2:
                yield lfr

[*strings_for_list(lst1)]

# [[5, 0, 3, 8], [5, 3, 8], [6, 2, 1], [4, 0, 3, 8], [4, 3, 8], [7, 2, 1], [7, 3, 8], [0, 3, 8]]
```

Another option that presents itself is to put the entries in a dict, keyed by their initial and terminal digits, but I think that just changes what accept() looks like.

I presumed that you're looking for matches "in order," by which we mean that [[5,0],[0,3]] produces [5, 0, 3], but [[0,3],[5,0]] produces nothing.

Title: sort sublists by matching elements

Body:
I have a list like below:

lst1 = [[5, 0], [5, 3], [6, 2], [6, 1], [4, 0], [4, 1], [4, 3], [7, 2], [7, 1], [7, 3], [0, 3], [2, 1], [3, 8]]

I want to create a list like below:

lst2 = [[5, 0, 3, 8], [6, 2, 1], [4, 0, 3, 8], [7, 2, 1], [5, 3, 8]]

[5, 0, 3, 8] is created from [5, 0], [0, 3], and [3, 8] because the last item of [5, 0] matched with the first item of [0, 3] and the last item of [0, 3] matched with the first element of [3, 8]. Similarly, [6, 2, 1] is from [6, 2] and [2, 1] and so on. The problem is how can I iterate lst1 and create lst2? I know how to iterate list/list of lists, extract items, etc. but the difficulty I have here is by iterating lst1 once how can I create lst2.

Body:
Well, I can iterate over the top loop "once," but it's not really "once," in that each iteration waltzes over its sublist. O(n^2), if I'm not mistaken:

lst1 = [[5, 0], [5, 3], [6, 2], [6, 1], [4, 0], [4, 1], [4, 3], [7, 2], [7, 1], [7, 3], [0, 3], [2, 1], [3, 8]]

def accept(root, pair):
    if root[-1] == pair[0]:
        root.append(pair[1])

def longest_for_root(root, pairs):
    for i, pair in enumerate(pairs):
        accept(root, pairs[i])

def strings_for_list(pairs):
    for i, pair in enumerate(pairs):
        if i < len(pairs) - 1:
            lfr = pairs[i].copy()
            longest_for_root(lfr, pairs[i + 1:])
            if len(lfr) > 2:
                yield lfr

[*strings_for_list(lst1)]

# [[5, 0, 3, 8], [5, 3, 8], [6, 2, 1], [4, 0, 3, 8], [4, 3, 8], [7, 2, 1], [7, 3, 8], [0, 3, 8]]

Another option that presents itself is to put the entries in a dict, keyed by their initial and terminal digits, but I think that just changes what accept() looks like.

I presumed that you're looking for matches "in order," by which we mean that [[5,0],[0,3]] produces [5, 0, 3], but [[0,3],[5,0]] produces nothing.


问:
ASP.NET Core MVC: connecting to existing database using SQL Server authentication
I am new to webpage development, and trying to connect my ASP.NET Core MVC code to an existing SQL Server database, using SQL Server authentication. Right now it will only take my computer identification, which of course gets rejected by the SQL Server database. Can anyone tell me how I am supposed to do this?

Details:

Programing is done in Visual Studio 2019, with ASP.NET Core, Entity Framework. All software is up to date.

I followed this tutorial exactly: https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db  but it doesn't include SQL Server authentication.

I have my SQL Server login information, and it does allow me to manually connect using "Tools -> Connect to Database". I can see my database and navigate through it, but cannot connect to migrate the data over to my MVC files.

I did successfully complete the entire Microsoft ASP.NET MVC tutorial wherein you create a movies database and use that for an example webpage. The difficulty comes when connecting to an existing database.

答:
Depending on the Connection method you are using. In your appsettings.json, you can set the connection string like below:

For Windows authentication:

```<code>"ConnectionString": "Server=laptop-15;Database=testDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

For SQL Server authentication:

```<code>"ConnectionString": "Server=laptop-15;Database=testDatabase;User Id=user; Password=user;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

Let me know if this solves your issue. Thanks

Body:
Depending on the Connection method you are using. In your appsettings.json, you can set the connection string like below:

For Windows authentication:

"ConnectionString": "Server=laptop-15;Database=testDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"

For SQL Server authentication:

"ConnectionString": "Server=laptop-15;Database=testDatabase;User Id=user; Password=user;Trusted_Connection=True;MultipleActiveResultSets=true"

Let me know if this solves your issue. Thanks


问:
What is the reason for using of Service Binder while running multiple JBoss (JBoss 4.2)
I found couple of tutorials how to run multiple instances of JBoss on the same machine.

All of them mention uncommenting Service Binder and having separate service-binding.xml files for each server.

The question is why it's done like that? Is there any reason except adding additional layer of indirection?

It looks the same could be done by modification of ports in jboss-service.xml for each server. The only restriction would be that there won't be easy way to switch which instance of JBoss uses which set of ports.

答:
You are right with modifying the ports in jboss-service.xml. This is the straightforward and genuine way to change the ports.

Unfortunately, ports are not only defined in that file, but also in other places like jboss-web's configuration etc.

Catching all those places can be error prone.

So the idea was to have a central file (service-binding.xml) that lives in the root of a server installation. You basically copy the 'default' config to server1, server2 etc and then via command line pass in the server name when starting so that the correct port-offset for all of the services is taken from service-bindings.xml and applied to the resulting runtime configuration.

JBossAS 7 takes this concept one step further to the ServiceBindingGroups, where the base ports are defined on a domain level and then per server you pick a basic group + just a port offset by name, so that there is even less work needed than in as4


问:
Modifying the compilation process with SPEC to use LLVM
I am currently working on running some llvm passes and would like to benchmark their usefulness using the SPEC 2006 CPU benchmark suite. However, I've not figured out how to modify the SPEC setup to do anything other than use llvm-gcc to output llvm bitcode. Here is what I'd like to modify the workflow of SPEC to do:

compile the .o files with llvm into llvm-bytecode

```<code>llvm-gcc -emit-llvm *.c
</code>```

For each .o file, run opt (llvm's optimization pass):

```<code>opt -adce -mem2reg cfline.o
</code>```

Link with llvm-link:

```<code>llvm-link *.o -o out.o.linked
</code>```

Turn the llvm bytecode into assembly

```<code>llc out.o.linked
</code>```

And finally turn that into executable code:

```<code>gcc out.o.linked -o out.executable
</code>```

Is there a way I can do this? I know I can edit the .cfg files to emit llvm, but then I don't know how to choose a different linking/pre-linking procedure.

Thanks!

答: LLVM has a test-suite subproject that already knows how to build and run SPEC. See the docs for more info.</p>

Body:
I am currently working on running some llvm passes and would like to benchmark their usefulness using the SPEC 2006 CPU benchmark suite. However, I've not figured out how to modify the SPEC setup to do anything other than use llvm-gcc to output llvm bitcode. Here is what I'd like to modify the workflow of SPEC to do:

compile the .o files with llvm into llvm-bytecode

llvm-gcc -emit-llvm *.c

For each .o file, run opt (llvm's optimization pass):

opt -adce -mem2reg cfline.o

Link with llvm-link:

llvm-link *.o -o out.o.linked

Turn the llvm bytecode into assembly

llc out.o.linked

And finally turn that into executable code:

gcc out.o.linked -o out.executable

Is there a way I can do this? I know I can edit the .cfg files to emit llvm, but then I don't know how to choose a different linking/pre-linking procedure.

Thanks!


问:
How to extract dotted text from image?
I'm working on my bachelor's degree final project and I want to create an OCR for bottle inspection with python. I need some help with text recognition from the image. Do I need to apply the cv2 operations in a better way, train tesseract or should I try another method?

I tried image processing operations on the image and I used pytesseract to recognize the characters.

Using the code bellow I got from this photo:

to this one:

and then to this one:

Sharpen function:

```<code>def sharpen(img):
  sharpen = iaa.Sharpen(alpha=1.0, lightness = 1.0)
  sharpen_img = sharpen.augment_image(img)
  return sharpen_img
</code>```

Image processing code:

```<code>textZone = cv2.pyrUp(sharpen(originalImage[y:y + h - 1, x:x + w - 1])) #text zone cropped from the original image

sharp = cv2.cvtColor(textZone, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(sharp, 127, 255, cv2.THRESH_BINARY)

#the functions such as opening are inverted (I don't know why) that's why I did opening with MORPH_CLOSE parameter, dilatation with erode and so on

kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
open = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel_open)

kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,7))
dilate = cv2.erode(open,kernel_dilate)

kernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 5))
close = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernel_close)

print(pytesseract.image_to_string(close))
</code>```

This is the result of pytesseract.image_to_string:

```<code>22203;?!)

92:53 a
</code>```

The expected result is :

```<code>22/03/20

02:53 A
</code>```

答:
"Do I need to apply the cv2 operations in a better way, train tesseract or should I try another method?"

First, kudos for taking this project on and getting this far with it. What you have from the OpenCV/cv2 standpoint looks pretty good.

Now, if you're thinking of Tesseract to carry you the rest of the way, at the very least you'll have to train it. Here you have a tough choice: Invest in training Tesseract, or work up a CNN to recognize a limited alphabet. If you have a way to segment the image, I'd be tempted to go with the latter.

Title: How to extract dotted text from image?

Body:
I'm working on my bachelor's degree final project and I want to create an OCR for bottle inspection with python. I need some help with text recognition from the image. Do I need to apply the cv2 operations in a better way, train tesseract or should I try another method?

I tried image processing operations on the image and I used pytesseract to recognize the characters.

Using the code bellow I got from this photo:

to this one:

and then to this one:

Sharpen function:

def sharpen(img):
  sharpen = iaa.Sharpen(alpha=1.0, lightness = 1.0)
  sharpen_img = sharpen.augment_image(img)
  return sharpen_img

Image processing code:

textZone = cv2.pyrUp(sharpen(originalImage[y:y + h - 1, x:x + w - 1])) #text zone cropped from the original image

sharp = cv2.cvtColor(textZone, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(sharp, 127, 255, cv2.THRESH_BINARY)

#the functions such as opening are inverted (I don't know why) that's why I did opening with MORPH_CLOSE parameter, dilatation with erode and so on

kernel_open = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
open = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel_open)

kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,7))
dilate = cv2.erode(open,kernel_dilate)

kernel_close = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 5))
close = cv2.morphologyEx(dilate, cv2.MORPH_OPEN, kernel_close)

print(pytesseract.image_to_string(close))

This is the result of pytesseract.image_to_string:

22203;?!)

92:53 a

The expected result is :

22/03/20

02:53 A


问:
android emulator WHPX: Failed to emulate MMIO access , exit code 3
I had Android Studio with AMD TR 2950x
android emulator was working perfectly
then suddenly it start to give me this error
with this messages :

10:30 AM  Emulator: qemu-system-x86_64.exe: WHPX: Failed to emulate
  MMIO access with EmulatorReturnStatus: 2 (InternalEmulationFailure )

10:30 AM  Emulator: qemu-system-x86_64.exe: whpx_vcpu {
  emulator=000000000ec95f70, window_registered=false,
  interruptable=true, tpr=0, apic_base=fee00900,
  interruption_pending=false }

10:30 AM  Emulator: qemu-system-x86_64.exe: WHV_MEMORY_ACCESS_CONTEXT {
  Instruction={ size=16, bytes='A1 F0 00 E0 FE 80 CC 01 A3 F0 00 E0 FE
  C7 05 50 ' }, AccessInfo={ AccessType=0, GpaUnmapped=1, GvaValid=0,
  AsUINT32=4 }, Gpa=fee000f0, Gva=0 }

10:30 AM  Emulator: qemu-system-x86_64.exe: WHPX: Failed to exec a
  virtual processor

10:30 AM  Emulator: Warning: QObject::~QObject: Timers cannot be
  stopped from another thread ((null):0, (null))

10:30 AM  Emulator: Process finished with

答:
Update Windows to insder preview build 10.0.18890

https://developercommunity.visualstudio.com/content/problem/528337/whpx-problem-android-emulator.html


问:
When calling one of my functions in Node.js the program first calls emitHookFactory and gets stuck in an infinite loop
I'm running into an issue where my Node.js program gets stuck looping a function (emitHookFactory in \<node_internals>\internal\async_hooks.js) that I didn't even explicitly call. It happens when I access members or call functions on one of my own classes from my backend application. When I access those members or functions from my frontend app there is no problem.

Examples:

Backend: comp.UpdateMaster(); immediately goes into emitHookFactory and loops indefinitely.
Frontent: comp.UpdateMaster(); immediately goes into UpdateMaster as expected.

The backend code runs inside a Promise inside an Express.js Router's get handler, if that's any help.

答:
seems you're not the only one to have this issue. I found this post in response to a similar questions that you have. If you are using vscode to try and debug your nodejs application you should set this property:

```<code>"skipFiles": [
  "<node_internals>/**"
],
</code>```

To your config file in vscode.

Sorry if this isn't your issue, but it seems like this is happening to others.

Body:
seems you're not the only one to have this issue. I found this post in response to a similar questions that you have. If you are using vscode to try and debug your nodejs application you should set this property:

"skipFiles": [
  "<node_internals>/**"
],

To your config file in vscode.

Sorry if this isn't your issue, but it seems like this is happening to others.


问:
How to add unix timestamp as expiry in Redis records?
I am trying to add a unix timestamp to a record in redis so I am using expireat to do so. I have been able to achieve what I want using the following:

```<code>tokenBlacklist.set(splitId[0], splitId[1]);
tokenBlacklist.expireat(splitId[0], tokenExp); //tokenExp example: 1558786197
</code>```

Now, I want to know if there is any one liner to the above solution, something like:

```<code>tokenBlacklist.set(splitId[0], splitId[1], "EX", tokenExp);
</code>```

答:
The SET command can only specify a TTL, NOT an expiration time point. So you can use the tokenExp - current-time-in-second as the argument.

```<code>tokenBlacklist.set(splitId[0], splitId[1], "EX", tokenExp - Math.round((new Date()).getTime() / 1000));
</code>```

NOTE:

I'm not familiar with javascript. If the way to get current Unix time in second in wrong, please point it out. Thanks.

Body:
I am trying to add a unix timestamp to a record in redis so I am using expireat to do so. I have been able to achieve what I want using the following:

tokenBlacklist.set(splitId[0], splitId[1]);
tokenBlacklist.expireat(splitId[0], tokenExp); //tokenExp example: 1558786197

Now, I want to know if there is any one liner to the above solution, something like:

tokenBlacklist.set(splitId[0], splitId[1], "EX", tokenExp);

Body:
The SET command can only specify a TTL, NOT an expiration time point. So you can use the tokenExp - current-time-in-second as the argument.

tokenBlacklist.set(splitId[0], splitId[1], "EX", tokenExp - Math.round((new Date()).getTime() / 1000));

NOTE:

I'm not familiar with javascript. If the way to get current Unix time in second in wrong, please point it out. Thanks.