问:
Pure CSS scroll animation
I have been looking for a way to scroll down when clicking on a button that is located on top of a page using CSS3 only.

So I've found this tutorial: http://tympanus.net/codrops/2012/06/12/css-only-responsive-layout-with-smooth-transitions/

Demo: http://tympanus.net/Tutorials/SmoothTransitionsResponsiveLayout/

But it's a bit too advanced for my needs since I just want the browser to scroll down on a click on one button located on top of the page, so I was wondering: is it possible to do those CSS scrolls without the input buttons, just with an anchor tag?

HTML looks like this: Learn more

I have already some CSS which I need to trigger on button click:

```<code>/* Button animation tryout. */
.animate {
    animation: moveDown 0.6s ease-in-out 0.2s backwards;
}
@keyframes moveDown{
    0% {
        transform: translateY(-40px);
        opacity: 0;
    }
    100% {
        transform: translateY(0px);
        opacity: 1;
    }
}
</code>```

答:
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

```<code>~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();
</code>```

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

Title: Pure CSS scroll animation

Body:
I have been looking for a way to scroll down when clicking on a button that is located on top of a page using CSS3 only.

So I've found this tutorial: http://tympanus.net/codrops/2012/06/12/css-only-responsive-layout-with-smooth-transitions/

Demo: http://tympanus.net/Tutorials/SmoothTransitionsResponsiveLayout/

But it's a bit too advanced for my needs since I just want the browser to scroll down on a click on one button located on top of the page, so I was wondering: is it possible to do those CSS scrolls without the input buttons, just with an anchor tag?

HTML looks like this: Learn more

I have already some CSS which I need to trigger on button click:

/* Button animation tryout. */
.animate {
    animation: moveDown 0.6s ease-in-out 0.2s backwards;
}
@keyframes moveDown{
    0% {
        transform: translateY(-40px);
        opacity: 0;
    }
    100% {
        transform: translateY(0px);
        opacity: 1;
    }
}

Body:
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010


来源: stackexchange

问:
CSC : error CS7038: Failed to emit module
After installing Visual Studio 2015 and building my project I receive the error

"CSC : error CS7038: Failed to emit module".

However my solution is building fine in Visual Studio 2013.

It is an ASP.NET webforms project .NET 4.0

Anyone?

UPDATE: it looks like the problem has to do with Red Gate Smart Assembly in combination with method parameters with default values.

UPDATE: Smart Assembly 6.9 fixes the error for me.

答:
For me the issue occured after adding a postbuild step that changes the assemblyinfo.cs (NetRevisionTool.exe).
Take care to not change the AssemblyInfo.cs between building and Edit and continue.</p>

ContentLicense: CC BY-SA 3.0


问:
Printing 2d array in JOptionPane
I'm try to print random 1d and 2d arrays in JOptionPane.
but it comes out like this:

is there a way to format it to line up like this:

the row and col are also random.

another thing, is there a way to use only one function to print for 1d and 2d arrays? and if not can the 2d function use the 1st one?
This is for school homework. we are not allowed to mess with JOptionPane. It's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

```<code> public static String printMatrix(int[] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      result += m[i] + "                ";
    }
    return result;
  }

  public static String printMatrix2D(int[][] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      for (int j = 0; j < m[i].length; j++) {
        result += m[i][j] + "                ";
      }
      result += "\n";
    }
    return result;
  }
</code>```

答:
If you want your numbers to be placed as if they were in a table, you need to create a JPanel with a GridLayout with some hgap and vgap. This works for 4 digit and 5 digit numbers or any amount of digit numbers.

For example:

```<code>import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JOptionPanePrintingInColumns {

    private JPanel pane;
    private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
    private String[][] twoDArray = new String[][] {
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"}
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
    }

    private void createAndShowGui() {
        //For the 1D Array
        pane = new JPanel();
        pane.setLayout(new GridLayout(0, 5, 50, 10));
        for (int i = 0; i < oneDArray.length; i++) {
            JLabel label = new JLabel(oneDArray[i]);
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            pane.add(label);
        }
        JOptionPane.showMessageDialog(new JFrame(), pane);

        //For the 2D array
        pane = new JPanel();
        pane.setLayout(new GridLayout(0, 5, 50, 10));
        for (int i = 0; i < twoDArray.length; i++) {
            for (int j = 0; j < twoDArray[i].length; j++) {
                JLabel label = new JLabel(twoDArray[i][j]);
                label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                pane.add(label);
            }
        }
        JOptionPane.showMessageDialog(new JFrame(), pane);
    }
}
</code>```

Which will produce something like this:

And because we can see the borders, we can notice that each label is the same size as the largest one (i.e. the last in each row) this is why it works for larger or shorter numbers.

You might have noticed that I used this line:

```<code>pane.setLayout(new GridLayout(0, 5, 50, 10));
</code>```

But what does the 0 means? It means "create as many rows as needed of 5 columns each", so this works either for 1D or 2D arrays, just changing the way you get the data from each array.

Edit:

but i forgot to mention this is for school homework. we are not allowed to mess with JOptionPane. it's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

You could use HTML tags inside the String to convert it to a table, then place each number inside the cells of it, using some cellspacing to provide more or less space (play with it):

```<code>import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JOptionPanePrintingInColumns {

    private JPanel pane;
    private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
    private String[][] twoDArray = new String[][] {
        {"1000", "10000", "99999", "23000", "100000"},
        {"100", "180000", "9999", "3000", "1090000"},
        {"111000", "1220000", "9955999", "230100", "1000200"},
        {"10010", "1005400", "9999954", "9", "123"},
        {"100430", "1000054", "999", "23123000", "123456789"}
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
    }

    private void createAndShowGui() {
        String output;
        StringBuilder sb = new StringBuilder();
        sb.append("<html><table><tr>");
        for (int i = 0; i < oneDArray.length; i++) {
            sb.append("<td>").append(oneDArray[i]).append("</td>");
        }
        sb.append("</tr></table></html>");
        output = sb.toString();
        JOptionPane.showMessageDialog(new JFrame(), output);

        sb = new StringBuilder();
        sb.append("<html><table cellspacing=10>");
        for (int i = 0; i < twoDArray.length; i++) {
            sb.append("<tr>");
            for (int j = 0; j < twoDArray.length; j++) {
                sb.append("<td>").append(twoDArray[i][j]).append("</td>");
            }
        }
        sb.append("</tr></table></html>");
        output = sb.toString();
        JOptionPane.showMessageDialog(new JFrame(), output);
    }
}
</code>```

Title: Printing 2d array in JOptionPane

Body:
I'm try to print random 1d and 2d arrays in JOptionPane.
but it comes out like this:

is there a way to format it to line up like this:

the row and col are also random.

another thing, is there a way to use only one function to print for 1d and 2d arrays? and if not can the 2d function use the 1st one?
This is for school homework. we are not allowed to mess with JOptionPane. It's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

 public static String printMatrix(int[] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      result += m[i] + "                ";
    }
    return result;
  }

  public static String printMatrix2D(int[][] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      for (int j = 0; j < m[i].length; j++) {
        result += m[i][j] + "                ";
      }
      result += "\n";
    }
    return result;
  }

Body:
If you want your numbers to be placed as if they were in a table, you need to create a JPanel with a GridLayout with some hgap and vgap. This works for 4 digit and 5 digit numbers or any amount of digit numbers.

For example:

import java.awt.Color;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JOptionPanePrintingInColumns {

    private JPanel pane;
    private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
    private String[][] twoDArray = new String[][] {
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"},
        {"1000", "10000", "99999", "23000", "100000"}
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
    }

    private void createAndShowGui() {
        //For the 1D Array
        pane = new JPanel();
        pane.setLayout(new GridLayout(0, 5, 50, 10));
        for (int i = 0; i < oneDArray.length; i++) {
            JLabel label = new JLabel(oneDArray[i]);
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            pane.add(label);
        }
        JOptionPane.showMessageDialog(new JFrame(), pane);

        //For the 2D array
        pane = new JPanel();
        pane.setLayout(new GridLayout(0, 5, 50, 10));
        for (int i = 0; i < twoDArray.length; i++) {
            for (int j = 0; j < twoDArray[i].length; j++) {
                JLabel label = new JLabel(twoDArray[i][j]);
                label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                pane.add(label);
            }
        }
        JOptionPane.showMessageDialog(new JFrame(), pane);
    }
}

