答:
Either you mutate the variable:

```<code>fun main(args: Array<String>) {
    var listOfSeatRows = (1..127).toList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        listOfSeatRows = getListOfSeatRows(listOfSeatRows, seat)
    }
}
</code>```

or you mutate the list:

```<code>fun main(args: Array<String>) {
    var listOfSeatRows = (1..127).toMutableList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        reduceListOfSeatRows(listOfSeatRows, seat)
    }
}

private fun reduceListOfSeatRows(listOfSeat: MutableList<Int>, seatPosition: Seat) {
    val half = listOfSeat.size / 2
    when(seatPosition) {
        Seat.F, Seat.L -> {
            while (listOfSeat.size > half) listOfSeat.removeLast()
        }
        Seat.B, Seat.R -> {
            while (listOfSeat.size > half) listOfSeat.removeFirst()
        }
    }
}
</code>```

If you stick with mutating the property, your function can be simplified (and avoid wasteful creation of multiple intermediate lists) using take/takeLast:

```<code>private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
    return when(seatPosition) {
        Seat.F, Seat.L -> {
            listOfSeat.take(listOfSeat.size / 2)
        }
        Seat.B, Seat.R -> {
            listOfSeat.takeLast(listOfSeat.size / 2)
        }
    }
}
</code>```

Title: return a new list from function in a for loop to pass in the updated list

Body:
Either you mutate the variable:

fun main(args: Array<String>) {
    var listOfSeatRows = (1..127).toList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        listOfSeatRows = getListOfSeatRows(listOfSeatRows, seat)
    }
}

or you mutate the list:

fun main(args: Array<String>) {
    var listOfSeatRows = (1..127).toMutableList()

    // Just loop until all the listOfPass has completed.
    listOfPass.forEach { seatPass ->
        val seat = Seat.valueOf(seatPass.toString())
        // I want to pass in the new updated list not the same list
        reduceListOfSeatRows(listOfSeatRows, seat)
    }
}

private fun reduceListOfSeatRows(listOfSeat: MutableList<Int>, seatPosition: Seat) {
    val half = listOfSeat.size / 2
    when(seatPosition) {
        Seat.F, Seat.L -> {
            while (listOfSeat.size > half) listOfSeat.removeLast()
        }
        Seat.B, Seat.R -> {
            while (listOfSeat.size > half) listOfSeat.removeFirst()
        }
    }
}

If you stick with mutating the property, your function can be simplified (and avoid wasteful creation of multiple intermediate lists) using take/takeLast:

private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
    return when(seatPosition) {
        Seat.F, Seat.L -> {
            listOfSeat.take(listOfSeat.size / 2)
        }
        Seat.B, Seat.R -> {
            listOfSeat.takeLast(listOfSeat.size / 2)
        }
    }
}


来源: stackexchange

问:
How do you trigger a chrome extension via a keyboard shortcut?
I wrote a short chrome extension that works as intended when I click on it on my extension list.

Ie. my code runs onClicked (chrome.action.onClicked.addListener(...))

I would like to add a keyboard shortcut (eg. Ctrl+Shift+Q) but not sure how.

Any ideas?

For context: I don't really know javascript, I'm hacking this together as a helper for myself in my day to day work.

答:
You can use a command.

First step is to add the command to the manifest.json file.  I added an example down below it should look very similar to your, but the part you really need is the "commands": {} section.  This tells chrome to pay attention to when a user hits "Ctrl+Shift+Q".  Note you can add multiple commands, like in the example below.

```<code>{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },

  "devtools_page": "devtools.html",

  "commands": {
    "name-of-command-passed-into-function": {
      "suggested_key": "Ctrl+Shift+Q",
      "description": "do somthing"
    }
    "shortcut2": {
      "suggested_key": "Ctrl+Shift+A",
      "description": "do somthing else"
    }
  },
  "options_page": "options.html",
  "permissions": ["storage", "activeTab", "scripting","tabs"],
}
</code>```

Now when the user hits "Ctrl+Shift+Q" or "Ctrl+Shift+A", chrome will loos for some very specific code to run:

```<code>chrome.commands.onCommand.addListener((command,tab) => {
     //do stuff here
});
</code>```

Add this code and change the //do stuff here, to the code you want to run.  The command property will simply be a string that matches what was types into the manifest, "name-of-command-passed-into-function" or "shortcut2".  This is how you tell which command shortcut the user entered, but if you only need one, then delete the second one from the manifest file.

ContentLicense: CC BY-SA 4.0

Body:
You can use a command.

First step is to add the command to the manifest.json file.  I added an example down below it should look very similar to your, but the part you really need is the "commands": {} section.  This tells chrome to pay attention to when a user hits "Ctrl+Shift+Q".  Note you can add multiple commands, like in the example below.

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },

  "devtools_page": "devtools.html",

  "commands": {
    "name-of-command-passed-into-function": {
      "suggested_key": "Ctrl+Shift+Q",
      "description": "do somthing"
    }
    "shortcut2": {
      "suggested_key": "Ctrl+Shift+A",
      "description": "do somthing else"
    }
  },
  "options_page": "options.html",
  "permissions": ["storage", "activeTab", "scripting","tabs"],
}

Now when the user hits "Ctrl+Shift+Q" or "Ctrl+Shift+A", chrome will loos for some very specific code to run:

chrome.commands.onCommand.addListener((command,tab) => {
     //do stuff here
});

Add this code and change the //do stuff here, to the code you want to run.  The command property will simply be a string that matches what was types into the manifest, "name-of-command-passed-into-function" or "shortcut2".  This is how you tell which command shortcut the user entered, but if you only need one, then delete the second one from the manifest file.


