问:
Removing days and hours from a countdown timer
I'm using a countdown timer from this jQuery file but I want to remove the days and hours from it so it only shows minutes and seconds. Can anyone help me out? The digits are displayed from a png file which creates a flip board effect as it displays the countdown.

jQuery.fn.countdown = function(userOptions)
{
  // Default options
  var options = {
    stepTime: 60,
    // startTime and format MUST follow the same format.
    // also you cannot specify a format unordered (e.g. hh:ss:mm is wrong)
    format: "dd:hh:mm:ss",
    startTime: "01:12:32:55",
    digitImages: 6,
    digitWidth: 53,
    digitHeight: 77,
    timerEnd: function(){},
    image: "digits.png"
  };
  var digits = [], interval;

  // Draw digits in given container
  var createDigits = function(where)
  {
    var c = 0;
    // Iterate each startTime digit, if it is not a digit
    // we'll asume that it's a separator
    for (var i = 0; i < options.startTime.length; i++)
    {
      if (parseInt(options.startTime[i]) >= 0)
      {
        elem = $('
').css({
          height: options.digitHeight * options.digitImages * 10,
          float: 'left', background: 'url(\'' + options.image + '\')',
          width: options.digitWidth});
        digits.push(elem);
        margin(c, -((parseInt(options.startTime[i]) * options.digitHeight *
                              options.digitImages)));
        digits[c].__max = 9;
        // Add max digits, for example, first digit of minutes (mm) has
        // a max of 5. Conditional max is used when the left digit has reach
        // the max. For example second "hours" digit has a conditional max of 4
        switch (options.format[i]) {
          case 'h':
            digits[c].__max = (c % 2 == 0) ? 2: 9;
            if (c % 2 == 0)
              digits[c].__condmax = 4;
            break;
          case 'd':
            digits[c].__max = 9;
            break;
          case 'm':
          case 's':
            digits[c].__max = (c % 2 == 0) ? 5: 9;
        }
        ++c;
      }
      else
        elem = $('
').css({float: 'left'})
                .text(options.startTime[i]);

      where.append(elem)
    }
  };

  // Set or get element margin
  var margin = function(elem, val)
  {
    if (val !== undefined)
      return digits[elem].css({'marginTop': val + 'px'});

    return parseInt(digits[elem].css('marginTop').replace('px', ''));
  };

  // Makes the movement. This is done by "digitImages" steps.
  var moveStep = function(elem)
  {
    digits[elem]._digitInitial = -(digits[elem].__max * options.digitHeight * options.digitImages);
    return function _move() {
      mtop = margin(elem) + options.digitHeight;
      if (mtop == options.digitHeight) {
        margin(elem, digits[elem]._digitInitial);
        if (elem > 0) moveStep(elem - 1)();
        else
        {
          clearInterval(interval);
          for (var i=0; i < digits.length; i++) margin(i, 0);
          options.timerEnd();
          return;
        }
        if ((elem > 0) && (digits[elem].__condmax !== undefined) &&
            (digits[elem - 1]._digitInitial == margin(elem - 1)))
          margin(elem, -(digits[elem].__condmax * options.digitHeight * options.digitImages));
        return;
      }

      margin(elem, mtop);
      if (margin(elem) / options.digitHeight % options.digitImages != 0)
        setTimeout(_move, options.stepTime);

      if (mtop == 0) digits[elem].__ismax = true;
    }
  };

  $.extend(options, userOptions);
  this.css({height: options.digitHeight, overflow: 'hidden'});
  createDigits(this);
  interval = setInterval(moveStep(digits.length - 1), 1000);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Countdown that doesn't sucks</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.countdown.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
      $(function(){
        $('#counter').countdown({
          image: 'img/digits.png',
          startTime: '00:00:05:00'
        });

      });
    </script>

    <style type="text/css">
      br { clear: both; }
      .cntSeparator {
        font-size: 54px;
        margin: 10px 7px;
        color: #000;
      }
      .desc { margin: 7px 3px; }
      .desc div {
        float: left;
        font-family: Arial;
        width: 70px;
        margin-right: 65px;
        font-size: 13px;
        font-weight: bold;
        color: #000;
      }
    </style>
  </head>
<body></code>```

答:
To display only hours and minutes use the correct starttime and format arguments</p>

```<code>  $(function(){
    $('#counter').countdown({
      image: 'img/digits.png',
      format: "dd:hh:mm:ss",
      startTime: '05:00'
    });
  });
</code>```

Body:
I'm using a countdown timer from this jQuery file but I want to remove the days and hours from it so it only shows minutes and seconds. Can anyone help me out? The digits are displayed from a png file which creates a flip board effect as it displays the countdown.

jQuery.fn.countdown = function(userOptions)
{
  // Default options
  var options = {
    stepTime: 60,
    // startTime and format MUST follow the same format.
    // also you cannot specify a format unordered (e.g. hh:ss:mm is wrong)
    format: "dd:hh:mm:ss",
    startTime: "01:12:32:55",
    digitImages: 6,
    digitWidth: 53,
    digitHeight: 77,
    timerEnd: function(){},
    image: "digits.png"
  };
  var digits = [], interval;

  // Draw digits in given container
  var createDigits = function(where)
  {
    var c = 0;
    // Iterate each startTime digit, if it is not a digit
    // we'll asume that it's a separator
    for (var i = 0; i < options.startTime.length; i++)
    {
      if (parseInt(options.startTime[i]) >= 0)
      {
        elem = $('
').css({
          height: options.digitHeight * options.digitImages * 10,
          float: 'left', background: 'url(\'' + options.image + '\')',
          width: options.digitWidth});
        digits.push(elem);
        margin(c, -((parseInt(options.startTime[i]) * options.digitHeight *
                              options.digitImages)));
        digits[c].__max = 9;
        // Add max digits, for example, first digit of minutes (mm) has
        // a max of 5. Conditional max is used when the left digit has reach
        // the max. For example second "hours" digit has a conditional max of 4
        switch (options.format[i]) {
          case 'h':
            digits[c].__max = (c % 2 == 0) ? 2: 9;
            if (c % 2 == 0)
              digits[c].__condmax = 4;
            break;
          case 'd':
            digits[c].__max = 9;
            break;
          case 'm':
          case 's':
            digits[c].__max = (c % 2 == 0) ? 5: 9;
        }
        ++c;
      }
      else
        elem = $('
').css({float: 'left'})
                .text(options.startTime[i]);

      where.append(elem)
    }
  };

  // Set or get element margin
  var margin = function(elem, val)
  {
    if (val !== undefined)
      return digits[elem].css({'marginTop': val + 'px'});

    return parseInt(digits[elem].css('marginTop').replace('px', ''));
  };

  // Makes the movement. This is done by "digitImages" steps.
  var moveStep = function(elem)
  {
    digits[elem]._digitInitial = -(digits[elem].__max * options.digitHeight * options.digitImages);
    return function _move() {
      mtop = margin(elem) + options.digitHeight;
      if (mtop == options.digitHeight) {
        margin(elem, digits[elem]._digitInitial);
        if (elem > 0) moveStep(elem - 1)();
        else
        {
          clearInterval(interval);
          for (var i=0; i < digits.length; i++) margin(i, 0);
          options.timerEnd();
          return;
        }
        if ((elem > 0) && (digits[elem].__condmax !== undefined) &&
            (digits[elem - 1]._digitInitial == margin(elem - 1)))
          margin(elem, -(digits[elem].__condmax * options.digitHeight * options.digitImages));
        return;
      }

      margin(elem, mtop);
      if (margin(elem) / options.digitHeight % options.digitImages != 0)
        setTimeout(_move, options.stepTime);

      if (mtop == 0) digits[elem].__ismax = true;
    }
  };

  $.extend(options, userOptions);
  this.css({height: options.digitHeight, overflow: 'hidden'});
  createDigits(this);
  interval = setInterval(moveStep(digits.length - 1), 1000);
};

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Countdown that doesn't sucks</title>

Body:
To display only hours and minutes use the correct starttime and format arguments

  $(function(){
    $('#counter').countdown({
      image: 'img/digits.png',
      format: "dd:hh:mm:ss",
      startTime: '05:00'
    });
  });


来源: stackexchange

问:
Why is my VBScript throwing nine Pop Ups instead of one?
I have a Win7 64 bit Windows Professional Laptop. I have a VB Script taken from the net  and with certain alterations I am trying to  get  at Link speed for all Adaptors on my Laptop. The Vb script seems to be working except that I have to enter 9 times to get a complete list of all instances. This means that  when I double click the  script, the pop up shows only one instance. When I  press Enter again, it shows the  first and the second one, and likewise till I press Enter, nine times, I get the complete list, in one Pop Up. I know this is possible on the command prompt using CScript, but I prefer to get a single Popup. I am  not very versatile on VBScripts but I am willing to learn. Am I missing something ? Any help will be appreciated. Here's my script.</p>

```<code>strComputer = "."
strRslt = Wscript.ScriptName _
    & vbTab & "Computer Information " & vbcr _
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
strRslt = strRslt & vbNewLine  _
& "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
& "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
msgbox strRslt,&h51000, "speed"
Next
</code>```

答:
Because the variable strRslt populate data infos into for .. next loop

So, in this case, you should write your MsgBox after the Next and not inside the loop :

```<code>strComputer = "."
strRslt = Wscript.ScriptName & vbTab & "Computer Information"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
    strRslt = strRslt & vbNewLine & _
    "InstanceName: " & vbTab & objItem.InstanceName & vbcrlf & _
    "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
Next
MsgBox strRslt,vbInformation+&h51000, "speed"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Win7 64 bit Windows Professional Laptop. I have a VB Script taken from the net  and with certain alterations I am trying to  get  at Link speed for all Adaptors on my Laptop. The Vb script seems to be working except that I have to enter 9 times to get a complete list of all instances. This means that  when I double click the  script, the pop up shows only one instance. When I  press Enter again, it shows the  first and the second one, and likewise till I press Enter, nine times, I get the complete list, in one Pop Up. I know this is possible on the command prompt using CScript, but I prefer to get a single Popup. I am  not very versatile on VBScripts but I am willing to learn. Am I missing something ? Any help will be appreciated. Here's my script.

strComputer = "."
strRslt = Wscript.ScriptName _
    & vbTab & "Computer Information " & vbcr _
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
strRslt = strRslt & vbNewLine  _
& "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
& "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
msgbox strRslt,&h51000, "speed"
Next

Body:
Because the variable strRslt populate data infos into for .. next loop

So, in this case, you should write your MsgBox after the Next and not inside the loop :

strComputer = "."
strRslt = Wscript.ScriptName & vbTab & "Computer Information"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)
For Each objItem in colItems
    strRslt = strRslt & vbNewLine & _
    "InstanceName: " & vbTab & objItem.InstanceName & vbcrlf & _
    "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
