问:
Could not find an implementation of the query pattern for source tpe "Task<List<Stocks>> StockList" select not found
I tried to improve my desktop application by Adding Async/Await querying a database here is my code

```<code>public async Task<List<Stocks>> StockListAsync()
    {
        List<Stocks> stocks = new List<Stocks>();
        {
            conn = await App_Code.DbConnection.InitializeConnectionAsync();
            string cnt = "SELECT * FROM tblStock";
            cmd = new SqlCommand(cnt, conn);
            rd = cmd.ExecuteReader();
            if (rd.HasRows == true)
            {
                while (await rd.ReadAsync())
                {
                    var rm = new Stocks
                    {
                        ID = Convert.ToInt32(rd["ID"]),
                        Supplier = Convert.ToInt32(rd["Supplier"]),
                        StockCode = rd["StockCode"].ToString(),
                        StockName = rd["StockName"].ToString(),
                        Description = rd["Description"].ToString(),
                        UnitMeasure = rd["Measurement"].ToString(),
                        Quantity = Convert.ToInt32(rd["Quantity"]),
                        OrderQty = Convert.ToInt32(rd["OrderQty"]),
                        Cost = Convert.ToDouble(rd["Cost"]),
                    };
                    stocks.Add(rm);
                }
            }
            return stocks;
        }

        //}
    }
</code>```

This code above is a separate class called Stocks then I the windows form I want to display the result I have created an instance of the stock class like this * readonly Stocks stock = new Stocks();* and I also have a method GetStock below is the code

```<code> void GetStocks()
    {
        var list = stock.StockListAsync();
            var result = from g in list
                         select g;
            GrdFood.Rows.Clear();
            foreach (var item in result)
            {
                GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                    item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                    Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

            }
    }
</code>```

Then on the FormLoad event I called GetStocks The problem is that the List in the code below  is reporting an error Could not find an implementation of the query pattern for source type Task> StockList select not found

```<code> var list = stock.StockListAsync();
            var result = from g in list
                         select g;
</code>```

Everything was working fine before I made it Async Task, please how do I correct this implementation thanks.

答:
Because you aren't using async/await properly, the type of list is Task<List<Stock>>, not List<Stock> because that's how async works

```<code>Task<List<Stock>>list = stock.StockListAsync();
</code>```

What you actually want is:

```<code>List<Stock>> list = await stock.StockListAsync().ConfigureAwait(false);
</code>```

But, to use await, your function must be async:

```<code>async Task GetStocksAsync() <-- Async functions should have an Async suffix
{
    var list = await stock.StockListAsync().ConfigureAwait(false);
        var result = from g in list
                     select g;
        GrdFood.Rows.Clear();
        foreach (var item in result)
        {
            GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

        }
}
</code>```

Then your problem is that you need to change your code that calls GetStocksAsync to also be async/await etc etc.  At this point you are probably wondering if it's all really worth the effort to rewrite something that already works to be async.

Body:
I tried to improve my desktop application by Adding Async/Await querying a database here is my code

public async Task<List<Stocks>> StockListAsync()
    {
        List<Stocks> stocks = new List<Stocks>();
        {
            conn = await App_Code.DbConnection.InitializeConnectionAsync();
            string cnt = "SELECT * FROM tblStock";
            cmd = new SqlCommand(cnt, conn);
            rd = cmd.ExecuteReader();
            if (rd.HasRows == true)
            {
                while (await rd.ReadAsync())
                {
                    var rm = new Stocks
                    {
                        ID = Convert.ToInt32(rd["ID"]),
                        Supplier = Convert.ToInt32(rd["Supplier"]),
                        StockCode = rd["StockCode"].ToString(),
                        StockName = rd["StockName"].ToString(),
                        Description = rd["Description"].ToString(),
                        UnitMeasure = rd["Measurement"].ToString(),
                        Quantity = Convert.ToInt32(rd["Quantity"]),
                        OrderQty = Convert.ToInt32(rd["OrderQty"]),
                        Cost = Convert.ToDouble(rd["Cost"]),
                    };
                    stocks.Add(rm);
                }
            }
            return stocks;
        }

        //}
    }

This code above is a separate class called Stocks then I the windows form I want to display the result I have created an instance of the stock class like this * readonly Stocks stock = new Stocks();* and I also have a method GetStock below is the code

 void GetStocks()
    {
        var list = stock.StockListAsync();
            var result = from g in list
                         select g;
            GrdFood.Rows.Clear();
            foreach (var item in result)
            {
                GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                    item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                    Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

            }
    }

Then on the FormLoad event I called GetStocks The problem is that the List in the code below  is reporting an error Could not find an implementation of the query pattern for source type Task> StockList select not found

 var list = stock.StockListAsync();
            var result = from g in list
                         select g;

Everything was working fine before I made it Async Task, please how do I correct this implementation thanks.

Body:
Because you aren't using async/await properly, the type of list is Task<List<Stock>>, not List<Stock> because that's how async works

Task<List<Stock>>list = stock.StockListAsync();

What you actually want is:

List<Stock>> list = await stock.StockListAsync().ConfigureAwait(false);

But, to use await, your function must be async:

async Task GetStocksAsync() <-- Async functions should have an Async suffix
{
    var list = await stock.StockListAsync().ConfigureAwait(false);
        var result = from g in list
                     select g;
        GrdFood.Rows.Clear();
        foreach (var item in result)
        {
            GrdFood.Rows.Add(GrdFood.RowCount + 1, item.Supplier, item.StockName,
                item.Description, item.Quantity.ToString("N2"), item.OrderQty.ToString("N2"),
                Convert.ToDouble(item.Cost).ToString("N2"), item.ID);

        }
}

Then your problem is that you need to change your code that calls GetStocksAsync to also be async/await etc etc.  At this point you are probably wondering if it's all really worth the effort to rewrite something that already works to be async.


来源: stackexchange

问:
why the error you can not use it as an observer context showed up?
I need your support as I'm using the (interact) command as a button it it gives me an error ( you can not use it as an observer context), as I need to make interaction in area = 1 among agents.the setup button as I defined 5 areas with agents with different colors, and I want them to move to area = 1 and interact as per their culture features

This is the code

```<code>breed [ parents   parent ]
breed [ childrens children ]
patches-own [ area]
turtles-own [ my_area culture   ]

to setup
  ca
   define_areas
  create_parent
  create_children
 ask turtles [ set culture [] ]
  ask turtles [ set my_area [area] of patch-here ]

  repeat cultural_features
  [ ask turtles [ set culture fput  ( random traits_per_feature + 1 ) culture ] ]

reset-ticks
end

to define_areas

  ask patches with [ (pxcor > -3) and (pxcor < 3) and (pycor > -3) and (pycor < 3) ] [  set pcolor white set area 1  ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 2 ]
  ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 3 ]
   ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 4 ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 5 ]

end

to create_parent

  ask n-of Population  patches with [  ( area = 2 ) ] [ sprout  1  [ set shape "person" set color green set size 1.5   ]  ]
  ask n-of Population  patches with [  ( area = 3 ) ] [ sprout  1 [ set shape "person" set color red set size 1.5 ]  ]
  ask n-of Population  patches with [  ( area = 4 ) ] [ sprout  1 [ set shape "person" set color blue  set size 1.5 ] ]
  ask n-of Population  patches with [  ( area = 5 ) ] [ sprout  1  [ set shape "person" set color grey set size 1.5 ] ]

end

to create_children

  ask n-of ( kids * ( Population / 2 ) ) patches with [  ( area = 2 ) ] [ sprout  1  [ set shape "person" set color green set size .5   ]  ]
  ask n-of ( kids * ( Population / 2 ) )  patches with [  ( area = 3 ) ] [ sprout  1 [ set shape "person" set color red set size .5 ]  ]
  ask n-of ( kids * ( Population / 2 ) ) patches with [  ( area = 4 ) ] [ sprout  1 [ set shape "person" set color blue  set size .5 ] ]
  ask n-of ( kids * ( Population / 2 ) )  patches with [  ( area = 5 ) ] [ sprout  1  [ set shape "person" set color grey set size .5 ] ]

end

to move_in_event
  ask n-of random  ( (count turtles with [ size = .5  ]) / 2 )  turtles with [ size = .5 ]
  [ move-to one-of patches with [ (not any? other turtles-here) and ( area = 1 ) ] ]
end
to interact

  ; identifing the agent chosen
  let selected_agent one-of  turtles with  [ area = 1  ]
  print ( word "selected agent="" " selected_agent)

  ;; culture of selected_agent
  let my_culture culture
  print ( word "selected agent culture ="" "my_culture)

  ;; the agent chooses one neighbor
  let chosen one-of neighbors with  [ area = 1  ]
  print ( word "chosen agent ="" "chosen)

  ;; identify the culture of her neighbor
  let chosen_culture [culture] of chosen
  print ( word "chosen agent culture ="" "chosen_culture)

  ; Creating a local variable to track the number of similarities between the
  ;agents and calculate the probabilities of interactions between two agents
  let similarities 0

  let position_different_traits []

  ; create a list from 0  to number of cultural features
  let N_traits n-values  cultural_features [ i -> i ]
  print ( word "Number of traits to be compared ="" "N_traits)

  ; For each traits of the cultural features
  foreach N_traits
  [ i -> ifelse ( (item i my_culture) = (item i chosen_culture ))
    [ set similarities similarities + 1 ]
    [ set position_different_traits lput i position_different_traits ]   ]

  ;; print out some information to check how does the procedure performs
  print ( word "position_different_traits ="" "position_different_traits)
  print ( word "number of similarities ="" "similarities)

  ; Calculate probability
  let p ( similarities / cultural_features) * 100

  print ( word "probability ="" "p)

  ; Calculate a random number between 1 & 100
  let dice random 100 + 1

  print ( word "Roll a die ="" "dice)

  if (dice <= p)
  [

    ifelse(similarities != cultural_features)
    [
      let position_  one-of position_different_traits
      print ( word "position_trait_to_be_changed in the agent="" "position_)

      let replacement_item item position_ chosen_culture
      print ( word "element to from chosen agent to be replaced in active agent culture="" "replacement_item)

      set culture replace-item position_  culture  replacement_item
      print ( word "active agent culture updated ="" "culture)
    ]
    [

    ]
  ]

  ; only for visualization purposes
  ask selected_agent [  set color [ color ] of chosen]
  ask chosen [  set color [ color ] of selected_agent ]

end
</code>```