问:
Preload Large Amounts of Datasets Before Attempting to Set Drop Down List Values
I'm attempting to load a rather large form (over 300 fields) on an angularjs razor page and I'm just struggling with it (I've only been learning and working with angularjs for 2 months).

The form has over 2 dozen drop down lists (I'm using angularjs-dropdown-multiselect.js for my controls) that depend on datasets that are being pulled from a service. I think need to pull a record of for the form they are loading that has all of the saved values for the form.  Then I set the selected value of each of the drop down lists.  The problem is, that my http.gets are not fully returned when the code executes to set the drop down list selected model.  This results in an error.  Sometimes I can get 15 or 16 of the datasets to pop before the code is executed to set the drop down list model, but it's variable depending on network traffic.

Is there any way to preload my data before the rest of the controller code executes?  I've tried using this for my get calls.

```<code>$http.get(myURL+ 'ProductsGet/' + ContactId)
        .then(function (response) {
            $scope.products = response.data;
        })
        .catch(function (data){
            $window.alert(data.xhrStatus);
        });
</code>```

Then this is where my code has a problem because the $scope.products is not actually set yet when this executes. The $scope.ds is set with another http.get data call.

```<code>  if ($scope.ds.productId!= null) {
                var prod = $filter('filter')($scope.products, function (value) { return value.productId === $scope.ds.productId; })
                $scope.productModel.push(prod[0]);
            }
</code>```

I've tried putting all of my data calls into a data factory and then using setting the $scope.products = dataFactory.GetProducts() but this still doesn't stop the controller code from executing so it plows right on through into the code that sets the drop down lists values.  I've tried using my own custom promise function:

```<code>   cachePromise = function () {
        var defer = $q.defer();
        $http.get(myURL+ 'ProductsGet/' + ContactId)
           .then(function (response) {
                $scope.products = response.data;
            })
            .catch(function (data){
                $window.alert(data.xhrStatus);
            });

       return defer.promise;
  };

   var init = function () {
       cachePromise().then(function succes() {
        if ($scope.profileId!= null) {
            $scope.view = 'Update';
            LoadProfileInformation();
        };
  };

 init();
</code>```

But the init function executes, it triggers the http.gets in the cachePromise function, but continues on into the LoadProfileInformation() function where I am seting the drop down list models based on my datasets and it fails because the gets haven't all returned data.

I tried setting up a $stateProvider using ui-router, but I kept getting errors trying to access the resolve function in the state provider from within my controller.  Here's an example of the state provider I tried used a dataset of franchiseTypes.  I kept getting an error that the franchiseTypeProvider was not defined.

```<code>var app = angular.module("myApp", ['ngResource', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.bootstrap', 'angularjs-dropdown-multiselect', 'ui.grid', 'ui.router' ]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = false;
    delete $httpProvider.defaults.headers.common["X-Requested-With"];
    $httpProvider.defaults.headers.common["Accept"] = "application/json";
    $httpProvider.defaults.headers.common["Content-Type"] = "application/json; charset=utf-8";
}
]);

app.config(['$stateProvider', '$urlRouterProvider',

    function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('MyPage', {
                url: '/MyPage',
                controller: 'InformationCtrl',
                resolve: {
                    franchiseTypes: function ($http) {
                        return $http({ method: "GET", url: myServiceURL + 'FranchiseTypesGet/' + sessionStorage.getItem('Id') });
                    }
                }
            });
    }

]);
app.controller("InformationCtrl", ['$scope', 'franchiseTypes', '$http', '$window', '$location', '$anchorScroll', '$filter', function ($scope, $http, $window, $location, $anchorScroll, $filter, franchiseTypes) {

//this is set as the source of one of my multi-select drop down lists
 $scope.franchiseTypeModel = [];

 $scope.franchiseTypes = franchiseTypes;

//$scope.ds is loaded through a http get request
 if ($scope.ds.FranchiseTypeId != null) {
    //this is what was failing in my original code because my data is not completely loaded by the time this code executes
    var fran = $filter('filter')($scope.franchiseTypes, function (value) { return value.FranchiseTypeId === $scope.ds.FranchiseTypeId ; })
    $scope.franchiseTypeModel.push(fran[0]);
  }
}]);
</code>```

Sorry for all of the code samples, I've been trying things for about two weeks now and can't get this to work.  My background is webforms and winforms where a line of code wouldn't be executed before the previously line of code is completely executed so trying to work with angularjs has been an interesting challenge.

答:
A helpful person on Reddit pointed me in the right direction. I ended up using something like this, with some of the get()s chained since one get() relies on the data from another get(). Posting this in case this helps someone else. I had tried chaining promises previously, but I wasn't sure how to use promises with $q.all, and still access the data returned from the promise.

This does everything I need it to. I just have all 20+ data calls added the the cachePromises array and then the LoadDataFields does not execute until they are all complete.

```<code>    $scope.cachePromises = [];
    $scope.cachePromises.push($http.get(myURL+ 'ProductGet/' + ContactId)
            .then(function (response) {
                $scope.products = response.data;
            })
            .catch(function (error) {
                $window.alert(error);
            })
    );

    $q.all($scope.cachePromises).then(function () {
           LoadDataFields();
    });
</code>```

Body:
I'm attempting to load a rather large form (over 300 fields) on an angularjs razor page and I'm just struggling with it (I've only been learning and working with angularjs for 2 months).

The form has over 2 dozen drop down lists (I'm using angularjs-dropdown-multiselect.js for my controls) that depend on datasets that are being pulled from a service. I think need to pull a record of for the form they are loading that has all of the saved values for the form.  Then I set the selected value of each of the drop down lists.  The problem is, that my http.gets are not fully returned when the code executes to set the drop down list selected model.  This results in an error.  Sometimes I can get 15 or 16 of the datasets to pop before the code is executed to set the drop down list model, but it's variable depending on network traffic.

Is there any way to preload my data before the rest of the controller code executes?  I've tried using this for my get calls.

$http.get(myURL+ 'ProductsGet/' + ContactId)
        .then(function (response) {
            $scope.products = response.data;
        })
        .catch(function (data){
            $window.alert(data.xhrStatus);
        });

Then this is where my code has a problem because the $scope.products is not actually set yet when this executes. The $scope.ds is set with another http.get data call.

  if ($scope.ds.productId!= null) {
                var prod = $filter('filter')($scope.products, function (value) { return value.productId === $scope.ds.productId; })
                $scope.productModel.push(prod[0]);
            }

I've tried putting all of my data calls into a data factory and then using setting the $scope.products = dataFactory.GetProducts() but this still doesn't stop the controller code from executing so it plows right on through into the code that sets the drop down lists values.  I've tried using my own custom promise function:

   cachePromise = function () {
        var defer = $q.defer();
        $http.get(myURL+ 'ProductsGet/' + ContactId)
           .then(function (response) {
                $scope.products = response.data;
            })
            .catch(function (data){
                $window.alert(data.xhrStatus);
            });

       return defer.promise;
  };

   var init = function () {
       cachePromise().then(function succes() {
        if ($scope.profileId!= null) {
            $scope.view = 'Update';
            LoadProfileInformation();
        };
  };

 init();

But the init function executes, it triggers the http.gets in the cachePromise function, but continues on into the LoadProfileInformation() function where I am seting the drop down list models based on my datasets and it fails because the gets haven't all returned data.

I tried setting up a $stateProvider using ui-router, but I kept getting errors trying to access the resolve function in the state provider from within my controller.  Here's an example of the state provider I tried used a dataset of franchiseTypes.  I kept getting an error that the franchiseTypeProvider was not defined.

var app = angular.module("myApp", ['ngResource', 'ngAnimate', 'ngTouch', 'ngSanitize', 'ui.bootstrap', 'angularjs-dropdown-multiselect', 'ui.grid', 'ui.router' ]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = false;
    delete $httpProvider.defaults.headers.common["X-Requested-With"];
    $httpProvider.defaults.headers.common["Accept"] = "application/json";
    $httpProvider.defaults.headers.common["Content-Type"] = "application/json; charset=utf-8";
}
]);

app.config(['$stateProvider', '$urlRouterProvider',

    function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('MyPage', {
                url: '/MyPage',
                controller: 'InformationCtrl',
                resolve: {
                    franchiseTypes: function ($http) {
                        return $http({ method: "GET", url: myServiceURL + 'FranchiseTypesGet/' + sessionStorage.getItem('Id') });
                    }
                }
            });
    }

]);
app.controller("InformationCtrl", ['$scope', 'franchiseTypes', '$http', '$window', '$location', '$anchorScroll', '$filter', function ($scope, $http, $window, $location, $anchorScroll, $filter, franchiseTypes) {

//this is set as the source of one of my multi-select drop down lists
 $scope.franchiseTypeModel = [];

 $scope.franchiseTypes = franchiseTypes;

//$scope.ds is loaded through a http get request
 if ($scope.ds.FranchiseTypeId != null) {
    //this is what was failing in my original code because my data is not completely loaded by the time this code executes
    var fran = $filter('filter')($scope.franchiseTypes, function (value) { return value.FranchiseTypeId === $scope.ds.FranchiseTypeId ; })
    $scope.franchiseTypeModel.push(fran[0]);
  }
}]);

Sorry for all of the code samples, I've been trying things for about two weeks now and can't get this to work.  My background is webforms and winforms where a line of code wouldn't be executed before the previously line of code is completely executed so trying to work with angularjs has been an interesting challenge.

Body:
A helpful person on Reddit pointed me in the right direction. I ended up using something like this, with some of the get()s chained since one get() relies on the data from another get(). Posting this in case this helps someone else. I had tried chaining promises previously, but I wasn't sure how to use promises with $q.all, and still access the data returned from the promise.

This does everything I need it to. I just have all 20+ data calls added the the cachePromises array and then the LoadDataFields does not execute until they are all complete.

    $scope.cachePromises = [];
    $scope.cachePromises.push($http.get(myURL+ 'ProductGet/' + ContactId)
            .then(function (response) {
                $scope.products = response.data;
            })
            .catch(function (error) {
                $window.alert(error);
            })
    );

    $q.all($scope.cachePromises).then(function () {
           LoadDataFields();
    });


问:
Why are items in a flex container not reordered when adding a new item?
I have two flex containers containing flex items, each with an order property. Each flex item has an event listener. When clicking on a flex item (a div in this case) the div moves to the other flex container.

But if I for instance click on the div with order 1 below, the new position will be to the right of the div with order 3 in the container with id #non-selected. So in some way the flex container is not updated. Do I do something wrong or is this the expected behaviour? I run Version 91.4.0esr, Firefox for openSUSE Leap, openSUSE-15.2 and Google Chrome Version 98.0.4758.80 (Official Build) (64-bit).

function moveOption() {

  let optionDivs = document.querySelectorAll('.item');

  optionDivs.forEach(function(div) {
    div.addEventListener('click', function() {
      if (this.parentElement.id === 'non-selected') {
        document.getElementById('selected').append(div);
      } else {
        document.getElementById('non-selected').append(div);
      }
    });
  });
}

moveOption();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#selected,
#non-selected {
  width: 50%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid black;
  padding: 3px;
  gap: 3px;
  background-color: white;
  height: 50px;
  max-height: 100px;
}

.item {
  border: 1px solid black;
  border-radius: 4px;
  background-color: #ccc;
  cursor: grab;
  width: max-content;
  box-sizing: border-box;
  align-items: center;
  display: flex;
  height: 40px;
  padding-right: 5px;
  padding-left: 5px;
}</code>```

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta charset="utf-8">

  Click or Order 1 "button" and it will be positioned right to the Order 3 "button" despite it has a lower value for the order property.

Order 1

Order 2

Order 3

```

答:
The non-standard order attribute does not affect ordering within a Flex or Grid container. You need to set the order CSS property instead.

So instead of:

```<code><div order="1">
</code>```

you need:

```<code><div style="order:1;">
</code>```

Updated demo:

function moveOption() {

  let optionDivs = document.querySelectorAll('.item');

  optionDivs.forEach(function(div) {
    div.addEventListener('click', function() {
      if (this.parentElement.id === 'non-selected') {
        document.getElementById('selected').append(div);
      } else {
        document.getElementById('non-selected').append(div);
      }
    });
  });
}

moveOption();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#selected,
#non-selected {
  width: 50%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid black;
  padding: 3px;
  gap: 3px;
  background-color: white;
  height: 50px;
  max-height: 100px;
}

.item {
  border: 1px solid black;
  border-radius: 4px;
  background-color: #ccc;
  cursor: grab;
  width: max-content;
  box-sizing: border-box;
  align-items: center;
  display: flex;
  height: 40px;
  padding-right: 5px;
  padding-left: 5px;
}</code>```

Order 1

Order 2

Order 3

```

Body:
I have two flex containers containing flex items, each with an order property. Each flex item has an event listener. When clicking on a flex item (a div in this case) the div moves to the other flex container.

But if I for instance click on the div with order 1 below, the new position will be to the right of the div with order 3 in the container with id #non-selected. So in some way the flex container is not updated. Do I do something wrong or is this the expected behaviour? I run Version 91.4.0esr, Firefox for openSUSE Leap, openSUSE-15.2 and Google Chrome Version 98.0.4758.80 (Official Build) (64-bit).

function moveOption() {

  let optionDivs = document.querySelectorAll('.item');

  optionDivs.forEach(function(div) {
    div.addEventListener('click', function() {
      if (this.parentElement.id === 'non-selected') {
        document.getElementById('selected').append(div);
      } else {
        document.getElementById('non-selected').append(div);
      }
    });
  });
}

moveOption();

#selected,
#non-selected {
  width: 50%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid black;
  padding: 3px;
  gap: 3px;
  background-color: white;
  height: 50px;
  max-height: 100px;
}

.item {
  border: 1px solid black;
  border-radius: 4px;
  background-color: #ccc;
  cursor: grab;
  width: max-content;
  box-sizing: border-box;
  align-items: center;
  display: flex;
  height: 40px;
  padding-right: 5px;
  padding-left: 5px;
}

  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta charset="utf-8">

  Click or Order 1 "button" and it will be positioned right to the Order 3 "button" despite it has a lower value for the order property.