Which will produce something like this:

And because we can see the borders, we can notice that each label is the same size as the largest one (i.e. the last in each row) this is why it works for larger or shorter numbers.

You might have noticed that I used this line:

pane.setLayout(new GridLayout(0, 5, 50, 10));

But what does the 0 means? It means "create as many rows as needed of 5 columns each", so this works either for 1D or 2D arrays, just changing the way you get the data from each array.

Edit:

but i forgot to mention this is for school homework. we are not allowed to mess with JOptionPane. it's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

You could use HTML tags inside the String to convert it to a table, then place each number inside the cells of it, using some cellspacing to provide more or less space (play with it):

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JOptionPanePrintingInColumns {

    private JPanel pane;
    private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
    private String[][] twoDArray = new String[][] {
        {"1000", "10000", "99999", "23000", "100000"},
        {"100", "180000", "9999", "3000", "1090000"},
        {"111000", "1220000", "9955999", "230100", "1000200"},
        {"10010", "1005400", "9999954", "9", "123"},
        {"100430", "1000054", "999", "23123000", "123456789"}
    };

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
    }

    private void createAndShowGui() {
        String output;
        StringBuilder sb = new StringBuilder();
        sb.append("<html><table><tr>");
        for (int i = 0; i < oneDArray.length; i++) {
            sb.append("<td>").append(oneDArray[i]).append("</td>");
        }
        sb.append("</tr></table></html>");
        output = sb.toString();
        JOptionPane.showMessageDialog(new JFrame(), output);

        sb = new StringBuilder();
        sb.append("<html><table cellspacing=10>");
        for (int i = 0; i < twoDArray.length; i++) {
            sb.append("<tr>");
            for (int j = 0; j < twoDArray.length; j++) {
                sb.append("<td>").append(twoDArray[i][j]).append("</td>");
            }
        }
        sb.append("</tr></table></html>");
        output = sb.toString();
        JOptionPane.showMessageDialog(new JFrame(), output);
    }
}


问:
Joomla Cache issues
I get 500 Internal server error several times on some pages, since my site was moved to a new server.
The problem automatically resolves after a few seconds (sometimes several seconds).
also when I clear joomla page cache, the problem resolves.
After installing jotcache and replace it with joomla page cache issues resolves but I want to use joomla page cache; because it's faster.
How can I fix this problem?

Joomla 3.8.2 ;
PHP 5.6 ;
MariaDB 10.2 (in old server mysql 5.5 )

答: You are probably using progressive caching, which is the worst type of Joomla caching and you most likely do not need it. Switch to Joomla conservative caching and see if that fixes the problem.</p>

Title: Joomla Cache issues


问:
Git Repository Cloning Error (terminal prompts disabled)
I am using 15.4.5 version of Visual Studio Enterprise and version 2.15.0 for GIT. I am trying to clone my repo from VSTS but I am getting an error which is mentioned below. Do you have any solution for that problem?

Git failed with a fatal error.
fatal: HttpRequestException encountered.
   An error occurred while sending the request.
error: cannot spawn askpass: No such file or directory
fatal: could not read Username for 'https://xxx.visualstudio.com': terminal prompts disabled

答: I fixed that problem myself. There was some misconfiguration regarding GIT, i think. It was preventing pop-ups. So, if you re-install GIT on your local machine, everything's gonna be OK.</p>


问:
Creating a UInt16 from 2 UInt8s
In order to illustrate a concept to use later for larger data types like UInt128, and UInt256, I'm trying to do the following function:

My function takes 2 UInt8s, shifts the first (theoretically the more significant bits), to the left 8 and then adds int2, (theoretically the lower bits)

```<code>func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
   let x: UInt16 = (int1 << 8) + int2
   return x
}
</code>```

Is there something that I need to do to avoid the error: (int1 << 8) + int2 isn't equal to the specified type UInt16?

答:
Just for fun an alternative is using Data

```<code>func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
    return Data([int2, int1]).withUnsafeBytes{ $0.pointee }
}
</code>```

Title: Creating a UInt16 from 2 UInt8s

Body:
In order to illustrate a concept to use later for larger data types like UInt128, and UInt256, I'm trying to do the following function:

My function takes 2 UInt8s, shifts the first (theoretically the more significant bits), to the left 8 and then adds int2, (theoretically the lower bits)

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
   let x: UInt16 = (int1 << 8) + int2
   return x
}

Is there something that I need to do to avoid the error: (int1 << 8) + int2 isn't equal to the specified type UInt16?

Body:
Just for fun an alternative is using Data

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
    return Data([int2, int1]).withUnsafeBytes{ $0.pointee }
}


问:
Select Top 1 from one table and all linked values from another in SQL
I have two tables

Table Tbl_Headline

```<code>ID_key
News_Type
</code>```

Table Tbl_Item

```<code>Item_ID
ID_key
</code>```

I need to get the top 1 from Tbl_Headline but all the Item_ID's from the second table that match on that ID_key in one query

Probably code 101 but I'm having a mental block

Thanks for any help

答:
I think I've understood the question correctly... Does this help?</p>

```<code>SELECT
   a.*, b.*

FROM
   Tbl_Headline a
   JOIN Tbl_Item b ON a.ID_key = b.ID_key

WHERE
   a.ID_key = (SELECT TOP 1 ID_key FROM Tbl_Headline)
</code>```

Body:
I have two tables

Table Tbl_Headline

ID_key
News_Type

Table Tbl_Item

Item_ID
ID_key

I need to get the top 1 from Tbl_Headline but all the Item_ID's from the second table that match on that ID_key in one query

Probably code 101 but I'm having a mental block

Thanks for any help

Body:
I think I've understood the question correctly... Does this help?

SELECT
   a.*, b.*

FROM
   Tbl_Headline a
   JOIN Tbl_Item b ON a.ID_key = b.ID_key

WHERE
   a.ID_key = (SELECT TOP 1 ID_key FROM Tbl_Headline)


问:
What is the approximate row limit for an html table using jQuery DataTables before the page becomes too slow?
If you had an html table of 10 or so columns,
and you apply the jQuery DataTables plugin to the table,
at what point (approximately) should one expect
the number of table rows to adversely affect browser-rendering
performance? </p>

答: I think it really depends on what you're rendering in each table row element and how many columns you have. If you're just doing text, I've experienced slowdown after a few hundred rows, with a mysql server on the same machine as the webhost. If you're placing image elements or event handlers with each row, expect slowdown to happen with fewer rows. A good idea is to get a browser that easily shows you load times, like Chrome, Safari, and Firefox+firebug. </p>

ContentLicense: CC BY-SA 2.5


问:
Why does do I have an IO error saying my file doesn't exist even though it does exist in the directory?
I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.

The error I get is:

```<code>IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
</code>```

My script:

```<code>for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
    data.append(k_fold(filename))
    continue
else:
    continue
</code>```

k_fold does this:

```<code>def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
</code>```

The entire traceback:

```<code>Traceback (most recent call last):
 File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
  File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
</code>```

My CSV files are such:

```<code>nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv

...

nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
</code>```

Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?

答:
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.

You need to join the dirname onto the filename returned:

```<code>data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
    k_fold(os.path.join(data_dir, filename))
</code>```

Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:

```<code>import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
    k_fold(filename)
</code>```

Body:
I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.

The error I get is:

IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'

My script:

for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
    data.append(k_fold(filename))
    continue
else:
    continue

k_fold does this:

def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()

The entire traceback:

Traceback (most recent call last):
 File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
  File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'

My CSV files are such:

nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv

...

nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv

Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?

Body:
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.

You need to join the dirname onto the filename returned:

data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
    k_fold(os.path.join(data_dir, filename))

Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:

import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
    k_fold(filename)


问:
In Angular 2, how can I focus to the bottom of a div on button click
I have a div with lot of components. On button click, the focus should reach to the bottom of the div. How is it possible in Angular 2?</p>