Next
MsgBox strRslt,vbInformation+&h51000, "speed"


问:
Java Singleton is not accessable although it is public static
I am currently programming a three layer architecture banking application as a student project.
As I understood the Dao pattern, I implemented it and want to handle the database interaction with it, but I actually can not, because my dao class can not access the database singleton  getInstanceDB. The dao class is an implementation of an interface. The classes are all in  the same package.
It seems to be an visablity problem, because the Singleton is not callable in any other class than itself.
Here is  the code.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class Database {
        private static Database instance;
        private Connection conn;
        private Statement stmt;

        private Database() {
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.leuphana.de:1521:oradb1", "...", "...");
                stmt = conn.createStatement();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // Thread-Safe Singleton
        public static synchronized Database getInstanceDB() {
            if (instance == null) {
                instance = new Database();
            }
            return instance;
        }
    }
```

<pre class="lang-java prettyprint-override"><code>// Select Data by CustomerID
    @Override
    public ResultSet select(Kunde kunde) {
        if (kunde == null)
            throw new IllegalArgumentException("given id is null");

        if (kunde.getId() < 0)
            throw new IllegalArgumentException("given id has an invalid value");

        String query = "SELECT * FROM customer WHERE customer_id=" + Integer.toString(kunde.getId());
        ResultSet rs  = null;
        try {
            Connection conn = getInstanceDB().getConnection();
            Statement stmt = conn.createStatement();
            rs =  stmt.executeQuery(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return rs;
    }
</code>```

I am new to stackoverflow, I hope this thread  is ok, if you need more information just ask me ^^

EDIT:
Error: The method getInstanceDao() is undefined for the type KundeDao
getConnection() see the answer, it's the same except the catch part

Thanks for the quick and helpful answers.

答:
I think your logic is kinda wrong. Try something like this.

```<code>public Connection getConnection() {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.leuphana.de:1521:oradb1", "...", "...");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return conn;
}
</code>```

then create your Database instance and call getConnection() method like this.

```<code>Database dbInstance = Database.getInstanceDB();

public void anyMethod(){
    try {
        Connection conn = dbInstance.getConnection();
        Statement stmt = conn.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

Note: To open close connections you should use try-with-resources for more convenient approach.

Body:
I am currently programming a three layer architecture banking application as a student project.
As I understood the Dao pattern, I implemented it and want to handle the database interaction with it, but I actually can not, because my dao class can not access the database singleton  getInstanceDB. The dao class is an implementation of an interface. The classes are all in  the same package.
It seems to be an visablity problem, because the Singleton is not callable in any other class than itself.
Here is  the code.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    public class Database {
        private static Database instance;
        private Connection conn;
        private Statement stmt;

        private Database() {
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.leuphana.de:1521:oradb1", "...", "...");
                stmt = conn.createStatement();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // Thread-Safe Singleton
        public static synchronized Database getInstanceDB() {
            if (instance == null) {
                instance = new Database();
            }
            return instance;
        }
    }

// Select Data by CustomerID
    @Override
    public ResultSet select(Kunde kunde) {
        if (kunde == null)
            throw new IllegalArgumentException("given id is null");

        if (kunde.getId() < 0)
            throw new IllegalArgumentException("given id has an invalid value");

        String query = "SELECT * FROM customer WHERE customer_id=" + Integer.toString(kunde.getId());
        ResultSet rs  = null;
        try {
            Connection conn = getInstanceDB().getConnection();
            Statement stmt = conn.createStatement();
            rs =  stmt.executeQuery(query);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return rs;
    }

I am new to stackoverflow, I hope this thread  is ok, if you need more information just ask me ^^

EDIT:
Error: The method getInstanceDao() is undefined for the type KundeDao
getConnection() see the answer, it's the same except the catch part

Thanks for the quick and helpful answers.

Body:
I think your logic is kinda wrong. Try something like this.

public Connection getConnection() {
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        conn = DriverManager.getConnection("jdbc:oracle:thin:@oracle.leuphana.de:1521:oradb1", "...", "...");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return conn;
}

then create your Database instance and call getConnection() method like this.

Database dbInstance = Database.getInstanceDB();

public void anyMethod(){
    try {
        Connection conn = dbInstance.getConnection();
        Statement stmt = conn.createStatement();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

Note: To open close connections you should use try-with-resources for more convenient approach.


问:
ML model for Signal Decomposition
So recently I got a task which can be summarized as follows:

Suppose we have 3 functions f1, f2, f3 and a certain combination of the functions gives us F.

```<code>af1 + bf2 + cf3 = F
</code>```

The component functions are simple and univariate. I have a range of values for their x and y.

In traditional regression, the task will be to approximate F while f1...f3 are the inputs which vary on each datapoint and a, b, c are the weights we want to approximate and they will then be the same values used to compute F for all data points with unknown F.

In my case, however, the task is to learn the combination of f1, f2, f3 that would yield a given F (or how F factorizes into f1, f2, f3). So F is known and f1,f2,f3 are known too
but the goal is to find the weights a, b, c which vary on data points.

I have researched how to frame this as an ML task and which paradigm to use but cannot find one yet. I have checked reverse regression, factorization machines, but none of these seems like what I need.

UPDATE: Some Context

I have 3 signals of intensity as a function of the wavelength of light used to generate the primary colours RGB. The functions to generate these signals are known. Now, these colours can be combined to obtain secondary colours whose signal is a linear combination of the RGB signals.

Hence, the task is: given the signal of a secondary colour, how do I determine the linear combination of RGB that gave that colour. Can a model be trained to learn the decomposition of the secondary colour signal into the RGB signals?

I hope this helps to better understand if my mathematical formulation above was not clear enough.

Any help on the direction to go will be appreciated.

答:
Seems that you are looking into a fitting problem (least square fit for example). This is equivalent to a Linear Regression with MSE loss. Your variables are a, b, c. Your Y_i = F(x_i), and your X_i = ( f1(x_i, f2(x_i), f3(x_i) ), where x_i is a set of discrete points of your choosing, the more the better, but you may want to start with about 20, and experiment by gradually increasing their number and see how your fit improves. Hope this helps. I assume you are familiar with sklearn, it has an excellent out of the box Linear Regression module (note that MSE loss is hardcoded into it's definition). Here is an example of extracting optimized parameters:

```<code>import numpy as np
from sklearn.linear_model import LinearRegression

# Generate X and Y from the equation y = 1 * x_0 + 2 * x_1 + 3
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
y = np.dot(X, np.array([1, 2])) + 3
# Fit Linear Regression model
reg = LinearRegression().fit(X, y)
# Get coefficients
print(reg.coef_)
</code>```

will output [1., 2.]

Addressing your particular question. I assume that you do not use filters and just observe a total intensity in each pixel of your detector irrespective of the underlying wavelengths. Lets assume that IR(x_i), IB(x_i), IG(x_i) are known distributions of red, green, and blue signals. Lets denote IM(x_i) = a*IR(x_i) + b*IB(x_i) + c*IG(x_i) to be a mixed color. expressed as a linear combination of intensities from the red, green and blue sources (values of all those intensities are known as a function of pixel position x_i). If the goal is to work out a, b, c, then you can denote Y_i = IM(x_i) and X_i = (IR(x_i) , IB(x_i) , IG(x_i)) and follow the linear regression code.

P.S. note that from fore the physical reasons, a, b, c are >= 0.

Title: ML model for Signal Decomposition

Body:
So recently I got a task which can be summarized as follows:

Suppose we have 3 functions f1, f2, f3 and a certain combination of the functions gives us F.

af1 + bf2 + cf3 = F

The component functions are simple and univariate. I have a range of values for their x and y.

In traditional regression, the task will be to approximate F while f1...f3 are the inputs which vary on each datapoint and a, b, c are the weights we want to approximate and they will then be the same values used to compute F for all data points with unknown F.

In my case, however, the task is to learn the combination of f1, f2, f3 that would yield a given F (or how F factorizes into f1, f2, f3). So F is known and f1,f2,f3 are known too
but the goal is to find the weights a, b, c which vary on data points.

I have researched how to frame this as an ML task and which paradigm to use but cannot find one yet. I have checked reverse regression, factorization machines, but none of these seems like what I need.

UPDATE: Some Context

I have 3 signals of intensity as a function of the wavelength of light used to generate the primary colours RGB. The functions to generate these signals are known. Now, these colours can be combined to obtain secondary colours whose signal is a linear combination of the RGB signals.

Hence, the task is: given the signal of a secondary colour, how do I determine the linear combination of RGB that gave that colour. Can a model be trained to learn the decomposition of the secondary colour signal into the RGB signals?

I hope this helps to better understand if my mathematical formulation above was not clear enough.

Any help on the direction to go will be appreciated.

Body:
Seems that you are looking into a fitting problem (least square fit for example). This is equivalent to a Linear Regression with MSE loss. Your variables are a, b, c. Your Y_i = F(x_i), and your X_i = ( f1(x_i, f2(x_i), f3(x_i) ), where x_i is a set of discrete points of your choosing, the more the better, but you may want to start with about 20, and experiment by gradually increasing their number and see how your fit improves. Hope this helps. I assume you are familiar with sklearn, it has an excellent out of the box Linear Regression module (note that MSE loss is hardcoded into it's definition). Here is an example of extracting optimized parameters:

import numpy as np
from sklearn.linear_model import LinearRegression

# Generate X and Y from the equation y = 1 * x_0 + 2 * x_1 + 3
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
y = np.dot(X, np.array([1, 2])) + 3
# Fit Linear Regression model
reg = LinearRegression().fit(X, y)
# Get coefficients
print(reg.coef_)

will output [1., 2.]

Addressing your particular question. I assume that you do not use filters and just observe a total intensity in each pixel of your detector irrespective of the underlying wavelengths. Lets assume that IR(x_i), IB(x_i), IG(x_i) are known distributions of red, green, and blue signals. Lets denote IM(x_i) = a*IR(x_i) + b*IB(x_i) + c*IG(x_i) to be a mixed color. expressed as a linear combination of intensities from the red, green and blue sources (values of all those intensities are known as a function of pixel position x_i). If the goal is to work out a, b, c, then you can denote Y_i = IM(x_i) and X_i = (IR(x_i) , IB(x_i) , IG(x_i)) and follow the linear regression code.

P.S. note that from fore the physical reasons, a, b, c are >= 0.


问:
Migrate Azure database server/database different region
Is there any way to migrate Azure SQL server/database from one geographical region to another region? Thanks.</p>

答: The official Azure documentation about moving SQL resources across regions.</p>

ContentLicense: CC BY-SA 3.0


问:
How can i find Huawei Ads Publisher Console?
I cant find Ad Slot ID.

In my console, i dont see Ads Kit console to create Ad Slot ID.

Please help me to get Ad Slot ID

答:
Ads Publisher Services are not available for Individual Accounts. To access the Ads Publishing console you have to use the Enterprise account.

In the Enterprise account If you are not able to see the Ads Publishing console then make sure you have added the widget from the Customize console option.


问:
Jquery autocomplete loops HTTP requests
I have a problem with the JQuery autocomplete plugin.

It's hard for me to explain but whenever I try to press a key it keeps looping with requests to the server.

See:

http://members.lycos.nl/saccon/loop.jpg

It should only request once!
Can anyone help me please?

答:
You have created a loop by wrapping the $(document).ready call in another function AutoCompleteStations the code should appear as below.

Also you don't need to call a function from the input directly, so you can remove the onkeyup event from the input tag.

```<code>$(document).ready(function() {
    $("#stations").autocomplete('http://' + server + '/Ajax/ajaxstations', {
        minChars: 2, lineSeparator: '\n', cellSeparator: '|', extraParams: {
            'countryId': function() {
                return $("#countries option:selected").val();
            }
        },
        formatItem: function(row) {
            return row['value'];
        }
     });
});
</code>```

Title: Jquery autocomplete loops HTTP requests

Body:
You have created a loop by wrapping the $(document).ready call in another function AutoCompleteStations the code should appear as below.

Also you don't need to call a function from the input directly, so you can remove the onkeyup event from the input tag.

$(document).ready(function() {
    $("#stations").autocomplete('http://' + server + '/Ajax/ajaxstations', {
        minChars: 2, lineSeparator: '\n', cellSeparator: '|', extraParams: {
            'countryId': function() {
                return $("#countries option:selected").val();
            }
        },
        formatItem: function(row) {
            return row['value'];
        }
     });
});


问:
How do I access the returned json data from my controller from my ASP.NET Core AJAX form?
In my ASP.NET Core 3.1 web application, I have created a very basic Ajax form that makes use of the Unobtrusive Ajax library.  When the form us submitted a check is carried out to find if a record with the same name currently exists and if it does, return any records that match that name as a Json Result along with the outcome of the request.

```<code><form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="md-form form-group">
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
    </div>
    <div class="md-form form-group">
        <button type="submit" value="Save" class="btn btn-info">Save</button>
    </div>
</form>
</code>```

Here is the controller that handles this form when it's submitted.

```<code>[HttpPost]
public IActionResult Create(Test model)
{
    if (ModelState.IsValid)
    {
        bool safetyCheck = _testService.GetTests().Any(x => x.Name == model.Name);

        if (safetyCheck == true)
        {
            var something = _testService.GetTests()
                .Where(x => x.Name == model.Name /*&& x.Active == model.Active*/)
                .Select(x => new { x.Id, x.Name })
                .ToList();

            return Json(new { success = false, error = something });
        }
        else {
            //Add Record
            _testService.InsertTest(model);
            return Json(new { success = true });
        }
    }
    else {
        return View();
    }
}
</code>```

As you can see, the model is passed in, the model state is checked for validity and then a check is carried out to find out if the name passed in from the model matches any currently existing record.  If the check is true then I create an object that can be sent back to the view via JSON along with the success = false.

If the name doesn't exist then the record is simply created.

What I want to know is, once this JSON data is returned, how do I then use it in my view, for example. If I return a list of all the records with the same name as I do above, how would I show the user this information along with a message?

答:
In short, you'd need to write a custom JS function to process the return data. To hook it up to the AJAX request completion you can specify it in data-ajax-complete attribute value on your form.

It will look approximately like this:

```<code><form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST"
    data-ajax-complete="ajax_handler">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="md-form form-group">
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
    </div>
    <div class="md-form form-group">
        <button type="submit" value="Save" class="btn btn-info">Save</button>
    </div>
</form>

@section Scripts
{
    ...
    <script>
        ajax_handler = function (xhr) {
            var data = xhr.responseJSON;
            // Process returned data here
        };
    </script>
}
</code>```

Body:
In my ASP.NET Core 3.1 web application, I have created a very basic Ajax form that makes use of the Unobtrusive Ajax library.  When the form us submitted a check is carried out to find if a record with the same name currently exists and if it does, return any records that match that name as a Json Result along with the outcome of the request.

<form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST">

        <input type="text" asp-for="Name" />

        <button type="submit" value="Save" class="btn btn-info">Save</button>

</form>

Here is the controller that handles this form when it's submitted.

[HttpPost]
public IActionResult Create(Test model)
{
    if (ModelState.IsValid)
    {
        bool safetyCheck = _testService.GetTests().Any(x => x.Name == model.Name);

        if (safetyCheck == true)
        {
            var something = _testService.GetTests()
                .Where(x => x.Name == model.Name /*&& x.Active == model.Active*/)
                .Select(x => new { x.Id, x.Name })
                .ToList();

            return Json(new { success = false, error = something });
        }
        else {
            //Add Record
            _testService.InsertTest(model);
            return Json(new { success = true });
        }
    }
    else {
        return View();
    }
}

As you can see, the model is passed in, the model state is checked for validity and then a check is carried out to find out if the name passed in from the model matches any currently existing record.  If the check is true then I create an object that can be sent back to the view via JSON along with the success = false.

If the name doesn't exist then the record is simply created.

What I want to know is, once this JSON data is returned, how do I then use it in my view, for example. If I return a list of all the records with the same name as I do above, how would I show the user this information along with a message?

Body:
In short, you'd need to write a custom JS function to process the return data. To hook it up to the AJAX request completion you can specify it in data-ajax-complete attribute value on your form.

It will look approximately like this:

<form asp-controller="Test" asp-action="Create" id="CreateForm"
    data-ajax="true"
    data-ajax-method="POST"
    data-ajax-complete="ajax_handler">

    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="md-form form-group">
        <label asp-for="Name"></label>
        <input type="text" asp-for="Name" />
    </div>
    <div class="md-form form-group">
        <button type="submit" value="Save" class="btn btn-info">Save</button>
    </div>
</form>

@section Scripts
{
    ...
    <script>
        ajax_handler = function (xhr) {
            var data = xhr.responseJSON;
            // Process returned data here
        };
    </script>
}


问:
Sum up amount in parquets using Java API
I am new to Spark in java. I have multiple parquets in HDFS whose paths are stored in a String[] paths and the parquets are in this format:

```<code>Amount |  User
10     |  User1
</code>```

Now I want to calculate the sum of amounts in all parquets, how should I do this?

Is it enough to do:

```<code>sparkSession.read().parquet(paths)
</code>```

or do I need to first do a union or join?

答: sparkSession.read().parquet(paths) is good enough to read all parquet</p>

Body:
I am new to Spark in java. I have multiple parquets in HDFS whose paths are stored in a String[] paths and the parquets are in this format:

Amount |  User
10     |  User1

Now I want to calculate the sum of amounts in all parquets, how should I do this?

Is it enough to do:

sparkSession.read().parquet(paths)

or do I need to first do a union or join?


问:
How to create complex anagram using Streams
I have a task

```<code>Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"
</code>```

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

```

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

答:
You could do it by splitting the string into words and then reverting the position of letter characters:

```<code> String input = "a1bcd efg!h a777b 123ab";
 Pattern word = Pattern.compile("\\s+");

 AtomicInteger position = new AtomicInteger(0);
 String collect = word.splitAsStream(input)
     .map(w -> Stream.iterate(w.length() - 1, (i) -> i >= 0, (i) -> --i)
                .collect(() -> new StringBuilder(w),
                   (b, i) -> {
                      if (i == w.length() - 1) position.set(0);
                      if (Character.isLetter(w.charAt(i))) {
                           while (!Character.isLetter(w.charAt(position.get()))
                              && position.get() < w.length())
                               position.incrementAndGet();
                           }
                           b.replace(position.get(),
                                     position.incrementAndGet(),
                                     w.substring(i, i + 1));
                      }
                   },
                   (b1, b2) -> b1.append(b2)
                   ).toString())
    .collect(joining(" "));
System.out.println(collect);
</code>```

results in:

```<code>d1cba hgf!e b777a 123ba
</code>```

Body:
I have a task

Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

Body:
You could do it by splitting the string into words and then reverting the position of letter characters:

 String input = "a1bcd efg!h a777b 123ab";
 Pattern word = Pattern.compile("\\s+");

 AtomicInteger position = new AtomicInteger(0);
 String collect = word.splitAsStream(input)
     .map(w -> Stream.iterate(w.length() - 1, (i) -> i >= 0, (i) -> --i)
                .collect(() -> new StringBuilder(w),
                   (b, i) -> {
                      if (i == w.length() - 1) position.set(0);
                      if (Character.isLetter(w.charAt(i))) {
                           while (!Character.isLetter(w.charAt(position.get()))
                              && position.get() < w.length())
                               position.incrementAndGet();
                           }
                           b.replace(position.get(),
                                     position.incrementAndGet(),
                                     w.substring(i, i + 1));
                      }
                   },
                   (b1, b2) -> b1.append(b2)
                   ).toString())
    .collect(joining(" "));