答:
You are using the button to run the interact procedure. Here is the beginning of that procedure with comments and printing deleted.

```<code>to interact
  let selected_agent one-of  turtles with  [ area = 1  ]
  let my_culture culture
</code>```

The first thing this procedure does is randomly select a turtle and give it the label 'selected_agent'. Then the next line says let my_culture culture but it doesn't say which agent's value of the variable 'culture' to use. Since 'culture' is an agent variable, the only way this line makes sense if it runs from the context of the agent, but you are running from the context of the observer. That's why you get the error.

The way to fix it is to specify which agent's value of culture you want to assign.

```<code>let my_culture [culture] of selected_agent
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need your support as I'm using the (interact) command as a button it it gives me an error ( you can not use it as an observer context), as I need to make interaction in area = 1 among agents.the setup button as I defined 5 areas with agents with different colors, and I want them to move to area = 1 and interact as per their culture features

This is the code

breed [ parents   parent ]
breed [ childrens children ]
patches-own [ area]
turtles-own [ my_area culture   ]

to setup
  ca
   define_areas
  create_parent
  create_children
 ask turtles [ set culture [] ]
  ask turtles [ set my_area [area] of patch-here ]

  repeat cultural_features
  [ ask turtles [ set culture fput  ( random traits_per_feature + 1 ) culture ] ]

reset-ticks
end

to define_areas

  ask patches with [ (pxcor > -3) and (pxcor < 3) and (pycor > -3) and (pycor < 3) ] [  set pcolor white set area 1  ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 2 ]
  ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor > 4) and (pycor < 16) ] [  set pcolor white set area 3 ]
   ask patches with [ (pxcor < -5 ) and (pxcor > -16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 4 ]
  ask patches with [ (pxcor > 5 ) and (pxcor < 16 ) and (pycor < -4) and (pycor > -16) ] [  set pcolor white set area 5 ]

end

to create_parent

  ask n-of Population  patches with [  ( area = 2 ) ] [ sprout  1  [ set shape "person" set color green set size 1.5   ]  ]
  ask n-of Population  patches with [  ( area = 3 ) ] [ sprout  1 [ set shape "person" set color red set size 1.5 ]  ]
  ask n-of Population  patches with [  ( area = 4 ) ] [ sprout  1 [ set shape "person" set color blue  set size 1.5 ] ]
  ask n-of Population  patches with [  ( area = 5 ) ] [ sprout  1  [ set shape "person" set color grey set size 1.5 ] ]

end

to create_children

  ask n-of ( kids * ( Population / 2 ) ) patches with [  ( area = 2 ) ] [ sprout  1  [ set shape "person" set color green set size .5   ]  ]
  ask n-of ( kids * ( Population / 2 ) )  patches with [  ( area = 3 ) ] [ sprout  1 [ set shape "person" set color red set size .5 ]  ]
  ask n-of ( kids * ( Population / 2 ) ) patches with [  ( area = 4 ) ] [ sprout  1 [ set shape "person" set color blue  set size .5 ] ]
  ask n-of ( kids * ( Population / 2 ) )  patches with [  ( area = 5 ) ] [ sprout  1  [ set shape "person" set color grey set size .5 ] ]

end

to move_in_event
  ask n-of random  ( (count turtles with [ size = .5  ]) / 2 )  turtles with [ size = .5 ]
  [ move-to one-of patches with [ (not any? other turtles-here) and ( area = 1 ) ] ]
end
to interact

  ; identifing the agent chosen
  let selected_agent one-of  turtles with  [ area = 1  ]
  print ( word "selected agent="" " selected_agent)

  ;; culture of selected_agent
  let my_culture culture
  print ( word "selected agent culture ="" "my_culture)

  ;; the agent chooses one neighbor
  let chosen one-of neighbors with  [ area = 1  ]
  print ( word "chosen agent ="" "chosen)

  ;; identify the culture of her neighbor
  let chosen_culture [culture] of chosen
  print ( word "chosen agent culture ="" "chosen_culture)

  ; Creating a local variable to track the number of similarities between the
  ;agents and calculate the probabilities of interactions between two agents
  let similarities 0

  let position_different_traits []

  ; create a list from 0  to number of cultural features
  let N_traits n-values  cultural_features [ i -> i ]
  print ( word "Number of traits to be compared ="" "N_traits)

  ; For each traits of the cultural features
  foreach N_traits
  [ i -> ifelse ( (item i my_culture) = (item i chosen_culture ))
    [ set similarities similarities + 1 ]
    [ set position_different_traits lput i position_different_traits ]   ]

  ;; print out some information to check how does the procedure performs
  print ( word "position_different_traits ="" "position_different_traits)
  print ( word "number of similarities ="" "similarities)

  ; Calculate probability
  let p ( similarities / cultural_features) * 100

  print ( word "probability ="" "p)

  ; Calculate a random number between 1 & 100
  let dice random 100 + 1

  print ( word "Roll a die ="" "dice)

  if (dice <= p)
  [

    ifelse(similarities != cultural_features)
    [
      let position_  one-of position_different_traits
      print ( word "position_trait_to_be_changed in the agent="" "position_)

      let replacement_item item position_ chosen_culture
      print ( word "element to from chosen agent to be replaced in active agent culture="" "replacement_item)

      set culture replace-item position_  culture  replacement_item
      print ( word "active agent culture updated ="" "culture)
    ]
    [

    ]
  ]

  ; only for visualization purposes
  ask selected_agent [  set color [ color ] of chosen]
  ask chosen [  set color [ color ] of selected_agent ]

end

Body:
You are using the button to run the interact procedure. Here is the beginning of that procedure with comments and printing deleted.

to interact
  let selected_agent one-of  turtles with  [ area = 1  ]
  let my_culture culture

The first thing this procedure does is randomly select a turtle and give it the label 'selected_agent'. Then the next line says let my_culture culture but it doesn't say which agent's value of the variable 'culture' to use. Since 'culture' is an agent variable, the only way this line makes sense if it runs from the context of the agent, but you are running from the context of the observer. That's why you get the error.

The way to fix it is to specify which agent's value of culture you want to assign.

let my_culture [culture] of selected_agent


问:
Can't get data from col which has datetime format
I am trying to get column data filtered by current time from MS SQL Server. Cells have datetime format. But I get empty response. Where is a mistake?

```<code><?php
$serverName = ''; // server name
$cinfo      = array(
    "Database" => "", // database
    "UID" => "", // user
    "PWD" => "" // pass
);
$conn       = sqlsrv_connect($serverName, $cinfo);

if ($conn) {
    echo "connected" . "<br/>";
    $datetimenow = current_time("d.m.Y H:i"); // wordpress function
    echo $datetimenow . "<br/>"; // 30.05.2020 14:10
    if (($result = sqlsrv_query($conn, "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime=$datetimenow")) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '<br />';
        }
    }
} else {
    die(print_r(sqlsrv_errors(), true));
}
?>
</code>```

答:
You need to change the statement and use parameterized query to prevent possible SQL injection issues. As is mentioned in the documentation, the sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply. This function provides a streamlined method to execute a query with a minimum amount of code. The sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.

When you use a parameter for datetime values, you have two options:

Pass datetime value as text, using unambiguous datetime format for the value of $datetimenow variable (in your case function current_time returns current time as text from formatted PHP datetime object).

Pass datetime value as PHP datetime object using extended parameter syntax.

PHP:

```<code><?php
$serverName = '';     // server name
$cinfo = array(
    "Database" => "", // database
    "UID" => "",      // user
    "PWD" => ""       // pass
);
$conn = sqlsrv_connect($serverName, $cinfo);

