问:
Certain python libraries are not loading in my Django application in production, but load fine in local server
In my views.py file of my Django application I'm trying to load the 'transformers' library with the following command:

```<code>from transformers import pipeline
</code>```

This works in my local environment, but on my Linux server at Linode, when I try to load my website, the page tries to load for 5 minutes then I get a Timeout error. I don't understand what is going on, I know I have installed the library correctly. I have also run the same code in the python shell on my server and it loads fine, it's is just that if I load it in my Django views.py file, no page of my website loads.

My server: Ubuntu 20.04 LTS, Nanode 1GB: 1 CPU, 25GB Storage, 1GB RAM

Library: transformers==3.0.2

I also have the same problem when I try to load tensorflow. All the other libraries are loading fine, like pytorch and pandas etc. I've been trying to solve this problem since more than a week, I've also changed hosts from GCP to Linode, but it's still the same.

Edit: I created a new server and installed everything from scratch and used a virtualenv this time, but still its the same problem. Following are the installed libraries outputted from pip freeze:

```<code>asgiref==3.2.10
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
Django==3.0.7
djangorestframework==3.11.0
filelock==3.0.12
future==0.18.2
idna==2.10
joblib==0.16.0
numpy==1.19.1
packaging==20.4
Pillow==7.2.0
pyparsing==2.4.7
pytz==2020.1
regex==2020.7.14
requests==2.24.0
sacremoses==0.0.43
sentencepiece==0.1.91
six==1.15.0
sqlparse==0.3.1
tokenizers==0.8.1rc1
torch==1.5.1+cpu
torchvision==0.6.1+cpu
tqdm==4.48.0
transformers==3.0.2
urllib3==1.25.10
</code>```

I also know transformers library is installed because if I try to import some library that doesn't exist then I simply get an error, like I should. But in this case it just loads forever and doesn't output any error. This is so bizarre.

答:
Based on this answer

Some third party packages for Python which use C extension modules, and this includes scipy and numpy, will only work in the Python main interpreter and cannot be used in sub interpreters as mod_wsgi by default uses.

transformers library uses numpy, so you should force the WSGI application to run in the main interpreter of the process by changing apache config:

```<code>## open apache config
$ nano /etc/apache2/sites-enabled/000-default.conf

## add this line to apache config
 WSGIApplicationGroup %{GLOBAL}

## restart apache
$ systemctl restart apache2
</code>```

now it works!!

for more information visit the link above.

Body:
In my views.py file of my Django application I'm trying to load the 'transformers' library with the following command:

from transformers import pipeline

This works in my local environment, but on my Linux server at Linode, when I try to load my website, the page tries to load for 5 minutes then I get a Timeout error. I don't understand what is going on, I know I have installed the library correctly. I have also run the same code in the python shell on my server and it loads fine, it's is just that if I load it in my Django views.py file, no page of my website loads.

My server: Ubuntu 20.04 LTS, Nanode 1GB: 1 CPU, 25GB Storage, 1GB RAM

Library: transformers==3.0.2

I also have the same problem when I try to load tensorflow. All the other libraries are loading fine, like pytorch and pandas etc. I've been trying to solve this problem since more than a week, I've also changed hosts from GCP to Linode, but it's still the same.

Edit: I created a new server and installed everything from scratch and used a virtualenv this time, but still its the same problem. Following are the installed libraries outputted from pip freeze:

asgiref==3.2.10
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
Django==3.0.7
djangorestframework==3.11.0
filelock==3.0.12
future==0.18.2
idna==2.10
joblib==0.16.0
numpy==1.19.1
packaging==20.4
Pillow==7.2.0
pyparsing==2.4.7
pytz==2020.1
regex==2020.7.14
requests==2.24.0
sacremoses==0.0.43
sentencepiece==0.1.91
six==1.15.0
sqlparse==0.3.1
tokenizers==0.8.1rc1
torch==1.5.1+cpu
torchvision==0.6.1+cpu
tqdm==4.48.0
transformers==3.0.2
urllib3==1.25.10

I also know transformers library is installed because if I try to import some library that doesn't exist then I simply get an error, like I should. But in this case it just loads forever and doesn't output any error. This is so bizarre.

Body:
Based on this answer

Some third party packages for Python which use C extension modules, and this includes scipy and numpy, will only work in the Python main interpreter and cannot be used in sub interpreters as mod_wsgi by default uses.

transformers library uses numpy, so you should force the WSGI application to run in the main interpreter of the process by changing apache config:

## open apache config
$ nano /etc/apache2/sites-enabled/000-default.conf

## add this line to apache config
 WSGIApplicationGroup %{GLOBAL}

## restart apache
$ systemctl restart apache2

now it works!!

for more information visit the link above.


来源: stackexchange

问:
Weird filter for function definition in Ocaml
Sorry for this noob question but I have this function definition :

```<code>let f x = function
    | 0 -> 0
    | y -> 1;;
</code>```

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

答:
The notation for functions of several arguments is a bit different in OCaml and in mathematics, which could be the cause of a little confusion here.

In OCaml the function notation makes it easy to partially apply functions.  For instance we can write something like

# let add x y = x  + y;;
val add : int -> int -> int = <fun>
(* The addition of integers as we know it. *)
```
<p>and specialise the first argument <em>x</em> to a 1, to define the successor operation:</p>
<pre class="lang-ml prettyprint-override"><code># let successor = add 1;;
val successor : int -> int = <fun>
(* successor y is equivalent to add 1 x *)
</code>```

so that we can try

```<code># successor 2;;
- : int = 3
</code>```

Note that in OCaml the function add we defined above is a different function than the function

```<code># let add' (x, y) = x + y;;
val add' : int * int -> int = <fun>
</code>```

See how the signature differs. In mathematics, we usually do not need to emphasise the difference and hence identify the two functions.  The add' function is, from OCaml perspective, a function of one argument, which is a pair.

In your analysis, you correctly state that f is a function of two arguments, x and y.  It does not actually depend on the value of x, since the identifier x does not appear right to the equal sign in let f x = ….  Instead for any value of x, f x returns the function defined by

function
| 0 -> 0
| y -> 1
```
<p>So any of the expressions <code>f ()</code>, <code>f "whatever"</code>, <code>f 0</code>, <code>f 7</code>, <code>f (0, 1)</code> will evaluate to the function</p>
<pre class="lang-ml prettyprint-override"><code>function
| 0 -> 0
| y -> 1
</code>```

(In these expressions x is bound to () or "whatever" or 0 or 7 or (0, 1) but that specific value does not participate to the actual computation of f x.)

We can try this out:

# let f x = function
    | 0 -> 0
    | y -> 1;;
val f : 'a -> int -> int = <fun>
# f ();;
- : int -> int = <fun>
# f "whatever";;
- : int -> int = <fun>
# f 0;;
- : int -> int = <fun>
# f 7;;
- : int -> int = <fun>
# f (0, 1);;
- : int -> int = <fun>
```
<p>If we add a second argument, this will actually return a 0 or a 1 according to that function definition:</p>
<pre class="lang-ml prettyprint-override"><code># f () 0;;
- : int = 0
# f () 11;;
- : int = 1
# f (0,1) 0;;
- : int = 0
# f (0,1) 11;;
- : int = 1
(* etc. *)
</code>```

We can also use parenthesis to emphasise how OCaml is actually reading these expressions

# (f ()) 0;;
- : int = 0
# (f (0,1)) 11;;
- : int = 1
```

ContentLicense: CC BY-SA 4.0

Body:
Sorry for this noob question but I have this function definition :

let f x = function
    | 0 -> 0
    | y -> 1;;

I understand that f is a function of x,y but why does it give :

0 if y = 0

1 if y = 1

Indeed according to the filter, should not f(0,1) give 0 since 0 -> 0 ?

Body:
The notation for functions of several arguments is a bit different in OCaml and in mathematics, which could be the cause of a little confusion here.

In OCaml the function notation makes it easy to partially apply functions.  For instance we can write something like

# let add x y = x  + y;;
val add : int -> int -> int = <fun>
(* The addition of integers as we know it. *)

and specialise the first argument x to a 1, to define the successor operation:

# let successor = add 1;;
val successor : int -> int = <fun>
(* successor y is equivalent to add 1 x *)

so that we can try

# successor 2;;
- : int = 3

Note that in OCaml the function add we defined above is a different function than the function

# let add' (x, y) = x + y;;
val add' : int * int -> int = <fun>

See how the signature differs. In mathematics, we usually do not need to emphasise the difference and hence identify the two functions.  The add' function is, from OCaml perspective, a function of one argument, which is a pair.

In your analysis, you correctly state that f is a function of two arguments, x and y.  It does not actually depend on the value of x, since the identifier x does not appear right to the equal sign in let f x = ….  Instead for any value of x, f x returns the function defined by

function
| 0 -> 0
| y -> 1

So any of the expressions f (), f "whatever", f 0, f 7, f (0, 1) will evaluate to the function

function
| 0 -> 0
| y -> 1

(In these expressions x is bound to () or "whatever" or 0 or 7 or (0, 1) but that specific value does not participate to the actual computation of f x.)

We can try this out:

# let f x = function
    | 0 -> 0
    | y -> 1;;
val f : 'a -> int -> int = <fun>
# f ();;
- : int -> int = <fun>
# f "whatever";;
- : int -> int = <fun>
# f 0;;
- : int -> int = <fun>
# f 7;;
- : int -> int = <fun>
# f (0, 1);;
- : int -> int = <fun>

If we add a second argument, this will actually return a 0 or a 1 according to that function definition:

# f () 0;;
- : int = 0
# f () 11;;
- : int = 1
# f (0,1) 0;;
- : int = 0
# f (0,1) 11;;
- : int = 1
(* etc. *)

We can also use parenthesis to emphasise how OCaml is actually reading these expressions

# (f ()) 0;;
- : int = 0
# (f (0,1)) 11;;
- : int = 1


问:
Informix procedure JDBC: How to call when first parameter is array of integers and second is out parameter
What is the proper syntax to call the procedure ? It works if I remove the 2nd out parameter and used returning
to return the result, but I have use case where there will be more than 1 different results
to be returned by the procedure.  I can't figure out other way to return different result
from a single procedure call. Any help are deeply appreciated.

Tools

```<code>IBM Informix Dynamic Server Version 12.10.FC13, 14.10.FC4W1DE
JDBC 4.10.14, 4.50.7
Java version "1.7.0_60"
</code>```

Stored procedure

```<code>create procedure sp_demo_set_arg5(
    arg1 set(integer not null),
    out arg2 integer
)
returning integer as retval;