System.out.println(collect);

results in:

d1cba hgf!e b777a 123ba


问:
NoClassDefFoundError: org/slf4j/LoggerFactory while creating a runnable *.jar with gradle
I'm just trying to create a runnable *.jar file for my application with the help of gradle and the application plugin.

Building ends with no errors, manifest file is OK etc etc, but when it comes to running the *.jar file this happens:

```<code>java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
    at main.Launcher.<clinit>(Launcher.java:19)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
Exception in thread "main"
Process finished with exit code 1
</code>```

It seems obvious that I am missing the library, but it is specified:

build.gradle

```<code>group 'Comparator'
version '0.9'

apply plugin: 'java'
apply plugin: 'application'

mainClassName = "main.Launcher"

compileJava {
    //enable compilation in a separate daemon process
    options.fork = true
    //enable incremental compilation
    options.incremental = true
}

repositories {
    mavenCentral()

}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    // GraphStream Core
    compile group: 'org.graphstream', name: 'gs-core', version: '1.3'
    // GraphStream
    //UI
    compile group: 'org.graphstream', name: 'gs-ui', version: '1.3'
    // GraphStream
    //algo
    compile group: 'org.graphstream', name: 'gs-algo', version: '1.3'
    // Jena
    // https://mvnrepository.com/artifact/org.apache.jena/jena-arq
    compile group: 'org.apache.jena', name: 'jena-arq', version: '2.13.0'
    compile group: 'org.apache.jena', name: 'jena-querybuilder', version: '2.13.0'

    // Log
    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'

    compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.9'
    compile group: 'ch.qos.logback', name: 'logback-core', version: '1.0.9'
    // https://mvnrepository.com/artifact/org.jgrapht/jgrapht-core
    compile group: 'org.jgrapht', name: 'jgrapht-core', version: '0.9.2'
    compile group: 'org.jgrapht', name: 'jgrapht-jdk1.5', version: '0.7.3'
    compile group: 'org.jgrapht', name: 'jgrapht-ext', version: '0.9.2'
    // CSV parser
    compile group: 'com.univocity', name: 'univocity-parsers', version: '1.0.0'

    // https://mvnrepository.com/artifact/com.google.guava/guava
    compile group: 'com.google.guava', name: 'guava', version: '11.0.2'

}

jar {
    manifest {
        attributes 'Main-Class': mainClassName,
                'Class-Path': configurations.runtime.files.collect { "$it.name" }.join(' ')
    }
}
</code>```