答:
Use viewchild and nativeelement. Then you will get an element, and you will able to use .focus() method. follow viewchild and nativeelement.
https://stackoverflow.com/a/45344187/4834833
It will help you.</p>


问:
Configuration in Azure AD B2C for Custom Policies
How do I use a "config file" in custom policies?  Like appsetting.json in ASP.Net Core.

Things to configure

TenantId

<LoadUri> for customizing the UI

Background: we have multiple B2C tenants for each environment (Local, Dev, QA, Prod, etc.).  We need to promote the custom policies from Local -> Dev -> ....  As it stands now, we have to modify the policies when promoting.

I'm hoping there is something like pulling Keys from the B2C app.

答:
There is currently nothing like the Policy Keys to enable environment to environment variable substitution for TenantId, LoadUri etc. in the Azure Portal.

Some potential approaches:

1) SlowCheetah is a Visual Studio 2015/17 tool that allows transformations to be made on XML files. You can utilize this to create an XML transformation file for each B2C policy and environment you have.

For example, you create a UAT transformation file for your B2C_1A_SignIn policy and configure all the variables you need. You then select UAT as the output environment and press F5 to build. This will output a transformed file to your applications bin folder. You will now have all the correct values for UAT, which you can upload to the Azure Portal.

2) Replace Tokens from Visual Studio Team Services Build and Release. This approach allows you to set all your variables as tokens in your policies. You would then initialize a build and release through VSTS and all your defined tokens will be replaced. This approach does require access to VSTS and the setup of code management, build and release. You would also need an output of the build files, e.g. a storage table or file directory on a server.

3) VSTS Build & Release: File transforms and variable substitution reference.


问:
Access angular component meta-data
is it possible to get the value of e.g. changeDetection attribute defined as part of a given component's decoration?

```<code>import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-banner',
  template: '<h1>{{title}}</h1>',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class BannerComponent { }
</code>```

i've tried:

```<code>Reflect.getMetadataKeys(BannerComponent) // []
Reflect.getOwnMetadataKeys(BannerComponent) // []
Reflect.getMetadata('annotations', BannerComponent) // undefined
</code>```

https://plnkr.co/edit/VXfcZH9BWPWbdyBOJRTV?p=preview

答:
Seemingly hacky but nevertherless a solution:

```<code>BannerComponent['__annotations__'][0]
</code>```

https://plnkr.co/edit/HAbomBljAACHVz6N33m5?p=preview

Credits this SO answer.

Title: Access angular component meta-data

Body:
is it possible to get the value of e.g. changeDetection attribute defined as part of a given component's decoration?

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-banner',
  template: '
{{title}}
',
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class BannerComponent { }

i've tried:

Reflect.getMetadataKeys(BannerComponent) // []
Reflect.getOwnMetadataKeys(BannerComponent) // []
Reflect.getMetadata('annotations', BannerComponent) // undefined

https://plnkr.co/edit/VXfcZH9BWPWbdyBOJRTV?p=preview

Body:
Seemingly hacky but nevertherless a solution:

BannerComponent['__annotations__'][0]

https://plnkr.co/edit/HAbomBljAACHVz6N33m5?p=preview

Credits this SO answer.


问:
Python compare two strings and check how many chars they have in common
I'm just wondering how I can check how many chars two string have in common.
For example if I have "car" and "cars", the result should be 3.

Anybody a clue?

Cheers and thanks in advance

Max

答:
Here's a solution using Counter.  We make a Counter for each of the words, then find the intersection of those Counters.  That itself is a Counter, and we can just sum the values to find the number of shared characters

```<code>from collections import Counter

def shared_chars(s1, s2):
    return sum((Counter(s1) & Counter(s2)).values())

print(shared_chars('car', 'carts'))
</code>```

will print

```<code>3
</code>```

In case of Counter, intersection is the minimum of corresponding counts.

```<code>>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})
</code>```

Body:
Here's a solution using Counter.  We make a Counter for each of the words, then find the intersection of those Counters.  That itself is a Counter, and we can just sum the values to find the number of shared characters

from collections import Counter

def shared_chars(s1, s2):
    return sum((Counter(s1) & Counter(s2)).values())

print(shared_chars('car', 'carts'))

will print

3

In case of Counter, intersection is the minimum of corresponding counts.

>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})


问:
Kibana 5.5.1 behind a nginx 1.13 proxy (dockerized)
Goal:

I want to run the elk stack in a docker container. To be able to access the ELK Stack over a nginx proxy to bypass the individual ports for the services.

The Kibana service (default port 5601)

```<code>http://<server>.com:5601
</code>```

should be reachable over the following address:

```<code>http://<server>.com/kibana
</code>```

Problem:

The problem is, that it is not possible to reach the kibana site after I add the server.basePath setting to the config. I only can bring up the service if I add every base api call of Kibana to the nginx config (/api, /ui, ...).

Config:

The config for Kibana:

```<code>/opt/kibana/config/kibana.yml
</code>```

Has the following entries:

```<code>server.host: "0.0.0.0"
server.basePath: "/kibana"
</code>```

everything else is default

Doku server.basePath

```<code># Enables you to specify a path to mount Kibana at if you are running behind a proxy. This only affects
# the URLs generated by Kibana, your proxy is expected to remove the basePath value before forwarding requests
# to Kibana. This setting cannot end in a slash.
</code>```

The nginx config:

```<code>location /kibana/ {
  rewrite ^/kibana(/.*)$ $1 break;
  proxy_pass http://<server>.com:5601/;
}
</code>```

I use the sebp/elk:551 docker image and the following docker-compose file:

```<code>version: '2'
services:
  elk:
    image: sebp/elk:551
    container_name: "elk"
    volumes:
      - /etc/kibana/config/kibana.yml:/opt/kibana/config/kibana.yml
    ports:
      - "5601:5601"
      - "9200:9200"
      - "5044:5044"
    environment:
      SERVICE_5601_NAME: "kibana"
      SERVICE_9200_NAME: "elasticsearch"
      SERVICE_5044_NAME: "logstash"
    restart: always
</code>```

What I have tried:

I have tried the same setup with Kibana 4.6.1 and it worked perfectly as expected.

Versions that I have tested and do not work: 5.4.3, 5.1.2, 5.0.2

What I dont want:

I dont want to add every subdirectory of Kibana like /api, /ui, /app/kibana, ... to add to the proxy config.

Is there an other solution or version?

Edit1:
@whites11: The browser return the 502 Bad Gateway site from nginx.
Browser infos:

General

```<code>Request URL:http://<server-name>.com/kibana/
Request Method:GET
Status Code:502 Bad Gateway
Remote Address:<server-ip>:80
Referrer Policy:no-referrer-when-downgrade
</code>```

Response Headers

```<code>Connection:keep-alive
Content-Length:575
Content-Type:text/html
Date:Thu, 24 Aug 2017 13:54:49 GMT
Server:nginx/1.13.3
</code>```

Request Headers

```<code>Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:<server-name>.com
Upgrade-Insecure-Requests:1
</code>```

Log from nginx

```<code>http://<server>.com/kibana
</code>```0

答:
I don't have exactly the same deployment as you do, but I am using a dockerized kibana.

First of all, you need the following in your nginx settings:

```<code>    location /kibana/ {
      proxy_pass http://kibana_server:5601/;
    }
</code>```

Change the values according to your environment, but the final slashes are critical! Don't remove them! They ensure that the rewriting is done as expected by Kibana --i.e., the kibana is removed from the URL in the petition that goes to the kibana server.

Then maintain the following:

```<code>server.basePath: /kibana
</code>```

in your kibana settings. That ensures that the documents provided by kibana (links and urls) have the prefix /kibana.

It works for me.

Body:
Goal:

I want to run the elk stack in a docker container. To be able to access the ELK Stack over a nginx proxy to bypass the individual ports for the services.

The Kibana service (default port 5601)

http://<server>.com:5601

should be reachable over the following address:

http://<server>.com/kibana

Problem:

The problem is, that it is not possible to reach the kibana site after I add the server.basePath setting to the config. I only can bring up the service if I add every base api call of Kibana to the nginx config (/api, /ui, ...).

Config:

The config for Kibana:

/opt/kibana/config/kibana.yml