if ($conn) {
    echo "connected" . "<br/>";

    // Datetime value in `yyyy-mm-ddThh:mi:ss` format
    $datetimenow = current_time("Y-m-d\TH:i:00");
    // or if you want a specific datetime value
    //$datetimenow = '2020-05-30T14:10:00';

    // Pass datetime value as text
    $sql = "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime = ?";
    $params = array($datetimenow);
    if (($result = sqlsrv_query($conn, $sql, $params)) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '<br />';
        }
    }

    // Pass datetime value as PHP datetime object
    $sql = "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime = ?";
    $params = array(
        array(
           date_create_from_format('Y-m-d\TH:i:s', $datetimenow),
           SQLSRV_PARAM_IN,
           SQLSRV_PHPTYPE_DATETIME,
           SQLSRV_SQLTYPE_DATETIME
        )
    );
    if (($result = sqlsrv_query($conn, $sql, $params)) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '<br />';
        }
    }

} else {
    die(print_r(sqlsrv_errors(), true));
}
?>
</code>```

Additional notes:

When you retrieve data from SQL Server, the datetime values are returned as PHP datetime objects by default, so you need to use DateTime->format() or to set 'ReturnDatesAsStrings' option in the connection string or at the statement level.

When you send bind values to a decimal or numeric column (also mentioned in the documentation), it is recommended to use strings as inputs to ensure precision and accuracy as PHP has limited precision for floating point numbers. The same applies to bigint columns, especially when the values are outside the range of an integer.

Body:
I am trying to get column data filtered by current time from MS SQL Server. Cells have datetime format. But I get empty response. Where is a mistake?

<?php
$serverName = ''; // server name
$cinfo      = array(
    "Database" => "", // database
    "UID" => "", // user
    "PWD" => "" // pass
);
$conn       = sqlsrv_connect($serverName, $cinfo);

if ($conn) {
    echo "connected" . "
";
    $datetimenow = current_time("d.m.Y H:i"); // wordpress function
    echo $datetimenow . "
"; // 30.05.2020 14:10
    if (($result = sqlsrv_query($conn, "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime=$datetimenow")) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '
';
        }
    }
} else {
    die(print_r(sqlsrv_errors(), true));
}
?>

Body:
You need to change the statement and use parameterized query to prevent possible SQL injection issues. As is mentioned in the documentation, the sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply. This function provides a streamlined method to execute a query with a minimum amount of code. The sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.

When you use a parameter for datetime values, you have two options:

Pass datetime value as text, using unambiguous datetime format for the value of $datetimenow variable (in your case function current_time returns current time as text from formatted PHP datetime object).

Pass datetime value as PHP datetime object using extended parameter syntax.

PHP:

<?php
$serverName = '';     // server name
$cinfo = array(
    "Database" => "", // database
    "UID" => "",      // user
    "PWD" => ""       // pass
);
$conn = sqlsrv_connect($serverName, $cinfo);

if ($conn) {
    echo "connected" . "<br/>";

    // Datetime value in `yyyy-mm-ddThh:mi:ss` format
    $datetimenow = current_time("Y-m-d\TH:i:00");
    // or if you want a specific datetime value
    //$datetimenow = '2020-05-30T14:10:00';

    // Pass datetime value as text
    $sql = "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime = ?";
    $params = array($datetimenow);
    if (($result = sqlsrv_query($conn, $sql, $params)) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '<br />';
        }
    }

    // Pass datetime value as PHP datetime object
    $sql = "SELECT * FROM dbo.GorElectroTrans WHERE GPS_datetime = ?";
    $params = array(
        array(
           date_create_from_format('Y-m-d\TH:i:s', $datetimenow),
           SQLSRV_PARAM_IN,
           SQLSRV_PHPTYPE_DATETIME,
           SQLSRV_SQLTYPE_DATETIME
        )
    );
    if (($result = sqlsrv_query($conn, $sql, $params)) !== false) {
        while ($obj = sqlsrv_fetch_object($result)) {
            echo $obj->Longitude . '<br />';
        }
    }

} else {
    die(print_r(sqlsrv_errors(), true));
}
?>

Additional notes:

When you retrieve data from SQL Server, the datetime values are returned as PHP datetime objects by default, so you need to use DateTime->format() or to set 'ReturnDatesAsStrings' option in the connection string or at the statement level.

When you send bind values to a decimal or numeric column (also mentioned in the documentation), it is recommended to use strings as inputs to ensure precision and accuracy as PHP has limited precision for floating point numbers. The same applies to bigint columns, especially when the values are outside the range of an integer.


问:
Amount not showing in PayPal payment in Braintree
Hi the amount does not display in paypal when making payment. The JavaScript code is shown below:

```<code>  var form = document.querySelector('#payment-form');
  var client_token = '{{ client_token }}';

  braintree.dropin.create({
    authorization: client_token,
    container: '#bt-dropin',
    card: {
    cardholderName: {
      required: true
    }
    },
    applePay: {
    displayName: 'Merchant Name',
    paymentRequest: {
    label: 'Localized Name',
    total: '10.00'
    }
    },
    paypal: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    paypalCredit: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    venmo: true

  }, function (createErr, instance) {
        if (createErr) {
        // Handle any errors that might've occurred when creating Drop-in
        console.error(err);
        return;
        }

    form.addEventListener('submit', function (event) {
      event.preventDefault();

      instance.requestPaymentMethod(function (err, payload) {
        if (err) {
          console.log('Error', err);
          return;
        }
        // Add the nonce to the form and submit
        document.querySelector('#nonce').value = payload.nonce;
        form.submit();
      });
    });
  });
</code>```

From the code, the amount is $10, but does not display in the PayPal payment page. Please what am i doing wrong?

答: Unless you pass line item information, an amount will not show during the PayPal checkout approval process.</p>

Body:
Hi the amount does not display in paypal when making payment. The JavaScript code is shown below:

  var form = document.querySelector('#payment-form');
  var client_token = '{{ client_token }}';

  braintree.dropin.create({
    authorization: client_token,
    container: '#bt-dropin',
    card: {
    cardholderName: {
      required: true
    }
    },
    applePay: {
    displayName: 'Merchant Name',
    paymentRequest: {
    label: 'Localized Name',
    total: '10.00'
    }
    },
    paypal: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    paypalCredit: {
    flow: 'checkout',
    amount: '10.00',
    currency: 'USD'
    },
    venmo: true

  }, function (createErr, instance) {
        if (createErr) {
        // Handle any errors that might've occurred when creating Drop-in
        console.error(err);
        return;
        }

    form.addEventListener('submit', function (event) {
      event.preventDefault();

      instance.requestPaymentMethod(function (err, payload) {
        if (err) {
          console.log('Error', err);
          return;
        }
        // Add the nonce to the form and submit
        document.querySelector('#nonce').value = payload.nonce;
        form.submit();
      });
    });
  });

From the code, the amount is $10, but does not display in the PayPal payment page. Please what am i doing wrong?


问:
IFileOperation and the progress dialog
so, I am working on this shell namespace extension that handles a kind of ZIP file (let's call it ZOP) like a folder.
Everything is in place, and file operations are processed through IFileOperation and IStream.

The thing is, when copying a file into my virtual ZOP folder, calling IStream::Commit is not trivial, and can take significant time, so I'd like to provide additional feedback to the user (and allow her to cancel the operation).

I already have a progress callback mechanism that kicks in when the stream is committed. What I've done for now is a custom dialog, including a progress bar, that pops up whenever IStream::Commit is called.

However, I can't seem to find the hWnd of the standard progress dialog so that mine can be modal (which means that my dialog can be hidden by the progress dialog itself, which defeats the purpose of my dialog).

I could go the IFileOperation::SetProgressDialog way, creating a bridge to IOperationsProgressDialog, but I'd still have to do some dirty code to find the progress bar from a stream I've not created - all I can think of to pass data around is the TLS, and boy do I hate this solution, akin to using a global variable.

Thoughts about retrieving the window handle or subclassing the standard dialog ?

Note: I've observed that sometimes, for relatively short operations, the standard dialog appears after the stream is flushed. Which is uncool too, as my custom dialog appears and goes away even before the operations seems to start.

Update: I've found the progress window using EnumWindows/FindWindowEx as the window has the Dialog class with a DirectUIHWND child. The funny thing is, when instantiating my dialog using DialogBoxParam() (in a distinct thread from IStream::Commit()), the call hangs even before my dialog is displayed, as it is getting stuck in NtUserCallHwndParamLock.

答: Sounds like a job for spy++, get the class name of the window who's hwnd your looking for and call FindWinow or FindWindowEx. </p>

ContentLicense: CC BY-SA 3.0

Title: IFileOperation and the progress dialog


问:
HTML to Markdown with Java
is there an easy way to transform HTML into markdown with JAVA?

I am currently using the Java MarkdownJ library to transform markdown to html.

```<code>import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
    MarkdownProcessor markdown_processor = new MarkdownProcessor();
    return markdown_processor.markdown(markdown);
}

public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}
</code>```

答:
There is a great library for JS called Turndown, you can try it online here. It works for htmls that the accepted answer errors out.

I needed it for Java (as the question), so I ported it. The library for Java is called CopyDown, it has the same test suite as Turndown and I've tried it with real examples that the accepted answer was throwing errors.

To install with gradle:

```<code>dependencies {
        compile 'io.github.furstenheim:copy_down:1.0'
}
</code>```

Then to use it:

CopyDown converter = new CopyDown();
String myHtml = "
Some title

Some html
Another paragraph

";
String markdown = converter.convert(myHtml);
System.out.println(markdown);
> Some title\n==========\n\nSome html\n\nAnother paragraph\n
```

PS. It has MIT license

OwnerDisplayName: Sergio del Amo

Title: HTML to Markdown with Java

Body:
is there an easy way to transform HTML into markdown with JAVA?

I am currently using the Java MarkdownJ library to transform markdown to html.

import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
    MarkdownProcessor markdown_processor = new MarkdownProcessor();
    return markdown_processor.markdown(markdown);
}

public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}

Body:
There is a great library for JS called Turndown, you can try it online here. It works for htmls that the accepted answer errors out.

I needed it for Java (as the question), so I ported it. The library for Java is called CopyDown, it has the same test suite as Turndown and I've tried it with real examples that the accepted answer was throwing errors.

To install with gradle:

dependencies {
        compile 'io.github.furstenheim:copy_down:1.0'
}

Then to use it:

CopyDown converter = new CopyDown();
String myHtml = "<h1>Some title</h1><div>Some html<p>Another paragraph</p></div>";
String markdown = converter.convert(myHtml);
System.out.println(markdown);
> Some title\n==========\n\nSome html\n\nAnother paragraph\n

PS. It has MIT license


问:
TeXForm from Ryacas package as R markdown output
I was attempting to use the Ryacas package in generating math questions involving fractions. Below is some minimal code in R:

```<code>a1 = 1
a2 = 2
b1 = 1
b2 = 3

linearFactor1 = x+1
linearFactor2 = x+3

question1 = (1/linearFactor1 + 2/linearFactor2) %>% y_fn("Simplify") %>% y_fn("TeXForm")
question1
</code>```

Output: ## [1] "\\frac{3 x + 7}{x ^{2} + 5 x + 6} "

I would like to display question with an inline code block as such:

Express $r question1$ in partial fractions.

However, I received an output like this:

When using a multiline to render the math i.e. Express $$r question1$$ in partial fractions, I get an output where the math is rendered correctly:

The question is: Why is there a difference in how R Markdown renders the math, and how can I get it to render as an inline block?

答:
The trailing space causes a problem in the in-line format $, but not if you render as equation with $$. Remove the trailing space and it should render correctly in RMarkdown.
I am not familiar with the package but if that happens with every equation, this is how you would get rid of the trailing space.

```<code># remove trailing whitespace on the right
question1 <- trimws(question1, "r")
</code>```

Or manually

