问:
Added data is only showing after reloading in flutter
here is a popup screen to add the transaction to the app, as you can see here

and when the add button pressed the data will add to database and also to the dislpay , here is the code

```<code>ElevatedButton(
              //on pressed
              onPressed: () async {
                final _categoryName = _nameEditingController.text;
                if (_categoryName.isEmpty) {
                  return;
                }

                final _type = selectedCategoryNotifier.value;
                //sending the data to model class
                final _category = CategoryModel(
                  id: DateTime.fromMillisecondsSinceEpoch.toString(),
                  name: _categoryName,
                  type: _type,
                );
                //inserting the data to database
                await CategoryDb.instance.insertCategory(_category);
                //refreshing the ui
                await CategoryDb.instance.refreshUI();
                //and quitting the popup screen
                Navigator.of(ctx).pop();
              },
              child: const Text('Add'),

            ),
</code>```

and in this code you can see that I called 2 functions that for insert data and also refresh the UI, in the refresh UI function I added the function that to get all data from database to screen, here the code of all functions for CRUD operatins

```<code>const databaseName = 'category-database';

abstract class CategoryDbFunctions {
  Future<List<CategoryModel>> getCategories();
  Future<void> insertCategory(CategoryModel value);
}

//CRUD operations code

class CategoryDb implements CategoryDbFunctions {
  CategoryDb._internal();
  static CategoryDb instance = CategoryDb._internal();
  factory CategoryDb() {
    return instance;
  }

  ValueNotifier<List<CategoryModel>> incomeCategoryListListener =
      ValueNotifier([]);
  ValueNotifier<List<CategoryModel>> expenseCategoryListListener =
      ValueNotifier([]);

  @override
  Future<void> insertCategory(CategoryModel value) async {
    final _categoryDB = await Hive.openBox<CategoryModel>(databaseName);
    await _categoryDB.add(value);
    await refreshUI();
  }

  @override
  Future<List<CategoryModel>> getCategories() async {
    final _categoryDB = await Hive.openBox<CategoryModel>(databaseName);
    return _categoryDB.values.toList();
  }

  Future<void> refreshUI() async {
    final _allCategories = await getCategories();
    incomeCategoryListListener.value.clear();
    expenseCategoryListListener.value.clear();
    await Future.forEach(
      _allCategories,
      (CategoryModel category) {
        if (category.type == CategoryType.income) {
          incomeCategoryListListener.value.add(category);
        } else {
          expenseCategoryListListener.value.add(category);
        }
      },
    );
  }
}

</code>```

so I checked the all things , but I couldn't find where I'm missing parts,

and here is the main part, it is adding to the database also displaying after I refresh the UI or change the tab here you can see what I mean by 'changing the tab'

this is the problem I'm trying to fix this for 2 day, i couldn't find any solution or mistake in my code

答:
There many ways you can handle this problem.

but I dont see where you notify youre ui that the data has been changed, flutter does only update the ui when you use setState etc.. these functions help flutter updating the ui where the data changed.

i would recommend you to use setState in the place you invoke youre dialog.

```<code>    onTap:(){
       setState(){
          await dialogStuff();
       }
    }
</code>```

Body:
here is a popup screen to add the transaction to the app, as you can see here

and when the add button pressed the data will add to database and also to the dislpay , here is the code

ElevatedButton(
              //on pressed
              onPressed: () async {
                final _categoryName = _nameEditingController.text;
                if (_categoryName.isEmpty) {
                  return;
                }

                final _type = selectedCategoryNotifier.value;
                //sending the data to model class
                final _category = CategoryModel(
                  id: DateTime.fromMillisecondsSinceEpoch.toString(),
                  name: _categoryName,
                  type: _type,
                );
                //inserting the data to database
                await CategoryDb.instance.insertCategory(_category);
                //refreshing the ui
                await CategoryDb.instance.refreshUI();
                //and quitting the popup screen
                Navigator.of(ctx).pop();
              },
              child: const Text('Add'),

            ),

and in this code you can see that I called 2 functions that for insert data and also refresh the UI, in the refresh UI function I added the function that to get all data from database to screen, here the code of all functions for CRUD operatins

const databaseName = 'category-database';

abstract class CategoryDbFunctions {
  Future<List<CategoryModel>> getCategories();
  Future<void> insertCategory(CategoryModel value);
}

//CRUD operations code

class CategoryDb implements CategoryDbFunctions {
  CategoryDb._internal();
  static CategoryDb instance = CategoryDb._internal();
  factory CategoryDb() {
    return instance;
  }

  ValueNotifier<List<CategoryModel>> incomeCategoryListListener =
      ValueNotifier([]);
  ValueNotifier<List<CategoryModel>> expenseCategoryListListener =
      ValueNotifier([]);

  @override
  Future<void> insertCategory(CategoryModel value) async {
    final _categoryDB = await Hive.openBox<CategoryModel>(databaseName);
    await _categoryDB.add(value);
    await refreshUI();
  }

  @override
  Future<List<CategoryModel>> getCategories() async {
    final _categoryDB = await Hive.openBox<CategoryModel>(databaseName);
    return _categoryDB.values.toList();
  }

  Future<void> refreshUI() async {
    final _allCategories = await getCategories();
    incomeCategoryListListener.value.clear();
    expenseCategoryListListener.value.clear();
    await Future.forEach(
      _allCategories,
      (CategoryModel category) {
        if (category.type == CategoryType.income) {
          incomeCategoryListListener.value.add(category);
        } else {
          expenseCategoryListListener.value.add(category);
        }
      },
    );
  }
}

so I checked the all things , but I couldn't find where I'm missing parts,

and here is the main part, it is adding to the database also displaying after I refresh the UI or change the tab here you can see what I mean by 'changing the tab'

this is the problem I'm trying to fix this for 2 day, i couldn't find any solution or mistake in my code

Body:
There many ways you can handle this problem.

but I dont see where you notify youre ui that the data has been changed, flutter does only update the ui when you use setState etc.. these functions help flutter updating the ui where the data changed.

i would recommend you to use setState in the place you invoke youre dialog.

    onTap:(){
       setState(){
          await dialogStuff();
       }
    }


来源: stackexchange

问:
Pandas substraction in intervals for column pairs
I would like to calculate the difference amount of total_spent for each customer_id by taking the difference for each two column pairs. In this case subtracting total_spent_2020 from  total_spent_2021  but in a more dynamic way. In numbers it would be substracting: column_3 from column_2 and column_5 from column_4 and so on.

I was thinking of taking the length of the df and add a range with a 2 interval but I am struggling to do the subtraction based on that interval number.

sample_df

```<code>customer_id  total_spent_2021 total_spent_2020  total_spent_2019 total_spent_2018
9391         120              100               80               90
2932         90               110               60               50
4294         150              130               40               50
</code>```

ouput_df

```<code>customer_id  total_spent_2021_2020_diff  total_spent_2019_2018_diff
9391         20                           -10
2932        -20                            10
4294         20                           -10
</code>```

答:
Create groups in array a by integer division by 2, create new column names by extract numbers and join and aggregate DataFrameGroupBy.diff with remove only NaNs columns with new columns names by s:

```<code>df = df.set_index('customer_id')
a = np.arange(len(df.columns)) // 2

s = (df.columns
       .to_series()
       .str.extract('(\d+)', expand=False)
       .groupby(a)
       .agg('_'.join)
       .radd('total_spent_')
       .add('_diff'))
print (s)
0    total_spent_2021_2020_diff
1    total_spent_2019_2018_diff
dtype: object

df = df.groupby(a, axis=1).diff(-1).dropna(how='all', axis=1)
df.columns = s
print (df)
             total_spent_2021_2020_diff  total_spent_2019_2018_diff
customer_id
9391                                 20                         -10
2932                                -20                          10
4294                                 20                         -10
</code>```

Another idea without groupby:

```<code>df1 = df.set_index('customer_id')
df1.columns = df1.columns.str.extract('(\d+)', expand=False)
a = np.arange(len(df.columns)) // 2

df2 = df1.iloc[:, ::2].sub(df1.iloc[:, 1::2].to_numpy())
df2.columns = 'total_spent_' + df1.columns[::2] + '_' + df1.columns[1::2] + '_diff'
print (df2)
             total_spent_2021_2020_diff  total_spent_2019_2018_diff
customer_id
9391                                 20                         -10
2932                                -20                          10
4294                                 20                         -10
</code>```

EDIT:

If there are strings mixed with numbers is possible convert them to missing values:

```<code>df = df.set_index('customer_id').apply(pd.to_numeric, errors='coerce')
</code>```

For testing:

```<code>print (df)
   customer_id  total_spent_2021  total_spent_2020  total_spent_2019  \
0         9391               120               100                80
1         2932                90               110                60
2         4294               150               130                40

   total_spent_2018
0                90
1                50
2                50

df = df.set_index('customer_id')
print (df)
             total_spent_2021  total_spent_2020  total_spent_2019  \
customer_id
9391                      120               100                80
2932                       90               110                60
4294                      150               130                40

             total_spent_2018
customer_id
9391                       90
2932                       50
4294                       50
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to calculate the difference amount of total_spent for each customer_id by taking the difference for each two column pairs. In this case subtracting total_spent_2020 from  total_spent_2021  but in a more dynamic way. In numbers it would be substracting: column_3 from column_2 and column_5 from column_4 and so on.

I was thinking of taking the length of the df and add a range with a 2 interval but I am struggling to do the subtraction based on that interval number.

sample_df

customer_id  total_spent_2021 total_spent_2020  total_spent_2019 total_spent_2018
9391         120              100               80               90
2932         90               110               60               50
4294         150              130               40               50

ouput_df

customer_id  total_spent_2021_2020_diff  total_spent_2019_2018_diff
9391         20                           -10
2932        -20                            10
4294         20                           -10

Body:
Create groups in array a by integer division by 2, create new column names by extract numbers and join and aggregate DataFrameGroupBy.diff with remove only NaNs columns with new columns names by s:

df = df.set_index('customer_id')
a = np.arange(len(df.columns)) // 2

s = (df.columns
       .to_series()
       .str.extract('(\d+)', expand=False)
       .groupby(a)
       .agg('_'.join)
       .radd('total_spent_')
       .add('_diff'))
print (s)
0    total_spent_2021_2020_diff
1    total_spent_2019_2018_diff
dtype: object

df = df.groupby(a, axis=1).diff(-1).dropna(how='all', axis=1)
df.columns = s
print (df)
             total_spent_2021_2020_diff  total_spent_2019_2018_diff
customer_id
9391                                 20                         -10
2932                                -20                          10
4294                                 20                         -10

Another idea without groupby:

df1 = df.set_index('customer_id')
df1.columns = df1.columns.str.extract('(\d+)', expand=False)
a = np.arange(len(df.columns)) // 2

df2 = df1.iloc[:, ::2].sub(df1.iloc[:, 1::2].to_numpy())
df2.columns = 'total_spent_' + df1.columns[::2] + '_' + df1.columns[1::2] + '_diff'
print (df2)
             total_spent_2021_2020_diff  total_spent_2019_2018_diff
customer_id
9391                                 20                         -10
2932                                -20                          10
4294                                 20                         -10

EDIT:

If there are strings mixed with numbers is possible convert them to missing values:

df = df.set_index('customer_id').apply(pd.to_numeric, errors='coerce')

For testing:

print (df)
   customer_id  total_spent_2021  total_spent_2020  total_spent_2019  \
0         9391               120               100                80
1         2932                90               110                60
2         4294               150               130                40

   total_spent_2018
0                90
1                50
2                50

df = df.set_index('customer_id')
print (df)
             total_spent_2021  total_spent_2020  total_spent_2019  \
customer_id
9391                      120               100                80
2932                       90               110                60
4294                      150               130                40

             total_spent_2018
customer_id
9391                       90
2932                       50
4294                       50


问:
how to update records in pure html file in asp.net mvc using jquery
```<code><script>
    $(function ()
    {
        var id = Request.QueryString["id"]
        $.get("/Employee/getEditId", { id: id }, function (data) {
            $("#txtname").val(data[0].custname);
            $("#txtcountry").val(data[0].country);
        });
    });

    $(function ()
    {
        $("#edit").click(function () {
            $.ajax({
                type: "POST",
                url: "/Employee/EditEmp",
                data: {
                    custname: $("#txtname").val(),
                    country: $("#txtcountry").val(),
                },
                success: function (data) {
                    clear();
                    alert(data);
                }
            })
        })
    })

    function clear() {
        $("#custname").val(''),
            $("#country").val('')
    }
</script>
</code>```

答:
You can use the method below to send your data to your Controller method using Ajax:

```<code>$(function ()
{
    $("#edit").click(function () {
        //Get your data here
        var custname=$("#txtname").val();
        var country=$("#txtcountry").val();

        var json = {
            custname: custname,
            country: country
        };

        $.ajax({
            type: 'POST',
            url: "/Employee/EditEmp",
            dataType: "json",
            data: {"json": JSON.stringify(json)},
            success: function (data) {
                 if(data.status=="true")
                 {
                   clear();
                   alert(data.msg);
                 }
             }
        })
    })
})
</code>```

And your Controller method will look like:

```<code>using System.Web.Script.Serialization;

[HttpPost]
public ActionResult EditEmp(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var custname= Convert.String(jsondata["custname"]);
    var country= Convert.String(jsondata["country"]);

    //Your logic to update the data

    return Json(new {status="true", msg= "Successfully updated data"});
}
</code>```

Body:
You can use the method below to send your data to your Controller method using Ajax:

$(function ()
{
    $("#edit").click(function () {
        //Get your data here
        var custname=$("#txtname").val();
        var country=$("#txtcountry").val();

        var json = {
            custname: custname,
            country: country
        };

        $.ajax({
            type: 'POST',
            url: "/Employee/EditEmp",
            dataType: "json",
            data: {"json": JSON.stringify(json)},
            success: function (data) {
                 if(data.status=="true")
                 {
                   clear();
                   alert(data.msg);
                 }
             }
        })
    })
})

And your Controller method will look like:

using System.Web.Script.Serialization;

[HttpPost]
public ActionResult EditEmp(string json)
{
    var serializer = new JavaScriptSerializer();
    dynamic jsondata = serializer.Deserialize(json, typeof(object));

    //Get your variables here from AJAX call
    var custname= Convert.String(jsondata["custname"]);
    var country= Convert.String(jsondata["country"]);

    //Your logic to update the data

    return Json(new {status="true", msg= "Successfully updated data"});
}


问:
Maven build - Download sources and javadoc (Sleeping) OK
When I am trying to save the pom.xml file, Eclipse is stuck in an endless loop with build status as -  Download sources and javadoc (Sleeping) OK while associating sources and javadoc with classpath.

My POM file looks like this:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sachindra</groupId>
    <artifactId>wwe</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-junit -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.5.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-picocontainer -->
        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.serenity-bdd/serenity-cucumber4 -->
        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber4</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>maven-cucumber-reporting</artifactId>
            <version>5.3.0</version>
        </dependency>
    </dependencies>
</project>
</code>```

The Maven setting configurations is such:

答:
I faced same issue,

In my case I updated Chrome and later i downloaded compatible chrome webdriver, and made changes in code respect to that.

Body:
When I am trying to save the pom.xml file, Eclipse is stuck in an endless loop with build status as -  Download sources and javadoc (Sleeping) OK while associating sources and javadoc with classpath.

My POM file looks like this:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sachindra</groupId>
    <artifactId>wwe</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>5.5.0</version>
        </dependency>

        <dependency>
            <groupId>io.cucumber</groupId>
            <artifactId>cucumber-picocontainer</artifactId>
            <version>5.5.0</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>net.serenity-bdd</groupId>
            <artifactId>serenity-cucumber4</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>net.masterthought</groupId>
            <artifactId>maven-cucumber-reporting</artifactId>
            <version>5.3.0</version>
        </dependency>
    </dependencies>
</project>

The Maven setting configurations is such:


问:
Why `VkPipelineStageFlagBits` does not only define pipeline stages?
VkPipelineStageFlagBits defines flags corresponding to stages that we would expect in a Graphics Pipeline such as VK_PIPELINE_STAGE_VERTEX_SHADER_BIT or VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, etc. We also have Compute Pipeline stages such as VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT.

But there are also some flags defined here that does not seem to correspond to any Graphics or Compute Pipeline stage at all, such as VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT and VK_PIPELINE_STAGE_ALL_COMMANDS_BIT (from which VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT and VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT are defined). Instead, these are defined in the specification by referring to commands. For instance:

VK_PIPELINE_STAGE_TRANSFER_BIT specifies the following commands:

All copy commands, including vkCmdCopyQueryPoolResults

vkCmdBlitImage2 and vkCmdBlitImage

vkCmdResolveImage2 and vkCmdResolveImage

All clear commands, with the exception of vkCmdClearAttachments

So if it is not a pipeline stage, why is it listed in Vk**PipelineStage**FlagBits? Why is it named this way? What does it mean if I use VK_PIPELINE_STAGE_TRANSFER_BIT as srcStageMask or dstStageMask in VkSubpassDependency for instance?

答:
VK_PIPELINE_STAGE_TRANSFER_BIT is from transfer pipeline, which has one stage.

VK_PIPELINE_STAGE_HOST_BIT pseudostage communicates there will be memory domain transfers between host and device.

VK_PIPELINE_STAGE_ALL_COMMANDS_BIT is a shortcut for |ing together all the bits applicable in a given context.

VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT and VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT are pipeline terminators. They do not mean any stage, but they are necessary on the API level to express "before first stage", and "after last stage".

What does it mean if I use VK_PIPELINE_STAGE_TRANSFER_BIT as srcStageMask or dstStageMask in VkSubpassDependency for instance?

You are not allowed to, unless that dependency is VK_SUBPASS_EXTERNAL.

In ordinary pipeline barrier or VK_SUBPASS_EXTERNAL dependency it means either some work is dependent on a copy being finished, or some copy depending on some writes to be made first.

How host memory sync works is that Vulkan divides it into domains. There's host memory domain, and there's device memory domain. If changes to a memory are not transitioned from one domain to the other before reading, it might be so the writes will not be visible on the other domain.

That's where VK_PIPELINE_STAGE_HOST_BIT (plus related access mask) comes in. It instructs the driver to do this potentialy expensive and disruptive domain transfer.

Now there's a rare implicit Vulkan behavior. The host write ordering guarantee. If you write from host to memory, and then vkQueueSubmit something, you don't need to do anything. Operations in that submission automatically see the host writes, and you won't use VK_PIPELINE_STAGE_HOST_BIT.

This doesn't work other way around though. If you want to read something on host that was written on device, you always need to use dstStage = VK_PIPELINE_STAGE_HOST_BIT (followed by a fence or such), otherwisely the writes might not be visible on the host domain when you try to read them.

Third option is when you submit first, and then you write something on the host. Previously this could happen with Events (but that was subsequently banned), and now it can happen when using extended semaphores. In that case you need to use srcStage = VK_PIPELINE_STAGE_HOST_BIT in addition to that host-device semaphore, otherwise your host writes might not be visible to the reads on that device.


问:
Cors not allowed while using Axios
Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

I already allowed cors when I was working with fetch, but for some reason cors is not allowed for xhr (Axios) requests

here is Axios defaults:

```<code>import axios from "axios"
import store from "@/store"
import { getLocalStorage } from "@/services/functions.services.js"

axios.defaults.baseURL = store.getters.getData("serverLink")
axios.defaults.withCredentials = true

axios.defaults.headers.common["Authorization"] = `Bearer ${getLocalStorage("access_token")} ${getLocalStorage("refresh_token")}`

</code>```

and here is how I use Axios:

```<code>function fetchF(link, body, method) {
    return new Promise(async (resolve, reject) => {
        axios[method.toLowerCase()](link, body)
            .then(rsp => {
                setLocalStorage("access_token", rsp.access_token);
                setLocalStorage("refresh_token", rsp.refresh_token);
                resolve(rsp);
            }).catch(error => {
                setLocalStorage("access_token", "");
                setLocalStorage("refresh_token", "");
                store.dispatch("changeData", {
                    option: "alertEl",
                    value: "Please log in, and try again",
                });
                return resolve({ isSuccess: false, err: "Please log in, and try again" });
            })
    });
}
</code>```

and here is how I enabled cors on the server-side:

```<code>app.use(cors({
    credentials: true,
}));

</code>```

here is the error:
error in the network page

答:
This is an error with your server, because for every request, a preflight request is sent before the actual one..

And from the error 'PreflightWildcardOriginNotAllowed' basically means that in your server configurations you have the list of domains set to the wildcard '*'

