问:
AJAX POST with datatables not working (using ajax loaded)
I'm trying to do this example https://datatables.net/blog/2017-03-31 everything works except the ajax request, the problem is that I'm trying to return data from a database and a barely know how to do it with ajax (newbie) this is how my code and ajax request look:

```<code>var id = 0;
$('#tablanormal tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var tdi = tr.find("i.fa");
            var row = table.row(tr);
            id = 0;
            id = parseInt(table.row(this).data().id_sol);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
                tdi.first().removeClass('fa-minus-square');
                tdi.first().addClass('fa-plus-square');
            } else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');
                tdi.first().removeClass('fa-plus-square');
                tdi.first().addClass('fa-minus-square');
            }
        });

        table.on("user-select", function (e, dt, type, cell, originalEvent) {
            if ($(cell.node()).hasClass("details-control")) {
                e.preventDefault();
            }
        });
    });

    function format(rowData) {
        var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

        $.ajax({
            method: 'POST',
            url: 'datatables_ajax/items.php',
            data: {idsol: id},
            dataType: 'json',
            success: function (json) {
                div
                        .html(json.html)
                        .removeClass('loading');
            },
            error: function (er) {
                console.error(error)
            }
        });

        return div;
    }
</code>```

item.php file

```<code><?php

include_once '../datatables_ajax/conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();

$idsol = $_POST['idsol'];
$consulta = "CALL Items('".$idsol."')";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);

//print json_encode($data, JSON_UNESCAPED_UNICODE);
echo '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;"><tbody>';
foreach(['ID','item','number'] as $attribute) {
    echo '<tr><th>'.$attribute.'</th>';
    foreach($data as $row) {
        echo '<td>'.$row[$attribute].'</td>';
    }
    echo '</tr>';
}
echo '</tbody></table>';
$conexion=null;
?>
</code>```

items.php returns id_sol, item_name, item_number I wanted to return it first as text(it works if you only open the file) but the table just stay in "Loading..." when trying to show it, also it would be helpful if someone help me to return that data as a table.

答:
First

you should remove the loading text when the ajax call is complete that's inside the complete: function(){} not inside the success: function(){}.

Second

you can return the data as a table from PHP like this:

```<code>if ($resultado->rowCount()){ //meaning if the request returned some data
    $data=$resultado->fetchAll(PDO::FETCH_ASSOC);
  $d = [];
  $i = ;
  foreach($data as $val){
    $d[i]['fieldName'] = $val['columnName'];
  }
  echo json_encode($data);
}else{ //no data returned
//error handling here
}
</code>```

Third

if you want to return the data as an HTML table then do this:

```<code>if ($resultado->rowCount()){ //meaning if the request returned some data
 $data=$resultado->fetchAll(PDO::FETCH_ASSOC);
 $output = "
 <table>
  <thead>
    <tr>
      <th>first header </th>
      <th>second header </th>
    </tr>
  </thead>
  <body>
 ";
     $d = [];
     $i = ;
     foreach($data as $val){
      $output .="
       <tr>
       <td>first header data=".$val[columnName]."</td>
       <td>second header data=".$val[columnName]."</td>
       </tr>";

        $d[i]['fieldName'] = $val['columnName'];
      }
      $output .="  </tbody>
      </table>";
      echo json_encode($output);
    }else{ //no data returned
    //error handling here
    }
</code>```

Body:
I'm trying to do this example https://datatables.net/blog/2017-03-31 everything works except the ajax request, the problem is that I'm trying to return data from a database and a barely know how to do it with ajax (newbie) this is how my code and ajax request look:

var id = 0;
$('#tablanormal tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var tdi = tr.find("i.fa");
            var row = table.row(tr);
            id = 0;
            id = parseInt(table.row(this).data().id_sol);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
                tdi.first().removeClass('fa-minus-square');
                tdi.first().addClass('fa-plus-square');
            } else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');
                tdi.first().removeClass('fa-plus-square');
                tdi.first().addClass('fa-minus-square');
            }
        });

        table.on("user-select", function (e, dt, type, cell, originalEvent) {
            if ($(cell.node()).hasClass("details-control")) {
                e.preventDefault();
            }
        });
    });

    function format(rowData) {
        var div = $('
')
                .addClass('loading')
                .text('Loading...');

        $.ajax({
            method: 'POST',
            url: 'datatables_ajax/items.php',
            data: {idsol: id},
            dataType: 'json',
            success: function (json) {
                div
                        .html(json.html)
                        .removeClass('loading');
            },
            error: function (er) {
                console.error(error)
            }
        });

        return div;
    }

item.php file

<?php

include_once '../datatables_ajax/conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();

$idsol = $_POST['idsol'];
$consulta = "CALL Items('".$idsol."')";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);

//print json_encode($data, JSON_UNESCAPED_UNICODE);
echo '

';
foreach(['ID','item','number'] as $attribute) {
    echo '
'.$attribute.'	';
    foreach($data as $row) {
        echo ''.$row[$attribute].'	';
    }
    echo '
';
}
echo '

';
$conexion=null;
?>

items.php returns id_sol, item_name, item_number I wanted to return it first as text(it works if you only open the file) but the table just stay in "Loading..." when trying to show it, also it would be helpful if someone help me to return that data as a table.

Body:
First

you should remove the loading text when the ajax call is complete that's inside the complete: function(){} not inside the success: function(){}.

Second

you can return the data as a table from PHP like this:

if ($resultado->rowCount()){ //meaning if the request returned some data
    $data=$resultado->fetchAll(PDO::FETCH_ASSOC);
  $d = [];
  $i = ;
  foreach($data as $val){
    $d[i]['fieldName'] = $val['columnName'];
  }
  echo json_encode($data);
}else{ //no data returned
//error handling here
}

Third

if you want to return the data as an HTML table then do this:

if ($resultado->rowCount()){ //meaning if the request returned some data
 $data=$resultado->fetchAll(PDO::FETCH_ASSOC);
 $output = "
 <table>
  <thead>
    <tr>
      <th>first header </th>
      <th>second header </th>
    </tr>
  </thead>
  <body>
 ";
     $d = [];
     $i = ;
     foreach($data as $val){
      $output .="
       <tr>
       <td>first header data=".$val[columnName]."</td>
       <td>second header data=".$val[columnName]."</td>
       </tr>";

        $d[i]['fieldName'] = $val['columnName'];
      }
      $output .="  </tbody>
      </table>";
      echo json_encode($output);
    }else{ //no data returned
    //error handling here
    }


来源: stackexchange

问:
Azure release pipeline - Build agent running SSH command returns weird error codes
In my release pipeline, I am trying to call below command.

```<code>echo 'Bring down all dockers'
cd /usr/src/project
sudo docker-compose down
echo 'Setting the ownership of /usr/src/project to $(serviceuser)'
sudo chown -R $(serviceuser) /usr/src/project
sudo chmod -R 777 /usr/src/project
</code>```

Everything is getting executed fine on the remote machine. But, it reports weird responses back to the agent. as below

```<code>2020-05-31T04:16:18.7284676Z Bring down all dockers
2020-05-31T04:16:18.7285634Z
2020-05-31T04:16:19.3872061Z ##[error]Stopping gateway_1   ...
Stopping web_1         ...
Stopping service_1          ...
Stopping service_2 ...

2020-05-31T04:16:19.8215312Z ##[error][13A[2K
Stopping gateway_1   ... [32mdone[0m
[13B
2020-05-31T04:16:21.0904515Z ##[error][5A[2K
Stopping service_1 ... [32mdone[0m
[5B
2020-05-31T04:16:21.8607668Z ##[error][7A[2K
Stopping service_2    ... [32mdone[0m
[7B
2020-05-31T04:16:22.9615503Z ##[error][4A[2K
Removing web_1       ... [32mdone[0m
[4B
2020-05-31T04:16:22.9665540Z ##[error][5A[2K
Removing service_1 ... [32mdone[0m
[5B
2020-05-31T04:16:22.9682527Z ##[error][11A[2K
Removing service_2          ... [32mdone[0m
[11B
2020-05-31T04:16:23.1683671Z Delete everything under  /usr/src/project/
2020-05-31T04:16:23.1684185Z
2020-05-31T04:16:23.1993484Z Creating new folder /usr/src/project/
2020-05-31T04:16:23.1994279Z
2020-05-31T04:16:23.2195927Z Setting the ownership of /usr/src/project to builduser
2020-05-31T04:16:23.2196728Z
2020-05-31T04:16:23.2584025Z ##[error]Command failed with errors on remote machine.
</code>```

So, this makes the job showing as failed. Any suggestion would be helpful.

Build Machine: RHEL 8
Service VM: RHEL 8
Azure Agenet: Self Hosted

Thanks!

答:
This is because docker writes those messages to stderr instead of stdout. In Azure DevOps pipeline in SSH task there is option Fail on STDERR which is checked by default.
You can try to uncheck this option to see if it works.

You can refer to this ticket with similar issue .

ContentLicense: CC BY-SA 4.0

Body:
In my release pipeline, I am trying to call below command.

echo 'Bring down all dockers'
cd /usr/src/project
sudo docker-compose down
echo 'Setting the ownership of /usr/src/project to $(serviceuser)'
sudo chown -R $(serviceuser) /usr/src/project
sudo chmod -R 777 /usr/src/project