Order 1

Order 2

Order 3

Body:
The non-standard order attribute does not affect ordering within a Flex or Grid container. You need to set the order CSS property instead.

So instead of:

<div order="1">

you need:

<div style="order:1;">

Updated demo:

function moveOption() {

  let optionDivs = document.querySelectorAll('.item');

  optionDivs.forEach(function(div) {
    div.addEventListener('click', function() {
      if (this.parentElement.id === 'non-selected') {
        document.getElementById('selected').append(div);
      } else {
        document.getElementById('non-selected').append(div);
      }
    });
  });
}

moveOption();

#selected,
#non-selected {
  width: 50%;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  border: 1px solid black;
  padding: 3px;
  gap: 3px;
  background-color: white;
  height: 50px;
  max-height: 100px;
}

.item {
  border: 1px solid black;
  border-radius: 4px;
  background-color: #ccc;
  cursor: grab;
  width: max-content;
  box-sizing: border-box;
  align-items: center;
  display: flex;
  height: 40px;
  padding-right: 5px;
  padding-left: 5px;
}

<div id="selected">
  <div style="order:1;" class="item">Order 1</div>
  <div style="order:2;" class="item">Order 2</div>
</div>

<div id="non-selected">
  <div style="order:3;" class="item">Order 3</div>
</div>


问:
Find first file in directory with Java
I have some sort of batch program that should pick up a file from a directory and process it.

Since this program is supposed to:

run on JDK 5,

be small (no external libraries)

and fast! (with a bang)

...what is the best way to only pick one file from the directory - without using File.list() (might be hundreds of files)?

答: If one look at the class class FileSystem which it boils down to for filesystem access there is only the list method so there seems to be no other way in "pure" JAVA to select a file than to list them all in a String array.</p>

ContentLicense: CC BY-SA 3.0

Title: Find first file in directory with Java


问:
Django Model Inheritance to multiple apps
```<code>class People(models.Model):

    # Utility Fields - auto fill

    # Timestamp

    # Base Fields

    # Methods, e.g save, get_absolute_url

    class Meta:
          abstract = True
</code>```

App clients: inherit from People model + its own Fields

App vendors: inherit from People model + its own Fields

Questions

Q1: Where should I place the code for the People model, since I want to use it for more than 2 apps?

Q2: Is this practice acceptable?

Q3: Will it work in a production environment efficiently?

答:
Q1: Where should I place the code for the People model, since I want to use it for more than 2 apps?

Just create a third app for abstract models. It's fine.

Q2: Is this practice acceptable?

Yes. abstract = True is just intended for this.

Q3: Will it work in a production environment efficiently?

Yes, also, abstract = True does not create new db tables or relations, is just code.

Body:
class People(models.Model):

    # Utility Fields - auto fill

    # Timestamp

    # Base Fields

    # Methods, e.g save, get_absolute_url

    class Meta:
          abstract = True

App clients: inherit from People model + its own Fields

App vendors: inherit from People model + its own Fields

Questions

Q1: Where should I place the code for the People model, since I want to use it for more than 2 apps?

Q2: Is this practice acceptable?

Q3: Will it work in a production environment efficiently?


问:
How to perform operation on specific elements of a list?
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

```<code>i=['0','7','2','3','4']
o=['0','14','2,'6','4']
</code>```

here's the code I tried:

```<code>list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)
</code>```

here's the error I get:

```<code>PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting
</code>```

答:
ls = ['1', '2', '3']

for i, el in enumerate(ls):
  if int(el) % 2:
    ls[i] = str(int(el)*2)

print(ls)
# prints ['2', '2', '6']
```
<p>If you intend to not mutate the input list and create a new list for the results:</p>
<pre class="lang-py prettyprint-override"><code>ls = ['1', '2', '3']
res = []

for el in ls:
  if int(el) % 2:
    res.append(str(int(el)*2))
  else:
    res.append(el)

print(res)
# prints ['2', '2', '6']
</code>```

If the input list were only integers you wouldn't need to convert the elements to integers and back to strings, of course:

ls = [1, 2, 3]

for i, el in enumerate(ls):
  if el % 2:
    ls[i] = el*2