```<code>question1 <- "\\frac{3 x + 7}{x ^{2} + 5 x + 6}"
</code>```

In the Rmd:

Works in line:

```<code>$`r question1`$
</code>```

Works as equation

```<code>$$`r question1`$$
</code>```

Body:
I was attempting to use the Ryacas package in generating math questions involving fractions. Below is some minimal code in R:

a1 = 1
a2 = 2
b1 = 1
b2 = 3

linearFactor1 = x+1
linearFactor2 = x+3

question1 = (1/linearFactor1 + 2/linearFactor2) %>% y_fn("Simplify") %>% y_fn("TeXForm")
question1

Output: ## [1] "\\frac{3 x + 7}{x ^{2} + 5 x + 6} "

I would like to display question with an inline code block as such:

Express $r question1$ in partial fractions.

However, I received an output like this:

When using a multiline to render the math i.e. Express $$r question1$$ in partial fractions, I get an output where the math is rendered correctly:

The question is: Why is there a difference in how R Markdown renders the math, and how can I get it to render as an inline block?

Body:
The trailing space causes a problem in the in-line format $, but not if you render as equation with $$. Remove the trailing space and it should render correctly in RMarkdown.
I am not familiar with the package but if that happens with every equation, this is how you would get rid of the trailing space.

# remove trailing whitespace on the right
question1 <- trimws(question1, "r")

Or manually

question1 <- "\\frac{3 x + 7}{x ^{2} + 5 x + 6}"

In the Rmd:

Works in line:

$`r question1`$

Works as equation

$$`r question1`$$


问:
PDO and binding multiple value sets during insert
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:

```<code>INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');
</code>```

As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.

So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:

```<code>$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
    "firstname"=>$firstName,
    "lastName"=>$lastName));
</code>```

So my question is: Is there any way to bind in a multi-insert statement? Something like:

```<code>INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));
</code>```

答:
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.

The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.

```<code>$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
    $stmt->execute($name);
}
</code>```

If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.

```<code>$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
    $stmt->execute($name);
}
$pdo->commit();
</code>```

Body:
Using PDO in PHP, when having to insert multiple rows into a table at once, I've used sql that looks something like this:

INSERT INTO some_names (firstName, lastName) VALUES ('Joe', 'Smith'),('Fred','Sampson'),('Lisa','Pearce');

As you can see I'm inserting three rows with one statement. The reason I do this is that I believe it is more efficient than executing three distinct statements to insert the rows.

So my question is this: how do I do this in PHP if I want to be able to bind my values to a statement like I do in single statement:

$query= ("INSERT INTO table (firstName, lastName) VALUE (:firstName, :lastName)", array = (
    "firstname"=>$firstName,
    "lastName"=>$lastName));

So my question is: Is there any way to bind in a multi-insert statement? Something like:

INSERT INTO table (firstName, lastName) VALUES((:firstName, :lastName),(:firstName, :lastName));

Body:
In theory, it might sound like a single statement is more efficient because you avoid making multiple calls to MySQL server, but the reality is that this a micro-optimization and you are overcomplicating your code for barely any benefit.

The cool thing about prepared statements is that it is prepared once and can be executed multiple times. This already saves you parsing the SQL statement multiple times. Simply prepare a statement outside of a loop and then execute it inside a loop.

$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO table (firstName, lastName) VALUES(?,?)');
foreach ($names as $name) {
    $stmt->execute($name);
}

If you wrap the whole thing in a transaction as Your Common Sense suggested in the comments then there is no noticeable difference in performance compared to one big statement.

$names = [['Joe', 'Smith'], ['Fred', 'Sampson'], ['Lisa', 'Pearce']];
$stmt = $pdo->prepare('INSERT INTO people (firstName, lastName) VALUES(?,?)');
$pdo->beginTransaction();
foreach ($names as $name) {
    $stmt->execute($name);
}
$pdo->commit();


问:
I'm attempting to render an array as a series of links
I'm trying to do this in a view file:

```<code><td><%= obj.user_ids.values.each {|user_id| link_to results_path(user_id)} %></td>
</code>```

But it is displayed as the unchanged array.  Why is this?

答:
Alternately you might try collect

```<code><%= obj.user_ids.values.collect {|user_id| link_to results_path(user_id)}.join %>
</code>```

Body:
I'm trying to do this in a view file:

<%= obj.user_ids.values.each {|user_id| link_to results_path(user_id)} %>

But it is displayed as the unchanged array.  Why is this?

Body:
Alternately you might try collect

<%= obj.user_ids.values.collect {|user_id| link_to results_path(user_id)}.join %>


问:
How to increase build number in Bitbucket Pipelines?
I have a Maven project where I use buildnumber-maven-plugin for incrementing the build number. After each "mvn package" command, a variable inside buildnumber.properties file is incremented to keep tracking of current build number.

Is there a way in Bitbucket Pipelines after I run the job with "mvn package" command to commit/push the changes made by buildnumber-maven-plugin in that file? Of course, this question makes sens if running a command in butbucket pipeline can change files inside the repository.

答:
If any users with access to the repo are able to push to the branch you would like to commit to, you are able to commit that file back to your repository as outlined here: https://community.atlassian.com/t5/Bitbucket-Pipelines-articles/Pushing-back-to-your-repository/ba-p/958407. Ensure to add [skip ci] so you don't create a new pipelines build for that new version bump commit.

If pushing to the branch is restricted, you can use one of these methods: https://confluence.atlassian.com/bitbucket/push-back-to-your-repository-962352710.html. However, this will require providing a single user with permission to push to the branch.


问:
Using Python How to fetch data from AWS Parameter store in CI Jenkin server (which runs my tests nightly)
I have spent a lot of time searching the web for this answer.

I know how to get my QA env aws_access_key_id & aws_secret_access_key while running my code locally on my PC which are stored in  my C:\Users[name].aws config file

```<code>[profile qa]
aws_access_key_id = ABC
aws_secret_access_key = XYZ

[profile crossaccount]
role_arn=arn:aws:ssm:us-east-1:12345678:parameter/A/B/secrets/C
source_profile=qa
</code>```

Like this python code and I actually see the correct values.

```<code>    import boto3
    session = boto3.Session(profile_name='qa')
    s3client = session.client('s3')
    credentials = session.get_credentials()
    accessKey = credentials.access_key
    secretKey = credentials.secret_key
    print("accessKey= " + str(accessKey) + " secretKey="+ secretKey)
</code>```

A) How do I get these when my code is running on CI do I pass the "aws_access_key_id" and "aws_secret_access_key" as arguments to the code?

B) How exactly do I assume a role and get the parameters from AWS System manager parameter store
Given I know

```<code>secretsExternalId: 'DEF',
secretsRoleArn: 'arn:aws:ssm:us-east-1:12345678:parameter/A/B/secrets/C',
</code>```

答:
Install boto3 and botocore on the CI server.
As you mentioned the CI(Jenkins) is also running on AWS. You can attach a role to the CI server(EC2) which provides SSM read permission.

Below is the sample permission for the role.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:Describe*",
                "ssm:Get*",
                "ssm:List*"
            ],
            "Resource": "*"
        }
    ]
}
</code>```

And from your python code, you can simply call the ssm to get the parameter values.

```<code>$ export parameter_value1="/path/to/ssm/parameter_1"
$ export parameter_value2="/path/to/ssm/parameter_2"
</code>```

```<code>import os
import boto3

session = boto3.Session(region_name='eu-west-1')
ssm = session.client('ssm')

MYSQL_HOSTNAME = os.environ.get('parameter_value1')
MYSQL_USERNAME = os.environ.get('parameter_value2')

hostname = ssm.get_parameter(Name=parameter_value1, WithDecryption=True)
username = ssm.get_parameter(Name=parameter_value2, WithDecryption=True)

print("Param1: {}".format(hostname['Parameter']['Value']))
print("Param2: {}".format(username['Parameter']['Value']))
</code>```

Body:
I have spent a lot of time searching the web for this answer.

I know how to get my QA env aws_access_key_id & aws_secret_access_key while running my code locally on my PC which are stored in  my C:\Users[name].aws config file

[profile qa]
aws_access_key_id = ABC
aws_secret_access_key = XYZ

[profile crossaccount]
role_arn=arn:aws:ssm:us-east-1:12345678:parameter/A/B/secrets/C
source_profile=qa

Like this python code and I actually see the correct values.

    import boto3
    session = boto3.Session(profile_name='qa')
    s3client = session.client('s3')
    credentials = session.get_credentials()
    accessKey = credentials.access_key
    secretKey = credentials.secret_key
    print("accessKey= " + str(accessKey) + " secretKey="+ secretKey)

A) How do I get these when my code is running on CI do I pass the "aws_access_key_id" and "aws_secret_access_key" as arguments to the code?

B) How exactly do I assume a role and get the parameters from AWS System manager parameter store
Given I know

secretsExternalId: 'DEF',
secretsRoleArn: 'arn:aws:ssm:us-east-1:12345678:parameter/A/B/secrets/C',

Body:
Install boto3 and botocore on the CI server.
As you mentioned the CI(Jenkins) is also running on AWS. You can attach a role to the CI server(EC2) which provides SSM read permission.

Below is the sample permission for the role.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:Describe*",
                "ssm:Get*",
                "ssm:List*"
            ],
            "Resource": "*"
        }
    ]
}

And from your python code, you can simply call the ssm to get the parameter values.

$ export parameter_value1="/path/to/ssm/parameter_1"
$ export parameter_value2="/path/to/ssm/parameter_2"

import os
import boto3

session = boto3.Session(region_name='eu-west-1')
ssm = session.client('ssm')

MYSQL_HOSTNAME = os.environ.get('parameter_value1')
MYSQL_USERNAME = os.environ.get('parameter_value2')

hostname = ssm.get_parameter(Name=parameter_value1, WithDecryption=True)
username = ssm.get_parameter(Name=parameter_value2, WithDecryption=True)

print("Param1: {}".format(hostname['Parameter']['Value']))
print("Param2: {}".format(username['Parameter']['Value']))


问:
Spring Security with MongoDB dataSource error
I would like to use Spring Security with my MongoDB database. I search some sample code for spring security but it not working with my mogno connection.

This is my MongoDB configuration file

```<code>@Configuration
@EnableMongoRepositories("com.lab.repository")
public class DatabaseConfiguration  extends AbstractMongoConfiguration{

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Bean
    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient(host + ":" + port);
    }
}
</code>```

When I use Spring Security config class

```<code>@EnableAuthorizationServer
@Configuration
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .withClient("clientIdPassword")
                .secret("secret")
                .authorizedGrantTypes(
                        "password", "authorization_code", "refresh_token")
                .scopes("read", "post");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

}
</code>```

and I ran application I get error

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource in com.newssystem.lab.config.OAuth2AuthorizationServerConfig required a bean of type 'javax.sql.DataSource' that could not be found.
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required classes 'javax.transaction.TransactionManager', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'

Action:

Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.
</code>```