The created manifest is as follows:

```<code>Manifest-Version: 1.0
Main-Class: main.Launcher
Class-Path: gs-core-1.3.jar gs-ui-1.3.jar gs-algo-1.3.jar jena-arq-2.1
 3.0.jar jena-querybuilder-2.13.0.jar slf4j-api-1.7.21.jar logback-cla
 ssic-1.0.9.jar logback-core-1.0.9.jar jgrapht-core-0.9.2.jar jgrapht-
 jdk1.5-0.7.3.jar jgrapht-ext-0.9.2.jar univocity-parsers-1.0.0.jar gu
 ava-11.0.2.jar junit-4.12.jar pherd-1.0.jar mbox2-1.0.jar scala-libra
 ry-2.10.1.jar commons-math-2.1.jar commons-math3-3.4.1.jar jfreechart
 -1.0.14.jar jena-core-2.13.0.jar httpclient-4.2.6.jar jsonld-java-0.5
 .1.jar httpclient-cache-4.2.6.jar libthrift-0.9.2.jar commons-csv-1.0
 .jar commons-lang3-3.3.2.jar slf4j-log4j12-1.7.6.jar log4j-1.2.17.jar
  apache-jena-libs-2.13.0.pom jgraphx-2.0.0.1.jar jgraph-5.13.0.0.jar
 jsr305-1.3.9.jar hamcrest-core-1.3.jar jcommon-1.0.17.jar itext-2.1.5
 .jar jena-iri-1.1.2.jar xercesImpl-2.11.0.jar httpcore-4.2.5.jar comm
 ons-codec-1.6.jar jackson-core-2.3.3.jar jackson-databind-2.3.3.jar j
 ena-tdb-1.1.2.jar bcmail-jdk14-138.jar bcprov-jdk14-138.jar jackson-a
 nnotations-2.3.0.jar jcl-over-slf4j-1.7.7.jar commons-logging-1.1.1.j
 ar xml-apis-1.4.01.jar
</code>```

Note that it does include slf4j, but i am still getting the exception.
Any ideas?

Thank you!

答:
I think that the problem comes from conflicting definitions in imported libraries which also reference sl4j. Using maven, I had to add manually instruct to exclude these references from other libraries. </p>