Has the following entries:

server.host: "0.0.0.0"
server.basePath: "/kibana"

everything else is default

Doku server.basePath

# Enables you to specify a path to mount Kibana at if you are running behind a proxy. This only affects
# the URLs generated by Kibana, your proxy is expected to remove the basePath value before forwarding requests
# to Kibana. This setting cannot end in a slash.

The nginx config:

location /kibana/ {
  rewrite ^/kibana(/.*)$ $1 break;
  proxy_pass http://<server>.com:5601/;
}

I use the sebp/elk:551 docker image and the following docker-compose file:

version: '2'
services:
  elk:
    image: sebp/elk:551
    container_name: "elk"
    volumes:
      - /etc/kibana/config/kibana.yml:/opt/kibana/config/kibana.yml
    ports:
      - "5601:5601"
      - "9200:9200"
      - "5044:5044"
    environment:
      SERVICE_5601_NAME: "kibana"
      SERVICE_9200_NAME: "elasticsearch"
      SERVICE_5044_NAME: "logstash"
    restart: always

What I have tried:

I have tried the same setup with Kibana 4.6.1 and it worked perfectly as expected.

Versions that I have tested and do not work: 5.4.3, 5.1.2, 5.0.2

What I dont want:

I dont want to add every subdirectory of Kibana like /api, /ui, /app/kibana, ... to add to the proxy config.

Is there an other solution or version?

Edit1:
@whites11: The browser return the 502 Bad Gateway site from nginx.
Browser infos:

General

Request URL:http://<server-name>.com/kibana/
Request Method:GET
Status Code:502 Bad Gateway
Remote Address:<server-ip>:80
Referrer Policy:no-referrer-when-downgrade

Response Headers

Connection:keep-alive
Content-Length:575
Content-Type:text/html
Date:Thu, 24 Aug 2017 13:54:49 GMT
Server:nginx/1.13.3

Request Headers

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:<server-name>.com
Upgrade-Insecure-Requests:1

Log from nginx

34#34: *8 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: <IP>, server: , request: "GET /kibana/ HTTP/1.1", upstream: "http://<server-ip>:5601/", host: "<server-name>.com"

Body:
I don't have exactly the same deployment as you do, but I am using a dockerized kibana.

First of all, you need the following in your nginx settings:

    location /kibana/ {
      proxy_pass http://kibana_server:5601/;
    }

Change the values according to your environment, but the final slashes are critical! Don't remove them! They ensure that the rewriting is done as expected by Kibana --i.e., the kibana is removed from the URL in the petition that goes to the kibana server.

Then maintain the following:

server.basePath: /kibana

in your kibana settings. That ensures that the documents provided by kibana (links and urls) have the prefix /kibana.

It works for me.


问:
Reading Insde of a Xdocument
Hi everyone i am Probably doing this wrong but im trying to get the inside elements in a xml document and every time i try the for loop it seems to return everything in one lump sum

sample xml

```<code><RStream>
  <CmdResponse>
  </CmdResponse>
  <TranResponse>
    <ProductData>
      <ProductCat1>02</ProductCat1>
      <ProductSubCat1>000</ProductSubCat1>
      <ProductQty1>32.00</ProductQty1>
      <ProductCat2>03</ProductCat2>
      <ProductSubCat2>000</ProductSubCat2>
      <ProductQty2>72.00</ProductQty2>
    </ProductData>
  </TranResponse>
</RStream>

foreach (XElement element in doc.Descendants("ProductData"))
{
    MessageBox.Show(element.Name.ToString());
    MessageBox.Show(element.Value);
}
</code>```

I get a response of ProductData
then a response of

Im Trying to get a response in the loop that will show me
ProductCat1 then 02
and so on there could be a unlimited number of responses in ProductData

答:
You have to use another foreach on sub children of ProductData:

Try this for example :

```<code>foreach (XElement element in doc.Descendants("ProductData"))
{
    foreach (XElement subElement in element.Elements())
    {
        Debug.WriteLine(subElement.Name.ToString());
        Debug.WriteLine(subElement.Value);
    }
}
</code>```

Hope this helps

Title: Reading Insde of a Xdocument

Body:
Hi everyone i am Probably doing this wrong but im trying to get the inside elements in a xml document and every time i try the for loop it seems to return everything in one lump sum

sample xml

<RStream>
  <CmdResponse>
  </CmdResponse>
  <TranResponse>
    <ProductData>
      <ProductCat1>02</ProductCat1>
      <ProductSubCat1>000</ProductSubCat1>
      <ProductQty1>32.00</ProductQty1>
      <ProductCat2>03</ProductCat2>
      <ProductSubCat2>000</ProductSubCat2>
      <ProductQty2>72.00</ProductQty2>
    </ProductData>
  </TranResponse>
</RStream>

foreach (XElement element in doc.Descendants("ProductData"))
{
    MessageBox.Show(element.Name.ToString());
    MessageBox.Show(element.Value);
}

I get a response of ProductData
then a response of

Im Trying to get a response in the loop that will show me
ProductCat1 then 02
and so on there could be a unlimited number of responses in ProductData

Body:
You have to use another foreach on sub children of ProductData:

Try this for example :

foreach (XElement element in doc.Descendants("ProductData"))
{
    foreach (XElement subElement in element.Elements())
    {
        Debug.WriteLine(subElement.Name.ToString());
        Debug.WriteLine(subElement.Value);
    }
}

Hope this helps


答:
You can easily solve this problem by using the Visual Studio debugger with a breakpoint. Doing so, you can inspect the value of the variable element, which is this

```<code><ProductData>
  <ProductCat1>02</ProductCat1>
  <ProductSubCat1>000</ProductSubCat1>
  <ProductQty1>32.00</ProductQty1>
  <ProductCat2>03</ProductCat2>
  <ProductSubCat2>000</ProductSubCat2>
  <ProductQty2>72.00</ProductQty2>
</ProductData>
</code>```

For getting what you want, you need this modified code:

```<code>foreach (XElement element in doc.Descendants("ProductData"))
{
    foreach (var xElement in element.Elements())
    {
        MessageBox.Show(xElement.Name.ToString());
        MessageBox.Show(xElement.Value);
    }
}
</code>```

Title: Reading Insde of a Xdocument

Body:
You can easily solve this problem by using the Visual Studio debugger with a breakpoint. Doing so, you can inspect the value of the variable element, which is this

<ProductData>
  <ProductCat1>02</ProductCat1>
  <ProductSubCat1>000</ProductSubCat1>
  <ProductQty1>32.00</ProductQty1>
  <ProductCat2>03</ProductCat2>
  <ProductSubCat2>000</ProductSubCat2>
  <ProductQty2>72.00</ProductQty2>
</ProductData>

For getting what you want, you need this modified code:

foreach (XElement element in doc.Descendants("ProductData"))
{
    foreach (var xElement in element.Elements())
    {
        MessageBox.Show(xElement.Name.ToString());
        MessageBox.Show(xElement.Value);
    }
}


问:
Which spellings checker to use?
A customer would like it if a spellings checker is added to an existing Delphi application. The texts that need to be checked are in multiple memo fields and the language is Dutch, which tends to limit my options.

So, what are my options for adding a dutch spellings checker to a Delphi/WIN32 application?

(Preferably something not webbased because the client has no direct Internet connection.)

It doesn't have to be free! The customer will pay if it's possible. :-)

Addictive Software offers an option, but I prefer to have more alternatives.

答:
Addictive software, as mentioned above, is one of the main ones.

But the TRichView component includes parsers for several spell-checkers that work out with Delphi. Check out their list and links that include:

Addict 3 and 4 by Addictive Software (shareware VCL component)

HunSpell by László Németh (DLL, open source)

ExpressSpellChecker by Developer Express Inc. (commercial VCL component)

EDSSpell 7 by OneDomain (shareware VCL component)

ASpell by Kevin Atkinson (DLL, license: LGPL)

VSSpell 8.0 by ComponentOne LLC (shareware ActiveX, discontinued)

VSSpell 3.0 by Visual Components, Inc (shipped with some versions of Delphi, ActiveX)