print(ls)
# prints [2, 2, 6]
```

Please avoid naming your lists list. This shadows the list type of python and can create a lot of confusion and subtle bugs later on.

Body:
So, I want the odd numbers of the list to be multiplied by two and form a new list with the same index value but no other changes in the initial list,
for example i is the initial list and o is the output i want

i=['0','7','2','3','4']
o=['0','14','2,'6','4']

here's the code I tried:

list=["1","3","7"]

for num in list:

    if num%2!=0:

        num*2

print(list)

here's the error I get:

PS C:\Users\suhas\Desktop\sujan> & C:/Users/suhas/AppData/Local/Programs/Python/Python39/python.exe c:/Users/suhas/Desktop/sujan/user_testing.py
Traceback (most recent call last):
  File "c:\Users\suhas\Desktop\sujan\user_testing.py", line 5, in <module>
    if num%2!=0:
TypeError: not all arguments converted during string formatting

Body:
ls = ['1', '2', '3']

for i, el in enumerate(ls):
  if int(el) % 2:
    ls[i] = str(int(el)*2)

print(ls)
# prints ['2', '2', '6']

If you intend to not mutate the input list and create a new list for the results:

ls = ['1', '2', '3']
res = []

for el in ls:
  if int(el) % 2:
    res.append(str(int(el)*2))
  else:
    res.append(el)

print(res)
# prints ['2', '2', '6']

If the input list were only integers you wouldn't need to convert the elements to integers and back to strings, of course:

ls = [1, 2, 3]

for i, el in enumerate(ls):
  if el % 2:
    ls[i] = el*2

print(ls)
# prints [2, 2, 6]

Please avoid naming your lists list. This shadows the list type of python and can create a lot of confusion and subtle bugs later on.


问:
return custom message from API gateway lambda Authorizer
I have a API gateway lambda Authorizer and when it fails it all i am getting is

```<code>{
   "Message": "User is not authorized to access this resource with an explicit deny"
}
</code>```

and the status code is 403

My lambda is written in dotnet core. The thing is i am doing something if my authentication failed and the status code should be 401 for that to happen. So just wanted to know if we have a way to customize this behavior

答:
You can configure your Access Denied response in the Gateway Responses section of your API Gateway.
Both response template and status code can be configured there.

If you want the response to include custom data, you can add it to the context map returned from your Lambda Authorizer (see Output from an Amazon API Gateway Lambda authorizer for more info).

This way you can customize your Access Denied response template, for example:

```<code>{
  "message": "$context.authorizer.error_message"
}
</code>```

Obviously you can include multiple properties and return more complex responses.

Body:
I have a API gateway lambda Authorizer and when it fails it all i am getting is

{
   "Message": "User is not authorized to access this resource with an explicit deny"
}

and the status code is 403

My lambda is written in dotnet core. The thing is i am doing something if my authentication failed and the status code should be 401 for that to happen. So just wanted to know if we have a way to customize this behavior

Body:
You can configure your Access Denied response in the Gateway Responses section of your API Gateway.
Both response template and status code can be configured there.

If you want the response to include custom data, you can add it to the context map returned from your Lambda Authorizer (see Output from an Amazon API Gateway Lambda authorizer for more info).

This way you can customize your Access Denied response template, for example:

{
  "message": "$context.authorizer.error_message"
}

Obviously you can include multiple properties and return more complex responses.


问:
Can you start AI platform jobs from HTTP requests?
I have a web app (react + node.js) running on App Engine.

I would like to kick off (from this web app) a Machine Learning job that requires a GPU (running in a container on AI platform or running on GKE using a GPU node pool like in this tutorial, but we are open to other solutions).

I was thinking of trying what is described at the end of this answer, basically making an HTTP request to start the job using project.job.create API.

More details on the ML job in case this is useful: it generates an output every second that is stored on Cloud Storage and then read in the web app.

I am looking for examples of how to set this up? Where would the job configuration live and how should I set up the API call to kick off that job? Are the there other ways to achieve the same result?

Thank you in advance!

答:
As mentionated, you can use the AI Platform api to create a job via a post.
Following is an example using Java Script and request to trig a job.
Some usefull tips:

Jobs console to create a job manually, then use the api to list this job then you will have a perfect json example of how to trig it.

You can use the Try this API tool to get the json output of the manually created job. Use this path to get the job: projects/<project name>/jobs/<job name>.

Get the authorization token using the OAuth 2.0 Playground for tests purposes (Step 2 -> Access token:). Check the docs for a definitive way.

Not all parameters are required on the json, thtas jus one example of the job that I have created and got the json using the steps above.

JS Example:

var request = require('request');

request({
  url: 'https://content-ml.googleapis.com/v1/projects/<project-name>/jobs?alt=json',
  method: 'POST',
  headers: {"authorization": "Bearer ya29.A0AR9999999999999999999999999"},
  json: {
    "jobId": "<job name>",
    "trainingInput": {
      "scaleTier": "CUSTOM",
      "masterType": "standard",
      "workerType": "cloud_tpu",
      "workerCount": "1",
      "args": [
        "--training_data_path=gs://<bucket>/*.jpg",
        "--validation_data_path=gs://<bucket>/*.jpg",
        "--num_classes=2",
        "--max_steps=2",
        "--train_batch_size=64",
        "--num_eval_images=10",
        "--model_type=efficientnet-b0",
        "--label_smoothing=0.1",
        "--weight_decay=0.0001",
        "--warmup_learning_rate=0.0001",
        "--initial_learning_rate=0.0001",
        "--learning_rate_decay_type=cosine",
        "--optimizer_type=momentum",
        "--optimizer_arguments=momentum=0.9"
      ],
      "region": "us-central1",
      "jobDir": "gs://<bucket>",
      "masterConfig": {
        "imageUri": "gcr.io/cloud-ml-algos/image_classification:latest"
      }
    },
    "trainingOutput": {
      "consumedMLUnits": 1.59,
      "isBuiltInAlgorithmJob": true,
      "builtInAlgorithmOutput": {
        "framework": "TENSORFLOW",
        "runtimeVersion": "1.15",
        "pythonVersion": "3.7"
      }
    }
  }
}, function(error, response, body){
  console.log(body);
});
```
<p>Result:</p>
<pre class="lang-json prettyprint-override"><code>...
{
 createTime: '2022-02-09T17:36:42Z',
  state: 'QUEUED',
  trainingOutput: {
    isBuiltInAlgorithmJob: true,
    builtInAlgorithmOutput: {
      framework: 'TENSORFLOW',
      runtimeVersion: '1.15',
      pythonVersion: '3.7'
    }
  },
  etag: '999999aaaac='
</code>```

Body:
As mentionated, you can use the AI Platform api to create a job via a post.
Following is an example using Java Script and request to trig a job.
Some usefull tips:

Jobs console to create a job manually, then use the api to list this job then you will have a perfect json example of how to trig it.

You can use the Try this API tool to get the json output of the manually created job. Use this path to get the job: projects/<project name>/jobs/<job name>.

Get the authorization token using the OAuth 2.0 Playground for tests purposes (Step 2 -> Access token:). Check the docs for a definitive way.

Not all parameters are required on the json, thtas jus one example of the job that I have created and got the json using the steps above.

JS Example:

var request = require('request');

request({
  url: 'https://content-ml.googleapis.com/v1/projects/<project-name>/jobs?alt=json',
  method: 'POST',
  headers: {"authorization": "Bearer ya29.A0AR9999999999999999999999999"},
  json: {
    "jobId": "<job name>",
    "trainingInput": {
      "scaleTier": "CUSTOM",
      "masterType": "standard",
      "workerType": "cloud_tpu",
      "workerCount": "1",
      "args": [
        "--training_data_path=gs://<bucket>/*.jpg",
        "--validation_data_path=gs://<bucket>/*.jpg",
        "--num_classes=2",
        "--max_steps=2",
        "--train_batch_size=64",
        "--num_eval_images=10",
        "--model_type=efficientnet-b0",
        "--label_smoothing=0.1",
        "--weight_decay=0.0001",
        "--warmup_learning_rate=0.0001",
        "--initial_learning_rate=0.0001",
        "--learning_rate_decay_type=cosine",
        "--optimizer_type=momentum",
        "--optimizer_arguments=momentum=0.9"
      ],
      "region": "us-central1",
      "jobDir": "gs://<bucket>",
      "masterConfig": {
        "imageUri": "gcr.io/cloud-ml-algos/image_classification:latest"
      }
    },
    "trainingOutput": {
      "consumedMLUnits": 1.59,
      "isBuiltInAlgorithmJob": true,
      "builtInAlgorithmOutput": {
        "framework": "TENSORFLOW",
        "runtimeVersion": "1.15",
        "pythonVersion": "3.7"
      }
    }
  }
}, function(error, response, body){
  console.log(body);
});

Result:

...
{
 createTime: '2022-02-09T17:36:42Z',
  state: 'QUEUED',
  trainingOutput: {
    isBuiltInAlgorithmJob: true,
    builtInAlgorithmOutput: {
      framework: 'TENSORFLOW',
      runtimeVersion: '1.15',
      pythonVersion: '3.7'
    }
  },
  etag: '999999aaaac='


问:
stdout log files are empty in azure web service
I have created an azure web service app used for testing purposes and run into a .Net / http issue (500.30). Ive looked into a lot of troubleshooting but nothing has worked or pointed me in the right direction.

It seems to get more info on the issue, I can use the stdout logs in the Azure app service through Kudu. This has been configured this and the files it creates are blank? Has anyone encountered this before?

What have I did, I set it up in the web.config file setting the stdlog to true but this creates the files with no info. I then removed the inprocess=hosting section as I read this fixed it for others but no joy.

Any pointers in the right direction would be appreciated

答:
HTTP Error 500.30, The log file is created but empty - This kind of scenario is trapped by the SDK when publishing a self-contained app.

There is a term called RID (Runtime Identifier) used to identify target platforms where a .NET Core application runs.

If the RID doesn't match the platform target then the SDK produces the above kind of errors.

For example, win10-x64 RID with <PlatformTarget>x86</PlatformTarget> in the project file.

Troubleshooting steps:

<PlatformTarget>x86</PlatformTarget> enables the IIS app pool for 32-bit apps in an x86 framework-dependent deployment and set Enable 32-bit Apps to True from the app pool's Advanced Settings of IIS Manager.

500.30 is In-Process Startup Failure as it's cause can be usually determined from entries in the Application Event Log and the ASP .NET Core Module stdout log.

The app is misconfigured due to targeting a version of the ASP .NET Core shared framework that isn't present. Check which versions of the ASP .NET Core Shared framework are installed on the target machine.

If you're using Azure Key Vault, check the policies in the targeted Key Vault to ensure that the correct permissions are granted.

Also, please visit this Thread related to logging not working fix.

And Application Insights should be enabled to get the log files in the Storage account.

You can stream the logs from the portal or using CLI:

```<code>az webapp log tail --name appname --resource-group myResourceGroup
</code>```

Use this reference to get the logs using the simple queries.

Body:
HTTP Error 500.30, The log file is created but empty - This kind of scenario is trapped by the SDK when publishing a self-contained app.

There is a term called RID (Runtime Identifier) used to identify target platforms where a .NET Core application runs.

If the RID doesn't match the platform target then the SDK produces the above kind of errors.

For example, win10-x64 RID with <PlatformTarget>x86</PlatformTarget> in the project file.

Troubleshooting steps:

<PlatformTarget>x86</PlatformTarget> enables the IIS app pool for 32-bit apps in an x86 framework-dependent deployment and set Enable 32-bit Apps to True from the app pool's Advanced Settings of IIS Manager.

500.30 is In-Process Startup Failure as it's cause can be usually determined from entries in the Application Event Log and the ASP .NET Core Module stdout log.

The app is misconfigured due to targeting a version of the ASP .NET Core shared framework that isn't present. Check which versions of the ASP .NET Core Shared framework are installed on the target machine.

If you're using Azure Key Vault, check the policies in the targeted Key Vault to ensure that the correct permissions are granted.

Also, please visit this Thread related to logging not working fix.

And Application Insights should be enabled to get the log files in the Storage account.

You can stream the logs from the portal or using CLI:

az webapp log tail --name appname --resource-group myResourceGroup

Use this reference to get the logs using the simple queries.


问:
2 boxes side by side, the second box goes off screen
I'm trying to make 2 boxes side by side and in smaller screen the second box goes off screen
like this:

I want it stay like this until at least 900px width
but the problem when screen be bigger the gap is disappears then expands
https://media.giphy.com/media/33a0O0ra1S3Ou8F7u0/giphy.gif

this is my code

.boxes {
  background-color: blue;
  display: flex;
  justify-content: space-between;
  gap: 1rem;
}

.box {
  width: 820px;
  height: 300px;
  margin-left: 0.5rem;
}

.box-1 {
  margin-bottom: 0.5rem;
  background-color: antiquewhite;
  margin-right: 1.5rem;
}

.box-2 {
  position: absolute;
  left: 95%;
  background-color: cadetblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="boxes">
  <div class="box box-1">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>

  </div>
  <div class="box box-2">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.
    </p>
  </div>

</div></code>```

答:
You can add a media query to do that. Add this to you CSS :</p>
```<code>@media all and ( min-width:900px) {
  .box-2 {
     position: relative;
     left: 0;
  }
}
</code>```

Body:
I'm trying to make 2 boxes side by side and in smaller screen the second box goes off screen
like this:

I want it stay like this until at least 900px width
but the problem when screen be bigger the gap is disappears then expands
https://media.giphy.com/media/33a0O0ra1S3Ou8F7u0/giphy.gif

this is my code

.boxes {
  background-color: blue;
  display: flex;
  justify-content: space-between;
  gap: 1rem;
}

.box {
  width: 820px;
  height: 300px;
  margin-left: 0.5rem;
}

.box-1 {
  margin-bottom: 0.5rem;
  background-color: antiquewhite;
  margin-right: 1.5rem;
}

.box-2 {
  position: absolute;
  left: 95%;
  background-color: cadetblue;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque.

Body:
You can add a media query to do that. Add this to you CSS :

@media all and ( min-width:900px) {
  .box-2 {
     position: relative;
     left: 0;
  }
}


问:
How would you grab old responses in cypress?
I have been trying to grab an old response to assert it has a certain response.

The issue is that the same call is posted at the same time and I can only grab the second response.

I was just wondering if there was a way to grab both responses so I can read each body to make sure the correct posts are made

I have used the following

public assertMixPanelCall(call: string): void {
        cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
            if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
              req.alias = 'correctBody'
            }
          });
        cy.wait('@correctBody');
    }
```

So the response I get is the last response,
But I want to grab the penultimate response

答:
I'm not seeing the complete picture, but I think you can use this pattern Intercepting a response

let responseCount = 0;
cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
  if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {

    req.continue((res) => {
      responseCount++;
      if (responseCount === 1) {
        req.alias = 'penultimate'
      }
      if (responseCount === 2) {
        req.alias = 'final'
      }
    })
  }
});
cy.wait('@penultimate')
```
<p>Not sure if dynamic aliasing works on a per-response basis.</p>
<p>There's also an undocumented alias suffix that lets you access the nth response</p>
<pre class="lang-js prettyprint-override"><code>cy.wait('@correctBody');   // must wait first
cy.get('@correctBody.1');  // then get to access response history
                           // - not sure if you need @correctBody.0 or @correctBody.1