```<code>     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
        <exclusions>
            <exclusion>
                <artifactId>org.slf4j</artifactId>
                <groupId>slf4j-api</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
        <exclusions>
            <exclusion>
                <artifactId>org.slf4j</artifactId>
                <groupId>slf4j-log4j12</groupId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

Body:
I'm just trying to create a runnable *.jar file for my application with the help of gradle and the application plugin.

Building ends with no errors, manifest file is OK etc etc, but when it comes to running the *.jar file this happens:

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
    at main.Launcher.<clinit>(Launcher.java:19)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
Exception in thread "main"
Process finished with exit code 1

It seems obvious that I am missing the library, but it is specified:

build.gradle

group 'Comparator'
version '0.9'

apply plugin: 'java'
apply plugin: 'application'

mainClassName = "main.Launcher"

compileJava {
    //enable compilation in a separate daemon process
    options.fork = true
    //enable incremental compilation
    options.incremental = true
}

repositories {
    mavenCentral()

}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    // GraphStream Core
    compile group: 'org.graphstream', name: 'gs-core', version: '1.3'
    // GraphStream
    //UI
    compile group: 'org.graphstream', name: 'gs-ui', version: '1.3'
    // GraphStream
    //algo
    compile group: 'org.graphstream', name: 'gs-algo', version: '1.3'
    // Jena
    // https://mvnrepository.com/artifact/org.apache.jena/jena-arq
    compile group: 'org.apache.jena', name: 'jena-arq', version: '2.13.0'
    compile group: 'org.apache.jena', name: 'jena-querybuilder', version: '2.13.0'

    // Log
    compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.21'

    compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.0.9'
    compile group: 'ch.qos.logback', name: 'logback-core', version: '1.0.9'
    // https://mvnrepository.com/artifact/org.jgrapht/jgrapht-core
    compile group: 'org.jgrapht', name: 'jgrapht-core', version: '0.9.2'
    compile group: 'org.jgrapht', name: 'jgrapht-jdk1.5', version: '0.7.3'
    compile group: 'org.jgrapht', name: 'jgrapht-ext', version: '0.9.2'
    // CSV parser
    compile group: 'com.univocity', name: 'univocity-parsers', version: '1.0.0'

    // https://mvnrepository.com/artifact/com.google.guava/guava
    compile group: 'com.google.guava', name: 'guava', version: '11.0.2'

}

jar {
    manifest {
        attributes 'Main-Class': mainClassName,
                'Class-Path': configurations.runtime.files.collect { "$it.name" }.join(' ')
    }
}

The created manifest is as follows:

Manifest-Version: 1.0
Main-Class: main.Launcher
Class-Path: gs-core-1.3.jar gs-ui-1.3.jar gs-algo-1.3.jar jena-arq-2.1
 3.0.jar jena-querybuilder-2.13.0.jar slf4j-api-1.7.21.jar logback-cla
 ssic-1.0.9.jar logback-core-1.0.9.jar jgrapht-core-0.9.2.jar jgrapht-
 jdk1.5-0.7.3.jar jgrapht-ext-0.9.2.jar univocity-parsers-1.0.0.jar gu
 ava-11.0.2.jar junit-4.12.jar pherd-1.0.jar mbox2-1.0.jar scala-libra
 ry-2.10.1.jar commons-math-2.1.jar commons-math3-3.4.1.jar jfreechart
 -1.0.14.jar jena-core-2.13.0.jar httpclient-4.2.6.jar jsonld-java-0.5
 .1.jar httpclient-cache-4.2.6.jar libthrift-0.9.2.jar commons-csv-1.0
 .jar commons-lang3-3.3.2.jar slf4j-log4j12-1.7.6.jar log4j-1.2.17.jar
  apache-jena-libs-2.13.0.pom jgraphx-2.0.0.1.jar jgraph-5.13.0.0.jar
 jsr305-1.3.9.jar hamcrest-core-1.3.jar jcommon-1.0.17.jar itext-2.1.5
 .jar jena-iri-1.1.2.jar xercesImpl-2.11.0.jar httpcore-4.2.5.jar comm
 ons-codec-1.6.jar jackson-core-2.3.3.jar jackson-databind-2.3.3.jar j
 ena-tdb-1.1.2.jar bcmail-jdk14-138.jar bcprov-jdk14-138.jar jackson-a
 nnotations-2.3.0.jar jcl-over-slf4j-1.7.7.jar commons-logging-1.1.1.j
 ar xml-apis-1.4.01.jar

Note that it does include slf4j, but i am still getting the exception.
Any ideas?

Thank you!

Body:
I think that the problem comes from conflicting definitions in imported libraries which also reference sl4j. Using maven, I had to add manually instruct to exclude these references from other libraries.

     <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
        <exclusions>
            <exclusion>
                <artifactId>org.slf4j</artifactId>
                <groupId>slf4j-api</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
        <exclusions>
            <exclusion>
                <artifactId>org.slf4j</artifactId>
                <groupId>slf4j-log4j12</groupId>
            </exclusion>
        </exclusions>
    </dependency>


问:
What's the difference between "number" and Number in javascript when iterating over an object?
here's an object.

```<code>let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};
</code>```

that's the right code

```<code>function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}
</code>```

and here's my code

```<code>function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }
</code>```

Please tell me what makes the difference?

答: The typeof operator returns a string containing the name of the type of the operand. Number is a function that converts its input to a number.

Body:
here's an object.

let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};

that's the right code

function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}

and here's my code

function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }

Please tell me what makes the difference?


问:
Semantic Diff Utilities
I'm trying to find some good examples of semantic diff/merge utilities.  The traditional paradigm of comparing source code files works by comparing lines and characters.. but are there any utilities out there (for any language) that actually consider the structure of code when comparing files?

For example, existing diff programs will report "difference found at character 2 of line 125. File x contains v-o-i-d, where file y contains b-o-o-l".  A specialized tool should be able to report "Return type of method doSomething() changed from void to bool".

I would argue that this type of semantic information is actually what the user is looking for when comparing code, and should be the goal of next-generation progamming tools.  Are there any examples of this in available tools?

答:
The solution to this would be on a per language basis. I.e. unless it's designed with a plugin architecture that defers a lot of the parsing of the code into a tree and the semantic comparison to a language specific plugin then it will be very difficult to support multiple languages. What language(s) are you interested in having such a tool for. Personally I'd love one for C#.

For C# there is an assembly diff add-in to Reflector but it only does a diff on the IL not the C#.

You can download the diff add-in here [zip] or go to the project on the codeplex site here.

ContentLicense: CC BY-SA 2.5

Title: Semantic Diff Utilities

OwnerDisplayName: Jonathan Parker

LastEditorDisplayName: Jonathan Parker


问:
Wordpress 3.1.2 Permalinks Broken
I have a fresh install of WordPress 3.1.2 (not upgraded but installed fresh), containing no plugins whatsoever.

I'm having what seems to be from my googling a fairly common problem, but none of the solutions I can find work for me.

I have a custom taxonomy and a custom post type running, the code from my functions.php:

```<code>register_post_type( 'product', array(
    'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product'),
        'add_new_item' => __( 'Add New Product'),
        'add_new' => __( 'Add a Product'),
        'edit_item' => __( 'Edit Product'),
        'new_item' => __( 'New Product'),
        'view_item' => __( 'View Product'),
        'search_items' => __( 'Search products' ),
        'not_found' => __( 'No products found' ),
        'not_found_in_trash' => __( 'No products found in Trash' )
    ),
    'public' => true,
    'supports' => array(
        'title',
        'editor'
    ),
    'has_archive' => true,
    'can_export' => true
));

register_taxonomy( 'product_category', 'product', array(
    'hierarchical' => true,
    'labels' => array(
        'name' => 'Product Categories',
        'singular_name' => 'Product Category',
        'search_items' =>  __( 'Search Product Categories' ),
        'all_items' => __( 'All Product Categories' ),
        'parent_item' => __( 'Parent Product Category' ),
        'parent_item_colon' => __( 'Parent Product Category:' ),
        'edit_item' => __( 'Edit Product Category' ),
        'update_item' => __( 'Update Product Category' ),
        'add_new_item' => __( 'Add New Product Category' ),
        'new_item_name' => __( 'New Product Category Name' ),
        'menu_name' => __( 'Product Categories' ),
    ),
    'public' => true,
    'rewrite' => array(
        'hierarchical' => true
    )
));
</code>```

The problem is that when I go to a product_category archive page, for example http://example.com/dairy-industry, I get a 404. I have tried about a gajillion fixes, including

every combination of rewrite arguments on the register_taxonomy code

re-saving permalinks

turning permalinks off, saving, then turning them on again

the above, but first deleting the .htaccess file from the server

the above, but first deleting the rewrite_rules option from the wp_options table

having the category base and tag base option set (and blank)

I also do not have $wp_rewrite->flush_rules() anywhere in my theme.

The most frustrating thing is that at various times throughout my fixes, and with no pattern I can identify, the custom taxonomy archive pages will start working again, but the regular pages will start giving me 404s instead. They never work at the same time, and I can't figure out which steps will reproducibly make one or the other work. It seems to be totally random.

For a further bit of interestingness, when the custom taxonomy archive pages are not working, one of them (dairy-industry) redirects to the slug of a similarly-named but different (2011/04/dairy-industry-products) post before giving me a 404.

I'm happy to share any code that may be helpful, just ask.

Can anyone help me figure out this perplexing conundrum?

答:
When i first encountered this 404 issue with permalinks, I was frantic. It impacted all of my own sites and several that I manage. Hundreds of folks used a hotfix function that I'd coded ... and then responding to various special cases from users ... we perfected it to the plugin that you mention.

The original article is here:
http://wpcodesnippets.info/blog/how-to-fix-the-wp-3-1-custom-permalinks-bug.html

It is my estimation that this bug has impacted thousands of WP sites. But, the official developers have declined to address it in any subsequent updates. Fortunately, the plugin should work in perpetuity.

Regarding your occasional 404's for new posts, I'm particularly curious if you discover the culprit. Here's one thing to try. As soon as this happens with a new post, pull your site up in a browser that you don't normally use ... and see if you can click a link to the new post from there.

Certainly, older plugins that modify or access the permalink structure will need minor mods until WP decides to address the issue.

Anyway, I'm glad the plugin has helped.

Title: Wordpress 3.1.2 Permalinks Broken

Body:
I have a fresh install of WordPress 3.1.2 (not upgraded but installed fresh), containing no plugins whatsoever.

I'm having what seems to be from my googling a fairly common problem, but none of the solutions I can find work for me.

I have a custom taxonomy and a custom post type running, the code from my functions.php:

register_post_type( 'product', array(
    'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product'),
        'add_new_item' => __( 'Add New Product'),
        'add_new' => __( 'Add a Product'),
        'edit_item' => __( 'Edit Product'),
        'new_item' => __( 'New Product'),
        'view_item' => __( 'View Product'),
        'search_items' => __( 'Search products' ),
        'not_found' => __( 'No products found' ),
        'not_found_in_trash' => __( 'No products found in Trash' )
    ),
    'public' => true,
    'supports' => array(
        'title',
        'editor'
    ),
    'has_archive' => true,
    'can_export' => true
));

register_taxonomy( 'product_category', 'product', array(
    'hierarchical' => true,
    'labels' => array(
        'name' => 'Product Categories',
        'singular_name' => 'Product Category',
        'search_items' =>  __( 'Search Product Categories' ),
        'all_items' => __( 'All Product Categories' ),
        'parent_item' => __( 'Parent Product Category' ),
        'parent_item_colon' => __( 'Parent Product Category:' ),
        'edit_item' => __( 'Edit Product Category' ),
        'update_item' => __( 'Update Product Category' ),
        'add_new_item' => __( 'Add New Product Category' ),
        'new_item_name' => __( 'New Product Category Name' ),
        'menu_name' => __( 'Product Categories' ),
    ),
    'public' => true,
    'rewrite' => array(
        'hierarchical' => true
    )
));

The problem is that when I go to a product_category archive page, for example http://example.com/dairy-industry, I get a 404. I have tried about a gajillion fixes, including

every combination of rewrite arguments on the register_taxonomy code

re-saving permalinks

turning permalinks off, saving, then turning them on again

the above, but first deleting the .htaccess file from the server

the above, but first deleting the rewrite_rules option from the wp_options table

having the category base and tag base option set (and blank)

I also do not have $wp_rewrite->flush_rules() anywhere in my theme.

The most frustrating thing is that at various times throughout my fixes, and with no pattern I can identify, the custom taxonomy archive pages will start working again, but the regular pages will start giving me 404s instead. They never work at the same time, and I can't figure out which steps will reproducibly make one or the other work. It seems to be totally random.

For a further bit of interestingness, when the custom taxonomy archive pages are not working, one of them (dairy-industry) redirects to the slug of a similarly-named but different (2011/04/dairy-industry-products) post before giving me a 404.

I'm happy to share any code that may be helpful, just ask.

Can anyone help me figure out this perplexing conundrum?


问:
How to make Transparent QT Dock Widget
On Windows ,I am trying to create Qt application with transparent DOCKWIDGETS, where background of dock widget is transparent when it is floated. So we can see through dock widget.
Currently it looks black as below.

Code as below

```<code>    QDockWidget * dock3 = new QDockWidget(tr("DOCK3 TranslucentBackground"),
    textEdit,Qt::FramelessWindowHint);
    dock3->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    //dock3->setWindowFlags(dock2->windowFlags()|Qt::FramelessWindowHint);
    dock3->setAttribute(Qt::WA_TranslucentBackground);
    //dock3->setAttribute(Qt::WA_NoSystemBackground);
   {
        QWidget* WindowRect = new QWidget(dock3);
        QWidget* titleRect = new QLabel ("Title",WindowRect);
        titleRect->setFixedSize(QSize(30,60));
        titleRect->setStyleSheet("background:rgb(0,0,255);");
        QWidget* ContentRect = new QLabel("Content",WindowRect);
        ContentRect->setFixedSize(QSize(60,30));
        ContentRect->setStyleSheet("background:rgb(0,255,0);");
        QVBoxLayout* layout = new QVBoxLayout(WindowRect);
        layout->addWidget(titleRect);
        layout->addWidget(ContentRect);
        dock3->setWidget(WindowRect);
    }