LS Speller by Luzius Schneider (based on former work of Alexander Obukhov) (freeware, uses ISpell and MS Office spell checkers (via CSAPI)).

Polar SpellChecker Component by Polar (shareware ActiveX)

Title: Which spellings checker to use?


问:
How can i add a header message for the mobile version in opencart 2.3.0.2?
I want to add a notification message on the header for the mobile version in opencart, so whenever a user visits my site on mobile he can see this header message which will indicate the user to visit the desktop site for better experience. your comments will be appreciated.</p>

答:
Since your theme is compatible with Bootstrap framework (like OpenCart default theme), you can use this code:

```<code><p class="alert alert-info visible-xs">add your message here</p>
</code>```

in this file:

```<code>catalog\view\theme\your-theme\template\common\header.tpl
</code>```

Here visible-xs class will make it visible only for extra small devices.

Body:
Since your theme is compatible with Bootstrap framework (like OpenCart default theme), you can use this code:

<p class="alert alert-info visible-xs">add your message here</p>

in this file:

catalog\view\theme\your-theme\template\common\header.tpl

Here visible-xs class will make it visible only for extra small devices.


问:
How do I keep the user logged-in with Implicit flow?
From what I understand, the end-result of the implicit flow is the access token, which allows the client (in my case a JS SPA) to authenticate into resource servers (APIs).

The access token is usually only valid for ~1 hour, then it expires - making it useless.

What should my JS app do then? Redirecting the user back to the auth server is unrealistic since then the user will have to reenter their credentials every 1 hour!

I also know that the implicit flow doesn't support refresh tokens so I can't use those either.

Is there a way to persist the user's login? How do things like Facebook keep you logged-in indefinitely?

答:
Just to clarify, you are asking about the Implicit flow which is detailed in the OAuth 2.0 RFC rather than OpenID Connect which deals more with authentication of a user?

With the implicit flow you do have to regularly call the authorisation endpoint to obtain a new token, but if the user remains logged into their identity provider then they should not be prompted to resubmit their credentials, and the token will be returned as a hash fragment in the redirect uri, with no user interaction required.

You can use an AJAX call to get the token on a back-channel so your SPA app user experience is not affected by the need to get new tokens.

To address the points you highlight in your question:

The access token is usually only valid for ~1 hour, then it expires -
making it useless.

Correct!

then the user will have to reenter their credentials every 1 hour!

Not necessarily.

If the user stays logged into the identity provider (e.g. facebook, google) then there will be a browser cookie between the user and that provider. This effectively means the identity provider does not need the user to re-enter credentials. The authorisation server should be able to return you a token with no interaction required.

Is there a way to persist the user's login?

You can't control it from your SPA. It's totally dependent on the user staying logged onto the identity provider. If they stay logged into facebook, google (or whatever IDP you app uses) then you should be able to get tokens non-interactively.

This article nicely explains how the implicit flow can be implemented.


问:
How to change CameraSource size like setPreviewSize and PictureSize
This is pertaining the google vision API. The CameraPreview works well for full Screen. But the image is distorted when previewing the camera in a box.

This is the code I have used. My problem is that the preview fills up the box but the preview is stretched and I am not able to adjust the size of the cameraPreview. The variable CameraPreview is of type SurfaceView. I use a CameraSource to start the preview. Is there any way to change the size of the CameraPreview(SurfaceView) and make the preview crop fit in a box?

```<code>  cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
            protected List<Camera.Size> mPreviewSizeList;
            protected List<Camera.Size> mPictureSizeList;
            protected Camera.Size mPreviewSize;
            protected Camera.Size mPictureSize;
            protected boolean mSurfaceChanged = false;
            private int mSurfaceChangedCallDepth = 0;
            private int mCenterPosX = -1;
            private int mCenterPosY = 0;
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ClientIdScannerActivity.this,
                            new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
                    Toast.makeText(ClientIdScannerActivity.this, "The App requires this permission", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    cameraSource.start(cameraPreview.getHolder());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                mSurfaceChangedCallDepth++;

             /*   cameraSource.stop();

                Camera.Parameters cameraParams = mCamera.getParameters();

                if (!mSurfaceChanged) {
                    Camera.Size previewSize = determinePreviewSize(cameraWidth, cameraHight);
                    Camera.Size pictureSize = determinePictureSize(previewSize);
                    mPreviewSize = previewSize;
                    mPictureSize = pictureSize;
                    mSurfaceChanged = adjustSurfaceLayoutSize(previewSize,i1, i2);

                    if (mSurfaceChanged && (mSurfaceChangedCallDepth <= 1)) {
                        return;
                    }
                }

                cameraParams.setRotation(270);
                if (UtilFunctions.isTablet()) {
                } else {
                    mCamera.setDisplayOrientation(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? 270 : 90);
                }*/

//            cameraParams.setRotation(270);
//            mCamera.setDisplayOrientation(UtilFunctions.isTablet() ? 90 : 270);

              /*  cameraParams.set("orientation", "portrait");
                //  cameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                cameraParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
                cameraParams.setPictureSize(mPictureSize.width, mPictureSize.height);
                if (cameraParams.getSupportedFocusModes().contains(
                        Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                    cameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                }*/

                mSurfaceChanged = false;

                try {
                    if (ActivityCompat.checkSelfPermission(ClientIdScannerActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        Toast.makeText(ClientIdScannerActivity.this, "App requires Camera permission to scan ID", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    cameraSource.start(cameraPreview.getHolder());
                } catch (Exception e) {
                    // Remove failed size

                    // Reconfigure
                    if (mPreviewSizeList.size() > 0) { // prevent infinite loop
                        surfaceChanged(null, 0, i1, i2);
                    } else {
//                Utils.showToast(CameraNewActivity.this, "Can't start preview", Toast.LENGTH_LONG);
                    }
                }

                mSurfaceChangedCallDepth--;
            }

            protected Camera.Size determinePreviewSize(int reqWidth, int reqHeight) {

                int reqPreviewWidth = 640;//reqHeight; // requested width in terms of camera hardware
                int reqPreviewHeight = 480;// reqWidth; // requested height in terms of camera hardware
                Camera.Size retSize = null;
                for (Camera.Size size : mPreviewSizeList) {
                    if (size.width == reqPreviewWidth && size.height == reqPreviewHeight) {
                        retSize = size;
                    }
                }
                //  retSize = mPreviewSizeList.get(mPreviewSizeList.size()-1);
                return retSize;
            }

            protected Camera.Size determinePictureSize(Camera.Size previewSize) {
                Camera.Size retSize = null;
                for (Camera.Size size : mPictureSizeList) {
                    if (size.equals(previewSize)) {
                        return size;
                    }
                }

                // if the preview size is not supported as a picture size
                float reqRatio = ((float) previewSize.width) / previewSize.height;
                float curRatio, deltaRatio;
                float deltaRatioMin = Float.MAX_VALUE;
                for (Camera.Size size : mPictureSizeList) {
                    curRatio = ((float) size.width) / size.height;
                    deltaRatio = Math.abs(reqRatio - curRatio);
                    if (deltaRatio < deltaRatioMin) {
                        deltaRatioMin = deltaRatio;
                        retSize = size;
                    }
                }

                return retSize;
            }

            protected boolean adjustSurfaceLayoutSize(Camera.Size previewSize,
                                                      int availableWidth, int availableHeight) {

                float tmpLayoutHeight = previewSize.width;
                float tmpLayoutWidth = previewSize.height;

                float factH, factW, fact;
                factH = availableHeight / tmpLayoutHeight;
                factW = availableWidth / tmpLayoutWidth;

//        if (factH < factW) {
//            fact = factH;
//        } else {
                fact = factW;
                //  }

                FrameLayout.LayoutParams layoutParams =(FrameLayout.LayoutParams) cameraPreview.getLayoutParams();
                int layoutHeight = (int) (tmpLayoutHeight * fact);
                int layoutWidth = (int) (tmpLayoutWidth * fact);

                boolean layoutChanged;
                if ((layoutWidth != cameraPreview.getWidth()) || (layoutHeight != cameraPreview.getHeight())) {
                    layoutParams.height = layoutHeight;
                    layoutParams.width = layoutWidth;
                    if (mCenterPosX >= 0) {
                        layoutParams.topMargin = mCenterPosY - (layoutHeight / 2);
                        layoutParams.leftMargin = mCenterPosX - (layoutWidth / 2);
                    }
                    cameraPreview.setLayoutParams(layoutParams); // this will trigger another surfaceChanged invocation.
                    layoutChanged = true;
                } else {
                    layoutChanged = false;
                }

                return layoutChanged;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                cameraSource.stop();
            }
        });
</code>```