So just change your cors options in the server for 'Access-Control-Allow-Origin' to your domain instead of '*'

And if your server has it's own way of handling preflight requests, which are basically requests sent with 'OPTIONS', you can set the domains handled by that to your domain

Title: Cors not allowed while using Axios

Body:
Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

I already allowed cors when I was working with fetch, but for some reason cors is not allowed for xhr (Axios) requests

here is Axios defaults:

import axios from "axios"
import store from "@/store"
import { getLocalStorage } from "@/services/functions.services.js"

axios.defaults.baseURL = store.getters.getData("serverLink")
axios.defaults.withCredentials = true

axios.defaults.headers.common["Authorization"] = `Bearer ${getLocalStorage("access_token")} ${getLocalStorage("refresh_token")}`

and here is how I use Axios:

function fetchF(link, body, method) {
    return new Promise(async (resolve, reject) => {
        axios[method.toLowerCase()](link, body)
            .then(rsp => {
                setLocalStorage("access_token", rsp.access_token);
                setLocalStorage("refresh_token", rsp.refresh_token);
                resolve(rsp);
            }).catch(error => {
                setLocalStorage("access_token", "");
                setLocalStorage("refresh_token", "");
                store.dispatch("changeData", {
                    option: "alertEl",
                    value: "Please log in, and try again",
                });
                return resolve({ isSuccess: false, err: "Please log in, and try again" });
            })
    });
}

and here is how I enabled cors on the server-side:

app.use(cors({
    credentials: true,
}));

here is the error:
error in the network page