</code>```

答:
One way is to use setWindowOpacity(qreal) of the QDockWidget.

But keep in mind that this will apply the opacity to all children of the QDockWidget.

For reference: https://doc.qt.io/qt-5/qwidget.html#windowOpacity-prop

Another way is to use style sheets:
setStyleSheet("background-color: transparent;");. Unfortunately this doesn't work for top level widgets until you set the attribute WA_TranslucentBackground of the base widget.

For reference:

https://doc.qt.io/qt-5/stylesheet.html

https://doc.qt.io/qt-5/qwidget.html#styleSheet-prop

Title: How to make Transparent QT Dock Widget

Body:
On Windows ,I am trying to create Qt application with transparent DOCKWIDGETS, where background of dock widget is transparent when it is floated. So we can see through dock widget.
Currently it looks black as below.

Code as below

    QDockWidget * dock3 = new QDockWidget(tr("DOCK3 TranslucentBackground"),
    textEdit,Qt::FramelessWindowHint);
    dock3->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    //dock3->setWindowFlags(dock2->windowFlags()|Qt::FramelessWindowHint);
    dock3->setAttribute(Qt::WA_TranslucentBackground);
    //dock3->setAttribute(Qt::WA_NoSystemBackground);
   {
        QWidget* WindowRect = new QWidget(dock3);
        QWidget* titleRect = new QLabel ("Title",WindowRect);
        titleRect->setFixedSize(QSize(30,60));
        titleRect->setStyleSheet("background:rgb(0,0,255);");
        QWidget* ContentRect = new QLabel("Content",WindowRect);
        ContentRect->setFixedSize(QSize(60,30));
        ContentRect->setStyleSheet("background:rgb(0,255,0);");
        QVBoxLayout* layout = new QVBoxLayout(WindowRect);
        layout->addWidget(titleRect);
        layout->addWidget(ContentRect);
        dock3->setWidget(WindowRect);
    }


问:
Print vs Return in Python Function
I am learning Python these days and I want to ask which code is better to write and applicable in real world or used in practice actually? Both codes are giving the same output though. In first function, I used return inside and then had to use print when it comes to invoking. While on the other hand, I used print inside and then just call the function. So, which is a good practice?

And apart from that, many times I would need to get many things inside my function and I will have an option to either get it back through "print" and "return" - so also in those conditions, what should I do ideally and what is being used in practice?

```<code>def min_func(values):
    return min(values)
print(min_func([3, 41, 12, 9, 74, 15]))
</code>```

```<code>def min_func(values):
    print(min(values))
min_func([3, 41, 12, 9, 74, 15])
</code>```

答: I think it is better to use the first approach you mentioned because it is more flexible to work with the value the function is returning and with the returned value you can do whatever you want</p>

Title: Print vs Return in Python Function

Body:
I am learning Python these days and I want to ask which code is better to write and applicable in real world or used in practice actually? Both codes are giving the same output though. In first function, I used return inside and then had to use print when it comes to invoking. While on the other hand, I used print inside and then just call the function. So, which is a good practice?

And apart from that, many times I would need to get many things inside my function and I will have an option to either get it back through "print" and "return" - so also in those conditions, what should I do ideally and what is being used in practice?

def min_func(values):
    return min(values)
print(min_func([3, 41, 12, 9, 74, 15]))

def min_func(values):
    print(min(values))
min_func([3, 41, 12, 9, 74, 15])


问:
Formatting data entry in Oracle APEX
does anyone know how to format data entry in the way that is shown in the picture? How to add this block which is marked with red square? I can't find anywhere this option in the page designer in Oracle APEX.

答: Not sure if I understand your question, but if you create a "Text Field" and under its properties, Appearance > Template, select "Optional Floating". When you're done, click on Appearance>Icon then pick an item, you'll get an item which look like the first and the third in your screenshot. To get the second, change the Template to "Required Floating"</p>

Title: Formatting data entry in Oracle APEX


答:
It depends on what you want your function to do.

For example, if we create a function to print the minimum number from a list, we can do this:

```<code>def print_min(values):
    print(min(values))
print_min([3, 41, 12, 9, 74, 15])
</code>```

Note that the function does not return any value. When you call this function, it will just print the value and return nothing. So, that value cannot be used later in the program.

On the other hand, if you want your function to return the minimum number so that you can use it to do more processing later (and print some other output later), you can do:

```<code>def get_min(values):
    return min(values)