答:
Note that the same problem exists for 'full screen' camera preview. There is no guarantee that the aspect ratio of your chosen preview size will be close enough to the aspect ratio of the screen. Please see more details here: Camera Preview Stretched on Few Android Devices.

You naturally must choose the optimum width and height to fit the view, but this is not enough. You must hide the 'hanging' parts of your preview surface behind some non-transparent views. See for example how you can make a circular preview.

Another important thing here is to always keep preview- and picture- sizes in sync. This does not mean that they must be the same, but the aspect ratios should. Some devices have weird effects when the aspect ratio changes to capture a photo.

Body:
This is pertaining the google vision API. The CameraPreview works well for full Screen. But the image is distorted when previewing the camera in a box.

This is the code I have used. My problem is that the preview fills up the box but the preview is stretched and I am not able to adjust the size of the cameraPreview. The variable CameraPreview is of type SurfaceView. I use a CameraSource to start the preview. Is there any way to change the size of the CameraPreview(SurfaceView) and make the preview crop fit in a box?

  cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
            protected List<Camera.Size> mPreviewSizeList;
            protected List<Camera.Size> mPictureSizeList;
            protected Camera.Size mPreviewSize;
            protected Camera.Size mPictureSize;
            protected boolean mSurfaceChanged = false;
            private int mSurfaceChangedCallDepth = 0;
            private int mCenterPosX = -1;
            private int mCenterPosY = 0;
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ClientIdScannerActivity.this,
                            new String[]{Manifest.permission.CAMERA}, RequestCameraPermissionId);
                    Toast.makeText(ClientIdScannerActivity.this, "The App requires this permission", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    cameraSource.start(cameraPreview.getHolder());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                mSurfaceChangedCallDepth++;

             /*   cameraSource.stop();

                Camera.Parameters cameraParams = mCamera.getParameters();

                if (!mSurfaceChanged) {
                    Camera.Size previewSize = determinePreviewSize(cameraWidth, cameraHight);
                    Camera.Size pictureSize = determinePictureSize(previewSize);
                    mPreviewSize = previewSize;
                    mPictureSize = pictureSize;
                    mSurfaceChanged = adjustSurfaceLayoutSize(previewSize,i1, i2);

                    if (mSurfaceChanged && (mSurfaceChangedCallDepth <= 1)) {
                        return;
                    }
                }

                cameraParams.setRotation(270);
                if (UtilFunctions.isTablet()) {
                } else {
                    mCamera.setDisplayOrientation(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? 270 : 90);
                }*/

//            cameraParams.setRotation(270);
//            mCamera.setDisplayOrientation(UtilFunctions.isTablet() ? 90 : 270);

              /*  cameraParams.set("orientation", "portrait");
                //  cameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                cameraParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
                cameraParams.setPictureSize(mPictureSize.width, mPictureSize.height);
                if (cameraParams.getSupportedFocusModes().contains(
                        Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                    cameraParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                }*/

                mSurfaceChanged = false;

                try {
                    if (ActivityCompat.checkSelfPermission(ClientIdScannerActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        Toast.makeText(ClientIdScannerActivity.this, "App requires Camera permission to scan ID", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    cameraSource.start(cameraPreview.getHolder());
                } catch (Exception e) {
                    // Remove failed size

                    // Reconfigure
                    if (mPreviewSizeList.size() > 0) { // prevent infinite loop
                        surfaceChanged(null, 0, i1, i2);
                    } else {
//                Utils.showToast(CameraNewActivity.this, "Can't start preview", Toast.LENGTH_LONG);
                    }
                }

                mSurfaceChangedCallDepth--;
            }

            protected Camera.Size determinePreviewSize(int reqWidth, int reqHeight) {

                int reqPreviewWidth = 640;//reqHeight; // requested width in terms of camera hardware
                int reqPreviewHeight = 480;// reqWidth; // requested height in terms of camera hardware
                Camera.Size retSize = null;
                for (Camera.Size size : mPreviewSizeList) {
                    if (size.width == reqPreviewWidth && size.height == reqPreviewHeight) {
                        retSize = size;
                    }
                }
                //  retSize = mPreviewSizeList.get(mPreviewSizeList.size()-1);
                return retSize;
            }

            protected Camera.Size determinePictureSize(Camera.Size previewSize) {
                Camera.Size retSize = null;
                for (Camera.Size size : mPictureSizeList) {
                    if (size.equals(previewSize)) {
                        return size;
                    }
                }

                // if the preview size is not supported as a picture size
                float reqRatio = ((float) previewSize.width) / previewSize.height;
                float curRatio, deltaRatio;
                float deltaRatioMin = Float.MAX_VALUE;
                for (Camera.Size size : mPictureSizeList) {
                    curRatio = ((float) size.width) / size.height;
                    deltaRatio = Math.abs(reqRatio - curRatio);
                    if (deltaRatio < deltaRatioMin) {
                        deltaRatioMin = deltaRatio;
                        retSize = size;
                    }
                }

                return retSize;
            }

            protected boolean adjustSurfaceLayoutSize(Camera.Size previewSize,
                                                      int availableWidth, int availableHeight) {

                float tmpLayoutHeight = previewSize.width;
                float tmpLayoutWidth = previewSize.height;

                float factH, factW, fact;
                factH = availableHeight / tmpLayoutHeight;
                factW = availableWidth / tmpLayoutWidth;

//        if (factH < factW) {
//            fact = factH;
//        } else {
                fact = factW;
                //  }

                FrameLayout.LayoutParams layoutParams =(FrameLayout.LayoutParams) cameraPreview.getLayoutParams();
                int layoutHeight = (int) (tmpLayoutHeight * fact);
                int layoutWidth = (int) (tmpLayoutWidth * fact);

                boolean layoutChanged;
                if ((layoutWidth != cameraPreview.getWidth()) || (layoutHeight != cameraPreview.getHeight())) {
                    layoutParams.height = layoutHeight;
                    layoutParams.width = layoutWidth;
                    if (mCenterPosX >= 0) {
                        layoutParams.topMargin = mCenterPosY - (layoutHeight / 2);
                        layoutParams.leftMargin = mCenterPosX - (layoutWidth / 2);
                    }
                    cameraPreview.setLayoutParams(layoutParams); // this will trigger another surfaceChanged invocation.
                    layoutChanged = true;
                } else {
                    layoutChanged = false;
                }

                return layoutChanged;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                cameraSource.stop();
            }
        });


问:
How to align button to right in bootstrap 4
I tried looking this up here but I can't find anything related to this specific problem.

I'm trying to make a header which has a button on the left and right of the screen with a logo in the middle, but whenever I make the window smaller or larger the button on the right doesnt stay aligned.

Small window

Large window

Here is the code:

```<code><header>
        <div id="container-fluid">
            <div class="row">
                <div class=" col-2">
                    Menu
                </div>
                <div class="col-8 text-center ">
                    Logo
                </div>
                <div class="col-2 float-right">
                    Contact
                </div>
            </div>
        </div>
     </header>
</code>```

What am I missing here?

Thanks in advance.

Fixed it, code now looks like this:

```<code>    <body>
    <header>
        <div id="container-fluid">
            <div class="row">
                <div class="col">
                    <span class="float-left">Menu</span>
                </div>
                <div class="col text-center">
                    Logo
                </div>
                <div class="col">
                    <span class="float-right">Contact</span>
                </div>
            </div>
        </div>
     </header>
</body>
</code>```

答:
You havn't defined what size of column grid you are using. Using col-xs,col-sm, col-md,col-lg will have different effects for the particular code. Run the snippet code in full page below and see how the col-size affects when the browser is resized.

Update - Bootstrap 4 has replaced the col-xs with col- .

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  Col:xs

      Menu

      Logo

      Contact

Col:sm

      Menu

      Logo

      Contact

Col:md

      Menu

      Logo

      Contact

Col:lg

      Menu

      Logo

      Contact

```

Body:
I tried looking this up here but I can't find anything related to this specific problem.

I'm trying to make a header which has a button on the left and right of the screen with a logo in the middle, but whenever I make the window smaller or larger the button on the right doesnt stay aligned.

Small window

Large window

Here is the code:

                    Menu

                    Logo

                    Contact

What am I missing here?

Thanks in advance.

Fixed it, code now looks like this:

                    Menu

                    Logo

                    Contact

Body:
You havn't defined what size of column grid you are using. Using col-xs,col-sm, col-md,col-lg will have different effects for the particular code. Run the snippet code in full page below and see how the col-size affects when the browser is resized.

Update - Bootstrap 4 has replaced the col-xs with col- .

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<div id="container-fluid">
  Col:xs
  <div class="row">
    <div class=" col-2">
      Menu
    </div>
    <div class="col-8 text-center ">
      Logo
    </div>
    <div class="col-2 float-right">
      Contact
    </div>
  </div>
</div>
<br>
<br>

<div id="container-fluid">
Col:sm
  <div class="row">
    <div class=" col-sm-2">
      Menu
    </div>
    <div class="col-sm-8 text-center ">
      Logo
    </div>
    <div class="col-sm-2 float-right">
      Contact
    </div>
  </div>
</div>
<br>
<br>

<div id="container-fluid">
Col:md
  <div class="row">
    <div class=" col-md-2">
      Menu
    </div>
    <div class="col-md-8 text-center ">
      Logo
    </div>
    <div class="col-md-2 float-right">
      Contact
    </div>
  </div>
</div>
<br>
<br>

<div id="container-fluid">
Col:lg
  <div class="row">
    <div class=" col-lg-2">
      Menu
    </div>
    <div class="col-lg-8 text-center ">
      Logo
    </div>
    <div class="col-lg-2 float-right">
      Contact
    </div>
  </div>
</div>


问:
wp7-how to make a thread navigate pages
I want to check for changes in the aplication state every time interval, and if it has changed, to open a window, and  give the user 10 seconds to press on the window, if he does press on the window, then to allow him to navigate freely in the window, and if he doesn't press, to return back to the window before. I thought to implement it with a thread running in the background and waking up every time interval I want. Maybe there is a better way?</p>

答:
This strikes me as a scenario with lots of potential issues.

How do you stop the "window" appearing at an inconvenient time to the user? (e.g. when they were just about to tap on som.ething)

Why not just raise the notification when the state actually changes? This way you wouldn't need to poll.

What is the "Window" you are displaying? How does it differ from the page it is replacing? Is this a popup or are you actually navigating to a different page?

What is the state that's changing? How is it changing without user interaction?

Can't you notify the user of the state change without a potentially intrusive display of a new "window"?

Title: wp7-how to make a thread navigate pages


问:
Include maven dependency from target folder
I'm building a web server using Java Spring Boot, and using swagger-codegen to generate the rest client for other projects to consume.

I want to test the rest-client in my integration tests, however including a maven project / jar that exists in my target directory (after the initial build), in my project's POM seems to be impossible.

Is it possible to build these tests with this new dependency?

答:
The jar in the target folder reached that place in two ways:

it has been build in the package phase.

it has been copied there by a plugin from the local repository.

Either way, you are not supposed to use the files in target. Rather, add the dependency (true dependency or project inside your pom) to the test dependencies of your server. Run your test at the integration phase.


问:
Could not build objective-c module 'Firebase' and 'FirebaseAnalytics/FirebaseAnalytics.h' file not found
As described in the title, the two errors I get when trying to build and run a project that used to work when I originally started this project a year ago are as follows:

Could not build objective-c module 'Firebase'

and

'FirebaseAnalytics/FirebaseAnalytics.h' file not found

my podfile is as follows:

```<code># Uncomment this line to define a global platform for your project
platform :ios, '9.0'

# Comment this line if you're not using Swift and don't want to use dynamic
frameworks
 use_frameworks!

# Pods for MyProject

target 'MyProject' do

    pod 'Firebase'
    pod 'Firebase/Database'
    pod 'Firebase/Auth'
    pod 'Firebase/Storage'

    # Pods for testing
 target 'MyProjectTests' do
    inherit! :search_paths
    pod 'Firebase'
 end

end
</code>```

One suggestion on GitHub was to change my Header Search Path to "inherit! :complete" but that did not work. Should I change it to that under the podfile section where it says instead "inherit! :search_paths"?

Again, this project worked fine a year ago and now I get these errors.

Any and all help is greatly appreciated.

答:
Mr. Paul's answer did not solve my problem too. But it seems this is also a CocoaPods issue.

Update your CocoaPods version to 1.4.0 using gem install cocoapods --pre. You might need sudo privileges too. Doing this solved my problem.

Body:
As described in the title, the two errors I get when trying to build and run a project that used to work when I originally started this project a year ago are as follows:

Could not build objective-c module 'Firebase'

and

'FirebaseAnalytics/FirebaseAnalytics.h' file not found

my podfile is as follows:

# Uncomment this line to define a global platform for your project
platform :ios, '9.0'

# Comment this line if you're not using Swift and don't want to use dynamic
frameworks
 use_frameworks!

# Pods for MyProject

target 'MyProject' do

    pod 'Firebase'
    pod 'Firebase/Database'
    pod 'Firebase/Auth'
    pod 'Firebase/Storage'

    # Pods for testing
 target 'MyProjectTests' do
    inherit! :search_paths
    pod 'Firebase'
 end

end

One suggestion on GitHub was to change my Header Search Path to "inherit! :complete" but that did not work. Should I change it to that under the podfile section where it says instead "inherit! :search_paths"?

Again, this project worked fine a year ago and now I get these errors.

Any and all help is greatly appreciated.


问:
Visual Studio: Release Build keeps changing AssemblyVersion and then complains about it (CS7034)
I took over a C# project, and I'm pretty new to the C#/Visual Studio world.

During development in the "Debug" configuration, the project built just fine. But now, since I switched to the "Release" configuration, I keep getting Error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]]

Before the build, in AssemblyInfo.cs I have:

```<code>[assembly: AssemblyVersion("2.4.0.4129")]
[assembly: AssemblyFileVersion("2.4.0.4129")]
</code>```

But the building process keeps changing this to

```<code>[assembly: AssemblyVersion("2.4.0.-1")]
[assembly: AssemblyFileVersion("2.4.0.-1")]
</code>```

and -1 is not a valid number. Where does that change come from?

I switched from SVN to git, and I wasn't able to permanently get rid of AnkhSVN integration. Could that be the culprit? 4128 was the latest SVN revision number. Maybe the plugin is looking for the latest revision but couldn't find any, resulting in -1?

答:
Found the solution. The .csproj file contained this:

```<code><Target Name="BeforeBuild" Condition="$(Configuration) == 'Release'">
...
</code>```

In this target the replacement was specified.

Body:
I took over a C# project, and I'm pretty new to the C#/Visual Studio world.

During development in the "Debug" configuration, the project built just fine. But now, since I switched to the "Release" configuration, I keep getting Error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]]

Before the build, in AssemblyInfo.cs I have:

[assembly: AssemblyVersion("2.4.0.4129")]
[assembly: AssemblyFileVersion("2.4.0.4129")]

But the building process keeps changing this to

[assembly: AssemblyVersion("2.4.0.-1")]
[assembly: AssemblyFileVersion("2.4.0.-1")]

and -1 is not a valid number. Where does that change come from?

I switched from SVN to git, and I wasn't able to permanently get rid of AnkhSVN integration. Could that be the culprit? 4128 was the latest SVN revision number. Maybe the plugin is looking for the latest revision but couldn't find any, resulting in -1?

Body:
Found the solution. The .csproj file contained this:

<Target Name="BeforeBuild" Condition="$(Configuration) == 'Release'">
...

In this target the replacement was specified.


问:
Is it possible to run a Bash script from Maven?
For creating configuration of my application I need to run bash script.
Is it possible to integrate execution of Bash scripts in Maven, maybe there are some plugins?</p>

答:
To experiment with commands you can use exec:exec:

```<code>$ mvn exec:exec -q -Dexec.executable=echo -Dexec.args="your   arguments"
your arguments

$ mvn exec:exec -q -Dexec.executable=echo -Dexec.args="'your   arguments'"
your   arguments
</code>```

This demonstrates:

passing arguments: if you need to pass several arguments: just split them with space

if you need to pass an argument with spaces: enclose it in quotes, as you would do in bash script/terminal

-q to shut up the mvn log

ContentLicense: CC BY-SA 4.0

Body:
To experiment with commands you can use exec:exec:

$ mvn exec:exec -q -Dexec.executable=echo -Dexec.args="your   arguments"
your arguments

$ mvn exec:exec -q -Dexec.executable=echo -Dexec.args="'your   arguments'"
your   arguments

This demonstrates:

passing arguments: if you need to pass several arguments: just split them with space

if you need to pass an argument with spaces: enclose it in quotes, as you would do in bash script/terminal

-q to shut up the mvn log


问:
jQuery's delegate conflict with another delegate in IE
It seems that in IE, some delegates may somehow cause another delegate to fail to work.

This is one possible case:

```<code><html>
 <head>
  <script src='jquery-1.4.2.min.js'></script>
  <script>
   $(function() {
    $('#main')
    .delegate('div', 'click', function() {
     alert('on div!');
    })
    .delegate('[name=first]', 'change', function() {
     alert('first!');
    })
    .delegate('[name=second]', 'change', function() {
     alert('second!');
    })
    ;
   });
  </script>
 </head>
 <body>
  <div id="main">
   <input name="first" />
   <input name="second" type="checkbox" />
   <div>Test</div>
  </div>
 </body>
</html>
</code>```

In this particular case, the handler for the checkbox won't fire.

As usual, the problem doesn't show up in other browsers.

Changing the call orders may solve an issue , but at the risk of causing another. Note that the delegate works on mutually exclusive elements so the order should be irrelevant.

What causes this?

答:
I cannot offer an explanation; but I have encountered similar behavior in IE8.  Oddly, in my case everything worked well if I rearranged bindings so that the delegate binding on one of my checkboxes came before delegate bindings on other form elements.  A delegated click handler on a link before the checkbox handler did not seem to cause problems.

In my case I had one click handler on a checkbox, two change handlers on select boxes, two click handlers on radio buttons, another click handler on another class of checkboxes, and several click handlers on links.

There are a lot of variables to account for and it is difficult to account for all of them here.  For example, the delegated selector for the checkbox that caused a problem for me was an id selector while the selector for the innocuous checkboxes was a class.

Body:
It seems that in IE, some delegates may somehow cause another delegate to fail to work.

This is one possible case:

   <input name="first" />
   <input name="second" type="checkbox" />

Test

In this particular case, the handler for the checkbox won't fire.

As usual, the problem doesn't show up in other browsers.

Changing the call orders may solve an issue , but at the risk of causing another. Note that the delegate works on mutually exclusive elements so the order should be irrelevant.

What causes this?


问:
Explanation regarding modulo operator and Math.floor function
I have two functions:

```<code>function getDigitsSum(number) {
  var sum = 0;

  while (number > 0) {

    sum += number % 10;
    number = Math.floor(number / 10);
  }

  return sum;
}

function findNumbers() {

   var results = [];

   for (var i = 1; i <= 100; i++) {
      if (getDigitsSum(i) == 8) {
        results.push(i);
      }
   }

   return results;
}
</code>```

Essentially I am displaying numbers from 1 to 100 whose sum of digits equal 8. I understand the second function completely but not the first function.

This I don't understand:

```<code>while (number > 0) {

    sum += number % 10;
    number = Math.floor(number / 10);
  }
</code>```

My questions would be:

What is the role of the modulo operator in this part of the code? I always thought it simply returns the remainder left over when one operand is divided by a second operand. Here it seems to have a different purpose of which I wasn't aware of. Why does it do what it does and how?

I understand what the Math.floor function is supposed to do but not what (number / 10) means while concerning the rest of the code. Why exactly is number divided by 10?

If there is an alternative code to this one, which of course gives the same result, I would be glad to see it.

答:
x % y (x modulo y) means, that you do an integer division x/y and substract the rest from x.

e.g. 17%5 = 2 because int(17/5) = 3, 5*3 = 15, 17-15 = 2.

The idea of

```<code>while (number > 0) {
    sum += number % 10;
    number = Math.floor(number / 10);
}
</code>```

is, that in each step you get the remainder of number / 10, which is the numbers last digit, and then remove that digit for the next step, by doing an integer division on the number using Math.floor(number / 10);. You keep doing that, until the number is 0, and then stop for obvious reasons.

Body:
I have two functions:

function getDigitsSum(number) {
  var sum = 0;

  while (number > 0) {

    sum += number % 10;
    number = Math.floor(number / 10);
  }

  return sum;
}

function findNumbers() {

   var results = [];

   for (var i = 1; i <= 100; i++) {
      if (getDigitsSum(i) == 8) {
        results.push(i);
      }
   }

   return results;
}

Essentially I am displaying numbers from 1 to 100 whose sum of digits equal 8. I understand the second function completely but not the first function.

This I don't understand:

while (number > 0) {

    sum += number % 10;
    number = Math.floor(number / 10);
  }

My questions would be:

What is the role of the modulo operator in this part of the code? I always thought it simply returns the remainder left over when one operand is divided by a second operand. Here it seems to have a different purpose of which I wasn't aware of. Why does it do what it does and how?

I understand what the Math.floor function is supposed to do but not what (number / 10) means while concerning the rest of the code. Why exactly is number divided by 10?

If there is an alternative code to this one, which of course gives the same result, I would be glad to see it.

Body:
x % y (x modulo y) means, that you do an integer division x/y and substract the rest from x.

e.g. 17%5 = 2 because int(17/5) = 3, 5*3 = 15, 17-15 = 2.

The idea of

while (number > 0) {
    sum += number % 10;
    number = Math.floor(number / 10);
}

is, that in each step you get the remainder of number / 10, which is the numbers last digit, and then remove that digit for the next step, by doing an integer division on the number using Math.floor(number / 10);. You keep doing that, until the number is 0, and then stop for obvious reasons.


问:
Linq: how can I speed up the string comparison inside for a RemoveAll predicate?
```<code>List<string> listToTemove
list.ForEach(e => e.Persons.RemoveAll(m => listToTemove.Any(m1 => m1 == m.Name)));
</code>```

Persons is a List<Person> and Person has a property Name

The operation lasts 70 seconds. The list has 30 elements each of which has a list of 400 elements for a total of 21000 string comparisons.

Most of Persons are removed..

答:
Instead of having it as a List<string> use a HashSet<string>:

```<code>HashSet<string> itemsToRemove = new HashSet<string>(listToTemove);
e.Persons.RemoveAll(m => itemsToRemove.Contains(m.Name));
</code>```

A single Contains on HashSet is an O(1) operation whereas on a List it is O(n). Lowering the total of an O(n^2) to O(n).

Also instead of removing you can maybe select only those you want:

```<code>e.Persons = e.Persons.Where(m => itemsToRemove.Contains(m.Name)).ToList();
</code>```

Body:
List<string> listToTemove
list.ForEach(e => e.Persons.RemoveAll(m => listToTemove.Any(m1 => m1 == m.Name)));

Persons is a List<Person> and Person has a property Name

The operation lasts 70 seconds. The list has 30 elements each of which has a list of 400 elements for a total of 21000 string comparisons.

Most of Persons are removed..

Body:
Instead of having it as a List<string> use a HashSet<string>:

HashSet<string> itemsToRemove = new HashSet<string>(listToTemove);
e.Persons.RemoveAll(m => itemsToRemove.Contains(m.Name));

A single Contains on HashSet is an O(1) operation whereas on a List it is O(n). Lowering the total of an O(n^2) to O(n).

Also instead of removing you can maybe select only those you want:

e.Persons = e.Persons.Where(m => itemsToRemove.Contains(m.Name)).ToList();