</code>```

But I can't see why cy.wait('@correctBody') doesn't catch the first response, generally you need to issue the wait twice to get both responses. Anyway, there's some things to try out here.

Body:
I have been trying to grab an old response to assert it has a certain response.

The issue is that the same call is posted at the same time and I can only grab the second response.

I was just wondering if there was a way to grab both responses so I can read each body to make sure the correct posts are made

I have used the following

public assertMixPanelCall(call: string): void {
        cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
            if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {
              req.alias = 'correctBody'
            }
          });
        cy.wait('@correctBody');
    }

So the response I get is the last response,
But I want to grab the penultimate response

Body:
I'm not seeing the complete picture, but I think you can use this pattern Intercepting a response

let responseCount = 0;
cy.intercept('POST', 'https://api-js.mixpanel.com/track/*', (req) => {
  if (atob(req.body.replace('data=', '')).includes(`"event": "${call}"`)) {

    req.continue((res) => {
      responseCount++;
      if (responseCount === 1) {
        req.alias = 'penultimate'
      }
      if (responseCount === 2) {
        req.alias = 'final'
      }
    })
  }
});
cy.wait('@penultimate')

Not sure if dynamic aliasing works on a per-response basis.

There's also an undocumented alias suffix that lets you access the nth response

cy.wait('@correctBody');   // must wait first
cy.get('@correctBody.1');  // then get to access response history
                           // - not sure if you need @correctBody.0 or @correctBody.1

But I can't see why cy.wait('@correctBody') doesn't catch the first response, generally you need to issue the wait twice to get both responses. Anyway, there's some things to try out here.


问:
RxJS - How to 'pipe' an Observable's result into another subject in one stream
In RxJS I sometimes come across an occasion when I have one Observable emitting, and I would like to 'trigger' another Observable's emission.

For example:

```<code>subject1$.subscribe(result => {/**/})

//...later

someObservable$.subscribe(result => {
  subject1$.next(result);
});
</code>```

I'd rather avoid two streams, but I can't work out is there's a pipable operator I can use to 'pipe' any omissions from someObservable$ into subject1$.

答:
A Subject is both an Observable and an Observer.

The tap operator accepts and Observer as its parameter.

The subscribe function also accepts and Observer as its parameter.

Putting all these things together, you may look at something like this

```<code>subject1$.subscribe(result => {/**/})

//...later

someObservable$.tap(subject1$).subscribe();

// or

someObservable$.subscribe(subject1$);
</code>```

Body:
In RxJS I sometimes come across an occasion when I have one Observable emitting, and I would like to 'trigger' another Observable's emission.

For example:

subject1$.subscribe(result => {/**/})

//...later

someObservable$.subscribe(result => {
  subject1$.next(result);
});

I'd rather avoid two streams, but I can't work out is there's a pipable operator I can use to 'pipe' any omissions from someObservable$ into subject1$.

Body:
A Subject is both an Observable and an Observer.

The tap operator accepts and Observer as its parameter.

The subscribe function also accepts and Observer as its parameter.

Putting all these things together, you may look at something like this

subject1$.subscribe(result => {/**/})

//...later

someObservable$.tap(subject1$).subscribe();

// or

someObservable$.subscribe(subject1$);


问:
Python requests.get content encoding problem
I am working on a scraping project using requests.get. The html file contains a relative path of the form href="../_static/new_page.html" for the css file.
I am using the below code to get the html file

```<code>import requests
url = "www.example.com"
req = requests.get(url)
req.content
</code>```

All the href containing "../_static" become "_static/...". I tried req.text and changed the encoding to utf-8, which is the encoding of the page. However, I am always getting the same result. I also tried urllib.request.get, and I also got the same problem.
Any suggestions!

答:
Adam.

Yes, it will be related to encoding format when you write the response content to Html file.

but you just have to consider the encoding type of response content itself.

Just check the encoding type of your requests library.

response = requests.get("url")
print(response.encoding)
```

You just need to choose the right encoding type like above.

response.encoding = "utf-8"

or

response.encoding = "ISO-8859-1"

or

response.encoding = "utf-8-sig"

...

Hope my answer helps you.

Regards

Body:
I am working on a scraping project using requests.get. The html file contains a relative path of the form href="../_static/new_page.html" for the css file.
I am using the below code to get the html file

import requests
url = "www.example.com"
req = requests.get(url)
req.content

All the href containing "../_static" become "_static/...". I tried req.text and changed the encoding to utf-8, which is the encoding of the page. However, I am always getting the same result. I also tried urllib.request.get, and I also got the same problem.
Any suggestions!

Body:
Adam.

Yes, it will be related to encoding format when you write the response content to Html file.

but you just have to consider the encoding type of response content itself.

Just check the encoding type of your requests library.

response = requests.get("url")
print(response.encoding)

You just need to choose the right encoding type like above.

response.encoding = "utf-8"

or

response.encoding = "ISO-8859-1"

or

response.encoding = "utf-8-sig"

...

Hope my answer helps you.

Regards


问:
for each output of a select statement, execute another query
Please consider this question:

A sqlite db with two tables, and I need to take bookName from one table and generate count on each of the results in another table.

$ sqlite3 Sqlite.db "select bookName from books"
myBook.1
myBook.2
myBook.3
myBook.4
myBook.5
```
<p>Tried subQuery, probably wrongly, with wrong results:</p>
<pre class="lang-sql prettyprint-override"><code>sqlite> select count(*) from tags where bookName = (select bookName from books);
753
</code>```

This is what I am trying to do:

$ sqlite3 SSqlite.db "select bookName from books" | while read a ; do  sqlite3 Sqlite.db "select bookName,count(*) from tags where bookName = \"$a\""; done
myBook.1|753
myBook.2|677
myBook.3|573
myBook.4|656
myBook.5|103
```

This must be possible much simpler within SQL, any input is much appreciated!

答:
If you want results only for the books in the table tags, then you should group by bookName:

```<code>SELECT COUNT(*) counter
FROM tags
GROUP BY bookName;
</code>```

If you want results for all the books in the table books then use a LEFT join and aggregation:

```<code>SELECT b.bookName, COUNT(t.bookName) counter
FROM books b LEFT JOIN tags t
ON t.bookName = b.bookName
GROUP BY b.bookName;
</code>```

Body:
Please consider this question:

A sqlite db with two tables, and I need to take bookName from one table and generate count on each of the results in another table.

$ sqlite3 Sqlite.db "select bookName from books"
myBook.1
myBook.2
myBook.3
myBook.4
myBook.5

Tried subQuery, probably wrongly, with wrong results:

sqlite> select count(*) from tags where bookName = (select bookName from books);
753

This is what I am trying to do:

$ sqlite3 SSqlite.db "select bookName from books" | while read a ; do  sqlite3 Sqlite.db "select bookName,count(*) from tags where bookName = \"$a\""; done
myBook.1|753
myBook.2|677
myBook.3|573
myBook.4|656
myBook.5|103

This must be possible much simpler within SQL, any input is much appreciated!

Body:
If you want results only for the books in the table tags, then you should group by bookName:

SELECT COUNT(*) counter
FROM tags
GROUP BY bookName;

If you want results for all the books in the table books then use a LEFT join and aggregation:

SELECT b.bookName, COUNT(t.bookName) counter
FROM books b LEFT JOIN tags t
ON t.bookName = b.bookName
GROUP BY b.bookName;


问:
Dynamic sheet name change bases on a range
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}```

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

答:
I found this StackOverflow that has a code that answer this question:

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1]; //Sheet 2
  var cell = sheet.getRange("A2");//Sheet2!A2
  var value = cell.getValue();//Added
  sheet.setName(value);//Sheet2 name changed
}
</code>```

Here is the Google Documentation.

Body:
I would like to get the current month weeks number on this range C3:C8. Based on that values, to rename the following tabs names: Sheet3, Sheet4, Sheet5, Sheet6, Sheet7, Sheet8

Also, I would like this script to work only on sheet name: Sheet1

Is there a google script that can acomplish this request?
I would really appreciate it.
Thank you very much!

function sheetsNames(){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sh = ss.getSheetByName('Sheet1')
  var values = sh.getRange('C3:C8').getValues()
  for (var i=values.length-1;i>=0;i--){
    ss.getSheets()[i+3].setName(values[i][0])
  }
}

UPDATE: I'm trying to attach the function renameSheetTabs() into a drawing but for some reason I'm getting the following error.

Body:
I found this StackOverflow that has a code that answer this question:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1]; //Sheet 2
  var cell = sheet.getRange("A2");//Sheet2!A2
  var value = cell.getValue();//Added
  sheet.setName(value);//Sheet2 name changed
}

Here is the Google Documentation.


问:
Installing AWS CLI v2 through PIP on Windows
Is it possible to install AWS CLI v2 through PIP on Windows?

In the instructions the recommended way to install is via MSI, but I want to use PIP.

What if I install CLI like given on Github in a Linux way:

```<code>python -m pip install awscli
</code>```

Will it install v1 or v2 by default?

答:
For people would like to use pipx to isolate between environments, the url mentioned by @FlyingTeller git+https://github.com/aws/aws-cli/tree/v2 does not work with pipx, instead you can try this:

```<code>pipx install git+https://github.com/aws/aws-cli.git@v2
</code>```

After that you can see:

```<code>$ aws --version
aws-cli/2.4.17 Python/3.9.9 Linux/5.4.0-99-generic source/x86_64.ubuntu.20 prompt/off
</code>```

Body:
Is it possible to install AWS CLI v2 through PIP on Windows?

In the instructions the recommended way to install is via MSI, but I want to use PIP.

What if I install CLI like given on Github in a Linux way:

python -m pip install awscli

Will it install v1 or v2 by default?

Body:
For people would like to use pipx to isolate between environments, the url mentioned by @FlyingTeller git+https://github.com/aws/aws-cli/tree/v2 does not work with pipx, instead you can try this:

pipx install git+https://github.com/aws/aws-cli.git@v2

After that you can see:

$ aws --version
aws-cli/2.4.17 Python/3.9.9 Linux/5.4.0-99-generic source/x86_64.ubuntu.20 prompt/off


答:
If I understand correctly you are looking for grouping query... You almost got that right:

```<code>select bookName, count(*) from tags group by bookName;
</code>```

Depending on your case you might want to join or right join with your other table (books).

Check documentation about:

GROUP BY

JOIN

Title: for each output of a select statement, execute another query

Body:
If I understand correctly you are looking for grouping query... You almost got that right:

select bookName, count(*) from tags group by bookName;

Depending on your case you might want to join or right join with your other table (books).

Check documentation about:

GROUP BY

JOIN


问:
Partially implement an Interface
I asked something similar but still I haven't got a clear idea. My objective is to partially implement an interface in C#.

Is it possible? Is there any pattern to achieve this result?

答:
I had a bunch of Query classes with a common interface, but I was not implementing all the methods.  The methods I did not implement throw NotImplementedException.  But I did not like it.

So I broke my interface into 4 interfaces like this:

Before

```<code>public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel>
{
    Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
    Task<TDetailsViewModel> GetDetailsViewModel(int id);
    Task<TCreateViewModel> GetCreateViewModel();
    Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
    Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
    Task<TEditViewModel> GetEditViewModel(int id);
}
</code>```

After

```<code>public interface IDetailsQuery<TDetailsViewModel>
{
    Task<TDetailsViewModel> GetDetailsViewModel(int id);
}