m = get_min([3, 41, 12, 9, 74, 15])
</code>```

Now you may print it, or write it to a file, or do some mathematical operations on it. The return value is available for your program to use later.

Title: Print vs Return in Python Function

Body:
It depends on what you want your function to do.

For example, if we create a function to print the minimum number from a list, we can do this:

def print_min(values):
    print(min(values))
print_min([3, 41, 12, 9, 74, 15])

Note that the function does not return any value. When you call this function, it will just print the value and return nothing. So, that value cannot be used later in the program.

On the other hand, if you want your function to return the minimum number so that you can use it to do more processing later (and print some other output later), you can do:

def get_min(values):
    return min(values)
m = get_min([3, 41, 12, 9, 74, 15])

Now you may print it, or write it to a file, or do some mathematical operations on it. The return value is available for your program to use later.


问:
Advanced search / replace Reg ex
I've done some research on the web, but I didn't found how to do what I want.
Here is my problem:
I have an HTML file with lots of links. I need to add parameters to all the links. So I will ant to add ?param_name=param_value if it is the first parameter in the link and &param_name=param_value if it isn't the first parameter.

I'm using Sublime Text with the search/replace with regex to do this.

I managed to search every link with a parameter and add the new parameter with this:
Search:

```<code>href="http(.*)\?(.*?)"
</code>```

Replace:

```<code>href="http${1}\?${2}&param_name=param_value"
</code>```

But what I can't manage is to search in the same way every link without a ? and then add ?param_name=param_value

Any idea?

答:
If you want to add a question mark followed by a key=value pair, you don't need a capturing group.

```<code>http[^\s?]+(?!\S)
</code>```

Regex demo

Explanation

http Match literally (or use https?://)

[^\s?]+ Match 1+ times any char except a whitespace char or question mark

(?!\S) Negative lookahead, assert a whitespace boundary on the right.

In the replacement use the full match $& followed by your replacement.

```<code>$&?param_name=param_value
</code>```

Another option could be specifically check if a format of ?key= does not occur in the link using a negative lookahead.

If it already ends with a ? and you don't want to double question mark, you could all a negative lookahead for that as well.

```<code>(?<!\S)http(?!.*\?[^\s=]+=)\S+(?!\S)
</code>```

Regex demo

Title: Advanced search / replace Reg ex

Body:
I've done some research on the web, but I didn't found how to do what I want.
Here is my problem:
I have an HTML file with lots of links. I need to add parameters to all the links. So I will ant to add ?param_name=param_value if it is the first parameter in the link and &param_name=param_value if it isn't the first parameter.

I'm using Sublime Text with the search/replace with regex to do this.

I managed to search every link with a parameter and add the new parameter with this:
Search:

href="http(.*)\?(.*?)"

Replace:

href="http${1}\?${2}&param_name=param_value"

But what I can't manage is to search in the same way every link without a ? and then add ?param_name=param_value

Any idea?

Body:
If you want to add a question mark followed by a key=value pair, you don't need a capturing group.

http[^\s?]+(?!\S)

Regex demo

Explanation

http Match literally (or use https?://)

[^\s?]+ Match 1+ times any char except a whitespace char or question mark

(?!\S) Negative lookahead, assert a whitespace boundary on the right.

In the replacement use the full match $& followed by your replacement.

$&?param_name=param_value

Another option could be specifically check if a format of ?key= does not occur in the link using a negative lookahead.

If it already ends with a ? and you don't want to double question mark, you could all a negative lookahead for that as well.

(?<!\S)http(?!.*\?[^\s=]+=)\S+(?!\S)

Regex demo


问:
Volley Server Error with null Network response
Every time I try to use POST method with Volley, I get sever error. I get null value in getCause, and some default value in getNetworkResponse.toString().

If I use GET method, this works fine (I get response from my url).

Can anybody help what can I do?

```<code>    Map<String, String> jsonParams = new HashMap<String, String>();
    jsonParams.put("teststr", "abd");

    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
    JsonObjectRequest request = new JsonObjectRequest(
            Request.Method.POST,
            url,
            new JSONObject(jsonParams),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show();
                    }catch(Exception e){
                        Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("abd", "Error: " + error
                                    + ">>" + error.networkResponse.statusCode
                                    + ">>" + error.networkResponse.data
                                    + ">>" + error.getCause()
                                    + ">>" + error.getMessage());
                }
            }) {

                @Override
                protected Map<String,String> getParams() {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("key", "value");
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
    };
    requestQueue.add(request);
</code>```

Error Log:

Error:
  Error: com.android.volley.ServerError>>404>>[B@42b1e0d0>>null>>null

UPDATE:
networkResponse.statusCode comes as 404, though the url is accessible (and return data if I just use GET method). If I remove header part in POST method, still the same.

the url:

```<code><?php
    $response = array();

    $jsonString = file_get_contents('php://input');
    $jsonObj = json_decode($jsonString, true);

    if(!isset($jsonObj['teststr'])){
        $response["msg"] = "No data.";
    }else{
        $response["msg"] = "Success: ".$jsonObj['teststr'];
    }
    echo json_encode($response);
?>
</code>```

答:
In my case, the answer is retry policy setting.
I put 30 seconds the timeout value, it should be 30000, not 30.</p>

Body:
Every time I try to use POST method with Volley, I get sever error. I get null value in getCause, and some default value in getNetworkResponse.toString().

If I use GET method, this works fine (I get response from my url).

Can anybody help what can I do?

    Map<String, String> jsonParams = new HashMap<String, String>();
    jsonParams.put("teststr", "abd");

    RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
    JsonObjectRequest request = new JsonObjectRequest(
            Request.Method.POST,
            url,
            new JSONObject(jsonParams),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        Toast.makeText(getApplicationContext(), "Success"+response.toString(), Toast.LENGTH_LONG).show();
                    }catch(Exception e){
                        Toast.makeText(getApplicationContext(), "JSON ERROR", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("abd", "Error: " + error
                                    + ">>" + error.networkResponse.statusCode
                                    + ">>" + error.networkResponse.data
                                    + ">>" + error.getCause()
                                    + ">>" + error.getMessage());
                }
            }) {

                @Override
                protected Map<String,String> getParams() {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("key", "value");
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }
    };
    requestQueue.add(request);

Error Log:

Error:
  Error: com.android.volley.ServerError>>404>>[B@42b1e0d0>>null>>null

UPDATE:
networkResponse.statusCode comes as 404, though the url is accessible (and return data if I just use GET method). If I remove header part in POST method, still the same.

the url:

<?php
    $response = array();

    $jsonString = file_get_contents('php://input');
    $jsonObj = json_decode($jsonString, true);

    if(!isset($jsonObj['teststr'])){
        $response["msg"] = "No data.";
    }else{
        $response["msg"] = "Success: ".$jsonObj['teststr'];
    }
    echo json_encode($response);
?>


问:
cardservice and additem for dropdown list: how to add an array?
I would like to add an array of elements in cardservice section "additem". I'm not familiar with cardservice.

```<code>   function myFunction() {
var action = CardService.newAction().setFunctionName('notificationCallback');
var pratiche =["ciaone","ciao","ciao2","ciao3"]

return CardService
     .newCardBuilder()
     .setHeader(
         CardService.newCardHeader()
             .setTitle('Elenco operazioni rapide')
             .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))

     .addSection(
          CardService.newCardSection()
              .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
              .setTitle("A group of checkboxes. Multiple selections are allowed.")
                 .setFieldName("CLIENTI")
                 .addItem(pratiche, "checkbox_one_value", false)

                 .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback')))
                 .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
              .setTitle("A group of checkboxes. Multiple selections are allowed.")
                 .setFieldName("PRATICHE")
                 .addItem("Elenco clienti2", "checkbox_two_value", false)
              .setOnChangeAction(CardService.newAction().setFunctionName('inseriscievento')))
              .addWidget(CardService.newTextButton().setText('Telefonata').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action))
              .addWidget(CardService.newTextButton().setText('Incontro').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action)))

     .build();
     }
</code>```

Peraphs it is easy, but...not runs. I've tried also pratiche[]...not runs...I also thought to insert a for cycle for additem, but it's not run.

答:
You need to add each dropdown option as a separate item

If you want to use checkboxes instead of a dropdown - please use CardService.SelectionInputType.CHECK_BOX

instead of

CardService.SelectionInputType.DROPDOWN

Sample

```<code>function myFunction() {
  var action = CardService.newAction().setFunctionName('notificationCallback');
  var pratiche =["ciaone","ciao","ciao2","ciao3"]

  return CardService
  .newCardBuilder()
  .setHeader(
    CardService.newCardHeader()
    .setTitle('Elenco operazioni rapide')
    .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))
  .addSection(
    CardService.newCardSection()
    .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.CHECK_BOX)
               .setTitle("A group of checkboxes. Multiple selections are allowed.")
               .setFieldName("CLIENTI")
               .addItem(pratiche[0], "checkbox_one_value", false)
               .addItem(pratiche[1], "checkbox_one_value", false)
               .addItem(pratiche[2], "checkbox_one_value", false)
               .addItem(pratiche[3], "checkbox_one_value", false)
               .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback')))
    .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
               .setTitle("A group of checkboxes. Multiple selections are allowed.")
               .setFieldName("PRATICHE")
               .addItem("Elenco clienti2", "checkbox_two_value", false)
               .setOnChangeAction(CardService.newAction().setFunctionName('inseriscievento')))
    .addWidget(CardService.newTextButton().setText('Telefonata').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action))
    .addWidget(CardService.newTextButton().setText('Incontro').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action)))
  .build();
}
</code>```

You can also do it with a loop:

```<code>  var widget = CardService.newSelectionInput()
  widget.setType(CardService.SelectionInputType.CHECK_BOX)
  .setTitle("A group of checkboxes. Multiple selections are allowed.")
  .setFieldName("CLIENTI")
  .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback'))
  for(var i = 0; i < pratiche.length; i++){
    widget.addItem(pratiche[i], "checkbox_one_value", false)
  }

  return CardService
  .newCardBuilder()
  .setHeader(
    CardService.newCardHeader()
    .setTitle('Elenco operazioni rapide')
    .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))
  .addSection(
    CardService.newCardSection()
    .addWidget(widget)
     ...
  ).build();