问:
Comparing two arrays in C ignoring the order of the elements inside each array
I want to compare two arrays in C, ignoring the order of the elements inside each array, I had two ideas to solve this problem.
Well, they're the same, to be honest. The first idea is to make a variable and increment it with 1 if we find our element inside the second table (please see the code below).
But this one doesn't work if we give it as an example {3, 2, 2, 1} {1, 2, 3, 4}.
the second idea (which I obviously couldn't code) is: setting a variable c=0 for example, after the first loop:

```<code>for (i = 0; i < n; i++) {
    c = 0;
    for (...
}
</code>```

this c will count the number of fails

```<code>if (T1[i] != T2[j]) {
    c += 1
}
</code>```

Then before exiting the j loop, we check if c==n where n is the length of the table. Meaning we have n fails.
after that, unsetting cat the beginning of the i loop

this is my code:

```<code>#include <stdio.h>

int main() {
    int n, i, j, c = 0;
    printf("give the size of the first array: \n");
    scanf("%d", &n);
    int T1[n];
    int T2[n];
    // remplissage de T1
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table1: ", i + 1);
        scanf("%d", &T1[i]);
    }
    // remplissage de T2
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table2: ", i + 1);
        scanf("%d", &T2[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (T1[i] == T2[j]) {
                c += 1;
                break;
            }
        }
    }
    if (c == n) {
        printf("True");
    } else {
        printf("False");
    }
}
</code>```

答:
I think i've found what you are asking for.
You need to do two double for to check equality in both ways, and then compare those 2 numbers.

```<code>    int c = 0;
    for(int i = 0; i < 4; i++){
        for(int y = 0; y < 4; y++){
            if(A1[i] == A2[y]){
                c += 1;
                break;
            }
        }
    }

    int d = 0;
    for(int i = 0; i < 4; i++){
        for(int y = 0; y < 4; y++){
            if(A2[i] == A1[y]){
                d += 1;
                break;
            }
        }
    }

    if(c != n || d != n || c != d){
        printf("False");
    }else{
        printf("true");
    }
</code>```

If c and d are not the same it means that there is a duplicate that triggers 2 times the equal in one way.
If c and d are the same but not equal to the array size it means that there are no duplicates, but not all the elements of one array are in the other.

I hope i've been helpfull

Body:
I want to compare two arrays in C, ignoring the order of the elements inside each array, I had two ideas to solve this problem.
Well, they're the same, to be honest. The first idea is to make a variable and increment it with 1 if we find our element inside the second table (please see the code below).
But this one doesn't work if we give it as an example {3, 2, 2, 1} {1, 2, 3, 4}.
the second idea (which I obviously couldn't code) is: setting a variable c=0 for example, after the first loop:

for (i = 0; i < n; i++) {
    c = 0;
    for (...
}

this c will count the number of fails

if (T1[i] != T2[j]) {
    c += 1
}

Then before exiting the j loop, we check if c==n where n is the length of the table. Meaning we have n fails.
after that, unsetting cat the beginning of the i loop

this is my code:

#include <stdio.h>

int main() {
    int n, i, j, c = 0;
    printf("give the size of the first array: \n");
    scanf("%d", &n);
    int T1[n];
    int T2[n];
    // remplissage de T1
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table1: ", i + 1);
        scanf("%d", &T1[i]);
    }
    // remplissage de T2
    for (i = 0; i < n; i++) {
        printf("give the value of %d case, table2: ", i + 1);
        scanf("%d", &T2[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            if (T1[i] == T2[j]) {
                c += 1;
                break;
            }
        }
    }
    if (c == n) {
        printf("True");
    } else {
        printf("False");
    }
}

Body:
I think i've found what you are asking for.
You need to do two double for to check equality in both ways, and then compare those 2 numbers.

    int c = 0;
    for(int i = 0; i < 4; i++){
        for(int y = 0; y < 4; y++){
            if(A1[i] == A2[y]){
                c += 1;
                break;
            }
        }
    }

    int d = 0;
    for(int i = 0; i < 4; i++){
        for(int y = 0; y < 4; y++){
            if(A2[i] == A1[y]){
                d += 1;
                break;
            }
        }
    }

    if(c != n || d != n || c != d){
        printf("False");
    }else{
        printf("true");
    }

If c and d are not the same it means that there is a duplicate that triggers 2 times the equal in one way.
If c and d are the same but not equal to the array size it means that there are no duplicates, but not all the elements of one array are in the other.

I hope i've been helpfull


问:
Java collector teeing a list of inputs
I am trying to implement a simple collector, which takes a list of collectors and simultaneously collects values in slightly different ways from a stream.

It is quite similar to Collectors.teeing, but differs in that it

Receives a list of collectors instead of just two

Requires all collectors to produce a value of the same type

The type signature I want to have is

```<code>public static <T, R> Collector<T, ?, List<R>> list(
      final List<Collector<T, ?, R>> downstreamCollectors);
</code>```

One way to create such a collector would be to recursively pair up teeing collectors, like so:

```<code>public static <T, R> Collector<T, ?, List<R>> list(
    final List<Collector<T, ?, R>> downstreamCollectors) {
  return listrec(
      Collectors.collectingAndThen(downstreamCollectors.get(0), List::of),
      downstreamCollectors.stream().skip(1).toList());
}

private static <T, R> Collector<T, ?, List<R>> listrec(
    final Collector<T, ?, List<R>> teedCollectors,
    final List<Collector<T, ?, R>> downstreamCollectors) {
  if (downstreamCollectors.size() == 0) {
    return teedCollectors;
  } else {
    return listrec(
        teeing(
            teedCollectors,
            downstreamCollectors.get(0),
            (l, s) -> Stream.concat(l.stream(), Stream.of(s)).toList()),
        downstreamCollectors.stream().skip(1).toList());
  }
}
</code>```

Something feels a little "off" with this solution, so I am trying to create the collector myself, something like:

```<code>public static <T, R> Collector<T, ?, List<R>> list2(
    final List<Collector<T, ?, R>> downstreamCollectors) {
  return Collector.of(
      () -> downstreamCollectors.stream().map(c -> c.supplier().get()).toList(),
      (accumulators, t) ->
          IntStream.range(0, downstreamCollectors.size())
              .forEach(
                  i -> downstreamCollectors.get(i).accumulator().accept(accumulators.get(i), t)),
      (accumulator1, accumulator2) ->
          IntStream.range(0, downstreamCollectors.size())
              .mapToObj(
                  i ->
                      downstreamCollectors
                          .get(i)
                          .combiner()
                          .apply(accumulator1.get(i), accumulator2.get(i)))
              .toList(),
      accumulators ->
          IntStream.range(0, downstreamCollectors.size())
              .mapToObj(i -> downstreamCollectors.get(i).finisher().apply(accumulators.get(i)))
              .toList());
}
</code>```

Because of the unbounded wildcard in the downstream collectors' accumulator type, this doesn't compile. Changing the type signature to

```<code>public static <T, A, R> Collector<? super T, ?, List<R>> list2(
    final List<Collector<? super T, A, R>> downstreamCollectors);
</code>```

solves the problem, but unfortunately renders the method much less usable as the downstream collectors (like the built in collectors from java.util.stream.Collectors) typically would have a unbounded wildcard in the accumulator type.

Is there another way to implement this, keeping the wildcard in the method signature?

I am using OpenJDK 17.0.2.

答:
Handling a list of collectors with arbitrary accumulator types as a flat list can’t be done in a type safe way, as it would require declaring n type variables to capture these types, where n is the actual list size.

Therefore, you can only implement the processing as a composition of operations, each with a finite number of components know at compile time, like your recursive approach.

This still has potential for simplifications, like replacing downstreamCollectors.size() == 0 with downstreamCollectors.isEmpty() or downstreamCollectors.stream().skip(1).toList() with a copying free downstreamCollectors.subList(1, downstreamCollectors.size()).

But the biggest impact has replacing the recursive code with a Stream Reduction operation:

public static <T, R> Collector<T, ?, List<R>> list(List<Collector<T, ?, R>> collectors) {
    return collectors.stream()
            .<Collector<T, ?, List<R>>>map(c-> Collectors.collectingAndThen(c, List::of))
            .reduce((c1, c2) -> teeing(c1, c2,
                        (l1, l2) -> Stream.concat(l1.stream(), l2.stream()).toList()))
            .orElseThrow(() -> new IllegalArgumentException("no collector specified"));
}
```
<p>This may work fairly well if you don’t have a really large number of collectors to compose. A disadvantage of this concise solution is that every result will be wrapped into a single element list before the actual merging of results and even the result merging may bear multiple list copying operations.</p>
<p>This result processing can be optimized using</p>
<pre class="lang-java prettyprint-override"><code>public static <T, R> Collector<T, ?, List<R>> list(List<Collector<T, ?, R>> collectors) {
    int num = collectors.size();
    switch(num) {
        case 0: throw new IllegalArgumentException("no collector specified");
        case 1: return collectingAndThen(collectors.get(0), List::of);
        case 2: return teeing(collectors.get(0), collectors.get(1), List::of);
        case 3: return teeing(teeing(collectors.get(0), collectors.get(1), List::of),
                           collectors.get(2), (l,r) -> List.of(l.get(0), l.get(1), r));
        default:
    }
    Collector<T,?,List<R>> c = teeing(collectors.get(0), collectors.get(1), (r1, r2) -> {
        var list = new ArrayList<R>(num);
        list.add(r1);
        list.add(r2);
        return list;
    });
    for(int ix = 2; ix < num; ix ++) {
        c = teeing(c, collectors.get(ix), (list, r) -> { list.add(r); return list; });
    }
    return collectingAndThen(c, List::copyOf);
}
</code>```

This provides special cases for small numbers of collectors whose results can be used to construct an immutable result list directly. For the other cases, all results are added to an ArrayList first, preventing excessive list copying, before converting the list to the final immutable list. This last step could be omitted, if getting an immutable result list is not important, I just tried to be as close to the Stream.toList() behavior of the original approach as possible.

There’s still an unbalanced recursive structure behind the scenes during the Stream processing which prohibits really large numbers of collectors. There are two approaches to solve this.

Implement your own type safe variant of teeing which exposes the intermediate container type, to allow to build a balanced tree and collecting all results into a list by traversing this tree without additional intermediate storage.

Abandon the type safety and implement the collector with a flat list and raw types. Try to limit the unsafe code as much as possible.

But this might not be needed when you have an estimate of the expected number of collectors to “tee” and find the first solution working good enough.

Title: Java collector teeing a list of inputs

Body:
I am trying to implement a simple collector, which takes a list of collectors and simultaneously collects values in slightly different ways from a stream.

It is quite similar to Collectors.teeing, but differs in that it

Receives a list of collectors instead of just two

Requires all collectors to produce a value of the same type

The type signature I want to have is

public static <T, R> Collector<T, ?, List<R>> list(
      final List<Collector<T, ?, R>> downstreamCollectors);

One way to create such a collector would be to recursively pair up teeing collectors, like so:

public static <T, R> Collector<T, ?, List<R>> list(
    final List<Collector<T, ?, R>> downstreamCollectors) {
  return listrec(
      Collectors.collectingAndThen(downstreamCollectors.get(0), List::of),
      downstreamCollectors.stream().skip(1).toList());
}

private static <T, R> Collector<T, ?, List<R>> listrec(
    final Collector<T, ?, List<R>> teedCollectors,
    final List<Collector<T, ?, R>> downstreamCollectors) {
  if (downstreamCollectors.size() == 0) {
    return teedCollectors;
  } else {
    return listrec(
        teeing(
            teedCollectors,
            downstreamCollectors.get(0),
            (l, s) -> Stream.concat(l.stream(), Stream.of(s)).toList()),
        downstreamCollectors.stream().skip(1).toList());
  }
}

Something feels a little "off" with this solution, so I am trying to create the collector myself, something like:

public static <T, R> Collector<T, ?, List<R>> list2(
    final List<Collector<T, ?, R>> downstreamCollectors) {
  return Collector.of(
      () -> downstreamCollectors.stream().map(c -> c.supplier().get()).toList(),
      (accumulators, t) ->
          IntStream.range(0, downstreamCollectors.size())
              .forEach(
                  i -> downstreamCollectors.get(i).accumulator().accept(accumulators.get(i), t)),
      (accumulator1, accumulator2) ->
          IntStream.range(0, downstreamCollectors.size())
              .mapToObj(
                  i ->
                      downstreamCollectors
                          .get(i)
                          .combiner()
                          .apply(accumulator1.get(i), accumulator2.get(i)))
              .toList(),
      accumulators ->
          IntStream.range(0, downstreamCollectors.size())
              .mapToObj(i -> downstreamCollectors.get(i).finisher().apply(accumulators.get(i)))
              .toList());
}

Because of the unbounded wildcard in the downstream collectors' accumulator type, this doesn't compile. Changing the type signature to

public static <T, A, R> Collector<? super T, ?, List<R>> list2(
    final List<Collector<? super T, A, R>> downstreamCollectors);

solves the problem, but unfortunately renders the method much less usable as the downstream collectors (like the built in collectors from java.util.stream.Collectors) typically would have a unbounded wildcard in the accumulator type.

Is there another way to implement this, keeping the wildcard in the method signature?

I am using OpenJDK 17.0.2.

Body:
Handling a list of collectors with arbitrary accumulator types as a flat list can’t be done in a type safe way, as it would require declaring n type variables to capture these types, where n is the actual list size.

Therefore, you can only implement the processing as a composition of operations, each with a finite number of components know at compile time, like your recursive approach.

This still has potential for simplifications, like replacing downstreamCollectors.size() == 0 with downstreamCollectors.isEmpty() or downstreamCollectors.stream().skip(1).toList() with a copying free downstreamCollectors.subList(1, downstreamCollectors.size()).

But the biggest impact has replacing the recursive code with a Stream Reduction operation:

public static <T, R> Collector<T, ?, List<R>> list(List<Collector<T, ?, R>> collectors) {
    return collectors.stream()
            .<Collector<T, ?, List<R>>>map(c-> Collectors.collectingAndThen(c, List::of))
            .reduce((c1, c2) -> teeing(c1, c2,
                        (l1, l2) -> Stream.concat(l1.stream(), l2.stream()).toList()))
            .orElseThrow(() -> new IllegalArgumentException("no collector specified"));
}

This may work fairly well if you don’t have a really large number of collectors to compose. A disadvantage of this concise solution is that every result will be wrapped into a single element list before the actual merging of results and even the result merging may bear multiple list copying operations.

This result processing can be optimized using

public static <T, R> Collector<T, ?, List<R>> list(List<Collector<T, ?, R>> collectors) {
    int num = collectors.size();
    switch(num) {
        case 0: throw new IllegalArgumentException("no collector specified");
        case 1: return collectingAndThen(collectors.get(0), List::of);
        case 2: return teeing(collectors.get(0), collectors.get(1), List::of);
        case 3: return teeing(teeing(collectors.get(0), collectors.get(1), List::of),
                           collectors.get(2), (l,r) -> List.of(l.get(0), l.get(1), r));
        default:
    }
    Collector<T,?,List<R>> c = teeing(collectors.get(0), collectors.get(1), (r1, r2) -> {
        var list = new ArrayList<R>(num);
        list.add(r1);
        list.add(r2);
        return list;
    });
    for(int ix = 2; ix < num; ix ++) {
        c = teeing(c, collectors.get(ix), (list, r) -> { list.add(r); return list; });
    }
    return collectingAndThen(c, List::copyOf);
}

This provides special cases for small numbers of collectors whose results can be used to construct an immutable result list directly. For the other cases, all results are added to an ArrayList first, preventing excessive list copying, before converting the list to the final immutable list. This last step could be omitted, if getting an immutable result list is not important, I just tried to be as close to the Stream.toList() behavior of the original approach as possible.

There’s still an unbalanced recursive structure behind the scenes during the Stream processing which prohibits really large numbers of collectors. There are two approaches to solve this.

Implement your own type safe variant of teeing which exposes the intermediate container type, to allow to build a balanced tree and collecting all results into a list by traversing this tree without additional intermediate storage.

Abandon the type safety and implement the collector with a flat list and raw types. Try to limit the unsafe code as much as possible.

But this might not be needed when you have an estimate of the expected number of collectors to “tee” and find the first solution working good enough.


问:
My selector is not calling the function in swift. Deleting tableViewCell programatically in iOS, swift 5
I have a method to delet a row in a tableview:

```<code>@objc func didTapDelete(_ sender: UIButton) {
    let point = sender.convert(CGPoint.zero, to: tableView)
    guard let indexPath = tableView.indexPathForRow(at: point) else {
        return
    }
    prescriptions.remove(at: indexPath.row)
    tableView.beginUpdates()
    tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .left)
    tableView.endUpdates()
}
</code>```

In my cellForRowAt, im calling the button.addTarget i declared in the Customcell

```<code>        cell.deleteButton.addTarget(self, action: #selector(didTapDelete(_:)), for: .touchUpInside)
</code>```

Here is the Button in the customCell

```<code>    let deleteButton: UIButton = {
    let variable = UIButton()
    variable.setTitle("Delete_Button".localized, for: .normal)
    variable.setTitleColor(Colors.red, for: .normal)
    variable.titleLabel?.font = UIFont.boldSystemFont(ofSize: Metrics.Spacing.medium)
    variable.translatesAutoresizingMaskIntoConstraints = false
    return variable
}()
</code>```

The method is in the View inside the viewController, but when I click on the button, even though the debugger stops at the selector.addTarget call, my didTapDelete method is not called.

Im using swift 5, viewCode.

picture of the screen

答:
I managed to resolve with

```<code>cell.contentView.isUserInteractionEnabled = false
</code>```

The problem was because the tap its recognizing the cell click did select, not the button.

Body:
I have a method to delet a row in a tableview:

@objc func didTapDelete(_ sender: UIButton) {
    let point = sender.convert(CGPoint.zero, to: tableView)
    guard let indexPath = tableView.indexPathForRow(at: point) else {
        return
    }
    prescriptions.remove(at: indexPath.row)
    tableView.beginUpdates()
    tableView.deleteRows(at: [IndexPath(row: indexPath.row, section: 0)], with: .left)
    tableView.endUpdates()
}

In my cellForRowAt, im calling the button.addTarget i declared in the Customcell

        cell.deleteButton.addTarget(self, action: #selector(didTapDelete(_:)), for: .touchUpInside)

Here is the Button in the customCell

    let deleteButton: UIButton = {
    let variable = UIButton()
    variable.setTitle("Delete_Button".localized, for: .normal)
    variable.setTitleColor(Colors.red, for: .normal)
    variable.titleLabel?.font = UIFont.boldSystemFont(ofSize: Metrics.Spacing.medium)
    variable.translatesAutoresizingMaskIntoConstraints = false
    return variable
}()

The method is in the View inside the viewController, but when I click on the button, even though the debugger stops at the selector.addTarget call, my didTapDelete method is not called.

Im using swift 5, viewCode.

picture of the screen

Body:
I managed to resolve with

cell.contentView.isUserInteractionEnabled = false

The problem was because the tap its recognizing the cell click did select, not the button.


问:
For loop on pandas Series
I'm trying to implement code that includes a for loop on a list of pandas Series:

```<code>a = pd.Series(dtype= 'float64')
b = pd.Series(dtype= 'float64')
c = pd.Series(dtype= 'float64')

data = [a,b,c]

for k in data:
    if len(k) < 1:
        k = k.append(pd.Series([1,2]))

print(a)

# returns: Series([], dtype: float64)

</code>```

I thought print(a) would return the appended Series containing [1,2]. But it just returned the original empty Series I initially defined. Of course, printing b and c also returned an empty Series. Meanwhile, if I directly do the append instead of using the for loop:

```<code>a = pd.Series(dtype= 'float64')
a = a.append(pd.Series([1,2]))

print(a)

# returns:

0    1
1    2
dtype: int64

</code>```

So the latter method returns the appended Series just fine. Why doesn't this work for the former method? I expected the first method to return the same result as the one in the second method. I thought the local characteristic only applied to defining functions, not for loops. Am I missing something here?

答:
When you use append (and almost all methods of Pandas), you get a "copy" of the Series. The modification is not in place.

Debug with id:

```<code>print(f"a: {id(a)}, {id(data[0])}")

for k in data:
    print(f"k before: {id(k)}")
    if len(k) < 1:
        k = k.append(pd.Series([1,2]))
        print(f"k after: {id(k)}")
    break
</code>```

Output:

```<code>a: 140711220977520, 140711220977520
k before: 140711220977520
k after: 140710157071840  # <- not data[0], not 'a'
</code>```

Update

One last question, then would the for loop work fine in terms of memory allocation for other objects (besides pandas objects such as Series) where the method doesn't create a new copy of the original variable?

If data contains mutable objects like list, it works:

```<code>a = []
b = []
c = []
data = [a, b, c]

for k in data:
    if len(k) < 1:
        k.append([1, 2])
</code>```

Output:

```<code>>>> a
[[1, 2]]
</code>```

Title: For loop on pandas Series

Body:
I'm trying to implement code that includes a for loop on a list of pandas Series:

a = pd.Series(dtype= 'float64')
b = pd.Series(dtype= 'float64')
c = pd.Series(dtype= 'float64')

data = [a,b,c]

for k in data:
    if len(k) < 1:
        k = k.append(pd.Series([1,2]))

print(a)

# returns: Series([], dtype: float64)

I thought print(a) would return the appended Series containing [1,2]. But it just returned the original empty Series I initially defined. Of course, printing b and c also returned an empty Series. Meanwhile, if I directly do the append instead of using the for loop:

a = pd.Series(dtype= 'float64')
a = a.append(pd.Series([1,2]))

print(a)

# returns:

0    1
1    2
dtype: int64

So the latter method returns the appended Series just fine. Why doesn't this work for the former method? I expected the first method to return the same result as the one in the second method. I thought the local characteristic only applied to defining functions, not for loops. Am I missing something here?

Body:
When you use append (and almost all methods of Pandas), you get a "copy" of the Series. The modification is not in place.

Debug with id:

print(f"a: {id(a)}, {id(data[0])}")

for k in data:
    print(f"k before: {id(k)}")
    if len(k) < 1:
        k = k.append(pd.Series([1,2]))
        print(f"k after: {id(k)}")
    break

Output:

a: 140711220977520, 140711220977520
k before: 140711220977520
k after: 140710157071840  # <- not data[0], not 'a'

Update

One last question, then would the for loop work fine in terms of memory allocation for other objects (besides pandas objects such as Series) where the method doesn't create a new copy of the original variable?

If data contains mutable objects like list, it works:

a = []
b = []
c = []
data = [a, b, c]

for k in data:
    if len(k) < 1:
        k.append([1, 2])

Output:

>>> a
[[1, 2]]


问:
How to use selectpicker and filter typing text
I implemented selectpicker to style select but I have no idea how to add filtering by type text like in select2. Does anyone have got idea how to do it ?</p>

答:
You can do that with data-live-search prop/attribute setting it to true.

Official link with working examples:

https://developer.snapappointments.com/bootstrap-select/examples/#live-search

ContentLicense: CC BY-SA 3.0


问:
Required attribute for property that is not required in the database
I have a form, where some fields are mandatory. A few of the mandatory fields have not always been mandatory, hence there are null values in the database.

If I add [Required] for the property, I will get a SqlNullValueException, because there are null values in the database.

What is the best practice to get a field to behave as if it had a [Required] attribute?

```<code>[Required]
public string? foo { get; set; }
</code>```

答:
You're a bit light on context here, but I assume you are using Entity Framework and you have a class setup for the entity and this is what has your [required] field. I am then assuming you are using this same class with your form.

If this is the case then, I would advise you to create a second class which will act as your view model. This way you have a data model (entity class) and a view model (front end specific class). Then you can easily separate the logic of the two behaviours.

You can use something like AutoMapper to make transferring of property values between the two a little easier too.

Body:
I have a form, where some fields are mandatory. A few of the mandatory fields have not always been mandatory, hence there are null values in the database.

If I add [Required] for the property, I will get a SqlNullValueException, because there are null values in the database.

What is the best practice to get a field to behave as if it had a [Required] attribute?

[Required]
public string? foo { get; set; }


问:
How to call parent methods in Java/Groovy
I'm new to Java and groovy , I mostly code in Python.I'm trying to understand why the code doesn't work.
The error i'm getting is
groovy.lang.MissingMethodException: No signature of method: static HelloWorld.TestingProduct() is applicable for argument types: () values: []

I've been tasked to add eventdate as sysdate on a project, and I'm just trying to understand how to add it by testing locally

```<code>import groovy.transform.ToString
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

public class HelloWorld{

     public static void main(String[] args){
        String testin = TestingProduct().Inventory()
        System.out.println(testin);
     }
}

class Parent {

   private String setDateNow() {
        OffsetDateTime now = OffsetDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        return formatter.format(now);
    }
}

class TestingProduct extends Parent {
   private static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
         productId:'1',
         productIdType:'2',
         eventType:'3',
         eventDate: setDateNow(),
      )
      return invent
   }
}

@Canonical()
@ToString(includeNames = true)
class ProductInventoryEvent {
    String productId
    String productIdType
    String eventType
    String eventDate

}
</code>```

答: Also i think, you can't call private method in parent´s class. you have to change the access modifier to protected</p>

Body:
I'm new to Java and groovy , I mostly code in Python.I'm trying to understand why the code doesn't work.
The error i'm getting is
groovy.lang.MissingMethodException: No signature of method: static HelloWorld.TestingProduct() is applicable for argument types: () values: []

I've been tasked to add eventdate as sysdate on a project, and I'm just trying to understand how to add it by testing locally

import groovy.transform.ToString
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter

public class HelloWorld{

     public static void main(String[] args){
        String testin = TestingProduct().Inventory()
        System.out.println(testin);
     }
}

class Parent {

   private String setDateNow() {
        OffsetDateTime now = OffsetDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME;
        return formatter.format(now);
    }
}

class TestingProduct extends Parent {
   private static ProductInventoryEvent Inventory(){
      def invent = new ProductInventoryEvent(
         productId:'1',
         productIdType:'2',
         eventType:'3',
         eventDate: setDateNow(),
      )
      return invent
   }
}

@Canonical()
@ToString(includeNames = true)
class ProductInventoryEvent {
    String productId
    String productIdType
    String eventType
    String eventDate

}


问:
Minimal "run this command in this docker image" jenkinsfile
There is a docker image whose name is IMAGE_NAME.

I want a Jenkins job to docker pull IMAGE_NAME and then docker run IMAGE_NAME /bin/bash -c '/usr/bin/my_startup arg1 arg2 arg3

I tried a few variations of a Jenkinsfile based on some googled examples but they don't work and I clearly don't understand stages, agent, what environment the steps {sh '...'} command runs in, or any of the Jenkins jargon at all.

What's a minimal jenkinsfile which will pull IMAGE_NAME and run a command with arguments in it?

答:
This worked:

```<code>docker.image('MY_IMAGE').inside {
  sh '/bin/my-command my-args'
}
</code>```

Apparently this is a Pipeline script, run in a Groovy sandbox in Jenkins 2.150.1.

Body:
This worked:

docker.image('MY_IMAGE').inside {
  sh '/bin/my-command my-args'
}

Apparently this is a Pipeline script, run in a Groovy sandbox in Jenkins 2.150.1.


问:
Why date comparison gives wrong result?
```<code>$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = date("d.m.Y");

print_r($examDay1 <= $today);  //true

print_r($examDay2 <= $today);  // false as I expected

print_r($examDay3 <= $today);  // true for some reason
</code>```

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

答:
You may use dateTime class. The method DateTime::createFromFormat can be usefull.
Try :</p>
```<code>$examDay1 = DateTime::createFromFormat('j.m.Y', '07.02.2022');

$examDay2 = DateTime::createFromFormat('j.m.Y', '18.03.2022');

$examDay3 = DateTime::createFromFormat('j.m.Y', '06.04.2022');

$today = new DateTime("now");;

print_r($examDay1 <= $today);

print_r($examDay2 <= $today);

print_r($examDay3 <= $today);

</code>```

Title: Why date comparison gives wrong result?

Body:
$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = date("d.m.Y");

print_r($examDay1 <= $today);  //true

print_r($examDay2 <= $today);  // false as I expected

print_r($examDay3 <= $today);  // true for some reason

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

Body:
You may use dateTime class. The method DateTime::createFromFormat can be usefull.
Try :

$examDay1 = DateTime::createFromFormat('j.m.Y', '07.02.2022');

$examDay2 = DateTime::createFromFormat('j.m.Y', '18.03.2022');

$examDay3 = DateTime::createFromFormat('j.m.Y', '06.04.2022');

$today = new DateTime("now");;

print_r($examDay1 <= $today);

print_r($examDay2 <= $today);

print_r($examDay3 <= $today);


问:
sqlpackage migration script always wants to rebuild
Can anyone explain when using sqlpackage.exe to produce a migration script always wants to drop the table and recreate when adding a field.

My databases are hosted on Azure PaaS service.

I have a database with a table created with the following sql:

```<code>CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);
</code>```

I then create a new temporary database and run the following sql (adding field 2)

```<code>CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Field 2]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);
</code>```

Then run the following command to extract the dacpac:

```<code>sqlpackage.exe /SourceConnectionString:"<tempdb>" /a:Extract /tf:local.dacpac
</code>```

Then run this to get a migration report:

```<code>sqlpackage.exe /TargetConnectionString:"<orginaldb>" /a:DeployReport /sourcefile:local.dacpac /outputpath:report.xml
</code>```

But it always wants to do this:

```<code><?xml version="1.0" encoding="utf-8"?>
<DeploymentReport xmlns="http://schemas.microsoft.com/sqlserver/dac/DeployReport/2012/02">
    <Alerts>
        <Alert Name="DataMotion">
            <Issue Value="[dbo].[test]" />
        </Alert>
    </Alerts>
    <Operations>
        <Operation Name="TableRebuild">
            <Item Value="[dbo].[test]" Type="SqlTable" />
        </Operation>
    </Operations>
</DeploymentReport>
</code>```

答: This probably happens because the new column is not the last column in the table (it is before other existing columns). In such a case also the SSMS Table Designer needs to recreate the table (to preserve the specified order of columns).</p>

Body:
Can anyone explain when using sqlpackage.exe to produce a migration script always wants to drop the table and recreate when adding a field.

My databases are hosted on Azure PaaS service.

I have a database with a table created with the following sql:

CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

I then create a new temporary database and run the following sql (adding field 2)

CREATE TABLE [dbo].[test] (
    [Id]             INT            IDENTITY (1, 1) NOT NULL,
    [Field 1]        INT            NULL,
    [Field 2]        INT            NULL,
    [Timestamp]      ROWVERSION     NOT NULL,
    [InsertedTime]   DATETIME       DEFAULT (getdate()) NOT NULL,
    [UpdatedTime]    DATETIME       NULL,
    [LastUpdatedBy]  NVARCHAR (100) NULL,
    [AssignedTo]     NVARCHAR (90)  NULL,
    [ActionRequired] NVARCHAR (MAX) NULL,
    [AuditLog]       XML            NULL,
    PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

Then run the following command to extract the dacpac:

sqlpackage.exe /SourceConnectionString:"<tempdb>" /a:Extract /tf:local.dacpac

Then run this to get a migration report:

sqlpackage.exe /TargetConnectionString:"<orginaldb>" /a:DeployReport /sourcefile:local.dacpac /outputpath:report.xml

But it always wants to do this:

<?xml version="1.0" encoding="utf-8"?>
<DeploymentReport xmlns="http://schemas.microsoft.com/sqlserver/dac/DeployReport/2012/02">
    <Alerts>
        <Alert Name="DataMotion">
            <Issue Value="[dbo].[test]" />
        </Alert>
    </Alerts>
    <Operations>
        <Operation Name="TableRebuild">
            <Item Value="[dbo].[test]" Type="SqlTable" />
        </Operation>
    </Operations>
</DeploymentReport>


问:
How to force SQL parameter instead of constant in Expression predicate
I want to create predicate expression so that it translates into WHERE clause with SQL parameter, e.g.:

WHERE e.Id = @id_1;
```
<p>I have this code</p>
<pre class="lang-cs prettyprint-override"><code>int id = 1;
Expression<Func<Entity, int>> keySelector = e => e.Id;
BinaryExpression equals = Expression.Equal(
   keySelector.Body,
   Expression.Constant(id, keySelector.Body.Type)); //replace this with a variable

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);
</code>```

but it translates into:

WHERE e.Id = 1;
```

which generates new query execution plan for each id.

Does EF core provide some internal mechanism, that I could (should) use, e.g. special subclass of Expression, or ExpressionVisitor?

答:
Does EF core provide some internal mechanism, that I could (should) use, e.g. special subclass of Expression, or ExpressionVisitor?

Nothing special. All you need is to emulate C# closure. This could be done in several ways - using anonymous type, concrete type, Tuple or even real C# compiler generated closure like

int id = 1;
Expression<Func<int>> valueSelector = () => id;
var value = valueSelector.Body; // use this in place of Expression.Constant
```
<p>Example of anonymous type approach</p>
<pre class="lang-cs prettyprint-override"><code>int id = 1;
var variable = new { id };
var value = Expression.Property(Expression.Constant(variable), nameof(id));
</code>```

Similar with new Tuple<int>(id) and Item1.

Body:
I want to create predicate expression so that it translates into WHERE clause with SQL parameter, e.g.:

WHERE e.Id = @id_1;

I have this code

int id = 1;
Expression<Func<Entity, int>> keySelector = e => e.Id;
BinaryExpression equals = Expression.Equal(
   keySelector.Body,
   Expression.Constant(id, keySelector.Body.Type)); //replace this with a variable

var predicate = Expression.Lambda<Func<Entity, bool>>(equals, keySelector.Parameters[0]);

but it translates into:

WHERE e.Id = 1;

which generates new query execution plan for each id.

Does EF core provide some internal mechanism, that I could (should) use, e.g. special subclass of Expression, or ExpressionVisitor?

Body:
Does EF core provide some internal mechanism, that I could (should) use, e.g. special subclass of Expression, or ExpressionVisitor?

Nothing special. All you need is to emulate C# closure. This could be done in several ways - using anonymous type, concrete type, Tuple or even real C# compiler generated closure like

int id = 1;
Expression<Func<int>> valueSelector = () => id;
var value = valueSelector.Body; // use this in place of Expression.Constant

Example of anonymous type approach

int id = 1;
var variable = new { id };
var value = Expression.Property(Expression.Constant(variable), nameof(id));

Similar with new Tuple<int>(id) and Item1.


问:
Brother Label Printer SDK bPac 3.1 Failed to print
I've got the printer driver, P-touch Editor, b-PAC 3.1 and client tools, all 64-bit, downloaded from the Brother website and installed on my 64-bit Windows 7 laptop. The P-touch Editor works/prints fine.

However, b-PAC failed, and none of the samples worked.  I debugged the code:

```<code>bool b = doc.PrintOut(1, bpac.PrintOptionConstants.bpoDefault);
</code>```

where b is false.  What could be wrong?

答:
I had the same problem (printOut gave me the error code 11).
The error appeared after switching from the printer PT-9800 to PT-P950.
Trying 32 and 64bit did not work for me.

What fixed it was uninstalling the driver of the PT-9800. I found a hint in the b-PAC 3.4 SDK Help in the section Troubleshooting: "if the old label printer will no longer be used, we recommend deleting the printer driver."

Body:
I've got the printer driver, P-touch Editor, b-PAC 3.1 and client tools, all 64-bit, downloaded from the Brother website and installed on my 64-bit Windows 7 laptop. The P-touch Editor works/prints fine.

However, b-PAC failed, and none of the samples worked.  I debugged the code:

bool b = doc.PrintOut(1, bpac.PrintOptionConstants.bpoDefault);

where b is false.  What could be wrong?


问:
Timings of functions inside python script
I've got a script with several complex functions, which looks something like this

```<code>import time

def function1(a,b,c):
   print(a,b,c)

def function2(d,e,f):
   print(d,e,f)
...
...
def function7(g,h,i):
   print(g,h,i)
</code>```

I am trying to record the timing for each function and then make a dataframe with all the timings for analysis. This is what I have attempted:

```<code>start1 = time.time()
function1(a,b,c)
end1 = time.time()
func1_time = end - start

start2 = time.time()
function2(d,e,f)
end2 = time.time()
func2_time = end - start
...
...
start7 = time.time()
function7(g,h,i)
end7 = time.time()
func7_time = end - start
</code>```

Above is a basic method using time.time, however, is there a more elegant/convenient way to carry this out?

答:
When you see variable1, variable2, etc. and you want your code to look more elegant, the answer is in 90% cases either a list or a dictionary:

```<code>funs = [function1, function2, function3]
times = []
for fun in funs:
    start = time.time()
    fun(a,b,c)
    end = time.time()
    times.append(end - start)
</code>```

Body:
I've got a script with several complex functions, which looks something like this

import time

def function1(a,b,c):
   print(a,b,c)

def function2(d,e,f):
   print(d,e,f)
...
...
def function7(g,h,i):
   print(g,h,i)

I am trying to record the timing for each function and then make a dataframe with all the timings for analysis. This is what I have attempted:

start1 = time.time()
function1(a,b,c)
end1 = time.time()
func1_time = end - start

start2 = time.time()
function2(d,e,f)
end2 = time.time()
func2_time = end - start
...
...
start7 = time.time()
function7(g,h,i)
end7 = time.time()
func7_time = end - start

Above is a basic method using time.time, however, is there a more elegant/convenient way to carry this out?

Body:
When you see variable1, variable2, etc. and you want your code to look more elegant, the answer is in 90% cases either a list or a dictionary:

funs = [function1, function2, function3]
times = []
for fun in funs:
    start = time.time()
    fun(a,b,c)
    end = time.time()
    times.append(end - start)


问:
Is there a way to use SmartSheet Control Center to bulk add reports to previously created projects?
I would like to bulk update Dashboards in SmartSheet, via Control Center, to leverage new reports I've created at the SCC/template level. I'm having two problems.

Is there a way to use SmartSheet Control Center to bulk add reports to previously created projects?  This article would seem to suggest there is -
https://community.smartsheet.com/discussion/71230/is-there-a-way-to-use-a-global-update-to-add-a-new-report-to-previously-provisioned-projects - however, I've been told by SmartSheet this is not possible.

At the same time, even if I manually create those reports, this Help article - https://help.smartsheet.com/articles/2479391-control-center-global-updates-dashboards - suggests that Global Updates will only recognize dashboards, reports and sheets that were created through Control Center.  So it would seem like a bad idea to manually create those reports because they would never "tie back to" to the template and be update-able by Control Center.

Does anyone have any thoughts on this issue?

答:
Unless it has been a change in the last few days.

Documentation is correct Control Center can only add to new projects.

Unfortunately it is not possible, even the API has no report manipulation, not a simple copy or move it, nothing. I've been struggling with this issue for some time now, you can only do it manually.


问:
Dynamic deep selection for a JavaScript object
With a single property this is fairly easy:

```<code>
var jsonobj = {
    "test": "ok"
}
var propname = "test";
// Will alert "ok"
alert(jsonobj[propname]);
</code>```

But what I want to do is use a nested property:

```<code>
var jsonobj = {
    "test": {
        "test2": "ok"
    }
}
var propname = "test.test2";
// Alerts undefined
alert(jsonobj[propname]);
</code>```

Is there any way of selecting a nested "dynamic" property?
I know I can do jsonobj.test.test2, but the problem is that propname can change to a property that goes 1,2 or 3 levels deep. (e.g test, test.test2, ...)

答:
I also just implemented this using an inner recursive function like so:

```<code>function get(obj, ns) {

    function recurse(o, props) {
        if (props.length === 0) {
            return o;
        }
        if (!o) {
            return undefined;
        }
        return recurse(o[props.shift()], props);
    }

    return recurse(obj, ns.split('.'));
}
</code>```

This will return the deep value of the property specified by the ns param, otherwise will always return undefined if it doesn't exist or there are any problems along the way.

ContentLicense: CC BY-SA 2.5

Body:
With a single property this is fairly easy:

var jsonobj = {
    "test": "ok"
}
var propname = "test";
// Will alert "ok"
alert(jsonobj[propname]);

But what I want to do is use a nested property:

var jsonobj = {
    "test": {
        "test2": "ok"
    }
}
var propname = "test.test2";
// Alerts undefined
alert(jsonobj[propname]);

Is there any way of selecting a nested "dynamic" property?
I know I can do jsonobj.test.test2, but the problem is that propname can change to a property that goes 1,2 or 3 levels deep. (e.g test, test.test2, ...)

Body:
I also just implemented this using an inner recursive function like so:

function get(obj, ns) {

    function recurse(o, props) {
        if (props.length === 0) {
            return o;
        }
        if (!o) {
            return undefined;
        }
        return recurse(o[props.shift()], props);
    }

    return recurse(obj, ns.split('.'));
}

This will return the deep value of the property specified by the ns param, otherwise will always return undefined if it doesn't exist or there are any problems along the way.


问:
make ChoiceField() take any value
I'm using the forms framework and I'm using a but of javascript magic to inject some values on the fly into a select box (the values of this select box relies on a value form another).

Basically you have Team and Players. You need to define a player, but the players data comes from a Team.

In my form class i have

```<code>team = forms.ModelChoiceField(queryset=Team.objects.all()
player = forms.ChoiceField()
</code>```

In the front end when the user selects a team from the select box, the (empty) players boxes gets correctly updated with new data. However when i hit submit, the player select box throws a error Select a valid choice. 2 is not one of the available choices. 2 IS a valid choice however.

Is there any way around this? Can i make the ChoiceField() take any value?

答:
You can use the data parameter passed to init function to update choices dynamically.</p>
```<code>class PlayerTeamForm(forms.ModelForm):
    team = forms.ModelChoiceField(queryset=Team.objects.all()
    player = forms.ChoiceField(choices = [])
    class Meta:
        model = PlayerTeamModel
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if kwargs.get('data'): # When form is submitted
            # prefix for formsets
            prefix = kwargs.get('prefix') + '-' if kwargs.get('prefix') else ''
            player = Player.objects.get(
                pk = kwargs.get('data').get(prefix + 'player')
            )
            self.fields['player'].choices = [[
                player.pk, player.name
            ]]
        else:
            self.fields['player'].choices = [[
                self.instance.player_id, self.instance.player.name
            ]]

</code>```

Title: make ChoiceField() take any value

Body:
I'm using the forms framework and I'm using a but of javascript magic to inject some values on the fly into a select box (the values of this select box relies on a value form another).

Basically you have Team and Players. You need to define a player, but the players data comes from a Team.

In my form class i have

team = forms.ModelChoiceField(queryset=Team.objects.all()
player = forms.ChoiceField()

In the front end when the user selects a team from the select box, the (empty) players boxes gets correctly updated with new data. However when i hit submit, the player select box throws a error Select a valid choice. 2 is not one of the available choices. 2 IS a valid choice however.

Is there any way around this? Can i make the ChoiceField() take any value?

Body:
You can use the data parameter passed to init function to update choices dynamically.

class PlayerTeamForm(forms.ModelForm):
    team = forms.ModelChoiceField(queryset=Team.objects.all()
    player = forms.ChoiceField(choices = [])
    class Meta:
        model = PlayerTeamModel
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if kwargs.get('data'): # When form is submitted
            # prefix for formsets
            prefix = kwargs.get('prefix') + '-' if kwargs.get('prefix') else ''
            player = Player.objects.get(
                pk = kwargs.get('data').get(prefix + 'player')
            )
            self.fields['player'].choices = [[
                player.pk, player.name
            ]]
        else:
            self.fields['player'].choices = [[
                self.instance.player_id, self.instance.player.name
            ]]


问:
High Google Firebase Storage Cost for saving and downloading .mp4 files?
I'm saving videos to Firebase Storage and creating a URL for it which I saving into Cloud Firestore. So when ever someone watch a video I call the URL and  Firebase downloads it. That increased my project costs enormously.

The question that I have is, is there a way to save the mp4 files cheaper?

And maybe also make it faster to download?

The best solution will be if I can like I used before. So in the new solution, also use the download URL which I saved in cloud Firestore. So that I don't need change too much. My Project is using Flutter in client side.

I created a mobile app, where user can upload videos for example like Instagram or TikTok.

I'm willing to pay if you freelancer and can help.

答: It is possible to upload videos to YouTube using Google API. There is an example done using flutter which can be ideal for your use-case. Have a look at this video on youtube.</p>


问:
Java DataLoader: Graphql query mismatches results
I am using boot-graphql-kick-start in my project. When I used Dataloader, the result is missmatching. where am I wrong? Can you help me?

Query:

```<code>query USE_ROLES_BY_PROJECT_ID($projectId: Int) {  # parameter value  =3
  userRolesByProjectId(projectId:$projectId) {
    id
    roleId
    projectId
    role {
      id
      name
      shortCode
    }
  }
</code>```

Result:

```<code>{
  "data": {
    "userRolesByProjectId": [
      {
        "id": 2,
        "projectId": 3,
        "roleId": 5,
        "role": {
          "id": 8,
          "name": "TESTER",
          "shortCode": "TESTER"
        }
      },
      {
        "id": 81,
        "projectId": 3,
        "roleId": 8,
        "role": {
          "id": 5,
          "name": "PROJECTADMIN",
          "shortCode": "PROJECTADMIN"
        }
      }
    ]
  }
}
</code>```

ResultForDetail

Entity: I have ManyToOne Relation With My RoleEntity

```<code>@Entity
public class UserRole extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_cfcs_user_role")
    @Column(name = "id")
    private Long id;

    @Column(name = "role_id")
    private Long roleId;

    @Column(name = "project_id")
    private Long projectId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "role_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Role role;
}
</code>```

QueryResolver:

```<code>@Component
public class UserRolesQueryResolver implements GraphQLQueryResolver {
    private final UserRoleService userRolesService;

    public List<UserRole> userRolesByProjectId(Long projectId){
        return userRolesService.getUserRole(projectId);
    }
}

@Component
public class UserRoleResolver
implements GraphQLResolver<UserRole> {
    private final IRoleService roleService;

    public CompletableFuture<Role> role(UserRole userRole, DataFetchingEnvironment dfe) {
        final DataLoader<Long, Role> dataloader = dfe.getDataLoaderRegistry()
                .getDataLoader("userRoleRoleDataLoader");
        return dataloader.load(userRole.getRoleId());
    }
}
</code>```

DataLoader Method: I'm Using BatchLoader for n+1.

```<code> private void role(DataFetchingEnvironment dfe) {
        BatchLoader<Long, Role> userRoleRoleDataLoader =
                roles -> CompletableFuture.supplyAsync(() -> {
                    return roleService.findByIdIn(roles);
                });
        dfe.getDataLoaderRegistry().register("userRoleRoleDataLoader",
                DataLoader.newDataLoader(userRoleRoleDataLoader));
    }
</code>```

Hibernate Query: In dataLoader Iam wathcing the result. Is seems  correctly

```<code>select role0_.id         as id1_18_,
       role0_.name       as name9_18_,
       role0_.short_code as short_c10_18_
from app_role role0_
where (role0_.is_actv = 1)
  and (role0_.id in (?, ?))
</code>```

答:
I had the same problem and the solution is to sort the output from your data loader according to the input. The order of the output has to match the order of the input.
For you this probably means something like this:</p>
```<code>private void role(DataFetchingEnvironment dfe) {
        BatchLoader<Long, Role> userRoleRoleDataLoader =
                roleIds -> CompletableFuture.supplyAsync(() -> {
                    List<Role> roles = roleService.findByIdIn(roleIds);
                    roles.sort(Comparator.comparing(n -> roleIds.indexOf(n.getId())));
                    return roles;
                });
        dfe.getDataLoaderRegistry().register("userRoleRoleDataLoader",
                DataLoader.newDataLoader(userRoleRoleDataLoader));
    }
</code>```

Body:
I am using boot-graphql-kick-start in my project. When I used Dataloader, the result is missmatching. where am I wrong? Can you help me?

Query:

query USE_ROLES_BY_PROJECT_ID($projectId: Int) {  # parameter value  =3
  userRolesByProjectId(projectId:$projectId) {
    id
    roleId
    projectId
    role {
      id
      name
      shortCode
    }
  }

Result:

{
  "data": {
    "userRolesByProjectId": [
      {
        "id": 2,
        "projectId": 3,
        "roleId": 5,
        "role": {
          "id": 8,
          "name": "TESTER",
          "shortCode": "TESTER"
        }
      },
      {
        "id": 81,
        "projectId": 3,
        "roleId": 8,
        "role": {
          "id": 5,
          "name": "PROJECTADMIN",
          "shortCode": "PROJECTADMIN"
        }
      }
    ]
  }
}

ResultForDetail

Entity: I have ManyToOne Relation With My RoleEntity

@Entity
public class UserRole extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_cfcs_user_role")
    @Column(name = "id")
    private Long id;

    @Column(name = "role_id")
    private Long roleId;

    @Column(name = "project_id")
    private Long projectId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "role_id", referencedColumnName = "id", insertable = false, updatable = false)
    private Role role;
}

QueryResolver:

@Component
public class UserRolesQueryResolver implements GraphQLQueryResolver {
    private final UserRoleService userRolesService;

    public List<UserRole> userRolesByProjectId(Long projectId){
        return userRolesService.getUserRole(projectId);
    }
}

@Component
public class UserRoleResolver
implements GraphQLResolver<UserRole> {
    private final IRoleService roleService;

    public CompletableFuture<Role> role(UserRole userRole, DataFetchingEnvironment dfe) {
        final DataLoader<Long, Role> dataloader = dfe.getDataLoaderRegistry()
                .getDataLoader("userRoleRoleDataLoader");
        return dataloader.load(userRole.getRoleId());
    }
}

DataLoader Method: I'm Using BatchLoader for n+1.

 private void role(DataFetchingEnvironment dfe) {
        BatchLoader<Long, Role> userRoleRoleDataLoader =
                roles -> CompletableFuture.supplyAsync(() -> {
                    return roleService.findByIdIn(roles);
                });
        dfe.getDataLoaderRegistry().register("userRoleRoleDataLoader",
                DataLoader.newDataLoader(userRoleRoleDataLoader));
    }

Hibernate Query: In dataLoader Iam wathcing the result. Is seems  correctly

select role0_.id         as id1_18_,
       role0_.name       as name9_18_,
       role0_.short_code as short_c10_18_
from app_role role0_
where (role0_.is_actv = 1)
  and (role0_.id in (?, ?))

Body:
I had the same problem and the solution is to sort the output from your data loader according to the input. The order of the output has to match the order of the input.
For you this probably means something like this:

private void role(DataFetchingEnvironment dfe) {
        BatchLoader<Long, Role> userRoleRoleDataLoader =
                roleIds -> CompletableFuture.supplyAsync(() -> {
                    List<Role> roles = roleService.findByIdIn(roleIds);
                    roles.sort(Comparator.comparing(n -> roleIds.indexOf(n.getId())));
                    return roles;
                });
        dfe.getDataLoaderRegistry().register("userRoleRoleDataLoader",
                DataLoader.newDataLoader(userRoleRoleDataLoader));
    }


问:
how can I process a file that has different names depending on the folder (in other words get the name first)?
Let's suppose there is a folder with several subfolders. In each subfolder there is a file, that has a different name depending on the folder. For example

```<code>basefolder
   |________f1_1_1:  video_1_1_1.mp4
   |________f1_2_1:  video_1_2_1.mp4
   |
   |_ .....
</code>```

I want to write a shell script that do some processing on these files

So I have

```<code>search_dir=/path/to/the/basefolder/
for entry in "$search_dir"*/
do
    echo "$entry"
    #ls  "$entry"   #<--------HERE

    echo "========================"
done
</code>```

As you can see I can list the subfolders.
I want to do something like

```<code>process video_1_1_1.mp4 video_1_1_1_out.mp4
</code>```

but the file name varies.
Yes I see that I can perhaps use the entry variable to compose the name of the file, but what if the files don't follow this pattern and the only thing I know is that they start with "video"?

Is there a way to get the name of the file in the folder so as to use it later?

答:
Consider this file tree:

```<code>$ tree /tmp/test
/tmp/test
├── one
│   ├── one-1.mp4
│   ├── one-2.mp4
│   ├── one-3.mp4
│   ├── video-1.mp4
│   └── video-2.mp4
└── two
    ├── two-1.mp4
    ├── two-2.mp4
    ├── two-3.mp4
    ├── video-1.mp4
    └── video-2.mp4

2 directories, 10 files
</code>```

You can use a recursive glob to find all the .mp4 files in that tree:

```<code>$ for fn in "/tmp/test/"**/*".mp4"; do echo "$fn"; done
/tmp/test/one/one-1.mp4
/tmp/test/one/one-2.mp4
/tmp/test/one/one-3.mp4
/tmp/test/one/video-1.mp4
/tmp/test/one/video-2.mp4
/tmp/test/two/two-1.mp4
/tmp/test/two/two-2.mp4
/tmp/test/two/two-3.mp4
/tmp/test/two/video-1.mp4
/tmp/test/two/video-2.mp4
</code>```

Or just the ones starting with video:

```<code>$ for fn in "/tmp/test/"**/"video-"*".mp4"; do echo "$fn"; done
/tmp/test/one/video-1.mp4
/tmp/test/one/video-2.mp4
/tmp/test/two/video-1.mp4
/tmp/test/two/video-2.mp4
</code>```

Instead of echo you can process...

If process involves more than one file, you can use xargs.

You can also use find:

```<code>$ find "/tmp/test/" -iname "video*.mp4" -type f
/tmp/test//one/video-1.mp4
/tmp/test//one/video-2.mp4
/tmp/test//two/video-1.mp4
/tmp/test//two/video-2.mp4
</code>```

Then you would construct a pipe to xargs or use find -exec:

```<code>$ find [ what ] -print0 | xargs -0 process # xargs way

$ find [ what ] -exec process {} +   # modern find
</code>```

Body:
Let's suppose there is a folder with several subfolders. In each subfolder there is a file, that has a different name depending on the folder. For example

basefolder
   |________f1_1_1:  video_1_1_1.mp4
   |________f1_2_1:  video_1_2_1.mp4
   |
   |_ .....

I want to write a shell script that do some processing on these files

So I have

search_dir=/path/to/the/basefolder/
for entry in "$search_dir"*/
do
    echo "$entry"
    #ls  "$entry"   #<--------HERE

    echo "========================"
done

As you can see I can list the subfolders.
I want to do something like

process video_1_1_1.mp4 video_1_1_1_out.mp4

but the file name varies.
Yes I see that I can perhaps use the entry variable to compose the name of the file, but what if the files don't follow this pattern and the only thing I know is that they start with "video"?

Is there a way to get the name of the file in the folder so as to use it later?

Body:
Consider this file tree:

$ tree /tmp/test
/tmp/test
├── one
│   ├── one-1.mp4
│   ├── one-2.mp4
│   ├── one-3.mp4
│   ├── video-1.mp4
│   └── video-2.mp4
└── two
    ├── two-1.mp4
    ├── two-2.mp4
    ├── two-3.mp4
    ├── video-1.mp4
    └── video-2.mp4

2 directories, 10 files

You can use a recursive glob to find all the .mp4 files in that tree:

$ for fn in "/tmp/test/"**/*".mp4"; do echo "$fn"; done
/tmp/test/one/one-1.mp4
/tmp/test/one/one-2.mp4
/tmp/test/one/one-3.mp4
/tmp/test/one/video-1.mp4
/tmp/test/one/video-2.mp4
/tmp/test/two/two-1.mp4
/tmp/test/two/two-2.mp4
/tmp/test/two/two-3.mp4
/tmp/test/two/video-1.mp4
/tmp/test/two/video-2.mp4

Or just the ones starting with video:

$ for fn in "/tmp/test/"**/"video-"*".mp4"; do echo "$fn"; done
/tmp/test/one/video-1.mp4
/tmp/test/one/video-2.mp4
/tmp/test/two/video-1.mp4
/tmp/test/two/video-2.mp4

Instead of echo you can process...

If process involves more than one file, you can use xargs.

You can also use find:

$ find "/tmp/test/" -iname "video*.mp4" -type f
/tmp/test//one/video-1.mp4
/tmp/test//one/video-2.mp4
/tmp/test//two/video-1.mp4
/tmp/test//two/video-2.mp4

Then you would construct a pipe to xargs or use find -exec:

$ find [ what ] -print0 | xargs -0 process # xargs way

$ find [ what ] -exec process {} +   # modern find


问:
How to translate a form in django?
I want to translate a django form. How do I translate the labels of the fields?

I tried field.label=ugettext_lazy(field.label), but the labels are not getting populated in django.po file

I may have gotten the concept of ugettext_lazy wrong, I think

In simple terms I want the field labels to be put into django.po file.

The other translations done using ugettext and {% trans %} tag are working well

I have been able to translate the fields based on a model by setting verbose_name but when I try that for a form field I get a TypeError

答:
As an alternative way, you can add script to your template.html</p>
```<code><script>
        labels = document.getElementsByTagName('label');
        for (var j = 0; j < labels.length; j++) {
             if (labels[j].textContent == "Username:") labels[j].textContent =    "Логін   ";
             if (labels[j].textContent == "First name:") labels[j].textContent =  "Ім'я    ";
             if (labels[j].textContent == "Last name:") labels[j].textContent =   "Прізвище";
             if (labels[j].textContent == "Email address:") labels[j].textContent =   "Email адреса ";
             if (labels[j].textContent == "Password:") labels[j].textContent =        "Пароль            ";
             if (labels[j].textContent == "Confirm password:") labels[j].textContent =        "Підтвердити пароль";
             };
</script>
</code>```

Title: How to translate a form in django?

Body:
As an alternative way, you can add script to your template.html

<script>
        labels = document.getElementsByTagName('label');
        for (var j = 0; j < labels.length; j++) {
             if (labels[j].textContent == "Username:") labels[j].textContent =    "Логін   ";
             if (labels[j].textContent == "First name:") labels[j].textContent =  "Ім'я    ";
             if (labels[j].textContent == "Last name:") labels[j].textContent =   "Прізвище";
             if (labels[j].textContent == "Email address:") labels[j].textContent =   "Email адреса ";
             if (labels[j].textContent == "Password:") labels[j].textContent =        "Пароль            ";
             if (labels[j].textContent == "Confirm password:") labels[j].textContent =        "Підтвердити пароль";
             };
</script>


答:
PHPs Date function returns a string, as stated in the documentation:

You can use "strtotime" to convert the date string to a timestamp integer, and use it for comparison.

```<code>$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = time();

var_dump(
    strtotime($examDay1) <= $today,
    strtotime($examDay2) <= $today,
    strtotime($examDay3) <= $today
);
</code>```

Title: Why date comparison gives wrong result?

Body:
$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = date("d.m.Y");

print_r($examDay1 <= $today);  //true

print_r($examDay2 <= $today);  // false as I expected

print_r($examDay3 <= $today);  // true for some reason

I am trying to give access to users in same specific dates. For example one of them started today and the comparison worked fine. However, somehow it says $examDay3 <=$today gives true. What am I doing wrong?

Body:
PHPs Date function returns a string, as stated in the documentation:

You can use "strtotime" to convert the date string to a timestamp integer, and use it for comparison.

$examDay1 = date("07.02.2022");

$examDay2 = date("18.03.2022");

$examDay3 = date("06.04.2022");

$today = time();

var_dump(
    strtotime($examDay1) <= $today,
    strtotime($examDay2) <= $today,
    strtotime($examDay3) <= $today
);