define p_arg1 integer;
define p_arg2 integer;
define p_retval integer;

begin

let p_arg2 = 0;
let p_retval = 0;

foreach
    select *
    into p_arg1
    from table(arg1)

    let p_arg2 = p_arg2 + p_arg1;
    let p_retval = 1;

end foreach ;

return p_retval;

end
end procedure;
</code>```

Java code

        String dbUrl = "jdbc:informix-sqli://someserver:28090/demodb:INFORMIXSERVER=ol_informix1410";
        String user = "someuser";
        String password = "somepass";
        String sql = "{ ? = call sp_demo_set_arg5(?::SET(integer not null), ?) }";

        HashSet<Integer> arg1 = new HashSet<>();
        Integer intObject;
        int i;
        for (i=1; i <= 1; i++)
        {
            intObject = new Integer(i);
            arg1.add(intObject);
            arg1.add(i);
        }

        Connection conn = null;

        try {
            conn = Database.getConnection(dbUrl, user, password);
            CallableStatement stmt = conn.prepareCall(sql);

            int arg2 = 0;

            stmt.setObject(1, arg1);
            stmt.registerOutParameter(2, Types.INTEGER );
            ResultSet rs = stmt.executeQuery();

            arg2 = stmt.getInt(2);
            while (rs.next()) {
                System.out.println("retval = " + rs.getInt(1) + " , arg2 = " + arg2);
            }

            return;

        } catch (SQLException e) {
            e.printStackTrace();
        }
```
<p>Stacktrace</p>
```java.sql.SQLException: Illegal attempt to convert a collection type into another type.
    at com.informix.util.IfxErrMsg.buildExceptionWithMessage(IfxErrMsg.java:422)
    at com.informix.util.IfxErrMsg.buildIsamException(IfxErrMsg.java:401)
    at com.informix.jdbc.IfxSqli.addException(IfxSqli.java:3022)
    at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3273)
    at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2269)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2194)
    at com.informix.jdbc.IfxSqli.executeFastPath(IfxSqli.java:4862)
    at com.informix.jdbc.IfxResultSet.executeFastPath(IfxResultSet.java:251)
    at com.informix.jdbc.IfxCallableStatement.executeFastPath(IfxCallableStatement.java:1470)
    at com.informix.jdbc.IfxCallableStatement.executeQuery(IfxCallableStatement.java:233)
```

答:
Have you tried using the driver's PreparedStatement (IfmxPreparedStatement)?

The classes:

```<code>com.informix.lang.IfxToJavaType,
com.informix.lang.JavaToIfxType
com.informix.lang.IfxTypes
</code>```

are very helpful.

And these ones:

```<code>com.informix.jdbc.IfxComplexInput
com.informix.jdbc.IfxComplexOutput
</code>```

make calls to IfxTypes' method:

```<code>public static boolean isCollection(int ifxType) {
    ifxType &= 0xFF;
    if (ifxType == 21 || ifxType == 19 || ifxType == 20)
      return true;
    return false;
 }
</code>```

(The IfxType for SET is 19)

Body:
What is the proper syntax to call the procedure ? It works if I remove the 2nd out parameter and used returning
to return the result, but I have use case where there will be more than 1 different results
to be returned by the procedure.  I can't figure out other way to return different result
from a single procedure call. Any help are deeply appreciated.

Tools

IBM Informix Dynamic Server Version 12.10.FC13, 14.10.FC4W1DE
JDBC 4.10.14, 4.50.7
Java version "1.7.0_60"

Stored procedure

create procedure sp_demo_set_arg5(
    arg1 set(integer not null),
    out arg2 integer
)
returning integer as retval;

define p_arg1 integer;
define p_arg2 integer;
define p_retval integer;

begin

let p_arg2 = 0;
let p_retval = 0;

foreach
    select *
    into p_arg1
    from table(arg1)

    let p_arg2 = p_arg2 + p_arg1;
    let p_retval = 1;

end foreach ;

return p_retval;

end
end procedure;

Java code

        String dbUrl = "jdbc:informix-sqli://someserver:28090/demodb:INFORMIXSERVER=ol_informix1410";
        String user = "someuser";
        String password = "somepass";
        String sql = "{ ? = call sp_demo_set_arg5(?::SET(integer not null), ?) }";

        HashSet<Integer> arg1 = new HashSet<>();
        Integer intObject;
        int i;
        for (i=1; i <= 1; i++)
        {
            intObject = new Integer(i);
            arg1.add(intObject);
            arg1.add(i);
        }

        Connection conn = null;

        try {
            conn = Database.getConnection(dbUrl, user, password);
            CallableStatement stmt = conn.prepareCall(sql);

            int arg2 = 0;

            stmt.setObject(1, arg1);
            stmt.registerOutParameter(2, Types.INTEGER );
            ResultSet rs = stmt.executeQuery();

            arg2 = stmt.getInt(2);
            while (rs.next()) {
                System.out.println("retval = " + rs.getInt(1) + " , arg2 = " + arg2);
            }

            return;

        } catch (SQLException e) {
            e.printStackTrace();
        }

Stacktrace

java.sql.SQLException: Illegal attempt to convert a collection type into another type.
    at com.informix.util.IfxErrMsg.buildExceptionWithMessage(IfxErrMsg.java:422)
    at com.informix.util.IfxErrMsg.buildIsamException(IfxErrMsg.java:401)
    at com.informix.jdbc.IfxSqli.addException(IfxSqli.java:3022)
    at com.informix.jdbc.IfxSqli.receiveError(IfxSqli.java:3273)
    at com.informix.jdbc.IfxSqli.dispatchMsg(IfxSqli.java:2269)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2194)
    at com.informix.jdbc.IfxSqli.executeFastPath(IfxSqli.java:4862)
    at com.informix.jdbc.IfxResultSet.executeFastPath(IfxResultSet.java:251)
    at com.informix.jdbc.IfxCallableStatement.executeFastPath(IfxCallableStatement.java:1470)
    at com.informix.jdbc.IfxCallableStatement.executeQuery(IfxCallableStatement.java:233)

Body:
Have you tried using the driver's PreparedStatement (IfmxPreparedStatement)?

The classes:

com.informix.lang.IfxToJavaType,
com.informix.lang.JavaToIfxType
com.informix.lang.IfxTypes

are very helpful.

And these ones:

com.informix.jdbc.IfxComplexInput
com.informix.jdbc.IfxComplexOutput

make calls to IfxTypes' method:

public static boolean isCollection(int ifxType) {
    ifxType &= 0xFF;
    if (ifxType == 21 || ifxType == 19 || ifxType == 20)
      return true;
    return false;
 }

(The IfxType for SET is 19)


问:
How to plot chart from external JSON and format X-AXIS to show time using Chart.JS?
I am using Chart.JS to plot some data from external JSON. But I am unable to format the X-AXIS in a proper way.

My html & javascripts codes are here:

$(document).ready(function(){
  $.ajax({
    url : "https://api.npoint.io/1f7ea8eeaa8996ad0d71",
    type : "POST",
    dataType: "json",
    success : function(data){
      console.log(data);

      var reg_date = [];
      var datetime = [];
      var temperature = [];
      var humidity = [];
      var effluent_level = [];

      for(var i in data) {
        reg_date.push(new Date(data[i].reg_date));
        temperature.push(data[i].temperature);
        humidity.push(data[i].humidity);
        effluent_level.push(data[i].effluent_level);
      }

      var chartdata = {
        labels: reg_date,
        type: 'time',
        distribution: 'linear',
        datasets: [
          {
            label: "Temperature",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(59, 89, 152, 0.75)",
            borderColor: "rgba(59, 89, 152, 1)",
            pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
            pointHoverBorderColor: "rgba(59, 89, 152, 1)",
            data: temperature
          },
          {
            label: "Humidity",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(29, 202, 255, 0.75)",
            borderColor: "rgba(29, 202, 255, 1)",
            pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
            pointHoverBorderColor: "rgba(29, 202, 255, 1)",
            data: humidity
          },
          {
            label: "Effluent Level",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(211, 72, 54, 0.75)",
            borderColor: "rgba(211, 72, 54, 1)",
            pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
            pointHoverBorderColor: "rgba(211, 72, 54, 1)",
            data: effluent_level
          }
        ]
      };

      var ctx = $("#mycanvas");

      var LineGraph = new Chart(ctx, {
        type: 'line',
        data: chartdata
      });
    },
    error : function(data) {

    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <title>ChartJS - LineGraph</title>
    <style>
      .chart-container {
        width: 640px;
        height: auto;
      }
    </style>
  </head>
  <body>
    <div class="chart-container">
      <canvas id="mycanvas"></canvas>
    </div>

    <!-- javascript -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
    <script type="text/javascript" src="linegraph.js"></script>
  </body>
</html></code>```

Output Image:

But I want to show only time values in X-AXIS (not losing date data). How to plot the graph in an effective way to represent the data?

答:
You can use a time axis:

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</body></code>```

or you can use a custom tick callback to achieve this

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(val) {
            return this.getLabelForValue(val).substring(16, 24);
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
</body></code>```

Documentation: https://www.chartjs.org/docs/master/axes/labelling.html#creating-custom-tick-formats

Body:
I am using Chart.JS to plot some data from external JSON. But I am unable to format the X-AXIS in a proper way.

My html & javascripts codes are here:

$(document).ready(function(){
  $.ajax({
    url : "https://api.npoint.io/1f7ea8eeaa8996ad0d71",
    type : "POST",
    dataType: "json",
    success : function(data){
      console.log(data);

      var reg_date = [];
      var datetime = [];
      var temperature = [];
      var humidity = [];
      var effluent_level = [];

      for(var i in data) {
        reg_date.push(new Date(data[i].reg_date));
        temperature.push(data[i].temperature);
        humidity.push(data[i].humidity);
        effluent_level.push(data[i].effluent_level);
      }

      var chartdata = {
        labels: reg_date,
        type: 'time',
        distribution: 'linear',
        datasets: [
          {
            label: "Temperature",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(59, 89, 152, 0.75)",
            borderColor: "rgba(59, 89, 152, 1)",
            pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
            pointHoverBorderColor: "rgba(59, 89, 152, 1)",
            data: temperature
          },
          {
            label: "Humidity",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(29, 202, 255, 0.75)",
            borderColor: "rgba(29, 202, 255, 1)",
            pointHoverBackgroundColor: "rgba(29, 202, 255, 1)",
            pointHoverBorderColor: "rgba(29, 202, 255, 1)",
            data: humidity
          },
          {
            label: "Effluent Level",
            fill: false,
            //lineTension: 0.1,
            backgroundColor: "rgba(211, 72, 54, 0.75)",
            borderColor: "rgba(211, 72, 54, 1)",
            pointHoverBackgroundColor: "rgba(211, 72, 54, 1)",
            pointHoverBorderColor: "rgba(211, 72, 54, 1)",
            data: effluent_level
          }
        ]
      };

      var ctx = $("#mycanvas");

      var LineGraph = new Chart(ctx, {
        type: 'line',
        data: chartdata
      });
    },
    error : function(data) {

    }
  });
});

<!DOCTYPE html>

    <title>ChartJS - LineGraph</title>

      <canvas id="mycanvas"></canvas>

Output Image:

But I want to show only time values in X-AXIS (not losing date data). How to plot the graph in an effective way to represent the data?

Body:
You can use a time axis:

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</body>

or you can use a custom tick callback to achieve this

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(val) {
            return this.getLabelForValue(val).substring(16, 24);
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
</body>

Documentation: https://www.chartjs.org/docs/master/axes/labelling.html#creating-custom-tick-formats


问:
DatePicker doesn't bind value in Blazor
I'm using date picker in my component to bind the value to my method in blazor. the value is always empty.

Here is my component :

```<code>  <input data-provide="datepicker" class="col-sm-2 form-control" @bind="date_selected" data-date-format="yyyy-mm-dd"
        style="width: 300x ;height:35px;">

code{
    string date_selected;

    public async Task GetTags()
    {
        AllTags = await Task.Run(() => tagsService.Map( date_selected));

    }

}
</code>```

my java script :

```<code>

$( document ).ready(function() {
    $("#from-datepicker").datepicker({
        format: 'yyyy-mm-dd HH:mm:ss'
    });
    $("#from-datepicker").on("change", function () {
        var fromdate = $(this).val();
        alert(fromdate);
    });
});

</code>```

Do you have any idea why I can't get the values and how can I solve it ?

答:
I'm not sure what you're trying to achieve, but I suppose you can do it with pure Blazor.  Maybe something like:</p>
```<code><input type="date" @onchange=HandledateChange />
<div>You selected: @date</div>

@code {
    string date = "";

    async Task HandledateChange(ChangeEventArgs args)
    {
        date = args.Value.ToString();
    }
}
</code>```

Title: DatePicker doesn't bind value in Blazor

Body:
I'm using date picker in my component to bind the value to my method in blazor. the value is always empty.

Here is my component :

  <input data-provide="datepicker" class="col-sm-2 form-control" @bind="date_selected" data-date-format="yyyy-mm-dd"
        style="width: 300x ;height:35px;">

code{
    string date_selected;

    public async Task GetTags()
    {
        AllTags = await Task.Run(() => tagsService.Map( date_selected));

    }

}

my java script :

$( document ).ready(function() {
    $("#from-datepicker").datepicker({
        format: 'yyyy-mm-dd HH:mm:ss'
    });
    $("#from-datepicker").on("change", function () {
        var fromdate = $(this).val();
        alert(fromdate);
    });
});

Do you have any idea why I can't get the values and how can I solve it ?

Body:
I'm not sure what you're trying to achieve, but I suppose you can do it with pure Blazor.  Maybe something like:

<input type="date" @onchange=HandledateChange />
<div>You selected: @date</div>

@code {
    string date = "";

    async Task HandledateChange(ChangeEventArgs args)
    {
        date = args.Value.ToString();
    }
}


问:
How to use "dateRestrict" parameter in Custom Search API
I am trying to modify some java code which uses the Google API. One of the features I have not been able to get is the dateRestrict. Information about this can be found here:

GoogleAPI

To implement this I attach the following string after my query. It is properly connected with the full URL because other parameters work with it.

String parameters = "&dateRestrict=2012-01-01";

I have also tried 1d and 1m but those don't work either as parameters

If someone could show me of an example of dateRestrict I would greatly appreciate it. I just don't understand how they mean to use it in the API. Thank you.

答:
I know question asked for this awhile ago, I had the same problem.

Use dateRestrict=d1 instead of dateRestrict=d[1]

The documentation made that a bit confusing. [] is used to show number as placeholder.

ContentLicense: CC BY-SA 3.0


问:
Connection is getting reset if I am doing a POST request
I am new to Node JS. Please help me to understand what am I doing wrong in the POST request. Sometimes my POST request is getting successfully resolved but sometimes it is giving me ECONNRESET.

I am sharing my app.js and file reader wrapper module.

GET is working perfectly fine.

Below is my App.js

```<code>const express = require('express');
const FileReader = require('./readFS');
const app = express();
const FS = new FileReader();

const port = 3000;
app.listen(3000, '127.0.0.1', () => {
  console.log(`App running on port ${port}`);
});
app.use(express.json());

app.get('/api/v1/tours', (request, response) => {
  const data = FS.read(`${__dirname}/dev-data/data/tours-simple.json`).then(
    (data) => {
      response.status(200).json({
        status: 'success',
        results: data.length,
        data: {
          tours: data,
        },
      });
    }
  );
});
app.post('/api/v1/tours', (request, response) => {
  (async (req, res) => {
    const tours = await FS.read(`${__dirname}/dev-data/data/tours-simple.json`);
    const newID = tours[tours.length - 1].id + 1;
    const newTour = Object.assign({ id: newID }, req.body);
    tours.push(newTour);
    console.log('File written Started');
    await FS.write(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours)
    );
    console.log('File written Successfully');
    res.status(200).send('Created Succesfully');
  })(request, response);
});
</code>```

File Reader Module:

```<code>
module.exports = class {
  constructor() {
    this.tours = [];
  }

  read(path) {
    return new Promise((resolve, reject) => {
      if (this.tours.length > 0) {
        resolve(this.tours);
      }
      fs.readFile(path, 'utf-8', (err, data) => {
        if (err) reject(er);
        this.tours = Object.assign(JSON.parse(data));
        resolve(this.tours);
      });
    });
  }
  write(path, data) {
    return new Promise((resolve, reject) => {
      if (data.length <= 0) reject('Data is empty');
      fs.writeFile(path, data, (err) => {
        if (err) reject('Could not write');
        resolve('Done');
      });
    });
  }
};
</code>```

答:
Explanation of the error I was encountering

My issue with occasionally receiving ECONNRESET when POSTing to my listening endpoint was caused by the endpoint automatically restarting after each successful POST of a file to that same endpoint.

Body:
I am new to Node JS. Please help me to understand what am I doing wrong in the POST request. Sometimes my POST request is getting successfully resolved but sometimes it is giving me ECONNRESET.

I am sharing my app.js and file reader wrapper module.

GET is working perfectly fine.

Below is my App.js

const express = require('express');
const FileReader = require('./readFS');
const app = express();
const FS = new FileReader();

const port = 3000;
app.listen(3000, '127.0.0.1', () => {
  console.log(`App running on port ${port}`);
});
app.use(express.json());

app.get('/api/v1/tours', (request, response) => {
  const data = FS.read(`${__dirname}/dev-data/data/tours-simple.json`).then(
    (data) => {
      response.status(200).json({
        status: 'success',
        results: data.length,
        data: {
          tours: data,
        },
      });
    }
  );
});
app.post('/api/v1/tours', (request, response) => {
  (async (req, res) => {
    const tours = await FS.read(`${__dirname}/dev-data/data/tours-simple.json`);
    const newID = tours[tours.length - 1].id + 1;
    const newTour = Object.assign({ id: newID }, req.body);
    tours.push(newTour);
    console.log('File written Started');
    await FS.write(
      `${__dirname}/dev-data/data/tours-simple.json`,
      JSON.stringify(tours)
    );
    console.log('File written Successfully');
    res.status(200).send('Created Succesfully');
  })(request, response);
});

File Reader Module:

module.exports = class {
  constructor() {
    this.tours = [];
  }

  read(path) {
    return new Promise((resolve, reject) => {
      if (this.tours.length > 0) {
        resolve(this.tours);
      }
      fs.readFile(path, 'utf-8', (err, data) => {
        if (err) reject(er);
        this.tours = Object.assign(JSON.parse(data));
        resolve(this.tours);
      });
    });
  }
  write(path, data) {
    return new Promise((resolve, reject) => {
      if (data.length <= 0) reject('Data is empty');
      fs.writeFile(path, data, (err) => {
        if (err) reject('Could not write');
        resolve('Done');
      });
    });
  }
};


问:
Group of objects with similar names
I have an object:

```<code>public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}
</code>```

I return a list that may look like the following:

```<code>var students = new List<Student>() {
                new Student(){ Id = 1, Name="Bill85"},
                new Student(){ Id = 2, Name="Bill66"},
                new Student(){ Id = 3, Name="Ram7895"},
                new Student(){ Id = 4, Name="Ram5566"},
                new Student(){ Id = 5, Name="Join1230"}
            };
</code>```

I want to group them together if they have similar names, to get the result like below, is there any quick way to solve this?

```<code>GroupStudentList
    UserList
        Id = 1, Name="Bill85"
        Id = 2, Name="Bill66"
    UserList
        Id = 3, Name="Ram7895"
        Id = 4, Name="Ram5566"
    UserList
        Id = 3, Name="Join1230"
</code>```

答:
Making the assumption that similar names refers to identical names when all digits are removed from each name (as suggested by @klaus-gütter), a simple implementation could be the following:

Group the students based on their Name, but stripped for digits (using Regex)

For each group of similarily named students, select the students in that group to constitute a sublist

resulting in a nested List of Students:

```<code>List<List<Student>> groupStudentList = students
    .GroupBy(
        s => Regex.Replace(s.Name, "[0-9]*", string.Empty),
        (similarName, students) => students.ToList())
    .ToList();
</code>```

The Regex expression above basically says "Replace all (if any) digits between 0 and 9 that exist in s.Name with an empty string". This means that if you have two students named "Tom1" and "T3o4m", they will also be grouped together -- because both names stripped for digits will be "Tom".

Optionally, you could create a UserList class:

```<code>public class UserList
{
    public List<Student> Students { get; set; }
}
</code>```

and create a UserList object for each grouping of students based on their name similarity:

```<code>List<UserList> groupStudentList = students
    .GroupBy(
        s => Regex.Replace(s.Name, "[0-9]*", string.Empty),
        (similarName, students) => new UserList { Students = students.ToList() })
    .ToList();
</code>```

Title: Group of objects with similar names

Body:
I have an object:

public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}

I return a list that may look like the following:

var students = new List<Student>() {
                new Student(){ Id = 1, Name="Bill85"},
                new Student(){ Id = 2, Name="Bill66"},
                new Student(){ Id = 3, Name="Ram7895"},
                new Student(){ Id = 4, Name="Ram5566"},
                new Student(){ Id = 5, Name="Join1230"}
            };

I want to group them together if they have similar names, to get the result like below, is there any quick way to solve this?

GroupStudentList
    UserList
        Id = 1, Name="Bill85"
        Id = 2, Name="Bill66"
    UserList
        Id = 3, Name="Ram7895"
        Id = 4, Name="Ram5566"
    UserList
        Id = 3, Name="Join1230"

Body:
Making the assumption that similar names refers to identical names when all digits are removed from each name (as suggested by @klaus-gütter), a simple implementation could be the following:

Group the students based on their Name, but stripped for digits (using Regex)

For each group of similarily named students, select the students in that group to constitute a sublist

resulting in a nested List of Students:

List<List<Student>> groupStudentList = students
    .GroupBy(
        s => Regex.Replace(s.Name, "[0-9]*", string.Empty),
        (similarName, students) => students.ToList())
    .ToList();

The Regex expression above basically says "Replace all (if any) digits between 0 and 9 that exist in s.Name with an empty string". This means that if you have two students named "Tom1" and "T3o4m", they will also be grouped together -- because both names stripped for digits will be "Tom".

Optionally, you could create a UserList class:

public class UserList
{
    public List<Student> Students { get; set; }
}

and create a UserList object for each grouping of students based on their name similarity:

List<UserList> groupStudentList = students
    .GroupBy(
        s => Regex.Replace(s.Name, "[0-9]*", string.Empty),
        (similarName, students) => new UserList { Students = students.ToList() })
    .ToList();


问:
How to copy table by spark-sql
Actually, I want to move one table to another database.
But spark don't permit this.

Then, how to copy table by spark-sql?

I already tried this.

```<code>SELECT *
INTO table1 IN new_database
FROM old_database.table1
</code>```

But it was not working.

答:
The following snippet will create a new table while preserving the definition of the "old" table.

```<code>CREATE TABLE db.new_table LIKE db.old_table;
</code>```

For more info, check the doc's CREATE TABLE.

Title: How to copy table by spark-sql

Body:
Actually, I want to move one table to another database.
But spark don't permit this.

Then, how to copy table by spark-sql?

I already tried this.

SELECT *
INTO table1 IN new_database
FROM old_database.table1

But it was not working.

Body:
The following snippet will create a new table while preserving the definition of the "old" table.

CREATE TABLE db.new_table LIKE db.old_table;

For more info, check the doc's CREATE TABLE.


问:
Merge dataframe rows in pandas
Hi I have a dataset like this:

ID
Gender
Group
Biomarker
Value

001
Male
Test
CA125
X1

001
Male
Test
CEA
X2

001
Male
Test
AFP
X3

002
Female
Control
CA125
X4

002
Female
Control
CEA
X5

002
Female
Control
AFP
X6

I want to merge all rows with the same id into a single row and change the column names to the biomarkers for example:

ID
Gender
Group
CA125
CEA
AFP

001
Male
Test
X1
X2
X3

002
Female
Control
X4
X5
X6

Some IDs might not have some of the biomarkers: I want them to have missing data in the final table***
Some IDs might have several values for a biomarker: I want them to have the minimum of the values

What should I do?

答:
You can use DataFrame.pivot() method

```<code>piv = df.pivot(index=['ID', 'Gender', 'Group'],
               columns='Biomarker',
               values='Value')\
               .reset_index()
</code>```

Title: Merge dataframe rows in pandas

Body:
You can use DataFrame.pivot() method

piv = df.pivot(index=['ID', 'Gender', 'Group'],
               columns='Biomarker',
               values='Value')\
               .reset_index()


问:
How to find how much bytes were sent on fetch request?
I am fetching data from different API with javascript's fetch API. But how can I find out how many bytes are sent on each request for analytics?

The request could be in any method.
I know that I can get the amount of bytes received with
response.headers["content-length"].
I need to find out a way to get the amount of bytes sent on the frontend (browser or mobile using React Native). Ideally, it would be the total size of the request, but just the size of the request body would be good enough.

答:
You can get the value that will be set in the Content-Length header by reading the Request's body as text and checking the length of the returned string:

(async () => {
  const formdata = new FormData();
  const file = new Blob(["data".repeat(1024)])
  formdata.append("key", file)
  const req = new Request("/", { method: "POST", body: formdata });
  // note that we .clone() the Request
  // so that we can still use the original one with fetch()
  console.log((await req.clone().text()).length);
  fetch(req);
  console.log("check the Network panel of your dev tools to see the sent header");
})();```

However this only applies for requests where this header is sent, i.e not for GET and HEAD requests.

Body:
You can get the value that will be set in the Content-Length header by reading the Request's body as text and checking the length of the returned string:

(async () => {
  const formdata = new FormData();
  const file = new Blob(["data".repeat(1024)])
  formdata.append("key", file)
  const req = new Request("/", { method: "POST", body: formdata });
  // note that we .clone() the Request
  // so that we can still use the original one with fetch()
  console.log((await req.clone().text()).length);
  fetch(req);
  console.log("check the Network panel of your dev tools to see the sent header");
})();

However this only applies for requests where this header is sent, i.e not for GET and HEAD requests.


问:
Change Mediaquery response
I'm starting my studies in fullstack and we were just shown bootstrap. I'm doing this site responsive, and I modified the menu bar to my please. The only thing I'd like to change is the menu to colapse into the toggle button only below 600px-ish wide (aka for phones). Any assistance will be appreciated
html</p>
```<code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="#"></a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarScroll">
      <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Inicio</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Academia</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#">Tienda</a>
        <li class="nav-item">
            <a class="nav-link" href="#">Nosotros</a>
        <li class="nav-item">
            <a class="nav-link" href="#">Contacto</a>
      </ul>
    </div>
  </div>
</nav>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</code>```

答: As mentioned in the How it works section of Bootstrap navbar documentation, you can use navbar-expand-sm instead of navbar-expand-lg. This will collapse the navbar only on screens smaller than 576px(sm).

Title: Change Mediaquery response

Body:
I'm starting my studies in fullstack and we were just shown bootstrap. I'm doing this site responsive, and I modified the menu bar to my please. The only thing I'd like to change is the menu to colapse into the toggle button only below 600px-ish wide (aka for phones). Any assistance will be appreciated
html

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

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

    </button>

          Inicio

          Academia

            Tienda

            Nosotros

            Contacto


问:
Bitbucket pipeline zipped files without directories
This is my script:

```<code>image: python:3.5.7

pipelines:
  default:
    - step:
        script:
          - apt-get update
          - apt-get -qq install zip curl
          - mkdir $BITBUCKET_REPO_SLUG

          - export VERSION_LABEL=$(date +%Y-%m-%d_%H:%M:%S)
          - export ZIP_FILE=update_$BITBUCKET_REPO_SLUG_$VERSION_LABEL.zip
          - export FILES=$(git diff-tree --no-commit-id --name-only -r HEAD^^..HEAD)

          - echo "Repo name is $BITBUCKET_REPO_SLUG & version is $VERSION_LABEL"
          - echo $FILES

          - cp -R $FILES $BITBUCKET_REPO_SLUG/

          - rm -f $BITBUCKET_REPO_SLUG/bitbucket-pipelines.yml
          - rm -f $BITBUCKET_REPO_SLUG/.gitignore

          - zip -r $ZIP_FILE $BITBUCKET_REPO_SLUG/
</code>```

Why all files in zip are in root and not in directories as I see then when I echo them?
What is the problem?

答:
I don't exactly understand your question but my first impression is it can be a relative path/full path situation. Bitbucket pipelines are using a standard directory something line /opt/atlassian/pipelines/agent/build to pull the code.  This variable can be extracted by using BITBUCKET_CLONE_DIR built-in variable, Maybe you can try to combine this variable with your relative path to create your directory. something like mkdir -p $BITBUCKET_CLONE_DIR/$BITBUCKET_REPO_SLUG can be useful.

Reference : https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/

Body:
This is my script:

image: python:3.5.7

pipelines:
  default:
    - step:
        script:
          - apt-get update
          - apt-get -qq install zip curl
          - mkdir $BITBUCKET_REPO_SLUG

          - export VERSION_LABEL=$(date +%Y-%m-%d_%H:%M:%S)
          - export ZIP_FILE=update_$BITBUCKET_REPO_SLUG_$VERSION_LABEL.zip
          - export FILES=$(git diff-tree --no-commit-id --name-only -r HEAD^^..HEAD)

          - echo "Repo name is $BITBUCKET_REPO_SLUG & version is $VERSION_LABEL"
          - echo $FILES

          - cp -R $FILES $BITBUCKET_REPO_SLUG/

          - rm -f $BITBUCKET_REPO_SLUG/bitbucket-pipelines.yml
          - rm -f $BITBUCKET_REPO_SLUG/.gitignore

          - zip -r $ZIP_FILE $BITBUCKET_REPO_SLUG/

Why all files in zip are in root and not in directories as I see then when I echo them?
What is the problem?


问:
does showModalDialog interfere with ClientScript.RegisterStartupScript?
I'm showing a modal dialog via "window.showModalDialog(..." which happens in a vbscript function (the page shown is aspx). I'd like to do some resizing of the window based on the number of rows in a datatable that's coming back. So naturally I go to register a startup script that resizes the window based on the number of rows. Well, that didn't work, so I tried to register a script that just showed a msgbox.

The code looks like (in the OnLoad event handler):

```<code> if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
        {
            this.ClientScript.RegisterStartupScript(typeof(MyPageClassName), "hello",
                    @"<script language=vbscript>
                        sub fnWindowOnLoad()
                            MsgBox ""hello""
                        end sub
                        <script>", false);
        }
        if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
        {
            throw new Exception("Failed to load script");
        }
</code>```

To me it looks like this should work and show a message box that says "hello" when the page loads (I've got the window's onload event set to fnWindowOnLoad). But what happens is nothing, no exception, no alert. I've tried every Type I could think of in the typeof call. Nothing seems to work. The only thing I can think of is that since the dialog is a modal ClientScript.RegisterStartupScript won't run properly. But that doesn't make any sense to me.

I put the MsgBox "hello" call into my script block directly and the alert showed, so it's possible. But I need to modify some arguments in the code behind so I have to use RegisterStartupScript as far as I can tell.

答:
Have you tried opening your window via window.open() rather than window.showModalDialog()? I've seen some postings on the web about incompatibilities between showModalDialog() and RegisterStartupScript.

showModalDialog() is an IE only method, so it's not recommended anyway. I know it's convenient because it returns a value, but there are various ways to simulate this functionality.

Edit: The other problem with showModalDialog() is that IE often caches the results. This means that if one time you calling the dialog, you do not resize it, then another time you do, then 2nd time might get your the first cached dialog. A way to get around this is to add a unique querystring at the end. Like MyDialog.aspx?q=320934 (randomly generated or generated based on server tics).

OwnerDisplayName: jcollum

ContentLicense: CC BY-SA 2.5

Body:
I'm showing a modal dialog via "window.showModalDialog(..." which happens in a vbscript function (the page shown is aspx). I'd like to do some resizing of the window based on the number of rows in a datatable that's coming back. So naturally I go to register a startup script that resizes the window based on the number of rows. Well, that didn't work, so I tried to register a script that just showed a msgbox.

The code looks like (in the OnLoad event handler):

 if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
        {
            this.ClientScript.RegisterStartupScript(typeof(MyPageClassName), "hello",
                    @"

LastEditorDisplayName: Keltex

OwnerDisplayName: Keltex


问:
Adding a new column to a list of data frames and then 'unlist' with names intact?
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

```<code>for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
</code>```

I want to add another column z to each of these dfs.

```<code>z <- rep("hello",10)

</code>```

How can I accomplish this?

Using lapply I have been able to do this

```<code>q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)
</code>```

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance

答:
Functionally the same as @jay.sf's answer, slightly more verbose/more lines of code, but perhaps easier to understand using transform().

# create dataframes
for (i in 1:10) {
  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}

# store dataframes into a list (only objects starting with df_)
df_list <- mget(ls(pattern="^df_"))

# add new column to each dataframe
lapply(df_list, \(x) transform(x, z = rep("hello", 10)))
```

Body:
I have a number of dfs to which I want to add a column.
For the sake of a mrp, these dfs are called df_1, df_2, df_3...

for (i in 1:10) {
assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}

I want to add another column z to each of these dfs.

z <- rep("hello",10)

How can I accomplish this?

Using lapply I have been able to do this

q <- list()
for (i in 1:10) {
q[[i]] <-  assign(paste("df_",i,sep = ""),data.frame(x = rep(1,10), y  = rep(2,10)))
}
z <- rep("hello",10)
q <- lapply(q, cbind,z)

This adds the required column, however, I don't know how to preserve the names. How can I still have df_1, df_2, etc but each with a new column z?

Thanks in advance


问:
c++ test if random number is positive or negative
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)</p>
```<code>#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}
</code>```

答:
Consider this sample code:

```<code>#include <iostream>
#include <string>

bool is_positive(int number)
{
    if (number >= 0) return true; // Positive number or 0
    else return false; // Negative number
}

int main()
{
    std::srand(time(0));

    for (int i = 0; i < 17; i++)
    {
        int number = std::rand() % 20 + -10;

        if (is_positive(number))
        {
            std::cout << number << " is positive" << std::endl;
        }
        else
        {
            std::cout << number << " is negative" << std::endl;
        }
    }
}
</code>```

Here I have defined a function is_positive that returns true if the number is greater than or equal to 0 else it returns false. I have also shown a simple implementation of the function.

Body:
I have school work with C++ and Im new to it. I have to generate 17 random numbers and then test if they are positive/negative/equal to zero. I can't seem to find a way to take the random generated number from the for loop to test it in the if/else if loop. Heeeeelp please :D (The b variable is just there from tests)

#include <ctime>
using namespace std;
int main() {

    srand(
          (unsigned) time(0)
    );

    int a;
    int b;
    int num;

    for(int a = 0; a<17; a++) {
        cout << "Skaitlis: " << rand()% 20 + -10 << "\n";

        if(b > 0){
            cout << b << " is a positive number." << endl;
        }
        else if (b == 0){
            cout << b << " is equal to zero." << endl;
        }
        else {
            cout << b << " is a negative number." << endl;
        }
   }
}

Body:
Consider this sample code:

#include <iostream>
#include <string>

bool is_positive(int number)
{
    if (number >= 0) return true; // Positive number or 0
    else return false; // Negative number
}

int main()
{
    std::srand(time(0));

    for (int i = 0; i < 17; i++)
    {
        int number = std::rand() % 20 + -10;

        if (is_positive(number))
        {
            std::cout << number << " is positive" << std::endl;
        }
        else
        {
            std::cout << number << " is negative" << std::endl;
        }
    }
}

Here I have defined a function is_positive that returns true if the number is greater than or equal to 0 else it returns false. I have also shown a simple implementation of the function.


问:
What is the hotkey in Xcode to open the function list & MARKs list in the current file editor
Instead of mouse clicking the section in Red box here, is there a hotkey for it in XCode?

答:
control-6.

Everything in that bar is found in the View➡Editor menu.

"Hotkey" is a Microsoft term. They are called "keyboard shortcuts" in the Apple ecosystem.


问:
Call destructor upon manual termination of the program
Suppose I have an instance of a class. Will the destructor be called automatically if I terminate the program manually (say, by pressing the cross icon in the CLI window)? If not, is there any option to make the destructor be called upon manual termination of the program?</p>

答:
This is not specified by the C++ standard. What happens depends entirely on your operating system, and your program.

However, nothing that happens in your program should be a big mystery of this kind. What happens with your program is controlled entirely by your program's logic.

So, you simply need to answer the following question, by yourself: did you write any code in your program, yourself, that explicitly checks if this close button is pushed, and if so your program performs an orderly termination, returning from main, and destroying all objects, including the one you are asking about?

So unless you've actually written any code to that effect, it is not going to happen. Your operating system will kill the process and it immediately stops.

If not, is there any option to make the destructor be called upon
manual termination of the program?

There's certainly a way to do that, this sounds like fairly basic task. You'll just have to actually write the code to do that. How to do that depends entirely on your operating system, and your operating system libraries. There is no single answer to this question that applies to every operating system in the world, from MS-Windows, to Mac OSX to Linux. Each one of these does it in their own way, and there are often different operating system libraries, where this task would be implemented in its own way.

Consult your operating system's development libraries for more information.


问:
Command doesn't work after upgrade flutter
Due to min v1.5 sdk  plugin needs, I use flutter upgrade, but since I can't use command ... I have bash command not found,

I tried manually download 1.5 sdk and replace previous folder, when I use flutter doctor He say I have 1.2.1 ... I tried to re-upgrade but I have this error :

```<code>Your flutter checkout has local changes that would be erased by upgrading. If you want to keep these changes, it is
recommended that you stash them via "git stash" or else commit the changes to a local branch. If it is okay to remove
local changes, then re-run this command with --force.

C:\Users\utilisateur>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [version 10.0.17134.829], locale fr-FR)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[!] VS Code, 64-bit edition (version 1.21.1)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (1 available)

! Doctor found issues in 1 category.
</code>```

I tried git clean -xfd

i have ...

```<code>C:\Users\utilisateur>git clean -xfd
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again?
(y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? (y/ngit stash save --keep-index
) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try againgit stash save --keep-index
? (y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? git stash save --keep-index
(y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? (y/n)
</code>```

答:
Press Windows+R to open the Run window.

Type cmd into the box.

Press Ctrl+Shift+Enter.

```<code>C:\>choco upgrade dart-sdk
</code>```

Note: Make sure you open cmd with Admin permission

Body:
Due to min v1.5 sdk  plugin needs, I use flutter upgrade, but since I can't use command ... I have bash command not found,

I tried manually download 1.5 sdk and replace previous folder, when I use flutter doctor He say I have 1.2.1 ... I tried to re-upgrade but I have this error :

Your flutter checkout has local changes that would be erased by upgrading. If you want to keep these changes, it is
recommended that you stash them via "git stash" or else commit the changes to a local branch. If it is okay to remove
local changes, then re-run this command with --force.

C:\Users\utilisateur>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [version 10.0.17134.829], locale fr-FR)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[!] VS Code, 64-bit edition (version 1.21.1)
    X Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (1 available)

! Doctor found issues in 1 category.

I tried git clean -xfd

i have ...

C:\Users\utilisateur>git clean -xfd
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again?
(y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? (y/ngit stash save --keep-index
) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try againgit stash save --keep-index
? (y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? git stash save --keep-index
(y/n) Sorry, I did not understand your answer. Please type 'y' or 'n'
Unlink of file '.AndroidStudio3.3/config/plugins/Dart/lib/Dart.jar' failed. Should I try again? (y/n)

Body:
Press Windows+R to open the Run window.

Type cmd into the box.

Press Ctrl+Shift+Enter.

C:\>choco upgrade dart-sdk

Note: Make sure you open cmd with Admin permission


问:
boto3 client NoRegionError: You must specify a region error only sometimes
I have a boto3 client :

```<code>boto3.client('kms')
</code>```

But it happens on new machines, They open and close dynamically.

```<code>    if endpoint is None:
        if region_name is None:
            # Raise a more specific error message that will give
            # better guidance to the user what needs to happen.
            raise NoRegionError()
</code>```

Why is this happening? and why only part of the time?

答:
If you are using lambdas, then you would likely want to use the region the lambda is deployed in.
You can use the following</p>
```<code>import boto3
import json
import os

def lambda_handler(event, context):
    region = os.environ['AWS_REGION']
    print('Lambda region: ', region)
    kms = boto3.client('kms', region_name=region)
</code>```

Body:
I have a boto3 client :

boto3.client('kms')

But it happens on new machines, They open and close dynamically.

    if endpoint is None:
        if region_name is None:
            # Raise a more specific error message that will give
            # better guidance to the user what needs to happen.
            raise NoRegionError()

Why is this happening? and why only part of the time?

Body:
If you are using lambdas, then you would likely want to use the region the lambda is deployed in.
You can use the following

import boto3
import json
import os

def lambda_handler(event, context):
    region = os.environ['AWS_REGION']
    print('Lambda region: ', region)
    kms = boto3.client('kms', region_name=region)


问:
Property 'forRoot' does not exist on type 'typeof NgbModule'.ts(2339)

```<code>{
    "resource": "/c:/Users/Karthick_Aadhi/example/src/app/app.module.ts",
    "owner": "typescript",
    "code": "2339",
    "severity": 8,
    "message": "Property 'forRoot' does not exist on type 'typeof NgbModule'.",
    "source": "ts",
    "startLineNumber": 15,
    "startColumn": 15,
    "endLineNumber": 15,
    "endColumn": 22
}
</code>```

答:
In latest bootstrap version:

NgbModule.forRoot() Reaplace  NgbModule

So, you can used NgbModule instead of NgbModule.forRoot() without any issue.


问:
LeafletMap is showing error even after importing the leaflet package in react js
I was working on a covid application which shows covid mortality rate during all the three waves, particularly for my country India, but here the issue is while I'm trying to use leaflet package, its showing an error

import React from "react";
import { Map as LeafletMap, TileLayer } from "react-leaflet";
import "./Map.css";
import { showDataOnMap } from "./util";

function Map({ countries, casesType, center, zoom }) {
  return (

      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© OpenStreetMap contributors'
        />
        {showDataOnMap(countries, casesType)}
      </LeafletMap>

  );
}

export default Map;```

this package name: Map.js

even I had run the cmd in the terminal which imports the leaflet: npm i react-leaflet, but it is still showing error, please help anyone

This is localhost error which it is showing

答:
Problem is that you're trying to export function Map which has the same name as Map you assigned to LeafletMap, try to change your function name, for instance</p>
```<code>import React from "react";
import { Map as LeafletMap, TileLayer } from "react-leaflet";
import "./Map.css";
import { showDataOnMap } from "./util";

function NewMap({ countries, casesType, center, zoom }) {
  return (
    <div className="map">
      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        {showDataOnMap(countries, casesType)}
      </LeafletMap>
    </div>
  );
}

export default NewMap;
</code>```

Body:
I was working on a covid application which shows covid mortality rate during all the three waves, particularly for my country India, but here the issue is while I'm trying to use leaflet package, its showing an error

import React from "react";
import { Map as LeafletMap, TileLayer } from "react-leaflet";
import "./Map.css";
import { showDataOnMap } from "./util";

function Map({ countries, casesType, center, zoom }) {
  return (

      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='© OpenStreetMap contributors'
        />
        {showDataOnMap(countries, casesType)}
      </LeafletMap>

  );
}

export default Map;

this package name: Map.js

even I had run the cmd in the terminal which imports the leaflet: npm i react-leaflet, but it is still showing error, please help anyone

This is localhost error which it is showing

Body:
Problem is that you're trying to export function Map which has the same name as Map you assigned to LeafletMap, try to change your function name, for instance

import React from "react";
import { Map as LeafletMap, TileLayer } from "react-leaflet";
import "./Map.css";
import { showDataOnMap } from "./util";

function NewMap({ countries, casesType, center, zoom }) {
  return (
    <div className="map">
      <LeafletMap center={center} zoom={zoom}>
        <TileLayer
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        {showDataOnMap(countries, casesType)}
      </LeafletMap>
    </div>
  );
}

export default NewMap;


问:
How to stream semi-live audio over internet
I want to write something like Skype, i.e. I have a constant audio stream on one computer and then recompress it in a format that's suitable for a latent internet connection, receive it on the other end and play it.

Let's also assume that the internet connection is fairly modern and fast, i.e. DSL or alike, no slow connections over phone and such. The involved computers will also be rather modern (Dual Core Intel CPUs at 2GHz or more).

I know how to handle the audio on the machines. What I don't know is how to transmit the audio in an efficient way.

The challenges are:

I'd like get good audio quality across the line.

The stream should be received without drops. The stream may, however, be received with a little delay (a second delay is acceptable). I imagine that the transport software could first determine the average (and max) latency, then start the stream and tell the receiver to wait for that max latency before starting to play the audio. With that, if the latency doesn't get any higher, the entire stream will be playable on the other side without stutter or drops.

If, due to unexpected IP latencies or blockages, the stream does get cut off, I want to be able to notice this so that I can take actions (e.g. abort the stream) and eventually start a new transmission.

What are my options if I want do use ready-made software for the compression and tranmission? I have no intention to write my own audio compression engine, really. OTOH, I plan to sell the solution in a vertical market, meaning I can afford a few dollars of license fees per copy, but not $100s.

I guess the simplest solution would be to just open a TCP stream, send a few packets back and forth to determine their running time (or even use UDP for that), then use the results as the guide for my max latency value, then simply fire the audio data in its raw form (uncompressed 16 bit stereo), along with a timing code over the TCP connection. The receiver reads the data and plays it with the pre-determined delay. That might just work with the type of fast connection I expect.

I just wonder if there are better solutions to reach this goal, with better performance (lower latency) and less data (compressed).

BTW, I first try to implement this on OS X, but might want to do it on Windows, too, if it proves successful.

答: ShoutCAST + SAM Broadcaster or Winamp. Will do the trick easily.</p>

OwnerDisplayName: Thomas Tempelmann


问:
Array.contains in Firestore rules
How to use the JS native array.contains in Firestore rules?

function isCool() {
  return [
    'xxx',
    'yyy',
  ].contains(req.auth.uid)
}
```

The function above gives an error

答:
You are looking for in operator:

function isCool() {
  return request.auth.uid in ['xxx', 'yyy'];
}
```

It returns true if the value is present in the given list/array.

Title: Array.contains in Firestore rules

Body:
How to use the JS native array.contains in Firestore rules?

function isCool() {
  return [
    'xxx',
    'yyy',
  ].contains(req.auth.uid)
}

The function above gives an error

Body:
You are looking for in operator:

function isCool() {
  return request.auth.uid in ['xxx', 'yyy'];
}

It returns true if the value is present in the given list/array.


问:
ArangoDB crashes while arangorestore.exe

To reproduce:

Have corrupted database (I think it's the same-time writing issue for non waitForSync collection)

Use arangodump.exe

Use arangorestore.exe (Service arangod.exe stops working while run)

Get Arangod.exe crashed after trying to launch the service

To make backup I were ignoring some collection using --maskings option and rule set. I have gotten an error if I weren't.
To restore the data I did use stable and also nightly, the latest versions of ArangoDB server.

There is not much useful info for the deeper log level.

Also happens for another win10 computer. And can't be run on linux (wsl debian) because my computer's processor doesn't support sse 4.2 or higher

答: Older version 3.8.5-1 works fine! (upgraded my previous version 3.8.1)


问:
How do I solve this django-private-chat error?
so I've been trying to implement django-private-chat into an existing problem but always encountered an error. So, I tried to run the example project found on under django-private-chat on Github and I received the same error. Thanks for the help!</p>

```<code>    25.04.20 10:45:49:ERROR:Error in connection handler
Traceback (most recent call last):
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/websockets/server.py", line 191, in handler
    await self.ws_handler(self, path)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/handlers.py", line 259, in main_handler
    user_owner = get_user_from_session(session_id)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/utils.py", line 15, in get_user_from_session
    session = Session.objects.get(session_key=session_key)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get
    num = len(clone)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 258, in __len__
    self._fetch_all()
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql
    cursor = self.connection.cursor()
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
25.04.20 10:45:49:DEBUG:server ! failing OPEN WebSocket connection with code 1011
25.04.20 10:45:49:DEBUG:server - state = CLOSING
25.04.20 10:45:49:DEBUG:server > Frame(fin=True, opcode=8, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False)
25.04.20 10:45:49:DEBUG:server x half-closing TCP connection
25.04.20 10:45:49:DEBUG:server - event = connection_lost(None)
25.04.20 10:45:49:DEBUG:server - state = CLOSED
25.04.20 10:45:49:DEBUG:server x code = 1006, reason = [no reason]
</code>```

答: Django Private Chat2 supports upto django 4</p>

Body:
so I've been trying to implement django-private-chat into an existing problem but always encountered an error. So, I tried to run the example project found on under django-private-chat on Github and I received the same error. Thanks for the help!

    25.04.20 10:45:49:ERROR:Error in connection handler
Traceback (most recent call last):
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/websockets/server.py", line 191, in handler
    await self.ws_handler(self, path)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/handlers.py", line 259, in main_handler
    user_owner = get_user_from_session(session_id)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django_private_chat/utils.py", line 15, in get_user_from_session
    session = Session.objects.get(session_key=session_key)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get
    num = len(clone)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 258, in __len__
    self._fetch_all()
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1142, in execute_sql
    cursor = self.connection.cursor()
  File "/opt/anaconda3/envs/testEnv/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
25.04.20 10:45:49:DEBUG:server ! failing OPEN WebSocket connection with code 1011
25.04.20 10:45:49:DEBUG:server - state = CLOSING
25.04.20 10:45:49:DEBUG:server > Frame(fin=True, opcode=8, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False)
25.04.20 10:45:49:DEBUG:server x half-closing TCP connection
25.04.20 10:45:49:DEBUG:server - event = connection_lost(None)
25.04.20 10:45:49:DEBUG:server - state = CLOSED
25.04.20 10:45:49:DEBUG:server x code = 1006, reason = [no reason]


问:
Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"
I followed the Maven tutorial to the letter but I still can't get Maven installed on Windows.

When I run the following in command prompt:

```<code>E:\Documents and Settings\zach>mvn --version
</code>```

I get:

```<code>'mvn' is not recognized as an internal or external command, operable program or batch file.
</code>```

I navigated to the maven install folder and ran mvn --version and got:

```<code>E:\java resources\apache-maven-2.2.0\bin>mvn --version
ERROR: JAVA_HOME is set to an invalid directory.
JAVA_HOME = "E:\Sun\SDK\jdk\bin"
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation
</code>```

but when I run java -version I get:

```<code>java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode)
</code>```

So I do have Java installed. Anyone know what the problem is?

答:
I ran into this issue with a Grails install.

The problem was my JAVA_HOME was c:\sun\jdk\ and my PATH has %JAVA_HOME%bin

I changed it to: JAVA_HOME= "c:\sun\jdk" and PATH="%JAVA_HOME%\bin"

It worked after that.

Body:
I followed the Maven tutorial to the letter but I still can't get Maven installed on Windows.

When I run the following in command prompt:

E:\Documents and Settings\zach>mvn --version

I get:

'mvn' is not recognized as an internal or external command, operable program or batch file.

I navigated to the maven install folder and ran mvn --version and got:

E:\java resources\apache-maven-2.2.0\bin>mvn --version
ERROR: JAVA_HOME is set to an invalid directory.
JAVA_HOME = "E:\Sun\SDK\jdk\bin"
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation

but when I run java -version I get:

java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Client VM (build 14.0-b16, mixed mode)

So I do have Java installed. Anyone know what the problem is?


问:
How can i run script in firebase automatically
I made an App and I want delete a story automatically after 24 hours. I can make it, but user should open app to check.

Now how can i check from firebase server without open app? I think it something like run script in server without stop.

I use firebase realtime database

答:
You can use Firebase's Cloud Functions

Schedule Functions on an interval to delete a story:

```<code>exports.scheduledFunction = functions.pubsub.schedule('every 5
minutes').onRun((context) => {
  // your code to delete something
  console.log('This will be run every 5 minutes!');
  return null;
});
</code>```

Reference to scheduling Cloud Functions:

https://firebase.google.com/docs/functions/schedule-functions

Body:
You can use Firebase's Cloud Functions

Schedule Functions on an interval to delete a story:

exports.scheduledFunction = functions.pubsub.schedule('every 5
minutes').onRun((context) => {
  // your code to delete something
  console.log('This will be run every 5 minutes!');
  return null;
});

Reference to scheduling Cloud Functions:

https://firebase.google.com/docs/functions/schedule-functions


问:
What would make a printk not show up immediately in dmesg?
I am making a Linux kernel module on Ubuntu 4.14.12.

My understanding of printk() is that it is guaranteed to output to console immediately before the next line of code is run, rather than having its output placed on a buffer that is eventually flushed at some point. Is this correct?

I was getting a crash that occurred several hundred lines after multiple printk calls whose output did not appear in dmesg using the -wH command or in dmesg sent through tee to a file which I read after rebooting.

Is there lag between the time a printk is sent to console and it shows up in dmesg that would allow my system to freeze up before I saw the output? Or is there something else occurring?

dmesg shows the printks in question after fixing the problematic line of code. The console log level was set higher than the console log level of the printks in question.

答: I have a similar situation. It's good when I add '\n' at end of msg.</p>


问:
App runs smoothly on emulators but crashes on real device
I am beginner to android studio, currently i am working on an Video calling app. My app runs smoothly on multiple emulators in android studio but when i try to run it on real device (Oppo f9 pro) through USB Debugging, the app get installs but crashes immediately.

There are several errors in logcat. I searched about every error on google but didn't found any solution. The following are errors in logcat.

2021-12-14 20:23:12.541 2314-2314/? E/com.ahmad.nexo: Unknown bits set in runtime_flags: 0x8000
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: >>> msg's executing time is too long
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: Blocked msg = { when=-2s417ms what=110 target=android.app.ActivityThread$H obj=AppBindData{appInfo=ApplicationInfo{cc71d2b com.ahmad.nexon}} } , cost  = 2390 ms
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: >>>Current msg List is:
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <1>  = { when=-2s413ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <2>  = { when=-2s411ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.998 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <3>  = { when=-2s396ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <4>  = { when=-2s394ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <5>  = { when=-2s392ms what=9999 target=android.app.ActivityThread$H }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <6>  = { when=-2s353ms what=149 target=android.app.ActivityThread$H obj=android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <7>  = { when=-2s348ms what=0 target=android.app.ActivityThread$H callback=com.android.internal.util.function.pooled.PooledLambdaImpl }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <8>  = { when=-1s886ms what=159 target=android.app.ActivityThread$H obj=ClientTransaction hashCode, mActivityToken = android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <9>  = { when=-1s886ms what=137 target=android.app.ActivityThread$H arg1=1 obj=android.os.BinderProxy@5ecb588 }
2021-12-14 20:23:14.999 2314-2314/com.ahmad.nexon E/ANR_LOG: Current msg <10>  = { when=+980ms what=131 target=android.app.ActivityThread$H obj=android.app.ActivityThread$ProviderRefCount@448eb21 }
2021-12-14 20:23:15.000 2314-2314/com.ahmad.nexon E/ANR_LOG: >>>CURRENT MSG DUMP OVER<<<
```

答:
The problem was with angle attribute. For example if you use angle of 112 or 100 or 130 etc that will crash your app. Always use angle dividable on 45  for example android:angle="90"
android:angle="180"
etc.</p>


问:
Hide or show navbar in ReactJS?
I was wondering how to change the navbar behavior based on the webpage position. I've seen a lot of tutorials about how to hide/show a navbar on scroll, which vie managed to implement successfully, however that seems to just cover two states. I would like my navbar to have three: show when I scroll up, hide when I scroll down, and change opacity if I'm at the top of the website. I've tried using a variety of useEffects and event listeners but I'm quite new to react and js.

Here's a good example of the effect I'm looking for https://brittanychiang.com/. As you can see once you are at the top of the webpage the opacity changes as well as the drop shadow, it all seems to be 'stuck' at the top instead of the floating look when you scroll up/down. Using dev tools I've found that the navbar class does seem to have three different names depending on the location of the scrollbar.

Thanks in advance!

答:
use blank array in useEffect to run it once when mounted

then use one state to set as (top,down,up) from window scroll event

working demo

js

```<code>export function headerSystem(){
    const [hState,sethState] = useState("top")

    useEffect(()=>{
        var lastVal = 0
        window.onscroll = function(){
            let y = window.scrollY
            if(y > lastVal){sethState("down")}
            if(y < lastVal) {sethState("up")}
            if(y === 0) {sethState("top")}
            lastVal = y
        }
    },[])

    return (
        <div className="root">
            <div className={"header text-center p-4 bg-blue-200 fixed w-full text-lg font-semibold " + hState}>this is header</div>
            <div className="pageContent bg-green-500">
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
            </div>
        </div>
    )
}
</code>```

css

```<code>  .header {
    background: rgba(0, 0, 0, 0);
    transition: all 0.3s ease;
  }

  .top {
    top: 0px;
  }

  .down {
    top: -80px;
  }

  .up {
    top: 0px;
  }

  .up,
  .down {
    background: rgba(0, 255, 242, 0.363);
    box-shadow: 0px 0px 5px black;
    padding: 8px;
  }
</code>```

Title: Hide or show navbar in ReactJS?

Body:
use blank array in useEffect to run it once when mounted

then use one state to set as (top,down,up) from window scroll event

working demo

js

export function headerSystem(){
    const [hState,sethState] = useState("top")

    useEffect(()=>{
        var lastVal = 0
        window.onscroll = function(){
            let y = window.scrollY
            if(y > lastVal){sethState("down")}
            if(y < lastVal) {sethState("up")}
            if(y === 0) {sethState("top")}
            lastVal = y
        }
    },[])

    return (
        <div className="root">
            <div className={"header text-center p-4 bg-blue-200 fixed w-full text-lg font-semibold " + hState}>this is header</div>
            <div className="pageContent bg-green-500">
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
                <div className="each h-screen"></div>
            </div>
        </div>
    )
}

css

  .header {
    background: rgba(0, 0, 0, 0);
    transition: all 0.3s ease;
  }

  .top {
    top: 0px;
  }

  .down {
    top: -80px;
  }

  .up {
    top: 0px;
  }

  .up,
  .down {
    background: rgba(0, 255, 242, 0.363);
    box-shadow: 0px 0px 5px black;
    padding: 8px;
  }


问:
Convert hex string to long
Are there any Cocoa classes that will help me convert a hex value in a NSString like 0x12FA to a long or NSNumber?  It doesn't look like any of the classes like NSNumberFormatter support hex numbers.

Thanks,
Hua-Ying

答:
here is the other way conversion,  a long long int to hex string.

first the hex to long long.

```<code>NSString* pString = @"ffffb382ddfe";
NSScanner* pScanner = [NSScanner scannerWithString: pString];

unsigned long long iValue2;
[pScanner scanHexLongLong: &iValue2];

NSLog(@"iValue2 = %lld", iValue2);
</code>```

and the other way,  longlong to hex string...

```<code>NSNumber *number;
NSString *hexString;

number = [NSNumber numberWithLongLong:iValue2];
hexString = [NSString stringWithFormat:@"%qx", [number longLongValue]];

NSLog(@"hexString = %@", hexString);
</code>```

Title: Convert hex string to long

Body:
here is the other way conversion,  a long long int to hex string.

first the hex to long long.

NSString* pString = @"ffffb382ddfe";
NSScanner* pScanner = [NSScanner scannerWithString: pString];

unsigned long long iValue2;
[pScanner scanHexLongLong: &iValue2];

NSLog(@"iValue2 = %lld", iValue2);

and the other way,  longlong to hex string...

NSNumber *number;
NSString *hexString;

number = [NSNumber numberWithLongLong:iValue2];
hexString = [NSString stringWithFormat:@"%qx", [number longLongValue]];

NSLog(@"hexString = %@", hexString);


问:
export a concatenated range of valued cells into text file
I want to export my concatenated range of valued cells into the text file.
Firstly, I input the data as below

Then, I concatenated into the different tab so-called 'Output2' :

and the coding so that the value depicted from concatenated cells will be exported into a desired text file as below:

```<code>Private Sub CommandButton1_Click()
Dim filename As String
Dim lineText As String
Dim my_range As Range

filename = ThisWorkbook.Path & "\File EFT" & Format(Now, "_ddmmyy") & ".txt"
Open filename For Output As #1
Set my_range = Worksheets("Output2").Range("B2")
For i = 1 To my_range.Rows.Count
For j = 1 To my_range.Columns.Count
lineText = IIf(j = 1, "", lineText & ",") & my_range.Cells(i, j)

Next j
Print #1, lineText

Next i
Close #1

MsgBox ("File is Generated")

End Sub
</code>```

I have a problem now which the text file only appeared at the first line. What I need is, a command which, as and when I input the value, say up to 10 rows, so it will be exported as 10 rows at text file as what I needed and later if I addon another input into 35 rows, the exported text file showing 35 lines

答:
Option Explicit
Private Sub CommandButton1_Click()

    Dim ar, n As Long, filename As String

    With Sheets("Input")
        ' determine number of rows
        n = .Cells(.Rows.Count, "A").End(xlUp).Row - 1
    End with

    With Sheets("Output2")
        If n = 0 Then
             MsgBox "No Data", vbCritical
             Exit Sub
        ElseIf n = 1 Then
             ReDim ar(0)
             ar(0) = .Range("B2").Value2
        Else
             ar = Application.Transpose(.Range("B2").Resize(n))
        End If
    End With

    ' text file
    filename = ThisWorkbook.Path & "\File EFT" & Format(Now, "_ddmmyy") & ".txt"

    With CreateObject("Scripting.FileSystemObject").CreateTextFile(filename)
       .writeline Join(ar, vbCrLf)
       .Close
    End With

    MsgBox n & " lines exported to " & filename, vbInformation
End Sub
```

Body:
I want to export my concatenated range of valued cells into the text file.
Firstly, I input the data as below

Then, I concatenated into the different tab so-called 'Output2' :

and the coding so that the value depicted from concatenated cells will be exported into a desired text file as below:

Private Sub CommandButton1_Click()
Dim filename As String
Dim lineText As String
Dim my_range As Range

filename = ThisWorkbook.Path & "\File EFT" & Format(Now, "_ddmmyy") & ".txt"
Open filename For Output As #1
Set my_range = Worksheets("Output2").Range("B2")
For i = 1 To my_range.Rows.Count
For j = 1 To my_range.Columns.Count
lineText = IIf(j = 1, "", lineText & ",") & my_range.Cells(i, j)

Next j
Print #1, lineText

Next i
Close #1

MsgBox ("File is Generated")

End Sub

I have a problem now which the text file only appeared at the first line. What I need is, a command which, as and when I input the value, say up to 10 rows, so it will be exported as 10 rows at text file as what I needed and later if I addon another input into 35 rows, the exported text file showing 35 lines