</code>```

Body:
I would like to add an array of elements in cardservice section "additem". I'm not familiar with cardservice.

   function myFunction() {
var action = CardService.newAction().setFunctionName('notificationCallback');
var pratiche =["ciaone","ciao","ciao2","ciao3"]

return CardService
     .newCardBuilder()
     .setHeader(
         CardService.newCardHeader()
             .setTitle('Elenco operazioni rapide')
             .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))

     .addSection(
          CardService.newCardSection()
              .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
              .setTitle("A group of checkboxes. Multiple selections are allowed.")
                 .setFieldName("CLIENTI")
                 .addItem(pratiche, "checkbox_one_value", false)

                 .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback')))
                 .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
              .setTitle("A group of checkboxes. Multiple selections are allowed.")
                 .setFieldName("PRATICHE")
                 .addItem("Elenco clienti2", "checkbox_two_value", false)
              .setOnChangeAction(CardService.newAction().setFunctionName('inseriscievento')))
              .addWidget(CardService.newTextButton().setText('Telefonata').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action))
              .addWidget(CardService.newTextButton().setText('Incontro').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action)))

     .build();
     }

Peraphs it is easy, but...not runs. I've tried also pratiche[]...not runs...I also thought to insert a for cycle for additem, but it's not run.

Body:
You need to add each dropdown option as a separate item

If you want to use checkboxes instead of a dropdown - please use CardService.SelectionInputType.CHECK_BOX

instead of

CardService.SelectionInputType.DROPDOWN

Sample

function myFunction() {
  var action = CardService.newAction().setFunctionName('notificationCallback');
  var pratiche =["ciaone","ciao","ciao2","ciao3"]

  return CardService
  .newCardBuilder()
  .setHeader(
    CardService.newCardHeader()
    .setTitle('Elenco operazioni rapide')
    .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))
  .addSection(
    CardService.newCardSection()
    .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.CHECK_BOX)
               .setTitle("A group of checkboxes. Multiple selections are allowed.")
               .setFieldName("CLIENTI")
               .addItem(pratiche[0], "checkbox_one_value", false)
               .addItem(pratiche[1], "checkbox_one_value", false)
               .addItem(pratiche[2], "checkbox_one_value", false)
               .addItem(pratiche[3], "checkbox_one_value", false)
               .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback')))
    .addWidget(CardService.newSelectionInput().setType(CardService.SelectionInputType.DROPDOWN)
               .setTitle("A group of checkboxes. Multiple selections are allowed.")
               .setFieldName("PRATICHE")
               .addItem("Elenco clienti2", "checkbox_two_value", false)
               .setOnChangeAction(CardService.newAction().setFunctionName('inseriscievento')))
    .addWidget(CardService.newTextButton().setText('Telefonata').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action))
    .addWidget(CardService.newTextButton().setText('Incontro').setTextButtonStyle(CardService.TextButtonStyle.FILLED).setOnClickAction(action)))
  .build();
}

You can also do it with a loop:

  var widget = CardService.newSelectionInput()
  widget.setType(CardService.SelectionInputType.CHECK_BOX)
  .setTitle("A group of checkboxes. Multiple selections are allowed.")
  .setFieldName("CLIENTI")
  .setOnChangeAction(CardService.newAction().setFunctionName('notificationCallback'))
  for(var i = 0; i < pratiche.length; i++){
    widget.addItem(pratiche[i], "checkbox_one_value", false)
  }

  return CardService
  .newCardBuilder()
  .setHeader(
    CardService.newCardHeader()
    .setTitle('Elenco operazioni rapide')
    .setSubtitle('Inserisci rapidamente gli eventi con questi tasti'))
  .addSection(
    CardService.newCardSection()
    .addWidget(widget)
     ...
  ).build();


问:
SAS Print a value in the log
I just want to print the output of a simple operation to the SAS log.

For instance, how can I see the value of quantile('T', .75, 1000)? Is there a smarter way to check what does quantile('T', .75, 1000) equal to than printing it to the log?

```<code>%let t_value = quantile('T', .75, 1000);
%put &t_value.;
</code>```

Others use a proc procedure as here but I cannot believe I need to create a data set to check a value...

答:
Use the macro function %SYSFUNC to invoke non-macro (i.e. DATA step) functions in macro.

Example:

```<code>%put NOTE: quantile('T', .75, 1000) is %SYSFUNC(quantile(T, .75, 1000));
</code>```

will log

```<code>11854  %put NOTE: quantile('T', .75, 1000) is %SYSFUNC(quantile(T, .75, 1000));
NOTE: quantile('T', .75, 1000) is 0.67473516460692
</code>```

Tip: Literal arguments you might use in DATA step do not need to be so in %SYSFUNC invocations.  Carefully examine %SYSFUNC(quantile(T, .75, 1000))

Title: SAS Print a value in the log

Body:
I just want to print the output of a simple operation to the SAS log.

For instance, how can I see the value of quantile('T', .75, 1000)? Is there a smarter way to check what does quantile('T', .75, 1000) equal to than printing it to the log?

%let t_value = quantile('T', .75, 1000);
%put &t_value.;

Others use a proc procedure as here but I cannot believe I need to create a data set to check a value...

Body:
Use the macro function %SYSFUNC to invoke non-macro (i.e. DATA step) functions in macro.

Example:

%put NOTE: quantile('T', .75, 1000) is %SYSFUNC(quantile(T, .75, 1000));

will log

11854  %put NOTE: quantile('T', .75, 1000) is %SYSFUNC(quantile(T, .75, 1000));
NOTE: quantile('T', .75, 1000) is 0.67473516460692

Tip: Literal arguments you might use in DATA step do not need to be so in %SYSFUNC invocations.  Carefully examine %SYSFUNC(quantile(T, .75, 1000))


答:
The difference is that 'number' is an string and Number is an build-in function.

```<code>console.log(typeof "number") //string
console.log(typeof Number) //function
</code>```

Title: What's the difference between "number" and Number in javascript when iterating over an object?

Body:
The difference is that 'number' is an string and Number is an build-in function.

console.log(typeof "number") //string
console.log(typeof Number) //function


问:
Find a XML node with a specific child using minidom
I am looking for a way to filter this XML string and print the "identifiant" value where the "source" field is HAL.

    <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>
```

<p>I only parsed the string using minidom</p>

<pre class="lang-py prettyprint-override"><code>dom = parseString(r.content)
</code>```

Many thanks !

答:
Below - 1 line of code</p>

```<code>import xml.etree.ElementTree as ET

xml = '''
 <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>
'''

root = ET.fromstring(xml)
hals = [s.find('identifiant').text for s in root.findall('.//result/[source="HAL"]')]
print(hals)
</code>```

Body:
I am looking for a way to filter this XML string and print the "identifiant" value where the "source" field is HAL.

    <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>

I only parsed the string using minidom

dom = parseString(r.content)

Many thanks !

Body:
Below - 1 line of code

import xml.etree.ElementTree as ET

xml = '''
 <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>
'''

root = ET.fromstring(xml)
hals = [s.find('identifiant').text for s in root.findall('.//result/[source="HAL"]')]
print(hals)


问:
Is possible update value cross pages by using Provider in flutter?
I'm working with Provider

```<code>provider: ^4.1.2
</code>```

I had 2 pages : A, B.

Page A and B show same simple design, with below codes :

PageA.dart

```<code>class PageA extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Column(children: <Widget>[
         FloatingActionButton.extended(
            onPressed: () {
                 // LOGIC : TRANSFER TO PAGE B AFTER CLICKED BUTTON FROM PAGE A
                 Navigator.push(context, MaterialPageRoute(
                     builder: (context) => PageB()));
            },
            label: Text('Click'),
           ),
         ),
         Text('$songTitle');
         // STEP 2 : while page B already got `songTitle`
         // to show on UI, I want `songTitle` also update on this page A
         // in the same time
     ]);

  }
}
</code>```

PageB.dart

```<code>class PageB extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Text('$songTitle');
   }

   @override
   void initState() {
     super.initState();

     // LOGIC : CALL API TO GET `songTitle` TO UPDATE ON UI
     api.request().then((title) {
        setState(() {
           this.songTitle = title;
           // STEP 1 : this causes update to page B
           // show `songTitle` got from api success
        });
     });
   }

}
</code>```

These codes run with no bugs.

What I want is after Step 1 got songTitle data,

It will updated its data to page A (Step 2) and page B (Step 1) in
the same time by using Provider (ex. Provider.of(context) ...)

People who knows,

Please tell me,

Thank you,

UPDATED I got correct @Chichebe answer in below already.

答:
Have you read the Provider examples?

In flutter don't let your widgets handle logic operations, such as making API requests, you could do that in your provider, and even better create an independent class that will handle HTTP requests for you, then you inject it in your provider code,

You could do something like that:

```<code>class Song{
  String title;

  Song(this.title);
}

class MyProvider extends ChangeNotifier{
   Song song;

   void getSongInformation(String song) async{
       try{
          final req = await doYourAPIRequest();
          song = Song(req['title']);

          notifyListeners(); // Notify the listeners about this change

       }catch(e){
          // handle the error
       }
   }
}
</code>```

Then in your Widgets

```<code>Consumer<Song>(
  builder: (context, song, child) {
    return Text(song.title);
  },
)
</code>```

So any Widgets that is listening for Song changes will be notified about any changes when you call notifyListeners(), if you only need the Provider to notify about a single Song change, then you can also use ValueNotifierProvider. Also, it's good practice to put your Consumer deep as possible in the Widget tree in order to rebuild only the Widgets that depends on that value.

Body:
I'm working with Provider

provider: ^4.1.2

I had 2 pages : A, B.

Page A and B show same simple design, with below codes :

PageA.dart

class PageA extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Column(children: <Widget>[
         FloatingActionButton.extended(
            onPressed: () {
                 // LOGIC : TRANSFER TO PAGE B AFTER CLICKED BUTTON FROM PAGE A
                 Navigator.push(context, MaterialPageRoute(
                     builder: (context) => PageB()));
            },
            label: Text('Click'),
           ),
         ),
         Text('$songTitle');
         // STEP 2 : while page B already got `songTitle`
         // to show on UI, I want `songTitle` also update on this page A
         // in the same time
     ]);

  }
}

PageB.dart

class PageB extends StatelessWidget {

   var songTitle = '';

   @override
   Widget build(BuildContext c) {
     return Text('$songTitle');
   }

   @override
   void initState() {
     super.initState();

     // LOGIC : CALL API TO GET `songTitle` TO UPDATE ON UI
     api.request().then((title) {
        setState(() {
           this.songTitle = title;
           // STEP 1 : this causes update to page B
           // show `songTitle` got from api success
        });
     });
   }

}

These codes run with no bugs.

What I want is after Step 1 got songTitle data,

It will updated its data to page A (Step 2) and page B (Step 1) in
the same time by using Provider (ex. Provider.of(context) ...)

People who knows,

Please tell me,

Thank you,

UPDATED I got correct @Chichebe answer in below already.

Body:
Have you read the Provider examples?

In flutter don't let your widgets handle logic operations, such as making API requests, you could do that in your provider, and even better create an independent class that will handle HTTP requests for you, then you inject it in your provider code,

You could do something like that:

class Song{
  String title;

  Song(this.title);
}

class MyProvider extends ChangeNotifier{
   Song song;

   void getSongInformation(String song) async{
       try{
          final req = await doYourAPIRequest();
          song = Song(req['title']);

          notifyListeners(); // Notify the listeners about this change

       }catch(e){
          // handle the error
       }
   }
}

Then in your Widgets

Consumer<Song>(
  builder: (context, song, child) {
    return Text(song.title);
  },
)

So any Widgets that is listening for Song changes will be notified about any changes when you call notifyListeners(), if you only need the Provider to notify about a single Song change, then you can also use ValueNotifierProvider. Also, it's good practice to put your Consumer deep as possible in the Widget tree in order to rebuild only the Widgets that depends on that value.