How can I add property DataSource for my Mongo configuration?

答:
DataSource is for SQL databases with drivers supporting JDBC. It won't work with MongoDB which is NoSQL (actually Mongo JDBC drivers do exist but I wouldn't go there). Simply provide your own implementations for TokenStore and ClientDetailsService that get the necessary information from a Mongo repository (or MongoTemplate). For the former, replace JdbcTokenStore with your TokenStore implementation. For the latter (assuming your clients are dynamic and need to be retrieved from Mongo), you can configure it as follows:</p>

```<code>@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(myClientDetailsService);
}
</code>```

Body:
I would like to use Spring Security with my MongoDB database. I search some sample code for spring security but it not working with my mogno connection.

This is my MongoDB configuration file

@Configuration
@EnableMongoRepositories("com.lab.repository")
public class DatabaseConfiguration  extends AbstractMongoConfiguration{

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Bean
    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient(host + ":" + port);
    }
}

When I use Spring Security config class

@EnableAuthorizationServer
@Configuration
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .withClient("clientIdPassword")
                .secret("secret")
                .authorizedGrantTypes(
                        "password", "authorization_code", "refresh_token")
                .scopes("read", "post");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        endpoints.tokenStore(tokenStore())
                .authenticationManager(authenticationManager);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

}

and I ran application I get error

***************************
APPLICATION FAILED TO START
***************************

Description:

Field dataSource in com.newssystem.lab.config.OAuth2AuthorizationServerConfig required a bean of type 'javax.sql.DataSource' that could not be found.
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'
    - Bean method 'dataSource' not loaded because @ConditionalOnClass did not find required classes 'javax.transaction.TransactionManager', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType'

Action:

Consider revisiting the conditions above or defining a bean of type 'javax.sql.DataSource' in your configuration.

How can I add property DataSource for my Mongo configuration?

Body:
DataSource is for SQL databases with drivers supporting JDBC. It won't work with MongoDB which is NoSQL (actually Mongo JDBC drivers do exist but I wouldn't go there). Simply provide your own implementations for TokenStore and ClientDetailsService that get the necessary information from a Mongo repository (or MongoTemplate). For the former, replace JdbcTokenStore with your TokenStore implementation. For the latter (assuming your clients are dynamic and need to be retrieved from Mongo), you can configure it as follows:

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.withClientDetails(myClientDetailsService);
}


问:
In Memory Database
I'm using SqlServer to drive a WPF application, I'm currently using NHibernate and pre-read all the data so it's cached for performance reasons. That works for a single client app, but I was wondering if there's an in memory database that I could use so I can share the information across multiple apps on the same machine. Ideally this would sit below my NHibernate stack, so my code wouldn't have to change. Effectively I'm looking to move my DB from it's traditional format on the server to be an in memory DB on the client.

Note I only need select functionality.

答: http://www.db4o.com/ can be your friend!</p>

OwnerDisplayName: MrTelly

ContentLicense: CC BY-SA 2.5

Title: In Memory Database

LastEditorDisplayName: MrTelly

OwnerDisplayName: Fox


问:
The sum of integers
I would like to print the sum of all integers from a to b containing both. So far I have stopped at this:

```<code>import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i<=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}
</code>```

What I am doing wrong?

答:
Let b=200 and a=195, so according to your logic j=(200-195)=5. With the loop, the sum will be 1+2+3+4+5=15. But you need sum of 195+196+197+198+199+200.

The loop should go as:

```<code> for(int i = a; i<=b ; i++){
        total+=i;
    }
</code>```

To understand how to debug a program please refer to https://techforhumans.site/java/right-way-to-debug-code-using-pen-and-paper/

Title: The sum of integers

Body:
I would like to print the sum of all integers from a to b containing both. So far I have stopped at this:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int j = b-a;
        int total = 0;
        for(int i = 0; i<=j ; i++){
            total+=i;
        }
        System.out.println(total);
    }
}

What I am doing wrong?

Body:
Let b=200 and a=195, so according to your logic j=(200-195)=5. With the loop, the sum will be 1+2+3+4+5=15. But you need sum of 195+196+197+198+199+200.

The loop should go as:

 for(int i = a; i<=b ; i++){
        total+=i;
    }

To understand how to debug a program please refer to https://techforhumans.site/java/right-way-to-debug-code-using-pen-and-paper/


问:
Why when im installing react app, it gives me this error?
So I don't know what's going with my computer, everyone I ask is saying this is strange and they never seen it before so I hoping someone here can help me before i just buy another computer lol...jk

This screenshot you see here is what happens after i run "npm create-react-app

idk why it just stays there and it only gives three files instead of giving me all the file i need for the react app (like public, SRC).

If someone sends me the folder with all the correct files Im able to run the react app and work on it, the issue is that Im not being able to create for some reason and my OCD is really killing me on this.

Please and thank you! :)

```<code>$ npx create-react-app myapp13
Creating a new React app in C:\Users\joesa\Desktop\myapp13.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

yarn add v1.22.4
[1/4] Resolving packages...

[2/4] Fetching packages...

info fsevents@1.2.12: The platform "win32" is incompatible with this module.

info "fsevents@1.2.12" is an optional dependency and failed compatibility check.

Excluding it from installation.

info fsevents@2.1.2: The platform "win32" is incompatible with this module.

info "fsevents@2.1.2" is an optional dependency and failed compatibility check.

Excluding it from installation.

[3/4] Linking dependencies...

warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".

[4/4] Building fresh packages...

success Saved lockfile.

success Saved 14 new dependencies.

info Direct dependencies
├─ cra-template@1.0.3
├─ react-dom@16.13.1
├─ react-scripts@3.4.1
└─ react@16.13.1

info All dependencies
├─ @babel/plugin-syntax-typescript@7.10.1
├─ @babel/plugin-transform-flow-strip-types@7.9.0
├─ @babel/plugin-transform-runtime@7.9.0
├─ @babel/plugin-transform-typescript@7.10.1
├─ @babel/preset-typescript@7.9.0
├─ babel-preset-react-app@9.1.2
├─ cra-template@1.0.3
├─ eslint-config-react-app@5.2.1
├─ react-dev-utils@10.2.1
├─ react-dom@16.13.1
├─ react-error-overlay@6.0.7
├─ react-scripts@3.4.1
├─ react@16.13.1
└─ scheduler@0.19.1

Done in 12.46s.
</code>```

答:
Here you go: https://drive.google.com/drive/folders/1J-z39UQdqV5GP096TDs70m-WzJRiq_bY?usp=sharing

Make sure to run npm install

Body:
So I don't know what's going with my computer, everyone I ask is saying this is strange and they never seen it before so I hoping someone here can help me before i just buy another computer lol...jk

This screenshot you see here is what happens after i run "npm create-react-app

idk why it just stays there and it only gives three files instead of giving me all the file i need for the react app (like public, SRC).

If someone sends me the folder with all the correct files Im able to run the react app and work on it, the issue is that Im not being able to create for some reason and my OCD is really killing me on this.

Please and thank you! :)

$ npx create-react-app myapp13
Creating a new React app in C:\Users\joesa\Desktop\myapp13.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

yarn add v1.22.4
[1/4] Resolving packages...

[2/4] Fetching packages...

info fsevents@1.2.12: The platform "win32" is incompatible with this module.

info "fsevents@1.2.12" is an optional dependency and failed compatibility check.

Excluding it from installation.

info fsevents@2.1.2: The platform "win32" is incompatible with this module.

info "fsevents@2.1.2" is an optional dependency and failed compatibility check.

Excluding it from installation.

[3/4] Linking dependencies...

warning "react-scripts > @typescript-eslint/eslint-plugin > tsutils@3.17.1" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".

[4/4] Building fresh packages...

success Saved lockfile.

success Saved 14 new dependencies.

info Direct dependencies
├─ cra-template@1.0.3
├─ react-dom@16.13.1
├─ react-scripts@3.4.1
└─ react@16.13.1

info All dependencies
├─ @babel/plugin-syntax-typescript@7.10.1
├─ @babel/plugin-transform-flow-strip-types@7.9.0
├─ @babel/plugin-transform-runtime@7.9.0
├─ @babel/plugin-transform-typescript@7.10.1
├─ @babel/preset-typescript@7.9.0
├─ babel-preset-react-app@9.1.2
├─ cra-template@1.0.3
├─ eslint-config-react-app@5.2.1
├─ react-dev-utils@10.2.1
├─ react-dom@16.13.1
├─ react-error-overlay@6.0.7
├─ react-scripts@3.4.1
├─ react@16.13.1
└─ scheduler@0.19.1

Done in 12.46s.


问:
Create a new dataframe that list the keywords with sum of their respective value
This is the issue :

I have a dataframe that have a list of keywords.
I have a second dataframe with a list of keywords and values.

The goal is to create a new dataframe that list the keywords with sum of their respective value.