Everything is getting executed fine on the remote machine. But, it reports weird responses back to the agent. as below

2020-05-31T04:16:18.7284676Z Bring down all dockers
2020-05-31T04:16:18.7285634Z
2020-05-31T04:16:19.3872061Z ##[error]Stopping gateway_1   ...
Stopping web_1         ...
Stopping service_1          ...
Stopping service_2 ...

2020-05-31T04:16:19.8215312Z ##[error][13A[2K
Stopping gateway_1   ... [32mdone[0m
[13B
2020-05-31T04:16:21.0904515Z ##[error][5A[2K
Stopping service_1 ... [32mdone[0m
[5B
2020-05-31T04:16:21.8607668Z ##[error][7A[2K
Stopping service_2    ... [32mdone[0m
[7B
2020-05-31T04:16:22.9615503Z ##[error][4A[2K
Removing web_1       ... [32mdone[0m
[4B
2020-05-31T04:16:22.9665540Z ##[error][5A[2K
Removing service_1 ... [32mdone[0m
[5B
2020-05-31T04:16:22.9682527Z ##[error][11A[2K
Removing service_2          ... [32mdone[0m
[11B
2020-05-31T04:16:23.1683671Z Delete everything under  /usr/src/project/
2020-05-31T04:16:23.1684185Z
2020-05-31T04:16:23.1993484Z Creating new folder /usr/src/project/
2020-05-31T04:16:23.1994279Z
2020-05-31T04:16:23.2195927Z Setting the ownership of /usr/src/project to builduser
2020-05-31T04:16:23.2196728Z
2020-05-31T04:16:23.2584025Z ##[error]Command failed with errors on remote machine.

So, this makes the job showing as failed. Any suggestion would be helpful.

Build Machine: RHEL 8
Service VM: RHEL 8
Azure Agenet: Self Hosted

Thanks!


问:
jQuery hover effect
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

```<code>.bgHvr {
  background-color: #FFFACD;
}
</code>```

The only way I know how to add the hover effect I desire is:

```<code>jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});
</code>```

UPDATE:

After some more help I found out a simpler way of a hover effect:

```<code>$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});
</code>```

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

答:
```<code>$('#table tbody tr').hover(
    function() {
        $(this).addClass('bgHvr');
    }, function() {
        $(this).removeClass('bgHvr');
    }
);
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery hover effect

Body:
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

.bgHvr {
  background-color: #FFFACD;
}

The only way I know how to add the hover effect I desire is:

jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});

UPDATE:

After some more help I found out a simpler way of a hover effect:

$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.


问:
ClassNotFoundException with Kafka Connect MQTT connector
I am trying to subscribe to a mqtt topic  with kafka connect, for this I used this connector: https://github.com/johanvandevenne/kafka-connect-mqtt. I followed the steps described there with a little modification and everything seemed to work. However, when I start the connector I get a ClassNotFoundException (screenshot) and the connector stops. It seems like it's coming from IMqttMessageListener but I don't know how to solve this.

Any ideas on what I can do?

This is my source file:

```<code>connector.class : be.jovacon.kafka.connect.MQTTSourceConnector
mqtt.broker : tcp://localhost:1883
mqtt.clientID: 1
mqtt.topic : test
kafka.topic: timestamp
key.converter:org.apache.kafka.connect.storage.StringConverter
key.converter.schemas.enable:false
value.converter:org.apache.kafka.connect.storage.StringConverter
value.converter.schemas.enable:false
</code>```

答: You need to copy all the 6 jars in the directory /kafka-connect-mqtt/target/kafka-connect-mqtt-1.1.0-package/kafka-connect-mqtt/. Your path is probably different from the one mentioned in the readme file for the repo that you are following.</p>

Body:
I am trying to subscribe to a mqtt topic  with kafka connect, for this I used this connector: https://github.com/johanvandevenne/kafka-connect-mqtt. I followed the steps described there with a little modification and everything seemed to work. However, when I start the connector I get a ClassNotFoundException (screenshot) and the connector stops. It seems like it's coming from IMqttMessageListener but I don't know how to solve this.

Any ideas on what I can do?

This is my source file:

connector.class : be.jovacon.kafka.connect.MQTTSourceConnector
mqtt.broker : tcp://localhost:1883
mqtt.clientID: 1
mqtt.topic : test
kafka.topic: timestamp
key.converter:org.apache.kafka.connect.storage.StringConverter
key.converter.schemas.enable:false
value.converter:org.apache.kafka.connect.storage.StringConverter
value.converter.schemas.enable:false


问:
Copy and replace part of date from field A to B
I need a simple code that takes date from fixed (always the same) field (B 26 on example below) and copy only the MM.YYYY (from date 19.09.2020  I need the copy only of 09.2020) and this MM.YYYY insert into the date field B2 and replace the old MM.YYYY. Day DD (01 from example) from B2 should stay.

Example:
B26 ->      I need copy of 09.2020
B2 ->       01.08.2020 needs to be raplaced by 09.2020, result should be 01.09.2020.
B3…B25 ->   all lines from B3 to B25 should bet he same, B3 should be 02.09.2020, B4 should be 03.09.2020…

I have an issue probably with wrong format of date.

```<code>Range("B26").Select
Selection.Copy
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "8/1/2020"
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B25"), Type:=xlFillDefault
Range("B2:B25").Select
</code>```

答:
Loop through each cell that needs to be replaced and use the DateSerial function to create a date that consists of year and month of the B26 and the day of the current cell in the loop.</p>

```<code>Dim Cell As Range
For Each Cell In Range("D2:D25")
    Cell.Value = DateSerial(Year(Range("B26").Value), Month(Range("B26").Value), Day(Cell.Value))
Next Cell
</code>```

Body:
I need a simple code that takes date from fixed (always the same) field (B 26 on example below) and copy only the MM.YYYY (from date 19.09.2020  I need the copy only of 09.2020) and this MM.YYYY insert into the date field B2 and replace the old MM.YYYY. Day DD (01 from example) from B2 should stay.

Example:
B26 ->      I need copy of 09.2020
B2 ->       01.08.2020 needs to be raplaced by 09.2020, result should be 01.09.2020.
B3…B25 ->   all lines from B3 to B25 should bet he same, B3 should be 02.09.2020, B4 should be 03.09.2020…

I have an issue probably with wrong format of date.

Range("B26").Select
Selection.Copy
Range("B2").Select
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "8/1/2020"
Range("B2").Select
Selection.AutoFill Destination:=Range("B2:B25"), Type:=xlFillDefault
Range("B2:B25").Select

Body:
Loop through each cell that needs to be replaced and use the DateSerial function to create a date that consists of year and month of the B26 and the day of the current cell in the loop.

Dim Cell As Range
For Each Cell In Range("D2:D25")
    Cell.Value = DateSerial(Year(Range("B26").Value), Month(Range("B26").Value), Day(Cell.Value))
Next Cell


问:
How to synchronize view component data with a partial view?
I want to display my .NET Core web page as per the below image.

For the left pane, I am using a partial view whereas I'm rendering the right pane with view components.

I call different API's to retrieve data from the database in order to display data in both panes.

I want to synchronize the left pane record count with right pane view component data.

Is their any pattern/combination of view components or partial views to achieve my requirements?

答:
I want to synchronize left pane record count with right pane view components data. Is their any pattern/combination of view-components or partial views to synchronize my requirement.

You can put rows of each view component into specific "container" with specific css class, such as "vc1-row",  "vc2-row" etc.

On client side, you can traverse rows of view component(s) and calculate count of rows of each view component after DOM is ready, and update/repopulate left panel record count via JavaScript/jQuery code.

Besides, if you'd like to implement something like portal/dashboard, which could retrieve data from back-end service and push real-time data to clients and update clients UI with new data, you can try to use SignalR.


问:
Airflow Kubernetes executor , Tasks in queued state and pod says invalid image and uses local executor
strong textI have installed airflow in docker and using kubernetes executor unable to trigger dags. Dag runs are in queued state. KubernetesExecutor is creating pod but it says invalid image. If i describe the pod it uses local executor instead of kubernetes executor. Please help

Attaching log file for reference

```<code>**kubectl describe pod tablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc
Name:         swedschematablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc
Namespace:    default
Priority:     0
Node:         10.73.96.181
Start Time:   Mon, 11 May 2020 18:22:15 +0530
Labels:       airflow-worker=5888feda-6aee-49c8-a94b-39cbe5758062
              airflow_version=1.10.10
              dag_id=Swed-schema-tables-creation
              execution_date=2020-05-11T12_52_09.829627_plus_00_00
              kubernetes_executor=True
              task_id=Schema_Tables_Creation
              try_number=1
Annotations:  <none>
Status:       Pending
IP:           172.17.0.46
IPs:
  IP:  172.17.0.46
Containers:
  base:
    Container ID:
    Image:         :
    Image ID:
    Port:          <none>
    Host Port:     <none>
    Command:
      airflow
      run
      Swed-schema-tables-creation
      Schema_Tables_Creation
      2020-05-11T12:52:09.829627+00:00
      --local
      --pool
      default_pool
      -sd
      /root/airflow/dags/User_Creation_dag.py
    State:          Waiting
      Reason:       InvalidImageName
    Ready:          False
    Restart Count:  0
    Environment:
      AIRFLOW__CORE__EXECUTOR:          LocalExecutor
      AIRFLOW__CORE__SQL_ALCHEMY_CONN:  postgresql://airflowkube:airflowkube@10.73.96.181:5434/airflowkube
    Mounts:
      /root/airflow/dags from airflow-dags (ro)
      /root/airflow/logs from airflow-logs (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-64cxg (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  airflow-dags:
    Type:          HostPath (bare host directory volume)
    Path:          /data/Naveen/Airflow/dags
    HostPathType:
  airflow-logs:
    Type:          HostPath (bare host directory volume)
    Path:          /data/Naveen/Airflow/Logs
    HostPathType:
  default-token-64cxg:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-64cxg
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason         Age                     From                           Message
  ----     ------         ----                    ----                           -------
  Normal   Scheduled      <unknown>               default-scheduler              Successfully assigned default/swedschematablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc to evblfnclnullnull1538
  Warning  Failed         2m15s (x12 over 4m28s)  kubelet, evblfnclnullnull1538  Error: InvalidImageName
  Warning  InspectFailed  2m (x13 over 4m28s)     kubelet, evblfnclnullnull1538  Failed to apply default image tag ":": couldn't parse image reference ":": invalid reference format**
</code>```

答:
It looks like there is no image defined for the workers. You can set this in the airflow.cfg. Be sure to set these worker_container_repository and  worker_container_tag. These are null by default which results in the behaviour you're experiencing.
A working example:

```<code> AIRFLOW__KUBERNETES__WORKER_CONTAINER_REPOSITORY: "apache/airflow"
 AIRFLOW__KUBERNETES__WORKER_CONTAINER_TAG: "1.10.10-python3.6"
 AIRFLOW__KUBERNETES__RUN_AS_USER: "50000"
</code>```

The airflow docs have some more detailed info on the available properties: https://airflow.apache.org/docs/stable/configurations-ref.html#kubernetes

Body:
strong textI have installed airflow in docker and using kubernetes executor unable to trigger dags. Dag runs are in queued state. KubernetesExecutor is creating pod but it says invalid image. If i describe the pod it uses local executor instead of kubernetes executor. Please help

Attaching log file for reference

**kubectl describe pod tablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc
Name:         swedschematablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc
Namespace:    default
Priority:     0
Node:         10.73.96.181
Start Time:   Mon, 11 May 2020 18:22:15 +0530
Labels:       airflow-worker=5888feda-6aee-49c8-a94b-39cbe5758062
              airflow_version=1.10.10
              dag_id=Swed-schema-tables-creation
              execution_date=2020-05-11T12_52_09.829627_plus_00_00
              kubernetes_executor=True
              task_id=Schema_Tables_Creation
              try_number=1
Annotations:  <none>
Status:       Pending
IP:           172.17.0.46
IPs:
  IP:  172.17.0.46
Containers:
  base:
    Container ID:
    Image:         :
    Image ID:
    Port:          <none>
    Host Port:     <none>
    Command:
      airflow
      run
      Swed-schema-tables-creation
      Schema_Tables_Creation
      2020-05-11T12:52:09.829627+00:00
      --local
      --pool
      default_pool
      -sd
      /root/airflow/dags/User_Creation_dag.py
    State:          Waiting
      Reason:       InvalidImageName
    Ready:          False
    Restart Count:  0
    Environment:
      AIRFLOW__CORE__EXECUTOR:          LocalExecutor
      AIRFLOW__CORE__SQL_ALCHEMY_CONN:  postgresql://airflowkube:airflowkube@10.73.96.181:5434/airflowkube
    Mounts:
      /root/airflow/dags from airflow-dags (ro)
      /root/airflow/logs from airflow-logs (rw)
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-64cxg (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  airflow-dags:
    Type:          HostPath (bare host directory volume)
    Path:          /data/Naveen/Airflow/dags
    HostPathType:
  airflow-logs:
    Type:          HostPath (bare host directory volume)
    Path:          /data/Naveen/Airflow/Logs
    HostPathType:
  default-token-64cxg:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-64cxg
    Optional:    false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 300s
                 node.kubernetes.io/unreachable:NoExecute for 300s
Events:
  Type     Reason         Age                     From                           Message
  ----     ------         ----                    ----                           -------
  Normal   Scheduled      <unknown>               default-scheduler              Successfully assigned default/swedschematablescreationschematablescreation-ecabd38a66664a33b6645a72ef056edc to evblfnclnullnull1538
  Warning  Failed         2m15s (x12 over 4m28s)  kubelet, evblfnclnullnull1538  Error: InvalidImageName
  Warning  InspectFailed  2m (x13 over 4m28s)     kubelet, evblfnclnullnull1538  Failed to apply default image tag ":": couldn't parse image reference ":": invalid reference format**

Body:
It looks like there is no image defined for the workers. You can set this in the airflow.cfg. Be sure to set these worker_container_repository and  worker_container_tag. These are null by default which results in the behaviour you're experiencing.
A working example:

 AIRFLOW__KUBERNETES__WORKER_CONTAINER_REPOSITORY: "apache/airflow"
 AIRFLOW__KUBERNETES__WORKER_CONTAINER_TAG: "1.10.10-python3.6"
 AIRFLOW__KUBERNETES__RUN_AS_USER: "50000"

The airflow docs have some more detailed info on the available properties: https://airflow.apache.org/docs/stable/configurations-ref.html#kubernetes


问:
NUnit expected exceptions
I've got a set of test cases, some of which are expected to throw exceptions. Because of this, I have have set the attributes for these tests to expect exceptions like so:

```<code>[ExpectedException("System.NullReferenceException")]
</code>```

When I run my tests locally all is good. However when I move my tests over to the CI server running TeamCity, all my tests that have expected exceptions fail. This is a known bug.

I am aware that there is also the Assert.Throws<> and Assert.Throws methods that NUnit offers.

My question is how can I make use of these instead of the attribute I'm currently using?

I've had a look around StackOverflow and tried a few things none of which seem to work for me.

Is there a simple 1 line solution to using this?

答: By default, TeamCity uses NUnit 2.2.10, which doesn't have ExpectedException.  Check the TeamCity "NUnit for NAnt" docs to see how to change it to something more modern, including the specific list of releases TeamCity provides.</p>

Title: NUnit expected exceptions

Body:
I've got a set of test cases, some of which are expected to throw exceptions. Because of this, I have have set the attributes for these tests to expect exceptions like so:

[ExpectedException("System.NullReferenceException")]

When I run my tests locally all is good. However when I move my tests over to the CI server running TeamCity, all my tests that have expected exceptions fail. This is a known bug.

I am aware that there is also the Assert.Throws<> and Assert.Throws methods that NUnit offers.

My question is how can I make use of these instead of the attribute I'm currently using?

I've had a look around StackOverflow and tried a few things none of which seem to work for me.

Is there a simple 1 line solution to using this?


问:
Fastest way to determine if an integer is between two integers (inclusive) with known sets of values
Is there a faster way than x >= start && x <= end in C or C++ to test if an integer is between two integers?

UPDATE: My specific platform is iOS. This is part of a box blur function that restricts pixels to a circle in a given square.

UPDATE: After trying the accepted answer, I got an order of magnitude speedup on the one line of code over doing it the normal x >= start && x <= end way.

UPDATE: Here is the after and before code with assembler from XCode:

NEW WAY

```<code>// diff = (end - start) + 1
#define POINT_IN_RANGE_AND_INCREMENT(p, range) ((p++ - range.start) < range.diff)

Ltmp1313:
 ldr    r0, [sp, #176] @ 4-byte Reload
 ldr    r1, [sp, #164] @ 4-byte Reload
 ldr    r0, [r0]
 ldr    r1, [r1]
 sub.w  r0, r9, r0
 cmp    r0, r1
 blo    LBB44_30
</code>```

OLD WAY

```<code>#define POINT_IN_RANGE_AND_INCREMENT(p, range) (p <= range.end && p++ >= range.start)

Ltmp1301:
 ldr    r1, [sp, #172] @ 4-byte Reload
 ldr    r1, [r1]
 cmp    r0, r1
 bls    LBB44_32
 mov    r6, r0
 b      LBB44_33
LBB44_32:
 ldr    r1, [sp, #188] @ 4-byte Reload
 adds   r6, r0, #1
Ltmp1302:
 ldr    r1, [r1]
 cmp    r0, r1
 bhs    LBB44_36
</code>```

Pretty amazing how reducing or eliminating branching can provide such a dramatic speed up.

答:
For any variable range checking:

```<code>if (x >= minx && x <= maxx) ...
</code>```

It is faster to use bit operation:

```<code>if ( ((x - minx) | (maxx - x)) >= 0) ...
</code>```

This will reduce two branches into one.

If you care about type safe:

```<code>if ((int32_t)(((uint32_t)x - (uint32_t)minx) | ((uint32_t)maxx - (uint32_t)x)) > = 0) ...
</code>```

You can combine more variable range checking together:

```<code>if (( (x - minx) | (maxx - x) | (y - miny) | (maxy - y) ) >= 0) ...
</code>```

This will reduce 4 branches into 1.

It is 3.4 times faster than the old one in gcc:

Body:
Is there a faster way than x >= start && x <= end in C or C++ to test if an integer is between two integers?

UPDATE: My specific platform is iOS. This is part of a box blur function that restricts pixels to a circle in a given square.

UPDATE: After trying the accepted answer, I got an order of magnitude speedup on the one line of code over doing it the normal x >= start && x <= end way.

UPDATE: Here is the after and before code with assembler from XCode:

NEW WAY

// diff = (end - start) + 1
#define POINT_IN_RANGE_AND_INCREMENT(p, range) ((p++ - range.start) < range.diff)

Ltmp1313:
 ldr    r0, [sp, #176] @ 4-byte Reload
 ldr    r1, [sp, #164] @ 4-byte Reload
 ldr    r0, [r0]
 ldr    r1, [r1]
 sub.w  r0, r9, r0
 cmp    r0, r1
 blo    LBB44_30

OLD WAY

#define POINT_IN_RANGE_AND_INCREMENT(p, range) (p <= range.end && p++ >= range.start)

Ltmp1301:
 ldr    r1, [sp, #172] @ 4-byte Reload
 ldr    r1, [r1]
 cmp    r0, r1
 bls    LBB44_32
 mov    r6, r0
 b      LBB44_33
LBB44_32:
 ldr    r1, [sp, #188] @ 4-byte Reload
 adds   r6, r0, #1
Ltmp1302:
 ldr    r1, [r1]
 cmp    r0, r1
 bhs    LBB44_36

Pretty amazing how reducing or eliminating branching can provide such a dramatic speed up.

Body:
For any variable range checking:

if (x >= minx && x <= maxx) ...

It is faster to use bit operation:

if ( ((x - minx) | (maxx - x)) >= 0) ...

This will reduce two branches into one.

If you care about type safe:

if ((int32_t)(((uint32_t)x - (uint32_t)minx) | ((uint32_t)maxx - (uint32_t)x)) > = 0) ...

You can combine more variable range checking together:

if (( (x - minx) | (maxx - x) | (y - miny) | (maxy - y) ) >= 0) ...

This will reduce 4 branches into 1.

It is 3.4 times faster than the old one in gcc:


问:
Possible to set legend size to auto? (ggplot2)
I have a problem showing the legend in a ggplot. My data changes every day, and sometimes I have about 20 data points, sometimes only 5 data points.

The plot legend exceeds the limits of the diagram. But plotting it low scaled all the time is not a good option.

Here is a plot:

```<code>require(data.table)
require(ggplot2)

df <- data.table(name = c("A12345678901234567890", "B12345678901234567890", "C12345678901234567890", "D12345678901234567890", "E12345678901234567890", "F12345678901234567890", "G12345678901234567890", "H12345678901234567890", "I12345678901234567890"), val = runif(n = 9))

plotcolors <- rainbow(df[,.N, by = name][,.N], end = 0.65)
p <- ggplot(data = df)
p <- p +
  scale_fill_manual(values = plotcolors) +
  aes(x = name, y = val, fill = name) +
  theme(axis.text.x=element_blank(), legend.position = "bottom", text = element_text(size = 10), legend.text = element_text(size = 10), legend.title = element_text(size = 10), plot.margin = margin(10, 10, 10, 10, "pt")) +
  xlab(NULL) +
  scale_y_continuous()
p <- p + geom_bar(stat = "identity", colour = "black")

print(p)
</code>```

Outputting it on a square canvas writes the legend off range.
Is it possible to create a kind of auto scale?

Update 2020-06-08:

This is how the plot looks like:

The amount of curves differs. So the legend changes, and I need to adjust the size manually. I might calculate the size by counting the characters for each element and try to estimate the possible scaling. But it would be nice, if ggplot2 does it by itself.

答:
To my knowledge, no such legend autoscaling exists in ggplot. Making the plot larger (either via ggsave or by just making the device larger) can help to fit the legend into the plot.

But in the example given here, you are going to have a much easier time labeling the x-axis properly, because you are mapping the same variable to x and fill. You don't really need fill but you can still add it, ideally without a legend.

If you still want to modify the layout of the legend, look into guide_legend(), but it really is not the way to go here.

library(data.table)
library(ggplot2)

set.seed(42)
df <- data.table(name = c("A12345678901234567890", "B12345678901234567890", "C12345678901234567890", "D12345678901234567890", "E12345678901234567890", "F12345678901234567890", "G12345678901234567890", "H12345678901234567890", "I12345678901234567890"), val = runif(n = 9))

# Simple version
ggplot(df) +
  geom_bar(aes(name, val), stat = "identity") +
  theme(axis.text.x = element_text(angle = 90))
```

<p><img src="https://i.imgur.com/TtMZQ1Y.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code># Version with fill also mapped to name
ggplot(df) +
  geom_bar(aes(name, val, fill = name), stat = "identity") +
  theme(axis.text.x = element_text(angle = 90),
        legend.position = "none")
</code>```

Body:
I have a problem showing the legend in a ggplot. My data changes every day, and sometimes I have about 20 data points, sometimes only 5 data points.

The plot legend exceeds the limits of the diagram. But plotting it low scaled all the time is not a good option.

Here is a plot:

require(data.table)
require(ggplot2)

df <- data.table(name = c("A12345678901234567890", "B12345678901234567890", "C12345678901234567890", "D12345678901234567890", "E12345678901234567890", "F12345678901234567890", "G12345678901234567890", "H12345678901234567890", "I12345678901234567890"), val = runif(n = 9))

plotcolors <- rainbow(df[,.N, by = name][,.N], end = 0.65)
p <- ggplot(data = df)
p <- p +
  scale_fill_manual(values = plotcolors) +
  aes(x = name, y = val, fill = name) +
  theme(axis.text.x=element_blank(), legend.position = "bottom", text = element_text(size = 10), legend.text = element_text(size = 10), legend.title = element_text(size = 10), plot.margin = margin(10, 10, 10, 10, "pt")) +
  xlab(NULL) +
  scale_y_continuous()
p <- p + geom_bar(stat = "identity", colour = "black")

print(p)

Outputting it on a square canvas writes the legend off range.
Is it possible to create a kind of auto scale?

Update 2020-06-08:

This is how the plot looks like:

The amount of curves differs. So the legend changes, and I need to adjust the size manually. I might calculate the size by counting the characters for each element and try to estimate the possible scaling. But it would be nice, if ggplot2 does it by itself.

Body:
To my knowledge, no such legend autoscaling exists in ggplot. Making the plot larger (either via ggsave or by just making the device larger) can help to fit the legend into the plot.

But in the example given here, you are going to have a much easier time labeling the x-axis properly, because you are mapping the same variable to x and fill. You don't really need fill but you can still add it, ideally without a legend.

If you still want to modify the layout of the legend, look into guide_legend(), but it really is not the way to go here.

library(data.table)
library(ggplot2)

set.seed(42)
df <- data.table(name = c("A12345678901234567890", "B12345678901234567890", "C12345678901234567890", "D12345678901234567890", "E12345678901234567890", "F12345678901234567890", "G12345678901234567890", "H12345678901234567890", "I12345678901234567890"), val = runif(n = 9))

# Simple version
ggplot(df) +
  geom_bar(aes(name, val), stat = "identity") +
  theme(axis.text.x = element_text(angle = 90))

# Version with fill also mapped to name
ggplot(df) +
  geom_bar(aes(name, val, fill = name), stat = "identity") +
  theme(axis.text.x = element_text(angle = 90),
        legend.position = "none")


问:
forever loop sql
I am trying to find all staff not logged on in the last 6 months so I have this code. It seems to be looping forever but I'm not sure why

--select all staff not logged on in the last 6 months
SELECT
[fkStaffId],
[dteLogon]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[fkStaffId]
NOT IN
(--select all staff logged on in the last 6 months
    SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE()) --this is a list of each staffID
                                               --logged on in the last 6 months
)
ORDER BY [dteLogon] DESC
```

<p>anybody got any idea why?</p>

<p>if i just execute</p>

<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE())
</code>```

on it's own, I get a sensible sized list of 309 lines which is about the number I'm expecting, however, the last time I tried to run the entire code, it was still executing after 25 minutes!!

答:
I'd do a GROUP BY, and use HAVING to only return users who have not logged in recently:

```<code>SELECT
    [fkStaffId], MAX([dteLogon])
FROM
    [dbo].[tbl_Staff_Logon]
GROUP BY [fkStaffId]
HAVING MAX([dteLogon]) < DATEADD(MONTH, -6, GETDATE())
</code>```

Title: forever loop sql

Body:
I am trying to find all staff not logged on in the last 6 months so I have this code. It seems to be looping forever but I'm not sure why

--select all staff not logged on in the last 6 months
SELECT
[fkStaffId],
[dteLogon]
FROM
[dbo].[tbl_Staff_Logon]
WHERE
[fkStaffId]
NOT IN
(--select all staff logged on in the last 6 months
    SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE()) --this is a list of each staffID
                                               --logged on in the last 6 months
)
ORDER BY [dteLogon] DESC

anybody got any idea why?

if i just execute

SELECT DISTINCT
    [fkStaffId]
    FROM
    [dbo].[tbl_Staff_Logon]
    WHERE
    [dteLogon] > DATEADD(MONTH, -6, GETDATE())

on it's own, I get a sensible sized list of 309 lines which is about the number I'm expecting, however, the last time I tried to run the entire code, it was still executing after 25 minutes!!

Body:
I'd do a GROUP BY, and use HAVING to only return users who have not logged in recently:

SELECT
    [fkStaffId], MAX([dteLogon])
FROM
    [dbo].[tbl_Staff_Logon]
GROUP BY [fkStaffId]
HAVING MAX([dteLogon]) < DATEADD(MONTH, -6, GETDATE())


问:
opengl glDrawArray throws exception
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)</p>

```<code>glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);
</code>```

答:
Your glDrawArrays call is equivalent to:

```<code>glBegin(GL_LINE_LOOP);
glVertex2fv(data +  0);
glVertex2fv(data +  2);
glVertex2fv(data +  4);
glVertex2fv(data +  6);
glVertex2fv(data +  8);
glVertex2fv(data + 10);
glVertex2fv(data + 12);
glVertex2fv(data + 14);
glEnd();
</code>```

So you are definitely trying to access some memory outside of data.

Title: opengl glDrawArray throws exception

Body:
I'm new to openGL and I need to directly use it for debuging perpose can anyone please tell me why in this code glDrawArray should throw exception (trying to access memory at 0x00000000)

glEnableClientState(GL_VERTEX_ARRAY);
float data[8];
data[0] = 10;
data[1] = 10;
data[2] = 10;
data[3] = 20;
data[4] = 20;
data[5] = 20;
data[6] = 20;
data[7] = 10;
glVertexPointer(2,GL_FLOAT,0,data);
glDrawArrays(GL_LINE_LOOP,0,4);
glDisableClientState(GL_VERTEX_ARRAY);

Body:
Your glDrawArrays call is equivalent to:

glBegin(GL_LINE_LOOP);
glVertex2fv(data +  0);
glVertex2fv(data +  2);
glVertex2fv(data +  4);
glVertex2fv(data +  6);
glVertex2fv(data +  8);
glVertex2fv(data + 10);
glVertex2fv(data + 12);
glVertex2fv(data + 14);
glEnd();

So you are definitely trying to access some memory outside of data.


问:
How to Expand a List with Selenium Webdriver for Python
I am trying to expand a list with Selenium WebDriver for Python, which is controlled by a button that looks like this:

List When Closed

To give you an idea of how it looks when open:

List When Open

The HTML looks like this:

```<code><div>  ##just for more information on the tree
<div>  ##
<ul>   ##

<li>
role = "presentation"
ng-if = "session.hasOccurrences" ## this is the name of a span
class = "expand-children ng-scope"

<button
role = "button"
class = "icon-button has tooltip"
bb-translate-attrs = "{aria-label ': 'session.session-list.toggle-occurrences-aria'}"
aria-pressed = "false"
ng-click = "expand()"
aria-label = "Toggle session occurrences">
</button>

</li>

</ul>  ##
</div> ##
</div> ##
</code>```

Since it had a tag name "button", I tried to use the following but it did not work:

```<code>url = 'Example.com'
driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_tag_name("button").click()
</code>```

I tried to use xpath and CSS selectors, which I have very minimal experience with. Is there something I could do to expand the list?

Thank you for your help in advance.

UPDATE 6/6/2020

My life became difficult because there was JS on the web page I am trying to access. One of the changes this JS makes is that it hides some of the elements' paths. It is strange; on the web page they are accessible and clickable, but no XPATH can locate them.

I tried to outsmart this by locating an accessible element on the page using ActionChains, then tabbing into the element I want to access and click it. But when I reach the element by tabbing, I can't click it. I printed the element to see what Python sees, and it sees "None". Is there any workaround to this?

答:
Try an xpath like:

```<code>WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[@class='icon-button has tooltip']"))).click()
</code>```

This is based strictly on the html you have shared, in other words, assuming the xpath will match just one item on the page.

Required imports:

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
</code>```

Body:
I am trying to expand a list with Selenium WebDriver for Python, which is controlled by a button that looks like this:

List When Closed

To give you an idea of how it looks when open:

List When Open

The HTML looks like this:

  ##just for more information on the tree

  ##

   ##

role = "presentation"
ng-if = "session.hasOccurrences" ## this is the name of a span
class = "expand-children ng-scope"

<button
role = "button"
class = "icon-button has tooltip"
bb-translate-attrs = "{aria-label ': 'session.session-list.toggle-occurrences-aria'}"
aria-pressed = "false"
ng-click = "expand()"
aria-label = "Toggle session occurrences">
</button>

  ##

 ##

 ##

Since it had a tag name "button", I tried to use the following but it did not work:

url = 'Example.com'
driver = webdriver.Chrome()
driver.get(url)

driver.find_element_by_tag_name("button").click()

I tried to use xpath and CSS selectors, which I have very minimal experience with. Is there something I could do to expand the list?

Thank you for your help in advance.

UPDATE 6/6/2020

My life became difficult because there was JS on the web page I am trying to access. One of the changes this JS makes is that it hides some of the elements' paths. It is strange; on the web page they are accessible and clickable, but no XPATH can locate them.

I tried to outsmart this by locating an accessible element on the page using ActionChains, then tabbing into the element I want to access and click it. But when I reach the element by tabbing, I can't click it. I printed the element to see what Python sees, and it sees "None". Is there any workaround to this?

Body:
Try an xpath like:

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//ul/li/button[@class='icon-button has tooltip']"))).click()

This is based strictly on the html you have shared, in other words, assuming the xpath will match just one item on the page.

Required imports:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait


问:
Wildcard Arguments in generics
In the program below, how does the step ob.num.doubleValue() in absEqual() method works? What is it trying to do?

```<code>class NumericFns<T extends Number>{
     T num;

     NumericFns(T n ){
         num = n ;
        }

     boolean absEqual(NumericFns<?> ob) {
         if (Math.abs(num.doubleValue())==
                 Math.abs(ob.num.doubleValue()))
             return true ;
         return false ;
     }
}
</code>```

```<code>public class demo  {

    public static void main(String[] args) {
        NumericFns<Integer> iob = new NumericFns<Integer>(6) ;
        NumericFns<Double> dob = new NumericFns<Double>(-6.0) ;
        if(iob.absEqual(dob))
            System.out.println("Absolute Values are equal") ;
        else
            System.out.println("They differ") ;
    }
}
</code>```

答:
ob is the object you want to compare the current object with.
ob.num is the generic of type T extends Number that your NumericFns class stores.
ob.num.doubleValue() just gives you the double value of ob.num.

The if statement just takes both double values and checks if they're the same.

Title: Wildcard Arguments in generics

Body:
In the program below, how does the step ob.num.doubleValue() in absEqual() method works? What is it trying to do?

class NumericFns<T extends Number>{
     T num;

     NumericFns(T n ){
         num = n ;
        }

     boolean absEqual(NumericFns<?> ob) {
         if (Math.abs(num.doubleValue())==
                 Math.abs(ob.num.doubleValue()))
             return true ;
         return false ;
     }
}

public class demo  {

    public static void main(String[] args) {
        NumericFns<Integer> iob = new NumericFns<Integer>(6) ;
        NumericFns<Double> dob = new NumericFns<Double>(-6.0) ;
        if(iob.absEqual(dob))
            System.out.println("Absolute Values are equal") ;
        else
            System.out.println("They differ") ;
    }
}


问:
How create class Python 3.x (singleton) for asyncpg?
I wanted to organize a connection pool when initializing the class with the method below

```<code>import asyncio
import asyncpg

class DBCommands:

    def __init__(self, uri: str) -> None:
        loop = asyncio.get_event_loop()
    self.pool: asyncpg.pool.Pool = loop.run_until_complete(asyncpg.create_pool(dsn=uri))

    async def get_id_admins(self) -> list:
        async with self.pool.acquire():
            result = await self.pool.fetch("SELECT chat_id FROM users WHERE role_user = 'admin'")
        admins_id = [row[0] for row in result]
        return admins_id
</code>```

Since the pool should be one, with the above implementation, this will not work. I decided to use singleton, but I don’t understand how to implement this. Below is the version that I came up with. Tell me how best to solve this problem. In addition, I do not understand how best and where to close connections. I'm new to using patterns and just starting to study OOP.

```<code>import asyncio
import asyncpg

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class DBManager(metaclass=Singleton):

    @classmethod
    def connect(cls, uri):
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(asyncpg.create_pool(dsn=uri))

class DBCommands:

    def __init__(self, uri) -> None:
        self.uri = uri
        self.pool = DBManager.connect(uri)

    async def get_id_admins(self) -> list:
        async with self.pool.acquire():
            result = await self.pool.fetch("SELECT chat_id FROM users WHERE role_user = 'admin'")
        admins_id = [row[0] for row in result]
        return admins_id
</code>```

I have an assumption that opening and closing a pool can be added to __aenter__  and  __aexit__

答:
You can use a class attribute and create the pool the first time it's needed in an async function:

class Database:

    self.pool = None

    ...

    async def get_id_admins(self)
        if self.pool is None:
            self.pool = await asyncpg.create_pool(dsn=...`).
```

<p>I generally use a regular class and create a single instance attached to global object (like the aiohttp application for web applications) as in:</p>

```class Database:

    def __init__(self, dsn):
        self.dsn = dsn
        self.pool = None

    async def connect(self):
        """Initialize asyncpg Pool"""
        self.pool = await asyncpg.create_pool(dsn=self.dsn, min_size=2, max_size=4)
        logging.info("successfully initialized database pool")

    async def get_id_admins(self):

    ...
```

<p>And use it like:</p>

<pre class="lang-py prettyprint-override"><code>async def startup(app):
    await app.database.connect()

async def shutdown(app):
    await app.database.pool.close()

def main():
    app = web.Application()
    app.database = Database(app.config.DSN)
    app.on_startup.append(startup)
    app.on_shutdown.append(shutdown)
</code>```

Body:
I wanted to organize a connection pool when initializing the class with the method below

import asyncio
import asyncpg

class DBCommands:

    def __init__(self, uri: str) -> None:
        loop = asyncio.get_event_loop()
    self.pool: asyncpg.pool.Pool = loop.run_until_complete(asyncpg.create_pool(dsn=uri))

    async def get_id_admins(self) -> list:
        async with self.pool.acquire():
            result = await self.pool.fetch("SELECT chat_id FROM users WHERE role_user = 'admin'")
        admins_id = [row[0] for row in result]
        return admins_id

Since the pool should be one, with the above implementation, this will not work. I decided to use singleton, but I don’t understand how to implement this. Below is the version that I came up with. Tell me how best to solve this problem. In addition, I do not understand how best and where to close connections. I'm new to using patterns and just starting to study OOP.

import asyncio
import asyncpg

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class DBManager(metaclass=Singleton):

    @classmethod
    def connect(cls, uri):
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(asyncpg.create_pool(dsn=uri))

class DBCommands:

    def __init__(self, uri) -> None:
        self.uri = uri
        self.pool = DBManager.connect(uri)

    async def get_id_admins(self) -> list:
        async with self.pool.acquire():
            result = await self.pool.fetch("SELECT chat_id FROM users WHERE role_user = 'admin'")
        admins_id = [row[0] for row in result]
        return admins_id

I have an assumption that opening and closing a pool can be added to __aenter__  and  __aexit__

Body:
You can use a class attribute and create the pool the first time it's needed in an async function:

class Database:

    self.pool = None

    ...

    async def get_id_admins(self)
        if self.pool is None:
            self.pool = await asyncpg.create_pool(dsn=...`).

I generally use a regular class and create a single instance attached to global object (like the aiohttp application for web applications) as in:

class Database:

    def __init__(self, dsn):
        self.dsn = dsn
        self.pool = None

    async def connect(self):
        """Initialize asyncpg Pool"""
        self.pool = await asyncpg.create_pool(dsn=self.dsn, min_size=2, max_size=4)
        logging.info("successfully initialized database pool")

    async def get_id_admins(self):

    ...

And use it like:

async def startup(app):
    await app.database.connect()

async def shutdown(app):
    await app.database.pool.close()

def main():
    app = web.Application()
    app.database = Database(app.config.DSN)
    app.on_startup.append(startup)
    app.on_shutdown.append(shutdown)


问:
SWIFT still fighting to assign a value to a nested array within a class
This carries on my last question struggling with value assignment to optional class variable, for which David provided me a good hint to a similar problem.
After numerous iterations I now came up with a different approach, however, it still fails and I have no idea why (and basically what happens)

I have the class definitions

struct HighScores: Codable {
    var Scores:Int
    var highscoreRecord: [HighscoreRecord]
}

struct HighscoreRecord: Codable {
    var Rank:Int
    var Date:String?
    var avDuration:Float?
    var Score:Int?
    var Tries:Int?
}
```

<p>In the view controller I have declared a variable of type HighScores, which may read the data from a JSON file or which may be initialized when setting the first high score. </p>

<pre class="lang-swift prettyprint-override"><code>class GameplayViewController: UIViewController {

    var jsonResult: HighScores?

   ...

    if firstHighscore == 1 {
        jsonResult?.Scores = 1
        jsonResult?.highscoreRecord.append(HighscoreRecord(Rank: 1, Date: formatter.string(from: dateStart), avDuration: Float(lblSpeed.text ?? "0.0"), Score: Int(lblRatio.text ?? "0"), Tries: hits + misses))
...
    print(jsonResult)
</code>```

This compiles and also runs. However, if I monitor the jsonResult variable, it still shows nil after assigning the Scores and and highscoreRecord values.

What happens, why can I assign a value without an error and without actually assigning it?
And first and foremost, how do I get my values into jsonResult?

Cheers

答:
So following on from the comments above if you changed the code to be something along the lines of this you create the instance of the struct and add the values.

var jsonResult: HighScores?

    if firstHighscore == 1 {
        jsonResult = HighScores(Scores: 1, highscoreRecord: [HighscoreRecord(Rank: 1, Date: "your date", avDuration: 0.0, Score: 0, Tries: 0)])
    }
```

once created you can add more highscorerecords to the array as needed, using the append method.

Body:
This carries on my last question struggling with value assignment to optional class variable, for which David provided me a good hint to a similar problem.
After numerous iterations I now came up with a different approach, however, it still fails and I have no idea why (and basically what happens)

I have the class definitions

struct HighScores: Codable {
    var Scores:Int
    var highscoreRecord: [HighscoreRecord]
}

struct HighscoreRecord: Codable {
    var Rank:Int
    var Date:String?
    var avDuration:Float?
    var Score:Int?
    var Tries:Int?
}

In the view controller I have declared a variable of type HighScores, which may read the data from a JSON file or which may be initialized when setting the first high score.

class GameplayViewController: UIViewController {

    var jsonResult: HighScores?

   ...

    if firstHighscore == 1 {
        jsonResult?.Scores = 1
        jsonResult?.highscoreRecord.append(HighscoreRecord(Rank: 1, Date: formatter.string(from: dateStart), avDuration: Float(lblSpeed.text ?? "0.0"), Score: Int(lblRatio.text ?? "0"), Tries: hits + misses))
...
    print(jsonResult)

This compiles and also runs. However, if I monitor the jsonResult variable, it still shows nil after assigning the Scores and and highscoreRecord values.

What happens, why can I assign a value without an error and without actually assigning it?
And first and foremost, how do I get my values into jsonResult?

Cheers

Body:
So following on from the comments above if you changed the code to be something along the lines of this you create the instance of the struct and add the values.

var jsonResult: HighScores?

    if firstHighscore == 1 {
        jsonResult = HighScores(Scores: 1, highscoreRecord: [HighscoreRecord(Rank: 1, Date: "your date", avDuration: 0.0, Score: 0, Tries: 0)])
    }

once created you can add more highscorerecords to the array as needed, using the append method.


答:
Hover basically combines the 2 events into one.

```<code>.hover(mouseover,mouseout)
</code>```

or in your case:

```<code>jQuery(document).ready(function($) {
  $('#table tbody tr').hover(function() {
    $(this).addClass('bgHvr');
  },function() {
    $(this).removeClass('bgHvr');
  });
});
</code>```

Title: jQuery hover effect

Body:
I am new to jQuery and trying to figure out how to use the .hover(); effect in place of the .mouseover() and .mouseout() effects. Here is the scenerio:

I am using a table and want to highlight the row with a CSS class that changes the background color to a light yellow. Here is the CSS:

.bgHvr {
  background-color: #FFFACD;
}

The only way I know how to add the hover effect I desire is:

jQuery(document).ready(function($) {
  $('#table tbody tr').mouseover(function() {
    $(this).addClass('bgHvr');
  });
  $('#table tbody tr').mouseout(function() {
    $(this).removeClass('bgHvr');
  });
});

UPDATE:

After some more help I found out a simpler way of a hover effect:

$('#table tbody tr').hover(function() {
  $(this).toggleClass('bgHvr');
});

This is possible after the 1.4.2 update to jQuery which changed how the .toggle() effect worked.

Body:
Hover basically combines the 2 events into one.

.hover(mouseover,mouseout)

or in your case:

jQuery(document).ready(function($) {
  $('#table tbody tr').hover(function() {
    $(this).addClass('bgHvr');
  },function() {
    $(this).removeClass('bgHvr');
  });
});


问:
Parsing json returned with schema element in Java
I have a question about a json. Is the json below a standard of some kind. I can see why its preferable as the element names are written once and datatypes are included. I cannot change how the JSON comes in, but is there a Java library that easily parses it? Of course I can loop and loop but there must be something that parses it. I tried both with Jackson and org.json but both fail as it is an array at start. Also "jq" parses it and I can get to the value "100" that I want as the COUNT but if the schema comes in different than directly referencing the array indexes would break.

```<code>[
  {
    "header": {
      "queryId": "query_1590948930986",
      "schema": "`ROWKEY` STRING KEY, `USERID` STRING, `ENTITYTYPE` STRING, `ENTITYID` STRING, `DATESEARCHED` STRING, `COUNT` BIGINT"
    }
  },
  {
    "row": {
      "columns": [
        "6938bb62-50a1-4d0b-a113-1ecca1082763|+|n|+|09066437|+|2020-05-11",
        "6938bb62-50a1-4d0b-a113-1ecca1082763",
        "n",
        "09066437",
        "2020-05-11",
        100
      ]
    }
  }
]
</code>```

in jq I can do this. but will fail if schema element comes in different.

```<code>| jq '.[1].row.columns[5]'
</code>```

答:
The returned JSON is valid. It is a JSON array containing two JSON Objects, each defining different properties.

In this specific case, the first element in the array contains metadata about the response, including the query id, (which may be included in server log lines or errors in the processing log), and the schema of the data returned in the row.columns array for the subsequent elements.

For example, the value "6938bb62-50a1-4d0b-a113-1ecca1082763|+|n|+|09066437|+|2020-05-11" corresponds to the ROWKEY STRING KEY column.

You can parse this data using Jackson. However, Jackson expects all elements in the array to share a common type.  To deserialize using Jackson you will need a common base type, e.g. ResponseElement and two sub-types, e.g. HeaderElement and RowElement, with appropriate fields.  You can then deserialize the JSON as a List<ResponseElement>.

More information on how to deserialize arrays with different element types can be found here:

How to deserialize a JSON array of elements with different types and varying number of elements?

Body:
I have a question about a json. Is the json below a standard of some kind. I can see why its preferable as the element names are written once and datatypes are included. I cannot change how the JSON comes in, but is there a Java library that easily parses it? Of course I can loop and loop but there must be something that parses it. I tried both with Jackson and org.json but both fail as it is an array at start. Also "jq" parses it and I can get to the value "100" that I want as the COUNT but if the schema comes in different than directly referencing the array indexes would break.

[
  {
    "header": {
      "queryId": "query_1590948930986",
      "schema": "`ROWKEY` STRING KEY, `USERID` STRING, `ENTITYTYPE` STRING, `ENTITYID` STRING, `DATESEARCHED` STRING, `COUNT` BIGINT"
    }
  },
  {
    "row": {
      "columns": [
        "6938bb62-50a1-4d0b-a113-1ecca1082763|+|n|+|09066437|+|2020-05-11",
        "6938bb62-50a1-4d0b-a113-1ecca1082763",
        "n",
        "09066437",
        "2020-05-11",
        100
      ]
    }
  }
]

in jq I can do this. but will fail if schema element comes in different.

| jq '.[1].row.columns[5]'


问:
How to make a list of numbers from a txt file in python?
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

```<code>L=[52,2,103,592,2090,34452,0,1]
</code>```

The best I have managed to do so far is:

```<code>txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)
</code>```

which returns:

```<code>L=['52','2','103','592','2090','34452','0','1']

</code>```

but the ' around the numbers bother me.

Any help is appreciated.

答:
but the ' around the numbers bother me : Use int(string, base)

Returns an integer value, which is equivalent of binary string in the given base.Check here! for more

but arranged as one column (under each other)

which returns L=['52','2','103','592','2090','34452','0','1']

Assumptions:

numbers arranged under each other without commas that returns ['52','2','103','592','2090','34452','0','1'] as per the question

file.txt:

```<code>52
2
103
592
2090
34452
0
1
</code>```

Answer:

imagine file.txt has 1000 numbers.

Approach 1: Use List as mentioned in the question

print([int(i.rstrip()) for i in open('file.txt')])
```

<p><strong>Size in memory</strong></p>

<ul>
<li>putting all numbers into a list would take 9032 bytes </li>
</ul>

<h2>Suggestion</h2>

<h3>Approach 2: Use Generator</h3>

<pre class="lang-py prettyprint-override"><code>print(*(int(i.rstrip()) for i in open('file.txt')))
</code>```

Size in memory

putting all 1000 numbers into a generator would take just 80 bytes.

iterable like a list, but way more memory efficient, enclosed in plain parantheses ()

Cons

Access by index not possible with generators

```<code>print(g[4])   # TypeError: 'generator' object has no attribute '__getitem__'
</code>```

Conclusion

if you want to just keep the numbers in the memory and want to iterate over it whenever necessary, the recommended way is to go with generators as its memory efficient

if want to access generators by index you can always convert a generator into a list like this list(generator)

Hope this helps!

Body:
I have text file containing the numbers 52, 2,103,592,2090,34452,0,1, but arranged as one column (under each other). I want to import the numbers into python and create a list

L=[52,2,103,592,2090,34452,0,1]

The best I have managed to do so far is:

txtfile=open('file.txt')

L=[]
for line in txtfile:
    L.append(line.rstrip())

print(L)

which returns:

L=['52','2','103','592','2090','34452','0','1']

but the ' around the numbers bother me.

Any help is appreciated.

Body:
but the ' around the numbers bother me : Use int(string, base)

Returns an integer value, which is equivalent of binary string in the given base.Check here! for more

but arranged as one column (under each other)

which returns L=['52','2','103','592','2090','34452','0','1']

Assumptions:

numbers arranged under each other without commas that returns ['52','2','103','592','2090','34452','0','1'] as per the question

file.txt:

52
2
103
592
2090
34452
0
1

Answer:

imagine file.txt has 1000 numbers.

Approach 1: Use List as mentioned in the question

print([int(i.rstrip()) for i in open('file.txt')])

Size in memory

putting all numbers into a list would take 9032 bytes

Suggestion

Approach 2: Use Generator

print(*(int(i.rstrip()) for i in open('file.txt')))

Size in memory

putting all 1000 numbers into a generator would take just 80 bytes.

iterable like a list, but way more memory efficient, enclosed in plain parantheses ()

Cons

Access by index not possible with generators

print(g[4])   # TypeError: 'generator' object has no attribute '__getitem__'

Conclusion

if you want to just keep the numbers in the memory and want to iterate over it whenever necessary, the recommended way is to go with generators as its memory efficient

if want to access generators by index you can always convert a generator into a list like this list(generator)

Hope this helps!


问:
How to call external API in django application with username and password
I am trying to receive data from an API endpoint in my django application. I found the solution here: Django rest framework & external api.

But when I tried this solution I got error:

SSLError at /external-api
HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /example (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

When I open the external API directly on browser, I need to provide the username and password of the account which has access to that API. But while calling through API I am not providing it anywhere.

I am not sure how to set the username and password in the URL or in the settings file to access the external API.

Edited: Also I am not sure what could be the reason behind the error.

答:
Then the certificate on the remote host failed verification (search the error message for a number of causes). If you think that's fine, then you can pass turn off verification:

r = requests.get("https://example.com/consumers", timeout=10, verify=False)
```


问:
How to change default validation error message in ASP.NET MVC?
Say I have this property in my model:

```<code>[DisplayName("test")]
[Required(ErrorMessage = "required")]
public DateTime? SomeDate { get; set; }
</code>```

when you type in "asdf" in Html.TextBoxFor(model => model.SomeDate), you get the validation error message "The value 'asdf' is not valid for test.".

How do you modify that message? ASP.NET MVC ignored [DataType(DataType.DateTime, ErrorMessage = 'some other message')]

答:
Apparently my question was already answered at How to replace the default ModelState error message in Asp.net MVC 2? .

I'll summarize it here:

Create App_GlobalResources folder for your project (right click to project -> Add -> Add ASP.NET folder -> App_GlobalResources).

Add a resx file in that folder. Say MyNewResource.resx.

Add resource key PropertyValueInvalid with the desired message format (e.g. "content {0} is invalid for field {1}"). If you want to change PropertyValueRequired too add it as well.

Add the code DefaultModelBinder.ResourceClassKey = "MyNewResource" to your Global.asax startup code.

You're all set.

Body:
Say I have this property in my model:

[DisplayName("test")]
[Required(ErrorMessage = "required")]
public DateTime? SomeDate { get; set; }

when you type in "asdf" in Html.TextBoxFor(model => model.SomeDate), you get the validation error message "The value 'asdf' is not valid for test.".

How do you modify that message? ASP.NET MVC ignored [DataType(DataType.DateTime, ErrorMessage = 'some other message')]


问:
Out of memory error: Java heap memory on Android Studio
How do I fix java.lang.OutOfMemoryError: Java heap space when compiling my Android project?

I get this after I upgraded to version 1 of Android Studio. But, I don't think this is the problem. Most likely when I start upgrading my app to SDK 21 (before this was SDK 20). But I wasn't so sure either.

I've googled around for some fix, but couldn't find one that works. Most of the fix are for Eclipse IDE.

This is the full logcat error that I get when compiling:

```<code>warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.

UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: Java heap space
    at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
    at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
    at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
    at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
    at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
    at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
    at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
    at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
    at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
    at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
    at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
    at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
    at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
    at com.android.dx.command.dexer.Main.processClass(Main.java:729)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
    at com.android.dx.command.dexer.Main.access$300(Main.java:82)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:632)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
    at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
    at com.android.dx.command.dexer.Main.run(Main.java:243)
    at com.android.dx.command.dexer.Main.main(Main.java:214)
    at com.android.dx.command.Main.main(Main.java:106)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\sdfasd\android-sdks\build-tools\21.1.1\dx.bat --dex --no-optimize --multi-dex --main-dex-list C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\multi-dex\debug\maindexlist.txt --output C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\dex\debug --input-list=C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
    3
Output:
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.

    UNEXPECTED TOP-LEVEL ERROR:
    java.lang.OutOfMemoryError: Java heap space
        at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
        at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
        at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
        at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
        at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
        at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
        at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
        at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
        at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
        at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
        at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
        at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
        at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
        at com.android.dx.command.dexer.Main.processClass(Main.java:729)
        at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
        at com.android.dx.command.dexer.Main.access$300(Main.java:82)
        at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
        at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
        at com.android.dx.command.dexer.Main.processOne(Main.java:632)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
        at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
        at com.android.dx.command.dexer.Main.run(Main.java:243)
        at com.android.dx.command.dexer.Main.main(Main.java:214)
        at com.android.dx.command.Main.main(Main.java:106)
</code>```

Is it because of one jar library I used (zip4j)? I did try to remove it, but the OOM error still occurs. Any idea how to fix this?

Edit:

I've also edited gradlew file to increase the -Xmx size.

```<code>GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\" \"-Xmx2048M \"-XX:MaxPermSize=512M\" \"-XX:ReservedCodeCacheSize=512M\""
</code>```

Nothing changes.

Edit 2:

Also did this fix but couldn't help it too:

Try the following:

Ctrl + Alt + S -> Compiler -> Gradle

InVM Options field write:

```<code>-Xmx2048m -XX:MaxPermSize=512m
</code>```

答:
None of the answers worked for me but finally I found something that worked in my case:

Automatically managing paging files size

In windows:

Under "Advanced System Settings"

Advanced Tab

Performance section, settings...

Advanced Tab

Virtual memory... Change...

Select Automatically manage paging files size for all drives

I don't remember why I had this unchecked but this was causing trouble in my gradle builds (with flutter).

Body:
How do I fix java.lang.OutOfMemoryError: Java heap space when compiling my Android project?

I get this after I upgraded to version 1 of Android Studio. But, I don't think this is the problem. Most likely when I start upgrading my app to SDK 21 (before this was SDK 20). But I wasn't so sure either.

I've googled around for some fix, but couldn't find one that works. Most of the fix are for Eclipse IDE.

This is the full logcat error that I get when compiling:

warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.
warning: Ignoring InnerClasses attribute for an anonymous inner class
(net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
associated EnclosingMethod attribute. This class was probably produced by a
compiler that did not target the modern .class file format. The recommended
solution is to recompile the class from source, using an up-to-date compiler
and without specifying any "-target" type options. The consequence of ignoring
this warning is that reflective operations on this class will incorrectly
indicate that it is *not* an inner class.

UNEXPECTED TOP-LEVEL ERROR:
java.lang.OutOfMemoryError: Java heap space
    at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
    at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
    at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
    at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
    at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
    at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
    at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
    at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
    at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
    at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
    at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
    at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
    at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
    at com.android.dx.command.dexer.Main.processClass(Main.java:729)
    at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
    at com.android.dx.command.dexer.Main.access$300(Main.java:82)
    at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
    at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
    at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
    at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
    at com.android.dx.command.dexer.Main.processOne(Main.java:632)
    at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
    at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
    at com.android.dx.command.dexer.Main.run(Main.java:243)
    at com.android.dx.command.dexer.Main.main(Main.java:214)
    at com.android.dx.command.Main.main(Main.java:106)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\sdfasd\android-sdks\build-tools\21.1.1\dx.bat --dex --no-optimize --multi-dex --main-dex-list C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\multi-dex\debug\maindexlist.txt --output C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\dex\debug --input-list=C:\Users\asdfasdf\workspace\Baucar\app\build\intermediates\tmp\dex\debug\inputList.txt
Error Code:
    3
Output:
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.unzip.Unzip$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.util.ArchiveMaintainer$2) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.
    warning: Ignoring InnerClasses attribute for an anonymous inner class
    (net.lingala.zip4j.zip.ZipEngine$1) that doesn't come with an
    associated EnclosingMethod attribute. This class was probably produced by a
    compiler that did not target the modern .class file format. The recommended
    solution is to recompile the class from source, using an up-to-date compiler
    and without specifying any "-target" type options. The consequence of ignoring
    this warning is that reflective operations on this class will incorrectly
    indicate that it is *not* an inner class.

    UNEXPECTED TOP-LEVEL ERROR:
    java.lang.OutOfMemoryError: Java heap space
        at com.android.dx.rop.code.RegisterSpec$ForComparison.toRegisterSpec(RegisterSpec.java:642)
        at com.android.dx.rop.code.RegisterSpec.intern(RegisterSpec.java:73)
        at com.android.dx.rop.code.RegisterSpec.make(RegisterSpec.java:90)
        at com.android.dx.cf.code.RopperMachine.run(RopperMachine.java:323)
        at com.android.dx.cf.code.Simulator$SimVisitor.visitLocal(Simulator.java:612)
        at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:412)
        at com.android.dx.cf.code.Simulator.simulate(Simulator.java:94)
        at com.android.dx.cf.code.Ropper.processBlock(Ropper.java:787)
        at com.android.dx.cf.code.Ropper.doit(Ropper.java:742)
        at com.android.dx.cf.code.Ropper.convert(Ropper.java:349)
        at com.android.dx.dex.cf.CfTranslator.processMethods(CfTranslator.java:280)
        at com.android.dx.dex.cf.CfTranslator.translate0(CfTranslator.java:137)
        at com.android.dx.dex.cf.CfTranslator.translate(CfTranslator.java:93)
        at com.android.dx.command.dexer.Main.processClass(Main.java:729)
        at com.android.dx.command.dexer.Main.processFileBytes(Main.java:673)
        at com.android.dx.command.dexer.Main.access$300(Main.java:82)
        at com.android.dx.command.dexer.Main$1.processFileBytes(Main.java:602)
        at com.android.dx.cf.direct.ClassPathOpener.processArchive(ClassPathOpener.java:284)
        at com.android.dx.cf.direct.ClassPathOpener.processOne(ClassPathOpener.java:166)
        at com.android.dx.cf.direct.ClassPathOpener.process(ClassPathOpener.java:144)
        at com.android.dx.command.dexer.Main.processOne(Main.java:632)
        at com.android.dx.command.dexer.Main.processAllFiles(Main.java:505)
        at com.android.dx.command.dexer.Main.runMultiDex(Main.java:332)
        at com.android.dx.command.dexer.Main.run(Main.java:243)
        at com.android.dx.command.dexer.Main.main(Main.java:214)
        at com.android.dx.command.Main.main(Main.java:106)

Is it because of one jar library I used (zip4j)? I did try to remove it, but the OOM error still occurs. Any idea how to fix this?

Edit:

I've also edited gradlew file to increase the -Xmx size.

GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\" \"-Xmx2048M \"-XX:MaxPermSize=512M\" \"-XX:ReservedCodeCacheSize=512M\""

Nothing changes.

Edit 2:

Also did this fix but couldn't help it too:

Try the following:

Ctrl + Alt + S -> Compiler -> Gradle

InVM Options field write:

-Xmx2048m -XX:MaxPermSize=512m


问:
Stop PhpStorm from aligning associative arrays
How can I tell PhpStorm (using version 8.0.3) to keep the following array as is when clicking Cmd+Alt+L to reformat my code:

```<code>$array = [
    'short' => 1, // I want this...
    'veryVeryVeryIncrediblyLong' => 123456789,
];
</code>```

Instead of doing this:

```<code>$array = [
    'short'                      => 1, // Not this...
    'veryVeryVeryIncrediblyLong' => 123456789,
];
</code>```

答: PhpStorm 2019 and up: Settings -> editor -> PHP -> Wrapping and Braces -> Array initializer -> Align key-value pairs [*] (Linux OS)

Body:
How can I tell PhpStorm (using version 8.0.3) to keep the following array as is when clicking Cmd+Alt+L to reformat my code:

$array = [
    'short' => 1, // I want this...
    'veryVeryVeryIncrediblyLong' => 123456789,
];

Instead of doing this:

$array = [
    'short'                      => 1, // Not this...
    'veryVeryVeryIncrediblyLong' => 123456789,
];


问:
For loop with bitshifts
Can anyone explain how does this foor loop works?

for (bitMask = 0x01; bitMask; bitMask <<= 1)

This is the first time that I have encountered such a syntax in a for loop and would love to know how the loop would end.

答:
If you got an unsigned int32 variable bitMask. At the 32nd cycle, its bit representation is

```<code>10000000 00000000 00000000 00000000
</code>```

Then shift one bit left, it overflows, and only lower 32 bits are kept, so the value becomes 0 and the loop condition becomes false.

```<code>1 00000000 00000000 00000000 00000000
↑
this bit is discarded
</code>```

What about if bitMask is a signed int? Then it's an undefined behavior.

C standard (N2716, 6.5.7 Bitwise shift operators) says:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined

C++ standard (N4713, 8.5.7 Shift operators) says:

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in
  the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2^E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

My perspective is never use such kind of loop as we will easily forget this only works for an unsigned integer. Instead, you should use something like following to generate mask for each bit.

for (int i = 0; i < 32; i++) {
    int bitMask = 1 << i;
}
```

Title: For loop with bitshifts

Body:
If you got an unsigned int32 variable bitMask. At the 32nd cycle, its bit representation is

10000000 00000000 00000000 00000000

Then shift one bit left, it overflows, and only lower 32 bits are kept, so the value becomes 0 and the loop condition becomes false.

1 00000000 00000000 00000000 00000000
↑
this bit is discarded

What about if bitMask is a signed int? Then it's an undefined behavior.

C standard (N2716, 6.5.7 Bitwise shift operators) says:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined

C++ standard (N4713, 8.5.7 Shift operators) says:

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in
  the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2^E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

My perspective is never use such kind of loop as we will easily forget this only works for an unsigned integer. Instead, you should use something like following to generate mask for each bit.

for (int i = 0; i < 32; i++) {
    int bitMask = 1 << i;
}