public interface ICreateQuery<TCreateViewModel>
{
    Task<TCreateViewModel> GetCreateViewModel();
    Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
}

public interface IEditQuery<TEditViewModel>
{
    Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
    Task<TEditViewModel> GetEditViewModel(int id);
}

public interface IIndexQuery<TIndexViewModel>
{
    Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
}
</code>```

Now I can implement them separately and I don't have to throw NotImplementedException.  I can implement one or more on the same class.

You can even use the original interface as-is like this!

```<code>/// <summary>
/// Enforce good practice and naming standards for ViewModel Query classes.
/// Allow allow partial implementation by using any of the other interface(s).
/// </summary>
public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel> :
    IIndexQuery<TIndexViewModel>,
    IDetailsQuery<TDetailsViewModel>,
    ICreateQuery<TCreateViewModel>,
    IEditQuery<TEditViewModel>
{
}
</code>```

Title: Partially implement an Interface

Body:
I had a bunch of Query classes with a common interface, but I was not implementing all the methods.  The methods I did not implement throw NotImplementedException.  But I did not like it.

So I broke my interface into 4 interfaces like this:

Before

public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel>
{
    Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
    Task<TDetailsViewModel> GetDetailsViewModel(int id);
    Task<TCreateViewModel> GetCreateViewModel();
    Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
    Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
    Task<TEditViewModel> GetEditViewModel(int id);
}

After

public interface IDetailsQuery<TDetailsViewModel>
{
    Task<TDetailsViewModel> GetDetailsViewModel(int id);
}

public interface ICreateQuery<TCreateViewModel>
{
    Task<TCreateViewModel> GetCreateViewModel();
    Task<TCreateViewModel> SetSelectLists(TCreateViewModel viewModel);
}

public interface IEditQuery<TEditViewModel>
{
    Task<TEditViewModel> SetSelectLists(TEditViewModel viewModel);
    Task<TEditViewModel> GetEditViewModel(int id);
}

public interface IIndexQuery<TIndexViewModel>
{
    Task<TIndexViewModel> GetIndexViewModel(TIndexViewModel viewModel = default);
}

Now I can implement them separately and I don't have to throw NotImplementedException.  I can implement one or more on the same class.

You can even use the original interface as-is like this!

/// <summary>
/// Enforce good practice and naming standards for ViewModel Query classes.
/// Allow allow partial implementation by using any of the other interface(s).
/// </summary>
public interface ICrudQueries<TIndexViewModel, TDetailsViewModel, TCreateViewModel, TEditViewModel> :
    IIndexQuery<TIndexViewModel>,
    IDetailsQuery<TDetailsViewModel>,
    ICreateQuery<TCreateViewModel>,
    IEditQuery<TEditViewModel>
{
}


问:
Cloud Run Fails on Step-2 Deploy with Permissions Error
I am having a heck of a time getting Cloud Run to work correctly. I am creating a new service from the GCP console with a Cloud Build trigger to my Github repo. Under the security tab, I am setting the service account to one of my service accounts which has the following permissions:

Cloud Build Service Account

Cloud Run Admin

Cloud Run Service Agent

Cloud Scheduler Service Agent

Service Account User

When I create the service, it always ends with the following error:

Step #2 - "Deploy": ERROR: (gcloud.run.services.update) PERMISSION_DENIED: Permission 'run.services.get' denied on resource 'namespaces/project/services/cloud_run_service_name' (or resource may not exist).

I can't figure out why I am getting this error. The service account has all the permissions listed in the Cloud Run documentation. Any ideas?

答:
I found out what the problem was. I was assuming that I should setup everything from Cloud Run, including my Cloud Build trigger since the Cloud Run interface offers that capability. Setting up the Cloud Build Trigger from Cloud Run doesn't take into account the service account that should be controlling the trigger.

The solution was to do everything from Cloud Build where I am able to specify the service account for the trigger and use a cloudbuild.yaml to control deploying to a Cloud Run service.


问:
Global view which blurry overlays other views and can be easily called
A similar question is asked here: SwiftUI: Global Overlay That Can Be Triggered From Any View. The examples however are shown a Toast, rather than a 'blocking' view. The accepted answer changes the presenting view (the toolbar is moving up after the toast is shown). Something is wrong with the code, but I don't know what (I just started learning SwiftUI). The code below is a combined effort from some other answers.

Alright, ideally I want to call a function on e.g. an EnvironmentObject which will automatically present an overlaying View with a ProgressView, to show that something is being loaded. The user should not be able to interact with the application while it is loading. The loading screen should be a bit blurry, overlapping with the presenting view.

Below shows what I have, the Text is never shown, but my breakpoint is hit when I click on the Load button. Any ideas why the LoadingView is never shown?

```<code>import SwiftUI
import UIKit

@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                LoadingView() // This view should always be hidden, unless it is loading
                ContentView()
            }
            .environmentObject(Load())
        }
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        if load.loader > 0 {
            GeometryReader { geometry in
                Text("LOADING")
                    .frame(
                        width: geometry.size.width,
                        height: geometry.size.height
                    )
                    .ignoresSafeArea(.all, edges: .all)
            }
        } else {
            EmptyView().frame(width: 0, height: 0)
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        NavigationView {
            Text("hi")
                .toolbar {
                    Button("Load") {
                        load.load()
                    }
                }

                .navigationBarTitle(Text("A List"), displayMode: .large)
        }
        .navigationViewStyle(.stack)
    }
}
</code>```

答:
There are a couple of things that could be adjusted with your code.

I'd make Load a @StateObject on a parent view so that the LoadingView can be conditionally displayed and not displayed all the time and just default to an EmptyView

In a ZStack, the topmost view should be last -- you have it first.

You can use .background(.ultraThinMaterial)

```<code>@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ParentView()
        }
    }
}

struct ParentView : View {
    @StateObject private var load = Load()

    var body: some View {
        ZStack {
            ContentView()
            if load.loader > 0 {
                LoadingView()
            }
        }.environmentObject(load)
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        VStack {
            Text("LOADING")
        }
        .ignoresSafeArea()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(.ultraThinMaterial)
    }
}