```<code>import pandas as pd

#Creating dataframe
d = {'col1':['a','b','b','b','c','d','c','a','z','c'] , 'col2': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(data=d)

keywords = {'col1':['a','b','c']}
letters = keywords['col1']

for x in letters:

    a1 = df[df['col1'].str.contains(x,na=False)]
    a2 = a1['col2'].sum()
    a3 = {'letter':[x],'sum':[a2]}
    a = pd.DataFrame(data=a)

</code>```

but it only shows

c - 22

答:
Use groupby and merge:

```<code>import pandas as pd

#Creating dataframe
d = {'col1':['a','b','b','b','c','d','c','a','z','c'] , 'col2': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(data=d)

keywords = pd.DataFrame({'col1':['a','b','c']})
grouped = df.groupby("col1").agg({"col2": "sum"}).reset_index()
keywords.merge(grouped, on="col1", how="left")
</code>```

Explanation:

The grouped dataframe sums over the values of col2 for each unique col1 value in df and so grouped is a dataframe with one row for each unique col1 value that has the sum of col2 in its col2 column. Merging them with how="left" means you ignore the col1 entries in grouped not in keywords and this gets you the desired result.

Body:
This is the issue :

I have a dataframe that have a list of keywords.
I have a second dataframe with a list of keywords and values.

The goal is to create a new dataframe that list the keywords with sum of their respective value.

import pandas as pd

#Creating dataframe
d = {'col1':['a','b','b','b','c','d','c','a','z','c'] , 'col2': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(data=d)

keywords = {'col1':['a','b','c']}
letters = keywords['col1']

for x in letters:

    a1 = df[df['col1'].str.contains(x,na=False)]
    a2 = a1['col2'].sum()
    a3 = {'letter':[x],'sum':[a2]}
    a = pd.DataFrame(data=a)

but it only shows

c - 22

Body:
Use groupby and merge:

import pandas as pd

#Creating dataframe
d = {'col1':['a','b','b','b','c','d','c','a','z','c'] , 'col2': [1,2,3,4,5,6,7,8,9,10]}
df = pd.DataFrame(data=d)

keywords = pd.DataFrame({'col1':['a','b','c']})
grouped = df.groupby("col1").agg({"col2": "sum"}).reset_index()
keywords.merge(grouped, on="col1", how="left")

Explanation:

The grouped dataframe sums over the values of col2 for each unique col1 value in df and so grouped is a dataframe with one row for each unique col1 value that has the sum of col2 in its col2 column. Merging them with how="left" means you ignore the col1 entries in grouped not in keywords and this gets you the desired result.


答:
You're not actually adding the integers between the a and b - you're adding all of the integers from 0 to a - b. Your loop should actually be from a to b, not 0 to a - b.

Consider the case where a is 5 and b is 10 - you should be adding 5 + 6 + 7 + 8 + 9 + 10, but instead your current algorithm adds 0 + 1 + 2 + 3 + 4 + 5.

Title: The sum of integers


问:
Can I switch between Jekyll themes on a mouse click?
I am building my website using a Jekyll theme. The basic website is up and running. However, I wanted to provide an option on the UI to change the theme. Is it possible to add a button such that a mouse click on it changes the theme?

Expanding on what I'm asking, Jekyll generates static pages. Is it possible to re-trigger Jekyll  from the webpage itself to generate pages with a new _layout and _sass?

One possible approach might be to keep the two themes in different branches, and then change the Github pages publishing source to the new branch. Is this approach possible? Or are there any alternatives?

答:
No, this approach is not possible - if the click would run the generator, it would no longer be a static page.

What you can do is

do the switch on the client side with js, swapping paths to css files or something

generate all pages with both themes, and have the button link to the respective other.


问:
Many clickers in one imageButton
I have this picture (this is one picture, not four). I want to make it an imagebutton. But, I want to divide it to four parts, so when I will click on Paul it will open for me new intent about Paul, and so on for John, Ringo and George.
Could I make it? how?

答:
You can use View.OnTouchListener to get coordinates from the click that occurred.

```<code>View.OnTouchListener onTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP:
                    float x = event.getX();

                    int width = v.getWidth();
                    int oneFourthWidth = width / 4;
                    if (x <= oneFourthWidth) {
                        // John Lennon
                    } else if (x > oneFourthWidth && x <= oneFourthWidth * 2) {
                        // Paul McCartney
                    } else if (x > oneFourthWidth * 2 && x <= oneFourthWidth * 3) {
                        // George Harrison
                    } else if (x > oneFourthWidth * 3) {
                        // Ringo Starr
                    }
                    break;
            }
            return true;
        }
    };
</code>```

```<code>yourView.setOnTouchListener(onTouchListener);
</code>```

The calculation of the exact coordinates of each image is up to each specific case.

Title: Many clickers in one imageButton

Body:
You can use View.OnTouchListener to get coordinates from the click that occurred.

View.OnTouchListener onTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_UP:
                    float x = event.getX();

                    int width = v.getWidth();
                    int oneFourthWidth = width / 4;
                    if (x <= oneFourthWidth) {
                        // John Lennon
                    } else if (x > oneFourthWidth && x <= oneFourthWidth * 2) {
                        // Paul McCartney
                    } else if (x > oneFourthWidth * 2 && x <= oneFourthWidth * 3) {
                        // George Harrison
                    } else if (x > oneFourthWidth * 3) {
                        // Ringo Starr
                    }
                    break;
            }
            return true;
        }
    };

yourView.setOnTouchListener(onTouchListener);

The calculation of the exact coordinates of each image is up to each specific case.


问:
h264 videos not being played by android
We provide facility to upload and stream video lectures to different schools. I recommend H264 video codec to be uploaded. We are facing issue on android where H264 is supported by android 6.0.0 and afterwards. Which video format we should be using to stream videos both on android app and web app.</p>

答:
You are correct, the h.264 main profile is only supported in Android 6+

However, if you use h.264 baseline profile, you can go back to Android 3.

Source: Android Developers. You can also check out other formats that are supported there.

Title: h264 videos not being played by android


问:
How to set the driver memory in a Spring Boot application?
I am trying to run Spark in local mode using Spring boot which will eventually be deployed as a Docker container.

What is the right way to set the driver memory?

The spark configuration page https://spark.apache.org/docs/latest/configuration.html says that for client mode it has to be before the JVM starts when running in embedded how can one pass these params?

The Spark configuration file that I am using.

```<code>@Configuration
public class SparkConfiguration {
    private static final Logger LOGGER = Logger.getLogger(SparkConfiguration.class);

    @Value("${config.spark.worker.threads}")
    private String workerThreads;

    @Value("${config.spark.driver.memory}")
    private String driveryMemory;

    @Value("${config.spark.sql.shuffle.partitions}")
    private String shuffleParitions;

    @Bean
    public SparkSession sparkSession() {
//        Logger.getLogger("org").setLevel(Level.OFF);
//        Logger.getLogger("akka").setLevel(Level.OFF);

        SparkSession sparkSession = SparkSession.builder()
                .master(getWorkerThreadCount())
                .appName("API-Spark")

                /*  Spark UI Config */
                .config("spark.ui.enabled", true)
                .config("spark.ui.killEnabled", true)
                .config("spark.ui.retainedJobs", 100)
                .config("spark.ui.retainedStages", 100)
                .config("spark.ui.retainedTasks", 1000)
                /* Spark performance configs */
                .config("spark.driver.memory", driveryMemory)
                .config("spark.sql.shuffle.partitions",shuffleParitions)
                .config("spark.sql.crossJoin.enabled",true)
                .getOrCreate();

        Map<String, String> all = sparkSession.conf().getAll();

        LOGGER.info(" Spark runtime config "+all);

        LOGGER.info("Started Spark App ::: UI at : " + sparkSession.sparkContext().uiWebUrl().get());
        return sparkSession;
    }

    private String getWorkerThreadCount() {
        return "local[WORKER_THREAD_COUNT]".replace("WORKER_THREAD_COUNT", workerThreads);
    }

}
</code>```

答:
You should create a SparkContext in SparkSession sparkSession() explicitly for the spark.driver.memory configuration properties to take effect. In the current setup, it's simply too late.

You may want to use web UI's Environment tab to see whether this spark.driver.memory configuration property is set to the correct value.

Body:
I am trying to run Spark in local mode using Spring boot which will eventually be deployed as a Docker container.

What is the right way to set the driver memory?

The spark configuration page https://spark.apache.org/docs/latest/configuration.html says that for client mode it has to be before the JVM starts when running in embedded how can one pass these params?

The Spark configuration file that I am using.

@Configuration
public class SparkConfiguration {
    private static final Logger LOGGER = Logger.getLogger(SparkConfiguration.class);

    @Value("${config.spark.worker.threads}")
    private String workerThreads;

    @Value("${config.spark.driver.memory}")
    private String driveryMemory;

    @Value("${config.spark.sql.shuffle.partitions}")
    private String shuffleParitions;

    @Bean
    public SparkSession sparkSession() {
//        Logger.getLogger("org").setLevel(Level.OFF);
//        Logger.getLogger("akka").setLevel(Level.OFF);

        SparkSession sparkSession = SparkSession.builder()
                .master(getWorkerThreadCount())
                .appName("API-Spark")

                /*  Spark UI Config */
                .config("spark.ui.enabled", true)
                .config("spark.ui.killEnabled", true)
                .config("spark.ui.retainedJobs", 100)
                .config("spark.ui.retainedStages", 100)
                .config("spark.ui.retainedTasks", 1000)
                /* Spark performance configs */
                .config("spark.driver.memory", driveryMemory)
                .config("spark.sql.shuffle.partitions",shuffleParitions)
                .config("spark.sql.crossJoin.enabled",true)
                .getOrCreate();

        Map<String, String> all = sparkSession.conf().getAll();

        LOGGER.info(" Spark runtime config "+all);

        LOGGER.info("Started Spark App ::: UI at : " + sparkSession.sparkContext().uiWebUrl().get());
        return sparkSession;
    }

    private String getWorkerThreadCount() {
        return "local[WORKER_THREAD_COUNT]".replace("WORKER_THREAD_COUNT", workerThreads);
    }

}