struct ContentView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        NavigationView {
            Text("hi")
                .onTapGesture {
                    print("tapped")
                }
                .font(.system(size: 100, weight: .bold, design: .default))
                .foregroundColor(.orange)
                .toolbar {
                    Button("Load") {
                        load.load()
                    }
                }
                .navigationBarTitle(Text("A List"), displayMode: .large)
        }
        .navigationViewStyle(.stack)
    }
}
</code>```

I've adjusted ContentView a bit, just to make the blur effect more obvious.

Update, with OP's request that only LoadingView responds to a change in the state, and not the parent view:

```<code>@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                ContentView()
                LoadingView()
            }
            .environmentObject(Load())
        }
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        if load.loader > 0 {
            VStack {
                Text("LOADING")
            }
            .ignoresSafeArea()
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(.ultraThinMaterial)
        } else {
            EmptyView()
        }
    }
}
</code>```

Body:
A similar question is asked here: SwiftUI: Global Overlay That Can Be Triggered From Any View. The examples however are shown a Toast, rather than a 'blocking' view. The accepted answer changes the presenting view (the toolbar is moving up after the toast is shown). Something is wrong with the code, but I don't know what (I just started learning SwiftUI). The code below is a combined effort from some other answers.

Alright, ideally I want to call a function on e.g. an EnvironmentObject which will automatically present an overlaying View with a ProgressView, to show that something is being loaded. The user should not be able to interact with the application while it is loading. The loading screen should be a bit blurry, overlapping with the presenting view.

Below shows what I have, the Text is never shown, but my breakpoint is hit when I click on the Load button. Any ideas why the LoadingView is never shown?

import SwiftUI
import UIKit

@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                LoadingView() // This view should always be hidden, unless it is loading
                ContentView()
            }
            .environmentObject(Load())
        }
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        if load.loader > 0 {
            GeometryReader { geometry in
                Text("LOADING")
                    .frame(
                        width: geometry.size.width,
                        height: geometry.size.height
                    )
                    .ignoresSafeArea(.all, edges: .all)
            }
        } else {
            EmptyView().frame(width: 0, height: 0)
        }
    }
}

struct ContentView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        NavigationView {
            Text("hi")
                .toolbar {
                    Button("Load") {
                        load.load()
                    }
                }

                .navigationBarTitle(Text("A List"), displayMode: .large)
        }
        .navigationViewStyle(.stack)
    }
}

Body:
There are a couple of things that could be adjusted with your code.

I'd make Load a @StateObject on a parent view so that the LoadingView can be conditionally displayed and not displayed all the time and just default to an EmptyView

In a ZStack, the topmost view should be last -- you have it first.

You can use .background(.ultraThinMaterial)

@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ParentView()
        }
    }
}

struct ParentView : View {
    @StateObject private var load = Load()

    var body: some View {
        ZStack {
            ContentView()
            if load.loader > 0 {
                LoadingView()
            }
        }.environmentObject(load)
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        VStack {
            Text("LOADING")
        }
        .ignoresSafeArea()
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(.ultraThinMaterial)
    }
}

struct ContentView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        NavigationView {
            Text("hi")
                .onTapGesture {
                    print("tapped")
                }
                .font(.system(size: 100, weight: .bold, design: .default))
                .foregroundColor(.orange)
                .toolbar {
                    Button("Load") {
                        load.load()
                    }
                }
                .navigationBarTitle(Text("A List"), displayMode: .large)
        }
        .navigationViewStyle(.stack)
    }
}

I've adjusted ContentView a bit, just to make the blur effect more obvious.

Update, with OP's request that only LoadingView responds to a change in the state, and not the parent view:

@main
struct TextLeadingApp: App {
    var body: some Scene {
        WindowGroup {
            ZStack {
                ContentView()
                LoadingView()
            }
            .environmentObject(Load())
        }
    }
}

class Load: ObservableObject {
    @Published var loader = 0

    func load() {
        loader += 1
    }
}

struct LoadingView: View {
    @EnvironmentObject var load: Load

    var body: some View {
        if load.loader > 0 {
            VStack {
                Text("LOADING")
            }
            .ignoresSafeArea()
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(.ultraThinMaterial)
        } else {
            EmptyView()
        }
    }
}


问:
Performance of symmetric sparse matrix of dimension 5 000 000: Save to Database or File?
I have a huge dataset (around 5 000 000 rows in a database) which I want to represent as a graph. For algorithmic reasons it is required to store the dataset in a adjacency matrix. The Matrix will be very sparse and symmmetric.

First I thought of storing the graph in a database table. This would require 5 000 000 rows, which should be no problem. But 5 000 000 columns? I don't know much of databases but I have the feeling, that this would be no recommended way of doing this.

After some searching within google, I found SciPy which has several Sparse Matrix Objects. lil_matrix and coo_matrix seem to be what I need.

Since I will operate on this matrix using python, SciPy seems a good why to go. The question for me now is how to store the graph aka sparse matrix?

Should I use a csv file? Should I use coo_matrix to save the matrix into a daatabase_table? Both would result into around 2 500 000 000 000 rows/lines

Or is there a far better way for creating and storing such a symmetric and sparse "Matrix" of dimension around 5 000 000 in python?

I am using numpy and some self written algorithms in python, which I want to run on the matrix. So it would be cool, if the suggestions make it easy to use python on the graph.

I don't know if I provided enough information for an answer. If you need more information: Feel free to ask me in a comment or so. I will gladly edit my answer.

Thanks in advance for any suggestion!

答:
I suggest using a dict to represent the matrix, which you can wrap in a class if you need a simple access.

```<code>class SymmetricSparseMatrix:
    def __init__(self, nlines, ncols):
        self.nlines = nlines
        self.ncols = ncols
        self._dict = {}

    def _check_coords(self, coords):
        """check coordinate range, and permutate i and j if necessary to
        take advantage of the symmety of the matrix"""
        i, j = coords
        if not(0 <= i < self.nlines) or not(0 <= j < self.ncols):
            raise ValueError(coords)
        if i > j:
            return j, i
        else:
            return coords

    def __setitem__(self, coords, val):
        coords = self._check_coords(coords)
        self._dict[coords] = val
        if val == 0:
            del self._dict[coords]

    def __getitem__(self, coords):
        coords = self._check_coords(coords)
        return self._dict.get(coords, 0)
</code>```

This is very close to scipy's dok_matrix core implementation, with additional processing ton only store half the values.

Body:
I suggest using a dict to represent the matrix, which you can wrap in a class if you need a simple access.

class SymmetricSparseMatrix:
    def __init__(self, nlines, ncols):
        self.nlines = nlines
        self.ncols = ncols
        self._dict = {}

    def _check_coords(self, coords):
        """check coordinate range, and permutate i and j if necessary to
        take advantage of the symmety of the matrix"""
        i, j = coords
        if not(0 <= i < self.nlines) or not(0 <= j < self.ncols):
            raise ValueError(coords)
        if i > j:
            return j, i
        else:
            return coords

    def __setitem__(self, coords, val):
        coords = self._check_coords(coords)
        self._dict[coords] = val
        if val == 0:
            del self._dict[coords]

    def __getitem__(self, coords):
        coords = self._check_coords(coords)
        return self._dict.get(coords, 0)

This is very close to scipy's dok_matrix core implementation, with additional processing ton only store half the values.


问:
Backref in list?
I'm trying to make a regex that matches strings in which the characters are arranged alphabetically, e.g. "ab", but not "ba". Here's my attempt: (.)[\1-z]. It captures the first character and uses that for the beginning of the range in the list. However, in the [], \1 means U+0001, so it matches any two characters:

>>> re.search("(.)[\1-z]", "ab")
<re.Match object; span=(0, 2), match='ab'>
>>> re.search("(.)[\1-z]", "ba")
<re.Match object; span=(0, 2), match='ba'>
```

How can I backref a captured character in a character list?

答:
You'll have to spell it out completely, i.e a*b*c*d*......

Here is how you could do that:

```<code>regex = "(?=.)" + "*".join(map(chr, range(97, 123))) + "*"
s = "afkdiolsieyrnbsgdysoepkzavfz"
print(re.findall(regex, s))
</code>```

Title: Backref in list?

Body:
I'm trying to make a regex that matches strings in which the characters are arranged alphabetically, e.g. "ab", but not "ba". Here's my attempt: (.)[\1-z]. It captures the first character and uses that for the beginning of the range in the list. However, in the [], \1 means U+0001, so it matches any two characters:

>>> re.search("(.)[\1-z]", "ab")
<re.Match object; span=(0, 2), match='ab'>
>>> re.search("(.)[\1-z]", "ba")
<re.Match object; span=(0, 2), match='ba'>

How can I backref a captured character in a character list?

Body:
You'll have to spell it out completely, i.e a*b*c*d*......

Here is how you could do that:

regex = "(?=.)" + "*".join(map(chr, range(97, 123))) + "*"
s = "afkdiolsieyrnbsgdysoepkzavfz"
print(re.findall(regex, s))


问:
Provide backwards compatibility for Geometry type in Jooq 3.16
first of all, I love using Jooq since it helps me efficiently ship the things I want to do. But one thing bothers me since the release of 3.16 bringing some new features.

Also it would be great to adopt semantic versioning so users can know when to expect something to break.

In second, 3.16 version brings org.jooq.impl.Geometry class which gets generated by default even if I use custom configuration (Converter to convert from byte array to jts) from previous version which did the job perfectly, see this config:

```<code><forcedType>
   <types>(geometry|GEOMETRY)</types>
   <userType>com.vividsolutions.jts.geom.Geometry</userType>
   <converter>com.example.GeometryConverter</converter> <!-- converts Object to com.vividsolutions.jts.geom.Geometry -->
</forcedType>
</code>```

In 3.15 generator generates the following code

```<code>createField(DSL.name("geopoint"), org.jooq.impl.DefaultDataType.getDefaultDataType("\"myDb\".\"geopoint\"").nullable(false), this, "", new GeometryConverter());
</code>```

and in 3.16:

```<code>createField(DSL.name("geopoint"), SQLDataType.GEOMETRY.nullable(false), this, "")
</code>```

this leaves me with mentioned org.jooq.impl.Geometry class which I don't find useful (specially because it contains String - instead of more useful bytes (containing WKB or WKT data) and does not bring any added value (in terms of handling geography)).

As far as I can understand from the log
The out of the box binding for geometry is available in the commercial jOOQ distribution only. Alternatively, you can implement your own custom binding. Jooq forced me to write my custom GeometryBinding class which will handle all I didn't need in the first place and worked in 3.15.

Is there a way to workaround this using configuration because release notes does not mention anything regarding this change or migration guide.

Jooq helps me save a lot of time during development but can take a lot of time when it is time to upgrade since I like to be kind of early adopter bringing (at least a) feedback back to the community so we can do great things!

PS: Jakarta upgrade is another problem since Jooq is always on top of some framework which may not support Jakarta validation 3.x yet leaving us (early adopters) with compilation issues, but this is a common problem. I will suggest to add an option to the generator which turns off validation code since is not needed in many cases.

答:
Turning off spatial data type support

Starting from jOOQ 3.17.0 and 3.16.5, you can turn off spatial data type support in jOOQ's code generator, in order to rever to the jOOQ 3.15 behaviour of generating a SQLDataType.OTHER type reference. For this, specify:

<configuration>
  <generator>
    <generate>
      <spatialTypes>false</spatialTypes>
    </generate>
  </generator>