问:
Modularizing subselect definitions within a SELECT?
I have a SELECT along the lines of

```<code>SELECT
(very complex calc1) as `amount`,
(very complex calc2) as `paid_onlne`,
(very complex calc3) as `paid_by_check`,
(very complex calc1) - (very complex calc2)-(very complex calc3) as `amount_due`

FROM  billings
GROUP BY billings.id
</code>```

All the calculations use one-many sub_selects

This has been asked before, but I am looking for a way to be able reuse the calc specifications 1,2,3 in subsequent columns without having to paste the code over and over - leaving a query that is very difficult to maintain.

答:
"The purpose is not to improve performance but to make editing easier. Calc1 in the real app used in 4 different columns - so if a change is needed I have to do it 4 times.

Yes it is possible with LATERAL JOIN - MySQL 8.0.14:

```<code>SELECT billings.id,
 s1.amount,
 s2.paid_onlne,
 s3.paid_by_check,
 s1.amount - s2.paid_online - s3.paid_by_check as `amount_due`
FROM  billings
,LATERAL JOIN (very complex calc1) s1
,LATERAL JOIN (very complex calc2) s2
,LATERAL JOIN (very complex calc3) s3
GROUP BY billings.id;
</code>```

Related: PostgreSQL: using a calculated column in the same query

Body:
I have a SELECT along the lines of

SELECT
(very complex calc1) as `amount`,
(very complex calc2) as `paid_onlne`,
(very complex calc3) as `paid_by_check`,
(very complex calc1) - (very complex calc2)-(very complex calc3) as `amount_due`

FROM  billings
GROUP BY billings.id

All the calculations use one-many sub_selects

This has been asked before, but I am looking for a way to be able reuse the calc specifications 1,2,3 in subsequent columns without having to paste the code over and over - leaving a query that is very difficult to maintain.

Body:
"The purpose is not to improve performance but to make editing easier. Calc1 in the real app used in 4 different columns - so if a change is needed I have to do it 4 times.

Yes it is possible with LATERAL JOIN - MySQL 8.0.14:

SELECT billings.id,
 s1.amount,
 s2.paid_onlne,
 s3.paid_by_check,
 s1.amount - s2.paid_online - s3.paid_by_check as `amount_due`
FROM  billings
,LATERAL JOIN (very complex calc1) s1
,LATERAL JOIN (very complex calc2) s2
,LATERAL JOIN (very complex calc3) s3
GROUP BY billings.id;

Related: PostgreSQL: using a calculated column in the same query


答:
Try this:</p>

```<code>npm uninstall -g create-react-app
npm install -g create-react-app@latest
npx create-react-app testApp
</code>```

Title: Why when im installing react app, it gives me this error?

Body:
Try this:

npm uninstall -g create-react-app
npm install -g create-react-app@latest
npx create-react-app testApp


问:
Automatically print the next line variable for debugging purpose
When you are debugging complex code, you sometimes need to transform:

```<code>def myfunction(self):
    ...
    self.foo.bar = self.baz.bla
</code>```

into

```<code>def myfunction(self):
    ...
    self.foo.bar = self.baz.bla
    print("myfunction", "self.foo.bar", self.foo.bar)  # add this for debugging purposes
</code>```

Is there a way (with a decorator or context manager or anything else) to automatically print the variable name and the value of the next line of code's assignement (and maybe also the current function)?

Example:

```<code>def myfunction(self):
    ...
    with debug:
        self.foo.bar = self.baz.bla
</code>```

would output:

```<code> "myfunction self.foo.bar 123"
</code>```

答:
You can use the inspect module:

```<code>from inspect import currentframe

def f():
    a = 5
    debug_print("a")

def debug_print(var):
    locals = currentframe().f_back.f_locals
    print(f"{var} = {locals[var]}")

f()
</code>```

See also here: Access parent namespace in python

I admit, it's only part of what you asked, but maybe a good start.

Edit: Ok what about this:

```<code>from inspect import currentframe, getsourcelines

class A:
    def f(self):
        self.b = 5
        debug_print()
        self.a = A()
        self.a.a = 4
        debug_print()

    @staticmethod
    def g():
        A.c = 5
        debug_print()

def debug_print():
    frame = currentframe().f_back
    locals = frame.f_locals
    globals = frame.f_globals
    source, start = getsourcelines(currentframe().f_back.f_code)
    var_name = source[frame.f_lineno - 1 - start].split("=")[0]
    tokens = var_name.strip().split(".")
    var = locals.get(tokens[0], globals.get(tokens[0], None))
    for t in tokens[1:]:
        var = getattr(var, t)
    print(f"{var_name} = {var}")

a = A()
a.f()
a.g()
</code>```

At least now, it works with member attributes (including self), even nested. Also assignment of global variables, such as static attributes to the class.

Body:
When you are debugging complex code, you sometimes need to transform:

def myfunction(self):
    ...
    self.foo.bar = self.baz.bla

into

def myfunction(self):
    ...
    self.foo.bar = self.baz.bla
    print("myfunction", "self.foo.bar", self.foo.bar)  # add this for debugging purposes

Is there a way (with a decorator or context manager or anything else) to automatically print the variable name and the value of the next line of code's assignement (and maybe also the current function)?

Example:

def myfunction(self):
    ...
    with debug:
        self.foo.bar = self.baz.bla

would output:

 "myfunction self.foo.bar 123"

Body:
You can use the inspect module:

from inspect import currentframe

def f():
    a = 5
    debug_print("a")

def debug_print(var):
    locals = currentframe().f_back.f_locals
    print(f"{var} = {locals[var]}")

f()

See also here: Access parent namespace in python

I admit, it's only part of what you asked, but maybe a good start.

Edit: Ok what about this:

from inspect import currentframe, getsourcelines

class A:
    def f(self):
        self.b = 5
        debug_print()
        self.a = A()
        self.a.a = 4
        debug_print()

    @staticmethod
    def g():
        A.c = 5
        debug_print()

def debug_print():
    frame = currentframe().f_back
    locals = frame.f_locals
    globals = frame.f_globals
    source, start = getsourcelines(currentframe().f_back.f_code)
    var_name = source[frame.f_lineno - 1 - start].split("=")[0]
    tokens = var_name.strip().split(".")
    var = locals.get(tokens[0], globals.get(tokens[0], None))
    for t in tokens[1:]:
        var = getattr(var, t)
    print(f"{var_name} = {var}")

a = A()
a.f()
a.g()

At least now, it works with member attributes (including self), even nested. Also assignment of global variables, such as static attributes to the class.


问:
Display Keyboard for EditText in Emulator (GenyMotion) Android 4.3
Does anybody know how to display the keyboard in the emulator when the EditText field has focus. I have tried so many solutions but none of them work. I am working in android 4.3 Jelly Bean. The Emulator I am using is GenyMotion. I would also like to know how to hide the keyboard when the EditText field loses focus. I assume however if the keyboard does not appear in the emulator it won't appear when testing on the device.

Any help much appreciated

答:
For new versions of Genymotion (mine is 3.1.0),

Right click on your virtual device and click "edit"

Then choose "Use virtual keyboard for text input" and click "CONFIRM"


问:
How can we center title of react-navigation header?
React-navigation docs are still young, and reading through the issues is not working quite much for me (changes on each version) does anyone have a working method to center title in Android using react-navigation in React Native?

答:
As of 30th May 2020, you can't no more pass any parameters to createStackNavigator().

To center your title, you have to use the following (with the headerTitleAlign property):

```<code><Stack.Screen
    name="Centered"
    component={Centered}
    options={{
      title: 'Centered title',
      headerShown: true,
      headerTitleAlign:'center'
    }}
/>
</code>```

Body:
As of 30th May 2020, you can't no more pass any parameters to createStackNavigator().

To center your title, you have to use the following (with the headerTitleAlign property):

<Stack.Screen
    name="Centered"
    component={Centered}
    options={{
      title: 'Centered title',
      headerShown: true,
      headerTitleAlign:'center'
    }}
/>


问:
Having a hard time positioning image behind Bootstrap navbar (Z-index)
This is the navbar layout

```<code><header id="navigation-bar" class="nav-header">
      <nav class="navbar navbar-expand-lg">
    <a class="navbar-brand" href="#">
      <img src="images/logo.svg" alt="logo-icon">
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">How we work <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item item2 active">
          <a class="nav-link" href="#">Blog<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item item2 active">
          <a class="nav-link" href="#">Account <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link nav-btn-link" href="#"><button class="nav-btn btn btn-outline-dark">View Plans</button><span class="sr-only">(current)</span></a>
        </li>
      </ul>
    </div>
  </nav>
    </header>
</code>```

bg-img1 is the image I'm trying to position behind navbar:

```<code><section id="Heading">
    <img class="bg-img1" src="images/bg-pattern-intro-right-desktop.svg" alt="bg-pattern-left">
    <div class="container-1">
      <div class="heading-text">
</code>```

I tried putting a header around the navbar and positioning the z-index but it doesnt seem to do it justice.

```<code>.nav-header {
  position: relative;
  padding: 1%;
  z-index: 10000;
}
</code>```

and this is how I positioned my image:

```<code>.bg-img1 {
  position: absolute;
  right: 0;
  width: 40%;
  top: 3%;
  z-index: 2;
}
</code>```

答:
You are doing everything right but because you are giving src to your img attribute, as a result of which it will be treated as an image which will not be appearing behind  the navbar but in front.

Instead of giving src to your image, you can use CSS background property for your img attribute which will make the img appear behind the navbar. So no need of any z-index