</configuration>
```

This new code generation feature is documented here

Your specific questions

Also it would be great to adopt semantic versioning so users can know when to expect something to break.

The official stance on backwards compatibility is here:
https://www.jooq.org/doc/latest/manual/getting-started/semantic-versioning/

There's an explicit section about code generation. One caveat is when we introduce new data types, in case of which existing converters / bindings (that assumed Object) stop working and need a migration. This has happened before for XML, JSON types, and now for GEOMETRY. I can't think of a reasonable way to prevent that, but the migration isn't too hard either.

In 3.15 generator generates the following code [...]

The fact that your converter is no longer added to the generated code looks like a bug to me. Feel free to report it with some additional details, including your CREATE TABLE statement: https://github.com/jOOQ/jOOQ/issues/new/choose

this leaves me with mentioned org.jooq.impl.Geometry class which I don't find useful (specially because it contains String - instead of more useful bytes (containing WKB or WKT data) and does not bring any added value (in terms of handling geography)).

The Spatial support project is vast, and it is far from complete. There were two options:

Wait forever for the next release, which includes a more complete integration

Ship an MVP which already adds quite a bit of value to those who wish to standardise over spatial extensions of different dialects.

Some issues to keep an eye out for:

https://github.com/jOOQ/jOOQ/issues/12736

https://github.com/jOOQ/jOOQ/issues/12738 (this will restore the JTS bindings for you)

As far as I can understand from the log The out of the box binding for geometry is available in the commercial jOOQ distribution only. Alternatively, you can implement your own custom binding. Jooq forced me to write my custom GeometryBinding class which will handle all I didn't need in the first place and worked in 3.15.

I know this is the caveat when we introduce support for new types. But unfortunately, I don't see another solution for this. But is writing this binding really that much work? It should take 10 minutes...

Jooq helps me save a lot of time during development but can take a lot of time when it is time to upgrade since I like to be kind of early adopter bringing (at least a) feedback back to the community so we can do great things!

Is this really the case every time, or did you just get unlucky with this particular binding thing?

Body:
first of all, I love using Jooq since it helps me efficiently ship the things I want to do. But one thing bothers me since the release of 3.16 bringing some new features.

Also it would be great to adopt semantic versioning so users can know when to expect something to break.

In second, 3.16 version brings org.jooq.impl.Geometry class which gets generated by default even if I use custom configuration (Converter to convert from byte array to jts) from previous version which did the job perfectly, see this config:

<forcedType>
   <types>(geometry|GEOMETRY)</types>
   <userType>com.vividsolutions.jts.geom.Geometry</userType>
   <converter>com.example.GeometryConverter</converter>
</forcedType>

In 3.15 generator generates the following code

createField(DSL.name("geopoint"), org.jooq.impl.DefaultDataType.getDefaultDataType("\"myDb\".\"geopoint\"").nullable(false), this, "", new GeometryConverter());

and in 3.16:

createField(DSL.name("geopoint"), SQLDataType.GEOMETRY.nullable(false), this, "")

this leaves me with mentioned org.jooq.impl.Geometry class which I don't find useful (specially because it contains String - instead of more useful bytes (containing WKB or WKT data) and does not bring any added value (in terms of handling geography)).

As far as I can understand from the log
The out of the box binding for geometry is available in the commercial jOOQ distribution only. Alternatively, you can implement your own custom binding. Jooq forced me to write my custom GeometryBinding class which will handle all I didn't need in the first place and worked in 3.15.

Is there a way to workaround this using configuration because release notes does not mention anything regarding this change or migration guide.

Jooq helps me save a lot of time during development but can take a lot of time when it is time to upgrade since I like to be kind of early adopter bringing (at least a) feedback back to the community so we can do great things!

PS: Jakarta upgrade is another problem since Jooq is always on top of some framework which may not support Jakarta validation 3.x yet leaving us (early adopters) with compilation issues, but this is a common problem. I will suggest to add an option to the generator which turns off validation code since is not needed in many cases.

Body:
Turning off spatial data type support

Starting from jOOQ 3.17.0 and 3.16.5, you can turn off spatial data type support in jOOQ's code generator, in order to rever to the jOOQ 3.15 behaviour of generating a SQLDataType.OTHER type reference. For this, specify:

<configuration>
  <generator>
    <generate>
      <spatialTypes>false</spatialTypes>
    </generate>
  </generator>
</configuration>

This new code generation feature is documented here

Your specific questions

Also it would be great to adopt semantic versioning so users can know when to expect something to break.

The official stance on backwards compatibility is here:
https://www.jooq.org/doc/latest/manual/getting-started/semantic-versioning/

There's an explicit section about code generation. One caveat is when we introduce new data types, in case of which existing converters / bindings (that assumed Object) stop working and need a migration. This has happened before for XML, JSON types, and now for GEOMETRY. I can't think of a reasonable way to prevent that, but the migration isn't too hard either.

In 3.15 generator generates the following code [...]

The fact that your converter is no longer added to the generated code looks like a bug to me. Feel free to report it with some additional details, including your CREATE TABLE statement: https://github.com/jOOQ/jOOQ/issues/new/choose

this leaves me with mentioned org.jooq.impl.Geometry class which I don't find useful (specially because it contains String - instead of more useful bytes (containing WKB or WKT data) and does not bring any added value (in terms of handling geography)).

The Spatial support project is vast, and it is far from complete. There were two options:

Wait forever for the next release, which includes a more complete integration

Ship an MVP which already adds quite a bit of value to those who wish to standardise over spatial extensions of different dialects.

Some issues to keep an eye out for:

https://github.com/jOOQ/jOOQ/issues/12736

https://github.com/jOOQ/jOOQ/issues/12738 (this will restore the JTS bindings for you)

As far as I can understand from the log The out of the box binding for geometry is available in the commercial jOOQ distribution only. Alternatively, you can implement your own custom binding. Jooq forced me to write my custom GeometryBinding class which will handle all I didn't need in the first place and worked in 3.15.

I know this is the caveat when we introduce support for new types. But unfortunately, I don't see another solution for this. But is writing this binding really that much work? It should take 10 minutes...

Jooq helps me save a lot of time during development but can take a lot of time when it is time to upgrade since I like to be kind of early adopter bringing (at least a) feedback back to the community so we can do great things!

Is this really the case every time, or did you just get unlucky with this particular binding thing?


问:
How to change theme in GTK4.0 on windows?
I'm new to development using GTK. I installed gtkmm4.0 on windows using mingw64, but i noticed that the applications generated follow the default theme(adwaita); however i want to change that and use the windows 10 native theme. Where is the settings.ini file located in windows 10? I have searched it in the usual places described on the web, but could not find it(even tried creating one myself),does GTK4.0 on windows have a settings.ini file at all?

答:
It is located in any of (but you will probably need to create it yourself):

```<code>DLL prefix/share/gtk-4.0/settings.ini
DLL prefix/etc/gtk-4.0/settings.ini
C:/Documents and Settings/All Users/Application Data/gtk-4.0/settings.ini
C:/Documents and Settings/username/Local Settings/Application Data/gtk-4.0/settings.ini
</code>```

You can also use the GTK_THEME environment variable.

Note that GTK no longer ships a default Windows imitation theme in GTK4 (in GTK3 it was really, really, really, bad anyway).
If you want to have a native Windows look, you will need to write your own theme.

Also, in recent versions of GTK, the default theme is not "Adwaita", but "Default"

Body:
It is located in any of (but you will probably need to create it yourself):

DLL prefix/share/gtk-4.0/settings.ini
DLL prefix/etc/gtk-4.0/settings.ini
C:/Documents and Settings/All Users/Application Data/gtk-4.0/settings.ini
C:/Documents and Settings/username/Local Settings/Application Data/gtk-4.0/settings.ini

You can also use the GTK_THEME environment variable.

Note that GTK no longer ships a default Windows imitation theme in GTK4 (in GTK3 it was really, really, really, bad anyway).
If you want to have a native Windows look, you will need to write your own theme.

Also, in recent versions of GTK, the default theme is not "Adwaita", but "Default"


问:
How can I identify the column, where two (or more) rows are different (same ID)?
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

```<code>ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)
</code>```
```<code>   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805
</code>```

My goal would be an additional column, which contains the changed column, i.e. desired output:

```<code>   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>
</code>```

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

Body:
I have a dataframe with duplicate IDs, but the rows are not identical. Is there a function, which identifies the column (or columns), where a difference appears?

My real application is a dataframe with hundreds of columns. I need some way to check, whether changes were made in important columns or in some irrelevant ones. So first of all I need to identify the changed columns.

Example:

ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)

   ID Info1 Info2 Info3
1   1    10     A   999
2   2    20     B   998
3   2    20     A   997
4   4    40     D   995
5   5    50     E   995
6   5    50     E   995
7   5    50     F   995
8   6    60     Z   946
9   6    60     A   800
10  7    70     B   805

My goal would be an additional column, which contains the changed column, i.e. desired output:

   ID Info1 Info2 Info3            col_diff
1   1    10     A   999                <NA>
2   2    20     B   998        Info2; Info3
3   2    20     A   997        Info2; Info3
4   4    40     D   995                <NA>
5   5    50     H   995               Info2
6   5    50     E   995               Info2
7   5    50     F   995               Info2
8   6    65     Z   946 Info1; Info2; Info3
9   6    60     A   800 Info1; Info2; Info3
10  7    70     B   805                <NA>

I hope my problem became clear. I hope there is some function within dplyr, which I do not know yet. Of course my solution with the additional column is not really elegant. So I am open to any ideas, which may solve my problem.

Thanks a lot!

Body:
Another possible solution:

library(tidyverse)

ID <- c(1,2,2,4,5,5,5,6,6,7)
Info1 <- c(10,20,20,40,50,50,50,65,60,70)
Info2 <- c('A','B','A','D', 'E','E','F', 'Z','A','B')
Info3 <- c(999,998,997,995,995,995,995,946,800,805)

df <- data.frame(ID, Info1, Info2, Info3)
df %>%
  group_by(ID) %>%
  mutate(across(starts_with("Info"),
   ~ if_else(n_distinct(.x) != 1, cur_column(), NA_character_))) %>% ungroup %>%
  unite("col_diff", starts_with("Info"), na.rm = T, sep = "; ") %>%
  na_if("") %>% inner_join(df, ., by = c("ID")) %>% distinct %>%
  inner_join(df, ., by = c("ID", "Info1", "Info2", "Info3"))

#>    ID Info1 Info2 Info3            col_diff
#> 1   1    10     A   999                <NA>
#> 2   2    20     B   998        Info2; Info3
#> 3   2    20     A   997        Info2; Info3
#> 4   4    40     D   995                <NA>
#> 5   5    50     E   995               Info2
#> 6   5    50     E   995               Info2
#> 7   5    50     F   995               Info2
#> 8   6    65     Z   946 Info1; Info2; Info3
#> 9   6    60     A   800 Info1; Info2; Info3
#> 10  7    70     B   805                <NA>