.bg-img1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url(https://images.unsplash.com/photo-1590845947667-381579052389?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60) no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<section id="Heading">
  <img class="bg-img1" alt="bg-pattern-left">
  <div class="container-1">
    <div class="heading-text">
    </div>
  </div>
</section>

<header id="navigation-bar " class="nav-header">
  <nav class="navbar bg-dark navbar-expand-lg">

      <img src="https://placehold.it/20x20" alt="logo-icon">

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

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item active">
          How we work <span class="sr-only">(current)</span>
        </li>
        <li class="nav-item item2 active">
          Blog<span class="sr-only">(current)</span>
        </li>
        <li class="nav-item item2 active">
          Account <span class="sr-only">(current)</span>
        </li>
        <li class="nav-item active">
          <button class="nav-btn btn btn-outline-dark">View
                  Plans</button><span class="sr-only">(current)</span>
        </li>
      </ul>
    </div>
  </nav>
</header></code>```

Body:
This is the navbar layout

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

    </button>

          How we work (current)

          Blog(current)

          Account (current)

          <button class="nav-btn btn btn-outline-dark">View Plans</button>(current)

bg-img1 is the image I'm trying to position behind navbar:

I tried putting a header around the navbar and positioning the z-index but it doesnt seem to do it justice.

.nav-header {
  position: relative;
  padding: 1%;
  z-index: 10000;
}

and this is how I positioned my image:

.bg-img1 {
  position: absolute;
  right: 0;
  width: 40%;
  top: 3%;
  z-index: 2;
}

Body:
You are doing everything right but because you are giving src to your img attribute, as a result of which it will be treated as an image which will not be appearing behind  the navbar but in front.

Instead of giving src to your image, you can use CSS background property for your img attribute which will make the img appear behind the navbar. So no need of any z-index

.bg-img1 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url(https://images.unsplash.com/photo-1590845947667-381579052389?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60) no-repeat;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

<section id="Heading">
  <img class="bg-img1" alt="bg-pattern-left">
  <div class="container-1">
    <div class="heading-text">
    </div>
  </div>
</section>

<header id="navigation-bar " class="nav-header">
  <nav class="navbar bg-dark navbar-expand-lg">
    <a class="navbar-brand" href="#">
      <img src="https://placehold.it/20x20" alt="logo-icon">
    </a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#">How we work <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item item2 active">
          <a class="nav-link" href="#">Blog<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item item2 active">
          <a class="nav-link" href="#">Account <span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item active">
          <a class="nav-link nav-btn-link" href="#"><button class="nav-btn btn btn-outline-dark">View
                  Plans</button><span class="sr-only">(current)</span></a>
        </li>
      </ul>
    </div>
  </nav>
</header>


问:
Pulling in email via IMAP to rails application
I am pulling email into my app via imap using Net::IMAP and copying the mail into an All Mail folder then marking it in inbox as deleted.

This then enables a backup of all emails for the user in All email folder and my app only pulls in emails from the inbox not flagged as deleted.

This works fine for gmail but i am trying to do it for horde webmail.

I successfully pull in the emails but cant seem to flag them as deleted and copy them to another folder.

Here is my code for doing this in gmail :

```<code>imap.uid_copy(uid, "[Gmail]/All Mail")
imap.uid_store(uid, "+FLAGS", [:Deleted])
</code>```

Any one help with this? What should the "[Gmail]/All Mail") be changed to for horde webmail?  Is this different for all email like hotmail / yahoo etc?

Any help on this would be great.
thanks

rick

答:
can you try this?

```<code>      connection.store( uid , "+FLAGS", [:DELETED])
      ...
      connection.expunge()
</code>```

e.g. "store" instead of "uid_store" ?

I'm not using Horde, but the above line is working for me for several IMAP servers.

Also make sure that you call connection.expunge on the mailbox where you flagged the messages for deletion..!

e.g. look at the net/imap API for #expunge:
http://www.ruby-doc.org/stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M001441

Body:
I am pulling email into my app via imap using Net::IMAP and copying the mail into an All Mail folder then marking it in inbox as deleted.

This then enables a backup of all emails for the user in All email folder and my app only pulls in emails from the inbox not flagged as deleted.

This works fine for gmail but i am trying to do it for horde webmail.

I successfully pull in the emails but cant seem to flag them as deleted and copy them to another folder.

Here is my code for doing this in gmail :

imap.uid_copy(uid, "[Gmail]/All Mail")
imap.uid_store(uid, "+FLAGS", [:Deleted])

Any one help with this? What should the "[Gmail]/All Mail") be changed to for horde webmail?  Is this different for all email like hotmail / yahoo etc?

Any help on this would be great.
thanks

rick

Body:
can you try this?

      connection.store( uid , "+FLAGS", [:DELETED])
      ...
      connection.expunge()

e.g. "store" instead of "uid_store" ?

I'm not using Horde, but the above line is working for me for several IMAP servers.

Also make sure that you call connection.expunge on the mailbox where you flagged the messages for deletion..!

e.g. look at the net/imap API for #expunge:
http://www.ruby-doc.org/stdlib/libdoc/net/imap/rdoc/classes/Net/IMAP.html#M001441


问:
React Native: image not visible
Using React Native v0.61.5.
The images are visible (iOS and Android) in dev mode only on the emulator or on the phone attached with cable and Terminal running. Once I close the terminal and I open again the app the images are not visible.

Code for the image
<Image source={require("../assets/image.png")} />

Code I found for copy the images from the ./assets folder to /res:
 npx react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

this code creates folders with the images I use but when I close the terminal and disconnect the phone the images are not visible.

Does it happen to you too? What should I do for be able to load the images without the terminal running?

答:
You should use a drawable folder in
ProjectName/android/app/src/main/res directory for android and for
ios use Images.xcassets drag and drop your images into this.

Add Images in this folder.

Access Image Like this <Image source={{uri:"imagename"}}/>

Title: React Native: image not visible


问:
How To Count Read and Unread message in PHP mysql
I want to make a read and Unread message count from Mysql.

This is my PHP code :

```<code><?php

$dbdata = "SELECT * FROM users";

if ($result = mysqli_query($db, $dbdata)) {
  if (mysqli_num_rows($result) > 0) {

    while ($row = mysqli_fetch_array($result)) {

      echo "<li class=online'><a href='?user=" .
        $row['username'] .
        "'><img alt='user pics' src='img/demo/av1.jpg' /> <span>" .
        $row['fname'] . ' ' .
        $row['lname'] . "</span><span class='msgcount'> 0</span></a></li>";

    }
    mysqli_free_result($result);

  } else {
    echo "No Students Found.";
  }

} else {
  echo "ERROR: Could not able to execute. ";
}

?>
</code>```

I want  0 to display a count of the unread messages of that user. And if the user is already clicked, the messages unread becomes 0 because messages are shown upon click.

Can you help me solve this logic? I just want to notify that there is an unread message. Thank you masters please help me.

This is the Output image of the Chat Message:

答:
In your database create a column "Status" of datatype int(1) Default 0.

If I read the message update the status with 1, as by default we are using 0 that means its unread message.

Now at the time counting. Create two variables $total_read = 0 and $total_unread = 0.

Inside your while loop your can go with this

```<code>while($row = mysqli_fetch_array($result)) {
    if($row['status'] == 0)
    {
        $total_unread = total_unread + 1
    } else {
        $total_read = total_read + 1
    }
}
</code>```

Body:
I want to make a read and Unread message count from Mysql.

This is my PHP code :

<?php

$dbdata = "SELECT * FROM users";

if ($result = mysqli_query($db, $dbdata)) {
  if (mysqli_num_rows($result) > 0) {

    while ($row = mysqli_fetch_array($result)) {

      echo "
 " .
        $row['fname'] . ' ' .
        $row['lname'] . " 0
";

    }
    mysqli_free_result($result);

  } else {
    echo "No Students Found.";
  }

} else {
  echo "ERROR: Could not able to execute. ";
}

?>

I want  0 to display a count of the unread messages of that user. And if the user is already clicked, the messages unread becomes 0 because messages are shown upon click.

Can you help me solve this logic? I just want to notify that there is an unread message. Thank you masters please help me.

This is the Output image of the Chat Message:

Body:
In your database create a column "Status" of datatype int(1) Default 0.

If I read the message update the status with 1, as by default we are using 0 that means its unread message.

Now at the time counting. Create two variables $total_read = 0 and $total_unread = 0.

Inside your while loop your can go with this

while($row = mysqli_fetch_array($result)) {
    if($row['status'] == 0)
    {
        $total_unread = total_unread + 1
    } else {
        $total_read = total_read + 1
    }
}


问:
function of `with` in `concurrent.futures`
The code below executes as expected by returning the total finish time as almost zero because it doesn't wait for the threads to finish every job.

```<code>import concurrent.futures
import time

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]

fs = [executor.submit(do_something, sec) for sec in secs]

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')
</code>```

But with the with command it does wait:

```<code>with concurrent.futures.ThreadPoolExecutor() as executor:
    secs = [10, 4, 3, 2, 1]

    fs = [executor.submit(do_something, sec) for sec in secs]
</code>```

Why? What is the reason that with has this behavior with multithreading?

答:
Using a concurrent.futures.Executor in a with statement is equivalent to calling Executor.shutdown after using it – causing the executor to wait for all tasks to complete. An Executor used in a with guarantees proper shutdown of concurrent tasks even if an error occurs inside the with block.

Executor.shutdown(wait=True)

Signal the executor that it should free any
  resources that it is using when the currently pending futures are done
  executing. Calls to Executor.submit() and Executor.map() made after
  shutdown will raise RuntimeError.

[...]

You can avoid having to call this method explicitly if you use the
  with statement, which will shutdown the Executor (waiting as if
  Executor.shutdown() were called with wait set to True):
  [...]

Body:
The code below executes as expected by returning the total finish time as almost zero because it doesn't wait for the threads to finish every job.

import concurrent.futures
import time

start = time.perf_counter()

def do_something(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'

executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]

fs = [executor.submit(do_something, sec) for sec in secs]

finish = time.perf_counter()

print(f'Finished in {round(finish-start, 2)} second(s)')

But with the with command it does wait:

with concurrent.futures.ThreadPoolExecutor() as executor:
    secs = [10, 4, 3, 2, 1]

    fs = [executor.submit(do_something, sec) for sec in secs]

Why? What is the reason that with has this behavior with multithreading?