问:
Determine the origin of a WM_CLOSE message
I have an app that prompts the user for confirmation on exit, which is (indirectly) done by opening a confirmation dialog when the WM_CLOSE message is received. However the message is also sent by the task manager when the user uses end task on the process.

Because I prevent the window from closing with the confirmation dialog, task manager sees it as the process hanging and forcefully terminates it preventing the app from doing a graceful exit when it's possible.

Is there any way to determine if it's the user closing the window from the message (e.g. clicking the close button, or Alt+F4), and not the task manager? As the message's parameters are unused the only way I could think of is checking for mouse events or WM_SYSCOMMAND that were received some time before the WM_CLOSE is received, but I'm unsure if this would handle all cases.

答:
I assume the task manager calls EndTask. Perhaps in the old days it only sent WM_CLOSE but it seems to send WM_SYSCOMMAND when I tested now so there are no clues in the messages you can use, it just looks like a normal Alt+F4.

If your app is asking about unsaved changes in a document, I would say, put up the dialog regardless and just accept the hard termination if that is what the user wants.

If you are just trying to prevent an accidental close, call GetForegroundWindow in WM_CLOSE. If you are not foreground, it was not an accidental close.


来源: stackexchange

问:
VB.Net - Write Records To Access Quickly
I have a large number of records to add to a Access database in realtime.  The items are temperatures, water flows etc from electronic instruments.

The code I have is below, can it be improved or is there a different way to add records more quickly - currently, 10,000 records takes approx. 10secs.

I am currently simulating the data to prove the concept of adding large number of records.

Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String

connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Neil Cooley\Desktop\Database1.accdb"

connection.Open()

Dim stop_watch_1 As New Stopwatch
Dim getDate As Date = Date.Now

For i As Integer = 1 To 10000 Step 1
  sql = "INSERT INTO Lines VALUES('TAG " & i.ToString & "','" & i.ToString & "','192','" & getDate & "')"

  oledbAdapter.InsertCommand = New OleDbCommand(sql, connection)
  oledbAdapter.InsertCommand.ExecuteNonQuery()
Next
stop_watch_1.Stop()
MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds.ToString)
```

答:
I think that the best you can hope for with that is to use SQL parameters, like this:

```<code>Dim connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Neil Cooley\Desktop\Database1.accdb"
Dim sql = "INSERT INTO Lines([tag], [num], [x], [dt]) VALUES(?, ?, '192', ?)"

Dim stop_watch_1 As New Stopwatch()

Using conn As New OleDbConnection(connString),
       cmd As New OleDbCommand(sql, conn)

    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@tag", .OleDbType = OleDbType.VarChar, .Size = 20})
    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@num", .OleDbType = OleDbType.VarChar, .Size = 20})
    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@date", .OleDbType = OleDbType.Date})

    cmd.Parameters("@date").Value = DateTime.UtcNow()

    conn.Open()

    For i As Integer = 1 To 10000 Step 1
        cmd.Parameters("@tag").Value = "TAG " & i.ToString()
        cmd.Parameters("@num").Value = i.ToString()
        cmd.ExecuteNonQuery()
    Next

End Using

stop_watch_1.Stop()
MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds)
</code>```

Make sure to set the data type and sizes of the parameters to match the database columns. You should declare the column names in the INSERT statement. The parameters are represented by ? in the query; they are added in the order they are used. The parameter names in the OleDbParameter instances are for convenience.

(Make sure to use a DateTime type in the database for DateTimes, and keeping it in UTC avoids daylight savings time change problems.)

Using a faster disk drive could help, perhaps one that the OS is not run from.

If using a different database is an option, perhaps a key-value store would serve you well. Or even just a plain CSV file.

ContentLicense: CC BY-SA 4.0

Body:
I think that the best you can hope for with that is to use SQL parameters, like this:

Dim connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Neil Cooley\Desktop\Database1.accdb"
Dim sql = "INSERT INTO Lines([tag], [num], [x], [dt]) VALUES(?, ?, '192', ?)"

Dim stop_watch_1 As New Stopwatch()

Using conn As New OleDbConnection(connString),
       cmd As New OleDbCommand(sql, conn)

    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@tag", .OleDbType = OleDbType.VarChar, .Size = 20})
    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@num", .OleDbType = OleDbType.VarChar, .Size = 20})
    cmd.Parameters.Add(New OleDbParameter With {.ParameterName = "@date", .OleDbType = OleDbType.Date})

    cmd.Parameters("@date").Value = DateTime.UtcNow()

    conn.Open()

    For i As Integer = 1 To 10000 Step 1
        cmd.Parameters("@tag").Value = "TAG " & i.ToString()
        cmd.Parameters("@num").Value = i.ToString()
        cmd.ExecuteNonQuery()
    Next

End Using

stop_watch_1.Stop()
MsgBox("Row(s) Inserted !! - " & stop_watch_1.ElapsedMilliseconds)

Make sure to set the data type and sizes of the parameters to match the database columns. You should declare the column names in the INSERT statement. The parameters are represented by ? in the query; they are added in the order they are used. The parameter names in the OleDbParameter instances are for convenience.

(Make sure to use a DateTime type in the database for DateTimes, and keeping it in UTC avoids daylight savings time change problems.)

Using a faster disk drive could help, perhaps one that the OS is not run from.

If using a different database is an option, perhaps a key-value store would serve you well. Or even just a plain CSV file.


问:
Circular dependency best practice
What is the best way to solve this.

I have projects the following projects:

Model

Logic (references model)

Synchronization (references both model and logic)

Web (references all projects)

All runs fine, the web project fires the synchronization project, which uses model and logic, and does it's work.
But now, some times, the logic project also has to call a method in the synchronization project, but this reference cannot be added because of the circular dependency that is not allowed.

What would be the easiest way to make this whole thing work?

A bit more on the synchronization project.
Synchronization works on it's own. It runs processes that bring data from an external database to the database in my application. It does this by creating objects based on the model and saves them by using the logic.
This works fine, and gives us the ability to simply create another synchronization project/assembly that could do the same thing, but targeted at a completely different type of database.

The problem is, that we now, from time to time, want to call a method in the sychronization project to update some data in the other direction / to the external database.

答: Create a new project "NewProject" and put that method "or the class that is holding it" in that it, and then add it as a reference to Synchronization and Logic.

ContentLicense: CC BY-SA 3.0

Title: Circular dependency best practice


问:
Python - How do i delete more than one character on python using slice method, find and rfind
I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.

It should work something like that

Input: {fefeef}this{feofeow}.4849

Output this.4849

Here is my code

```<code> def help_mmtf():

       while True:

           user_input = input("Filename?")
           text_input = str(user_input)

           if (text_input !=""):

                word = text_input

                index1 = word.find("{")
                index2 = word.find("}")
                print(index1)
                print(index2)

                index3 = word.rfind("{")
                index4 = word.rfind("}")

                print(index3)
                print(index4)

                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')

      else:

               break

</code>```

答:
Use sub function from re module:

```<code>import re

s = "{fefeef}this{feofeow}.4849"
out = re.sub(r'{[^}]*}', '', s)
</code>```

Output:

```<code>>>> out
'this.4849'
</code>```

For more explanation: Regex101

Body:
I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.

It should work something like that

Input: {fefeef}this{feofeow}.4849

Output this.4849

Here is my code

 def help_mmtf():

       while True:

           user_input = input("Filename?")
           text_input = str(user_input)

           if (text_input !=""):

                word = text_input

                index1 = word.find("{")
                index2 = word.find("}")
                print(index1)
                print(index2)

                index3 = word.rfind("{")
                index4 = word.rfind("}")

                print(index3)
                print(index4)

                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')

      else:

               break

Body:
Use sub function from re module:

import re

s = "{fefeef}this{feofeow}.4849"
out = re.sub(r'{[^}]*}', '', s)

Output:

>>> out
'this.4849'

For more explanation: Regex101


问:
How to add HTTP endpoint to ASP.NET Core 6 app?
I created an ASP.NET Core 6 app with "Configure for HTTPS" checked during project creation. For testing purposes I now need a plain HTTP endpoint. How can I add such an endpoint?

My code currently looks like this:

```<code>var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();
app.MapGet("/", () => "Hello World! - use /graphql");

app.Run();
</code>```

答:
Serhii and Serge pointed me to the launchSettings.json (note that it's inside the Properties folder!). That's how it looks like:

```<code>{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:20380",
      "sslPort": 44329
    }
  },
  "profiles": {
    "TestProject": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7090;http://localhost:5090",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

Note the line

```<code> "applicationUrl": "https://localhost:7090;http://localhost:5090",
</code>```

and note that the second URL is plain HTTP. I could call this URL without any issues (started project normally using F5, HTTPS link is called automatically, but one can just switch manually to the HTTP link in the browser).

So, nothing to do for me, no configuration change was needed etc :-)

Body:
I created an ASP.NET Core 6 app with "Configure for HTTPS" checked during project creation. For testing purposes I now need a plain HTTP endpoint. How can I add such an endpoint?

My code currently looks like this:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();
app.MapGet("/", () => "Hello World! - use /graphql");

app.Run();

Body:
Serhii and Serge pointed me to the launchSettings.json (note that it's inside the Properties folder!). That's how it looks like:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:20380",
      "sslPort": 44329
    }
  },
  "profiles": {
    "TestProject": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7090;http://localhost:5090",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Note the line

 "applicationUrl": "https://localhost:7090;http://localhost:5090",

and note that the second URL is plain HTTP. I could call this URL without any issues (started project normally using F5, HTTPS link is called automatically, but one can just switch manually to the HTTP link in the browser).

So, nothing to do for me, no configuration change was needed etc :-)


问:
Converting Gregorian date to Hijri date
How do you convert Gregorian dates to Islamic Hijri dates using JavaScript?</p>

答:
The safest is to use the built-in javascript Intl.DateTimeFormat() constructor.

Here is an example of the 4 output formats in the Islamic Hijri Calendar of today's date.

Also examples of extracting the year and months separately under different formats.

let myFormat = 'en-u-ca-islamic-umalqura-nu-latn'; // use islamic-umalqura calendar (most modern)
let myDate   = new Date(Date.now());  // today's date
let output   = new Intl.DateTimeFormat(myFormat,{dateStyle:'full'}).format(myDate);
console.log("Full format   : "+output);

output   = new Intl.DateTimeFormat(myFormat,{dateStyle:'long'}).format(myDate);
console.log("Long format   : "+output);

output   = new Intl.DateTimeFormat(myFormat,{dateStyle:'medium'}).format(myDate);
console.log("Medium format : "+output);

output   = new Intl.DateTimeFormat(myFormat,{dateStyle:'short'}).format(myDate);
console.log("Short format (m/d/yyyy): "+output);

console.log("=".repeat(50));

let yearFull = new Intl.DateTimeFormat(myFormat,{year:'numeric'}).format(myDate);
console.log("The full year     : "+yearFull);
console.log("The year number   : " +(+yearFull.split(" ")[0]));

let monthLong = new Intl.DateTimeFormat(myFormat,{month:'long'}).format(myDate);
let monthShort = new Intl.DateTimeFormat(myFormat,{month:'short'}).format(myDate);
let monthNum = new Intl.DateTimeFormat(myFormat,{month:'numeric'}).format(myDate);
let month2 = new Intl.DateTimeFormat(myFormat,{month:'2-digit'}).format(myDate);
console.log("The long month    : "+monthLong);
console.log("The short month   : "+monthShort);
console.log("The month number  : "+monthNum);
console.log("The month 2 digits: "+month2);```

Title: Converting Gregorian date to Hijri date


问:
Google Places Auto complete limit to only 1 state
I'm trying to use the Places AutoComplete API, to get results just for a single State and not all the possible matches in different places for example:

If the Input is Manhattan, right now it shows as Results:

Manhattan, New York, NY, USA
Manhattan Beach, CA, USA
Manhattan, IL, USA
Manhattan, MT, USA

However, I want to limit to see only results, for example, to the State of NY, that way the response should be only the first hit (Manhattan, New York, NY, USA) and not the rest of the previous example.

At the moment my API Request is:

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Manhattan&types=(regions)&components=country:us&key=[MY API KEY]

I tried changing components=country:us to components=state:ny but got errors only, is there a way to get this behavior and have it filter only by the state.

Kind Regards,

答:
country is the only component mentioned in the Autocomplete components filtering documentation:

https://developers.google.com/maps/documentation/places/web-service/autocomplete#components

Trying to do component filtering for other types (e.g. administrative_area_level_1 which would represent a US state) will result in an INVALID_REQUEST response.

The best option you have right now would be to filter the result list based on the received state data.


答:
Here is an alternative approach using pivot_wider:

```<code>library(dplyr)
library(tidyr)

df1 <- df %>%
  group_by(name) %>%
  mutate(id = row_number()) %>%
  pivot_wider(
    names_from = id,
    values_from = sequence
  )

write.table(df1, file = "df1.txt", sep = "\t",
            row.names = FALSE, col.names = FALSE)

</code>```
```<code>9073050 1   15  1   10  1   4   16  7
9079078 18  19  NA  NA  NA  NA  NA  NA
9085376 22  14  23  14  24  NA  NA  NA
</code>```

Title: R how to pivot a table (with two columns) with categories of different length?

Body:
I have a table, shown as below. I need to pivot it so that data is spread horizontally and store it in a txt file with sep = space. But since the number of items per category differs, I am not sure what data structure is the best to use.

I have been stuck with this for 3 days. Could anyone please kindly help me?

Many thanks

data.frame(
 name=c(9073050,9073050,9073050,9073050,9073050,9073050,9073050,9073050,9079078,9079078,9085376,9085376,9085376,9085376,9085376),
 sequence=c(1,15, 1,10,1, 4, 16,7,18,19,22,14,23,14,24)
)

    name sequence
1  9073050        1
2  9073050       15
3  9073050        1
4  9073050       10
5  9073050        1
6  9073050        4
7  9073050       16
8  9073050        7
9  9079078       18
10 9079078       19
11 9085376       22
12 9085376       14
13 9085376       23
14 9085376       14
15 9085376       24

9073050       1      15       1      10       1       4      16       7
9079078      18      19
9085376      22      14      23      14      24

Body:
Here is an alternative approach using pivot_wider:

library(dplyr)
library(tidyr)

df1 <- df %>%
  group_by(name) %>%
  mutate(id = row_number()) %>%
  pivot_wider(
    names_from = id,
    values_from = sequence
  )

write.table(df1, file = "df1.txt", sep = "\t",
            row.names = FALSE, col.names = FALSE)

9073050 1   15  1   10  1   4   16  7
9079078 18  19  NA  NA  NA  NA  NA  NA
9085376 22  14  23  14  24  NA  NA  NA


问:
Calculating the cumulative product of a matrix error, setting an array element with a sequence
```<code>matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
cumulative = np.zeros(5)
for i in range(len(matrix[0])):
    p = 1
    for j in range(0, i+1):
        p = p*(1 + matrix[1][j])
    p = p-1
    cumulative[i] = p
print(cumulative)
</code>```

I get a value error when I run this code:

```<code>TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
ValueError: setting an array element with a sequence.
</code>```

答:
There are many ways to make this code work, such as changing "i+1" on line 6 to "i-1", but that's not necessarily what you need. I hope you can clarify your purpose so that we can give the correct solution.

If you want to think by yourself, the following knowledge is what I think you need:

The shape of this matrix is:

>>> matrix.shape
(5, 2)
```
</li>
<li><p>The number of this matrix's rows is:</p>
<pre class="lang-py prettyprint-override"><code>>>> matrix.shape[0]
5
</code>```

The number of this matrix's columns is:

>>> matrix.shape[1]
2
```
</li>
<li><p>The first column of the matrix is:</p>
<pre class="lang-py prettyprint-override"><code>>>> matrix[:, 0]
matrix([[1.],
    [2.],
    [3.],
    [4.],
    [5.]])
</code>```

The first row of the matrix is:

>>> matrix[0]
matrix([[1.  , 0.01]])
```
</li>
<li><p>The first row and first column element of the matrix is:</p>
<pre class="lang-py prettyprint-override"><code>>>> matrix[0, 0]
1.0
</code>```

Body:
matrix = np.matrix([[1, 0.01], [2, 0.003], [3, 0.015], [4, 0.026], [5, 0.006]])
cumulative = np.zeros(5)
for i in range(len(matrix[0])):
    p = 1
    for j in range(0, i+1):
        p = p*(1 + matrix[1][j])
    p = p-1
    cumulative[i] = p
print(cumulative)

I get a value error when I run this code:

TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
ValueError: setting an array element with a sequence.

Body:
There are many ways to make this code work, such as changing "i+1" on line 6 to "i-1", but that's not necessarily what you need. I hope you can clarify your purpose so that we can give the correct solution.

If you want to think by yourself, the following knowledge is what I think you need:

The shape of this matrix is:

>>> matrix.shape
(5, 2)

The number of this matrix's rows is:

>>> matrix.shape[0]
5

The number of this matrix's columns is:

>>> matrix.shape[1]
2

The first column of the matrix is:

>>> matrix[:, 0]
matrix([[1.],
    [2.],
    [3.],
    [4.],
    [5.]])

The first row of the matrix is:

>>> matrix[0]
matrix([[1.  , 0.01]])

The first row and first column element of the matrix is:

>>> matrix[0, 0]
1.0


问:
When passing data from one class to another, should you pass the entire model, or separate arguments?
I have a model with quite a bit of parameters:

```<code>UserDataModel({
    this.id,
    this.name,
    this.email,
    this.phone,
    this.photo,
    this.firstName,
    this.lastName,
    this.birthday,
    this.sex,
    this.land,
    this.bio,
    this.interests,
    this.facebook,
    this.instagram,
    this.telegram,
    this.register,
    this.login,
    this.timezone,
    this.banned,
    this.bannedDate,
    this.locked,
    this.lockedDate,
    this.postsNum,
    this.likesNum,
    this.commentsNum,
    this.views,
    this.notifications,
    this.push,
    this.position,
    this.rating,
    this.rewards,
    this.verified,
    this.notify,
    this.the2Fa,
    this.params,
  });
</code>```

and I'm using a stream to pass this model to a widget that only needs rating.level(a submodel for the rating parameter) and photo.small(another submodel, but for the photo parameter).

And I'm wondering if passing the entire model to a widget that only requires 2 parameters can lead to more memory being used, for example. It's not a big deal to do it either way, and it would be a bit upsetting to leave some minor optimisation on the table.

Any help is appreciated. I guess this question can apply to any language, but since I'm using flutter, I'll tag it with that.

答:
It's cleaner to pass only what you need. If rating.level is an object, in your Flutter widget, add it as a requirement

```<code>Widget rating({required Level level})
</code>```

In when you call this rating widget, pass the level only:

```<code>return rating(level: myUserModel.rating.level)
</code>```

If this level is an int or String for example, do the same thing as well. I am not sure how significant this would impact performance, but the main reason for it is that this enables better widget reusability and recycling. Apply this to your other projects, when you have created a cool rating widget, but you have ratings for users, and for example products. Your rating model is the same, but the product and user data models are different.
Instead of having to create a model for ProductRating and UserRating, you can you the same rating widget, and this widget only requires the rating object, or level object.

Body:
I have a model with quite a bit of parameters:

UserDataModel({
    this.id,
    this.name,
    this.email,
    this.phone,
    this.photo,
    this.firstName,
    this.lastName,
    this.birthday,
    this.sex,
    this.land,
    this.bio,
    this.interests,
    this.facebook,
    this.instagram,
    this.telegram,
    this.register,
    this.login,
    this.timezone,
    this.banned,
    this.bannedDate,
    this.locked,
    this.lockedDate,
    this.postsNum,
    this.likesNum,
    this.commentsNum,
    this.views,
    this.notifications,
    this.push,
    this.position,
    this.rating,
    this.rewards,
    this.verified,
    this.notify,
    this.the2Fa,
    this.params,
  });

and I'm using a stream to pass this model to a widget that only needs rating.level(a submodel for the rating parameter) and photo.small(another submodel, but for the photo parameter).

And I'm wondering if passing the entire model to a widget that only requires 2 parameters can lead to more memory being used, for example. It's not a big deal to do it either way, and it would be a bit upsetting to leave some minor optimisation on the table.

Any help is appreciated. I guess this question can apply to any language, but since I'm using flutter, I'll tag it with that.

Body:
It's cleaner to pass only what you need. If rating.level is an object, in your Flutter widget, add it as a requirement

Widget rating({required Level level})

In when you call this rating widget, pass the level only:

return rating(level: myUserModel.rating.level)

If this level is an int or String for example, do the same thing as well. I am not sure how significant this would impact performance, but the main reason for it is that this enables better widget reusability and recycling. Apply this to your other projects, when you have created a cool rating widget, but you have ratings for users, and for example products. Your rating model is the same, but the product and user data models are different.
Instead of having to create a model for ProductRating and UserRating, you can you the same rating widget, and this widget only requires the rating object, or level object.


问:
Sorting out words that have letters in the wrong spot
So, I'm looking to sort out words that have letters in the wrong spot,
I think I need a way to represent a 'ghost' character that lets any letter go there.</p>
```<code> import sys
#list of words that are available
list1 = [
"hello",
"saryt",
"artsy"
]

c = 0
#letters that can't be used
deadletters = ("h","e","l","l","o")

#sorts out words with dead letters
for word in list1:
if not any(map(lambda x: x in word, deadletters)):
 if "a"+""+""+""+"y" in word:
   #only lets words with "a___y" through
   print(f"found: {word}")
   c += 1

print(c)
sys.exit
</code>```

答:
```<code>list1 = [
    "hello",
    "saryt",
    "artsy",
    "ahoy"
]

#letters that can't be used
deadletters='hello'

#sorts out words with dead letters
list2 = [w for w in list1 if not(any(set(w) & set(deadletters)))]
print(list2)

#only lets words with "a___y" through
found = [w for w in list2 if (w[0] == 'a') & (w[-1] == 'y')]

print(found)
</code>```

Body:
So, I'm looking to sort out words that have letters in the wrong spot,
I think I need a way to represent a 'ghost' character that lets any letter go there.

 import sys
#list of words that are available
list1 = [
"hello",
"saryt",
"artsy"
]

c = 0
#letters that can't be used
deadletters = ("h","e","l","l","o")

#sorts out words with dead letters
for word in list1:
if not any(map(lambda x: x in word, deadletters)):
 if "a"+""+""+""+"y" in word:
   #only lets words with "a___y" through
   print(f"found: {word}")
   c += 1

print(c)
sys.exit


问:
Convert Swift graphics code to UIKit in Xamarin iOS C#
I need to crop an image to a circle in my Xamarin app.
This is platform-dependent, so it'd have to use the UIKit.

I've found the following Swift code (credit Cut a UIImage into a circle):

```<code>extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }
    var circleMasked: UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}
</code>```

Could you help me convert it into UIKit C#?

Thanks!

P.S.  There were no relevant replies, so to the best of my abilities I've put together a version that works. See that below.

答:
For a circular image I recommend using - FFImageLoading

else trough xaml:

```<code><Image Source="Image">
          <Image.Clip>
                <EllipseGeometry Center="30,30">
                    <EllipseGeometry.RadiusX>
                        <OnPlatform x:TypeArguments="x:Double"
                                    iOS="30"
                                    Android="0"/>
                    </EllipseGeometry.RadiusX>
                    <EllipseGeometry.RadiusY>
                        <OnPlatform x:TypeArguments="x:Double"
                                    iOS="30"
                                    Android="0"/>
                    </EllipseGeometry.RadiusY>
                </EllipseGeometry>
          </Image.Clip>
</Image>
</code>```

Body:
I need to crop an image to a circle in my Xamarin app.
This is platform-dependent, so it'd have to use the UIKit.

I've found the following Swift code (credit Cut a UIImage into a circle):

extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }
    var circleMasked: UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}

Could you help me convert it into UIKit C#?

Thanks!

P.S.  There were no relevant replies, so to the best of my abilities I've put together a version that works. See that below.

Body:
For a circular image I recommend using - FFImageLoading

else trough xaml:

<Image Source="Image">
          <Image.Clip>
                <EllipseGeometry Center="30,30">
                    <EllipseGeometry.RadiusX>
                        <OnPlatform x:TypeArguments="x:Double"
                                    iOS="30"
                                    Android="0"/>
                    </EllipseGeometry.RadiusX>
                    <EllipseGeometry.RadiusY>
                        <OnPlatform x:TypeArguments="x:Double"
                                    iOS="30"
                                    Android="0"/>
                    </EllipseGeometry.RadiusY>
                </EllipseGeometry>
          </Image.Clip>
</Image>


问:
Svelte: check a checkbox without forcing it to be checked
I have kind of an interesting problem with a Svelte app I'm building. In one of the forms I have a checkbox that I want to toggle on once a certain condition has been met, but I still want to allow the user to uncheck it manually.

<input type="number" bind:value={number}>
<input type="checkbox" bind:checked={checked}> Checkbox
```

REPL

So once the number value is at least 2 the checkbox gets checked, but at that point it's impossible to uncheck it. What I want is that the "default value" gets changed to "checked" so to speak, but still allow the user to override. I hope my explanation makes sense!

How can I achieve this?

答:
Okay, managed to find a solution myself:

<input type="number" bind:value={number}>
<input type="checkbox" bind:checked={checked}> Checkbox
```

This allows the checkbox to be checked/unchecked automatically based on the form values, but still allows the user to change the selection state manually.

Body:
I have kind of an interesting problem with a Svelte app I'm building. In one of the forms I have a checkbox that I want to toggle on once a certain condition has been met, but I still want to allow the user to uncheck it manually.

<input type="number" bind:value={number}>
<input type="checkbox" bind:checked={checked}> Checkbox

REPL

So once the number value is at least 2 the checkbox gets checked, but at that point it's impossible to uncheck it. What I want is that the "default value" gets changed to "checked" so to speak, but still allow the user to override. I hope my explanation makes sense!

How can I achieve this?

Body:
Okay, managed to find a solution myself:

<script>
    let number = 0;
    let checked = false;

    $: {
        checked = number >= 2;
    }
</script>

<input type="number" bind:value={number}>
<label><input type="checkbox" bind:checked={checked}> Checkbox</label>

This allows the checkbox to be checked/unchecked automatically based on the form values, but still allows the user to change the selection state manually.


问:
converting Coldfusion query results to formatted javascript array
I am trying to write ColdFusion code runs a query then puts the results in an array in a certain format.

the query:

```<code><cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>
</code>```

and array with 1 element looks like:

```<code><script type="text/javascript">
    var addresses = [{ name: "<table width=100% style='font-size:14px'><td rowspan='3'>OBS:1</td><tr><td>"#cboxadd#"</td><td align='right'>LPU M-F: "#mflpu#"</td></tr><tr><td>Barrigada Guam, 96910 ("#boxtype#")</td><td align='right'>LPU Sat: "#satlpu#"</td></tr></table>", to: #cboxadd#", Barrigada Guam, 96910" }];
</script>
</code>```

How do I accomplish this?

答:
From what I see your object looks wrong, but I'm not sure what you are doing with it, so I'm unsure of how to make it right for you, so I just have a smaller example.

```<code><cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>

<cfset arrString = "">
<cfloop from="1" to="get_cbox.recordcount" index="i">
    <cfset arrString = listAppend(arrString,"{'name':'#get_cbox.CBOXADD[i]#','type':'#get_cbox.BOXTYPE[i]#'}")>
</cfloop>
<cfoutput>
<script type="text/javascript">
    var addresses = [#arrString#];
</script>
</cfoutput>
</code>```

This will build an array of objects, each object has the properties 'name' and 'type' with values populated from the query.

Body:
I am trying to write ColdFusion code runs a query then puts the results in an array in a certain format.

the query:

<cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>

and array with 1 element looks like:

How do I accomplish this?

Body:
From what I see your object looks wrong, but I'm not sure what you are doing with it, so I'm unsure of how to make it right for you, so I just have a smaller example.

<cfquery name="get_cbox" datasource="ds" username="un" password="pw">
    SELECT CBOXADD, MFLPU, SATLPU, BOXTYPE
    FROM myTable
</cfquery>

<cfset arrString = "">
<cfloop from="1" to="get_cbox.recordcount" index="i">
    <cfset arrString = listAppend(arrString,"{'name':'#get_cbox.CBOXADD[i]#','type':'#get_cbox.BOXTYPE[i]#'}")>
</cfloop>
<cfoutput>
<script type="text/javascript">
    var addresses = [#arrString#];
</script>
</cfoutput>

This will build an array of objects, each object has the properties 'name' and 'type' with values populated from the query.


问:
Karate Ui automation
Hi i am facing an issue with to read the table values by using script all when I am trying to execute getting this error “no step def method found for scriptAll” can you please any one can suggest how to resolve that issue?

I written like this
When def list = scriptAll('tr td', '_.textContent')

答:
Probably you are on an old version of Karate. Upgrade.

If still facing issues, follow this process: https://github.com/karatelabs/karate/wiki/How-to-Submit-an-Issue

Title: Karate Ui automation


问:
Xamarin.Forms - Counterpart to
 in XAML?
I am new to XAML / Xamarin.forms and come from a web-development background.

I am looking to make a box containing with text and images (like that can be done using a
 in HTML). Please explain how to approach this with XAML & Xamarin.forms.

Also, if anybody knows a resource that lists the available tags in XAML (like w3schools for HTML), please pass that on to me.

Thanks in advance :)

答:
Just use a Frame:</p>
```<code><StackLayout>
    <Frame x:Name="MyPanelABC">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupPanelABC(bool isVisiblePanelABC){
    MyPanelABC.IsVisible = isVisiblePanelABC;
}
</code>```

Title: Xamarin.Forms - Counterpart to <div> in XAML?

Body:
Just use a Frame:

<StackLayout>
    <Frame x:Name="MyPanelABC">
        <Label Text="My Stuff" />
    </Frame>
</StackLayout>

private void setupPanelABC(bool isVisiblePanelABC){
    MyPanelABC.IsVisible = isVisiblePanelABC;
}


问:
Selenium Javascript - Access webelements within iframe programatically
I am trying to access web elements within iFrame programatically. Using below method to check the same

Compare the URL of elements with the base URI

If its same then web element is in main DOM otherwise its in iFrame

Use switchTo.frame() to switch to iFrame and perform actions

In above method, the following methods used to get URI of element

```<code>document.getElementsByTagName("a")[0].baseURI;
</code>```

or

```<code>document.getElementsByClassName("w3-btn w3-border")[0].baseURI
</code>```

Queries:

Is there any function or method to get baseURI using xpath? I don't want to use Tagname or classname.

Also, how to achieve same when multiple iFrames or iFrame inside another iFrame.

Kindly suggest if any other method

答:
The following code will help in switch iframes automatically....
This code handles 2 level iframes i.e.

iframe -1                            -------> Level 1

iframe - 2                           -------> Level 1

----  child iframe - 1 [under iframe 2 ]   -------> Level 2

iframe - 3                            -------> Level 1

Code

```<code>async function switchtoiframe(wdriver, xpath) {
  //console.log(" ---- Code to switch iframes start ---- ");

  wdriver.switchTo().defaultContent();

  let parentEleFound = false;
  let childEleFound = false;
  let parentframeId;
  let childframeId;

  // find number iframes in main content
  await wdriver.findElements(By.tagName('iframe')).then(async function (pIframe) {
      console.log("Total iframe count - " + pIframe.length);

      // if number of iframes found then switch to iframe
      if (pIframe.length > 0) {
          for (let i = 0; i<pIframe.length; i++)
          {
              await wdriver.switchTo().frame(i);   // switch to parent iframe

              // find number of child iframes in parent frame
              await wdriver.findElements(By.tagName('iframe')).then(async function (cIframe) {
                  //console.log("total child iframe count - " + cIframe.length + " in parent frame " + i);

                  // if number of iframes found then switch to child iframe
                  if (cIframe.length > 0) {
                      for (let j = 0; j<cIframe.length; j++)
                      {
                          await wdriver.switchTo().frame(j);  // switch to child iframe

                          // check whether element is available in child iframe
                          await wdriver.findElements(By.xpath(xpath)).then(async function (cElement)
                          {
                              console.log("child for loop : j - "+ j);
                              console.log("child element - "+ cElement.length);
                              if(cElement.length == 1)
                              {
                                  childframeId = j;
                                  childEleFound = true;
                              }

                              // switch back to parent iframe
                              wdriver.switchTo().parentFrame(i);
                          });

                          console.log("Element found in child iframe - "+ childEleFound)
                          if (childEleFound == true ){
                              // switch to child iframe where element is found
                              await wdriver.switchTo().frame(childframeId)
                              break; // break for loop [j]
                          }
                      }
                  }
              });
              if (childEleFound == true ){  // if element found in child iframe then break the parent for loop [i] also.
                  break;
              }

              // if no child iframes then find element in parent iframe
              await wdriver.findElements(By.xpath(xpath)).then(async function (pElement)
              {
                  console.log("parent for loop : i - "+ i);
                  console.log("parent element - "+ pElement.length);
                  if(pElement.length == 1)
                  {
                      parentframeId = i;
                      parentEleFound = true;
                  }

                  // switch back to main content
                  wdriver.switchTo().defaultContent();
              });

              console.log("Element found in parent iframe - "+ parentEleFound)
              if (parentEleFound == true ){

                  // switch to iframe where element is found
                  await wdriver.switchTo().frame(parentframeId)
                  break;
              }
          }
      }
  });

  console.log(" ---- Code to switch iframes end ---- ");
}
</code>```

Body:
I am trying to access web elements within iFrame programatically. Using below method to check the same

Compare the URL of elements with the base URI

If its same then web element is in main DOM otherwise its in iFrame

Use switchTo.frame() to switch to iFrame and perform actions

In above method, the following methods used to get URI of element

document.getElementsByTagName("a")[0].baseURI;

or

document.getElementsByClassName("w3-btn w3-border")[0].baseURI

Queries:

Is there any function or method to get baseURI using xpath? I don't want to use Tagname or classname.

Also, how to achieve same when multiple iFrames or iFrame inside another iFrame.

Kindly suggest if any other method

Body:
The following code will help in switch iframes automatically....
This code handles 2 level iframes i.e.

iframe -1                            -------> Level 1

iframe - 2                           -------> Level 1

----  child iframe - 1 [under iframe 2 ]   -------> Level 2

iframe - 3                            -------> Level 1

Code

async function switchtoiframe(wdriver, xpath) {
  //console.log(" ---- Code to switch iframes start ---- ");

  wdriver.switchTo().defaultContent();

  let parentEleFound = false;
  let childEleFound = false;
  let parentframeId;
  let childframeId;

  // find number iframes in main content
  await wdriver.findElements(By.tagName('iframe')).then(async function (pIframe) {
      console.log("Total iframe count - " + pIframe.length);

      // if number of iframes found then switch to iframe
      if (pIframe.length > 0) {
          for (let i = 0; i<pIframe.length; i++)
          {
              await wdriver.switchTo().frame(i);   // switch to parent iframe

              // find number of child iframes in parent frame
              await wdriver.findElements(By.tagName('iframe')).then(async function (cIframe) {
                  //console.log("total child iframe count - " + cIframe.length + " in parent frame " + i);

                  // if number of iframes found then switch to child iframe
                  if (cIframe.length > 0) {
                      for (let j = 0; j<cIframe.length; j++)
                      {
                          await wdriver.switchTo().frame(j);  // switch to child iframe

                          // check whether element is available in child iframe
                          await wdriver.findElements(By.xpath(xpath)).then(async function (cElement)
                          {
                              console.log("child for loop : j - "+ j);
                              console.log("child element - "+ cElement.length);
                              if(cElement.length == 1)
                              {
                                  childframeId = j;
                                  childEleFound = true;
                              }

                              // switch back to parent iframe
                              wdriver.switchTo().parentFrame(i);
                          });

                          console.log("Element found in child iframe - "+ childEleFound)
                          if (childEleFound == true ){
                              // switch to child iframe where element is found
                              await wdriver.switchTo().frame(childframeId)
                              break; // break for loop [j]
                          }
                      }
                  }
              });
              if (childEleFound == true ){  // if element found in child iframe then break the parent for loop [i] also.
                  break;
              }

              // if no child iframes then find element in parent iframe
              await wdriver.findElements(By.xpath(xpath)).then(async function (pElement)
              {
                  console.log("parent for loop : i - "+ i);
                  console.log("parent element - "+ pElement.length);
                  if(pElement.length == 1)
                  {
                      parentframeId = i;
                      parentEleFound = true;
                  }

                  // switch back to main content
                  wdriver.switchTo().defaultContent();
              });

              console.log("Element found in parent iframe - "+ parentEleFound)
              if (parentEleFound == true ){

                  // switch to iframe where element is found
                  await wdriver.switchTo().frame(parentframeId)
                  break;
              }
          }
      }
  });

  console.log(" ---- Code to switch iframes end ---- ");
}


问:
Redirect to a new page not working on React application
When the user signups into the application the data is saved to DB using an API that returns an access token. After this step user needs to be redirected to another page (Signup Details). I am using the below-attached code to do the same. Once I submit the button the token is returned and the URL is changed to the new one. But the page is not displayed. Kindly help me fix this issue.

The new page to which the user should be redirected.

App.js

答:
You need to make the first route's url like this "/" instead of "*", because now it matches all routes.</p>
```<code><Route exact path="/" component={SignupForm} />
</code>```

Body:
You need to make the first route's url like this "/" instead of "*", because now it matches all routes.

<Route exact path="/" component={SignupForm} />


问:
Why is sign bit ON for positive numbers in Intel 8086 assembly language?
I'm working in Dosbox on ubuntu assembly language. My program has only this line:

```<code>mov al, 150 ;(not -150)
</code>```

When I use debugger, it shows the value of FLAG register as 0202 which means the sign bit is ON. The same happens for -150. I'm confused why the sign bit is set for a positive number?

答:
Because you are overflowing. On al you can have only numbers from 0 to 127, any greater overflows and becomes negative.
In fact the assembly allows that because al is not negative nor possitive. it just is. But if you know you will use signed ones you should not overflow it on the load.
In other words, you are storing 150 in unsigned form, and after that the system is actually transforming that to the signed value which is not actually 150.
in fact is..-106 the value you actually are setting into AL (as signed)
Now why you do not notice this or it complains?
Because it does not know if the value is signed or not (not sure assembly can notice that)
and it will depend on the instruction you use to make anything to it, on how the al is used.
(in fact for addition does not matter it works the same) but is for multipliation or division if maters or not.
Or for whatever parser you use to show.</p>

Body:
I'm working in Dosbox on ubuntu assembly language. My program has only this line:

mov al, 150 ;(not -150)

When I use debugger, it shows the value of FLAG register as 0202 which means the sign bit is ON. The same happens for -150. I'm confused why the sign bit is set for a positive number?


问:
Kustomize overlays when using a shared ConfigMap
I have an environment made of pods that address their target environment based on an environment variable called CONF_ENV that could be test, stage or prod.

The application running inside the Pod has the same source code across environments, the configuration file is picked according to the CONF_ENV environment variable.

I'v encapsulated this CONF_ENV in *.properties files just because I may have to add more environment variables later, but I make sure that each property file contains the expected CONF_ENV e.g.:

test.properites has CONF_ENV=test,

prod.properties has CONF_ENV=prod, and so on...

I struggle to make this work with Kustomize overlays, because I want to define a ConfigMap as a shared resource across all the pods within the same overlay e.g. test (each pod in their own directory, along other stuff when needed).

So the idea is:

base/ (shared) with the definition of the Namespace, the ConfigMap (and potentially other shared resources

base/pod1/ with the definition of pod1 picking from the shared ConfigMap (this defaults to test, but in principle it could be different)

Then the overlays:

overlay/test that patches the base with CONF_ENV=test (e.g. for overlay/test/pod1/ and so on)

overlay/prod/ that patches the base with CONF_ENV=prod (e.g. for overlay/prod/pod1/ and so on)

Each directory with their own kustomize.yaml.

The above doesn't work because when going into e.g. overlay/test/pod1/ and I invoke the command kubectl kustomize . to check the output YAML, then I get all sorts of errors depending on how I defined the lists for the YAML keys bases: or resources:.

I am trying to share the ConfigMap across the entire CONF_ENV environment in an attempt to minimize the boilerplate YAML by leveraging the patching-pattern with Kustomize.

The Kubernetes / Kustomize YAML directory structure works like this:

├── base
│   ├── configuration.yaml # I am trying to share this!
│   ├── kustomization.yaml
│   ├── my_namespace.yaml # I am trying to share this!
│   ├── my-scheduleset-etl-misc
│   │   ├── kustomization.yaml
│   │   └── my_scheduleset_etl_misc.yaml
│   ├── my-scheduleset-etl-reporting
│   │   ├── kustomization.yaml
│   │   └── my_scheduleset_etl_reporting.yaml
│   └── test.properties # I am trying to share this!
└── overlay
    └── test
        ├── kustomization.yaml # here I want tell "go and pick up the shared resources in the base dir"
        ├── my-scheduleset-etl-misc
        │   ├── kustomization.yaml
        │   └── test.properties # I've tried to share this one level above, but also to add this inside the "leaf" level for a given pod
        └── my-scheduleset-etl-reporting
            └── kustomization.yaml
```
<p>The command <code>kubectl</code> with Kustomize:</p>
<ul>
<li>sometimes complains that the shared namespace does not exist:</li>
</ul>
```error: merging from generator &{0xc001d99530 {  map[] map[]} {{ my-schedule-set-props merge {[CONF_ENV=test] [] [] } <nil>}}}:
id resid.ResId{Gvk:resid.Gvk{Group:"", Version:"v1", Kind:"ConfigMap", isClusterScoped:false}, Name:"my-schedule-set-props", Namespace:""}
does not exist; cannot merge or replace
```
<ul>
<li>sometimes doesn't allow to have shared resources inside an overlay:</li>
</ul>
```error: loading KV pairs: env source files: [../test.properties]:
security; file '/my/path/to/yaml/overlay/test/test.properties'
is not in or below '/my/path/to/yaml/overlay/test/my-scheduleset-etl-misc'
```
<ul>
<li>sometimes doesn't allow cycles when I am trying to have multiple bases - the shared resources and the original pod definition:</li>
</ul>
```error: accumulating resources: accumulation err='accumulating resources from '../':
'/my/path/to/yaml/overlay/test' must resolve to a file':
cycle detected: candidate root '/my/path/to/yaml/overlay/test'
contains visited root '/my/path/to/yaml/overlay/test/my-scheduleset-etl-misc'
```
<p>The overlay <code>kustomization.yaml</code> files inside the pod dirs have:</p>
<pre class="lang-yaml prettyprint-override"><code>bases:
  - ../ # tried with/without this to share the ConfigMap
  - ../../../base/my-scheduleset-etl-misc/
</code>```

The kustomization.yaml at the root of the overlay has:

bases:
  - ../../base
```
<p>The <code>kustomization.yaml</code> at the base dir contains this configuration for the ConfigMap:</p>
<pre class="lang-yaml prettyprint-override"><code># https://gist.github.com/hermanbanken/3d0f232ffd86236c9f1f198c9452aad9
configMapGenerator:
  - name: my-schedule-set-props
    namespace: my-ss-schedules
    envs:
      - test.properties

vars:
  - name: CONF_ENV
    objref:
      kind: ConfigMap
      name: my-schedule-set-props
      apiVersion: v1
    fieldref:
      fieldpath: data.CONF_ENV

configurations:
  - configuration.yaml
</code>```

With configuration.yaml containing:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

varReference:
- path: spec/confEnv/value
  kind: Pod
```

How do I do this?

How do I make sure that I minimise the amount of YAML by sharing all the ConfigMap stuff and the Pods definitions as much as I can?

答:
If I understand your goal correctly, I think you may be grossly over-complicating things. I think you want a common properties file defined in your base, but you want to override specific properties in your overlays. Here's one way of doing that.

In base, I have:

```<code>$ cd base
$ tree
.
├── example.properties
├── kustomization.yaml
└── pod1
    ├── kustomization.yaml
    └── pod.yaml
</code>```

Where example.properties contains:

```<code>SOME_OTHER_VAR=somevalue
CONF_ENV=test
</code>```

And kustomization.yaml contains:

```<code>resources:
  - pod1

configMapGenerator:
  - name: example-props
    envs:
      - example.properties
</code>```

I have two overlays defined, test and prod:

```<code>$ cd ../overlays
$ tree
.
├── prod
│   ├── example.properties
│   └── kustomization.yaml
└── test
    └── kustomization.yaml
</code>```

test/kustomization.yaml looks like this:

```<code>resources:
- ../../base
</code>```

It's just importing the base without any changes, since the value of CONF_ENV from the base directory is test.

prod/kustomization.yaml looks like this:

```<code>apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base

configMapGenerator:
  - name: example-props
    behavior: merge
    envs:
      - example.properties
</code>```

And prod/example.properties looks like:

```<code>CONF_ENV=prod
</code>```

If I run kustomize build overlays/test, I get as output:

```<code>apiVersion: v1
data:
  CONF_ENV: test
  SOME_OTHER_VAR: somevalue
kind: ConfigMap
metadata:
  name: example-props-7245222b9b
---
apiVersion: v1
kind: Pod
metadata:
  name: example
spec:
  containers:
  - command:
    - sleep
    - 1800
    envFrom:
    - configMapRef:
        name: example-props-7245222b9b
    image: docker.io/alpine
    name: alpine
</code>```

If I run kustomize build overlays/prod, I get:

```<code>apiVersion: v1
data:
  CONF_ENV: prod
  SOME_OTHER_VAR: somevalue
kind: ConfigMap
metadata:
  name: example-props-h4b5tc869g
---
apiVersion: v1
kind: Pod
metadata:
  name: example
spec:
  containers:
  - command:
    - sleep
    - 1800
    envFrom:
    - configMapRef:
        name: example-props-h4b5tc869g
    image: docker.io/alpine
    name: alpine
</code>```

That is, everything looks as you would expect given the configuration in base, but we have provided a new value for CONF_ENV.

You can find all these files here.

Body:
I have an environment made of pods that address their target environment based on an environment variable called CONF_ENV that could be test, stage or prod.

The application running inside the Pod has the same source code across environments, the configuration file is picked according to the CONF_ENV environment variable.

I'v encapsulated this CONF_ENV in *.properties files just because I may have to add more environment variables later, but I make sure that each property file contains the expected CONF_ENV e.g.:

test.properites has CONF_ENV=test,

prod.properties has CONF_ENV=prod, and so on...

I struggle to make this work with Kustomize overlays, because I want to define a ConfigMap as a shared resource across all the pods within the same overlay e.g. test (each pod in their own directory, along other stuff when needed).

So the idea is:

base/ (shared) with the definition of the Namespace, the ConfigMap (and potentially other shared resources

base/pod1/ with the definition of pod1 picking from the shared ConfigMap (this defaults to test, but in principle it could be different)

Then the overlays:

overlay/test that patches the base with CONF_ENV=test (e.g. for overlay/test/pod1/ and so on)

overlay/prod/ that patches the base with CONF_ENV=prod (e.g. for overlay/prod/pod1/ and so on)

Each directory with their own kustomize.yaml.

The above doesn't work because when going into e.g. overlay/test/pod1/ and I invoke the command kubectl kustomize . to check the output YAML, then I get all sorts of errors depending on how I defined the lists for the YAML keys bases: or resources:.

I am trying to share the ConfigMap across the entire CONF_ENV environment in an attempt to minimize the boilerplate YAML by leveraging the patching-pattern with Kustomize.

The Kubernetes / Kustomize YAML directory structure works like this:

├── base
│   ├── configuration.yaml # I am trying to share this!
│   ├── kustomization.yaml
│   ├── my_namespace.yaml # I am trying to share this!
│   ├── my-scheduleset-etl-misc
│   │   ├── kustomization.yaml
│   │   └── my_scheduleset_etl_misc.yaml
│   ├── my-scheduleset-etl-reporting
│   │   ├── kustomization.yaml
│   │   └── my_scheduleset_etl_reporting.yaml
│   └── test.properties # I am trying to share this!
└── overlay
    └── test
        ├── kustomization.yaml # here I want tell "go and pick up the shared resources in the base dir"
        ├── my-scheduleset-etl-misc
        │   ├── kustomization.yaml
        │   └── test.properties # I've tried to share this one level above, but also to add this inside the "leaf" level for a given pod
        └── my-scheduleset-etl-reporting
            └── kustomization.yaml

The command kubectl with Kustomize:

sometimes complains that the shared namespace does not exist:

error: merging from generator &{0xc001d99530 {  map[] map[]} {{ my-schedule-set-props merge {[CONF_ENV=test] [] [] } <nil>}}}:
id resid.ResId{Gvk:resid.Gvk{Group:"", Version:"v1", Kind:"ConfigMap", isClusterScoped:false}, Name:"my-schedule-set-props", Namespace:""}
does not exist; cannot merge or replace

sometimes doesn't allow to have shared resources inside an overlay:

error: loading KV pairs: env source files: [../test.properties]:
security; file '/my/path/to/yaml/overlay/test/test.properties'
is not in or below '/my/path/to/yaml/overlay/test/my-scheduleset-etl-misc'

sometimes doesn't allow cycles when I am trying to have multiple bases - the shared resources and the original pod definition:

error: accumulating resources: accumulation err='accumulating resources from '../':
'/my/path/to/yaml/overlay/test' must resolve to a file':
cycle detected: candidate root '/my/path/to/yaml/overlay/test'
contains visited root '/my/path/to/yaml/overlay/test/my-scheduleset-etl-misc'

The overlay kustomization.yaml files inside the pod dirs have:

bases:
  - ../ # tried with/without this to share the ConfigMap
  - ../../../base/my-scheduleset-etl-misc/

The kustomization.yaml at the root of the overlay has:

bases:
  - ../../base

The kustomization.yaml at the base dir contains this configuration for the ConfigMap:

# https://gist.github.com/hermanbanken/3d0f232ffd86236c9f1f198c9452aad9
configMapGenerator:
  - name: my-schedule-set-props
    namespace: my-ss-schedules
    envs:
      - test.properties

vars:
  - name: CONF_ENV
    objref:
      kind: ConfigMap
      name: my-schedule-set-props
      apiVersion: v1
    fieldref:
      fieldpath: data.CONF_ENV

configurations:
  - configuration.yaml

With configuration.yaml containing:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

varReference:
- path: spec/confEnv/value
  kind: Pod

How do I do this?

How do I make sure that I minimise the amount of YAML by sharing all the ConfigMap stuff and the Pods definitions as much as I can?

Body:
If I understand your goal correctly, I think you may be grossly over-complicating things. I think you want a common properties file defined in your base, but you want to override specific properties in your overlays. Here's one way of doing that.

In base, I have:

$ cd base
$ tree
.
├── example.properties
├── kustomization.yaml
└── pod1
    ├── kustomization.yaml
    └── pod.yaml

Where example.properties contains:

SOME_OTHER_VAR=somevalue
CONF_ENV=test

And kustomization.yaml contains:

resources:
  - pod1

configMapGenerator:
  - name: example-props
    envs:
      - example.properties

I have two overlays defined, test and prod:

$ cd ../overlays
$ tree
.
├── prod
│   ├── example.properties
│   └── kustomization.yaml
└── test
    └── kustomization.yaml

test/kustomization.yaml looks like this:

resources:
- ../../base

It's just importing the base without any changes, since the value of CONF_ENV from the base directory is test.

prod/kustomization.yaml looks like this:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base

configMapGenerator:
  - name: example-props
    behavior: merge
    envs:
      - example.properties

And prod/example.properties looks like:

CONF_ENV=prod

If I run kustomize build overlays/test, I get as output:

apiVersion: v1
data:
  CONF_ENV: test
  SOME_OTHER_VAR: somevalue
kind: ConfigMap
metadata:
  name: example-props-7245222b9b
---
apiVersion: v1
kind: Pod
metadata:
  name: example
spec:
  containers:
  - command:
    - sleep
    - 1800
    envFrom:
    - configMapRef:
        name: example-props-7245222b9b
    image: docker.io/alpine
    name: alpine

If I run kustomize build overlays/prod, I get:

apiVersion: v1
data:
  CONF_ENV: prod
  SOME_OTHER_VAR: somevalue
kind: ConfigMap
metadata:
  name: example-props-h4b5tc869g
---
apiVersion: v1
kind: Pod
metadata:
  name: example
spec:
  containers:
  - command:
    - sleep
    - 1800
    envFrom:
    - configMapRef:
        name: example-props-h4b5tc869g
    image: docker.io/alpine
    name: alpine

That is, everything looks as you would expect given the configuration in base, but we have provided a new value for CONF_ENV.

You can find all these files here.


问:
React Native / API Gateway axios post request fails in Android with 403
I am trying to call aws api gateway with a post request with signed headers. In iOS it works perfectly fine, while I get 403 with exactly the same request running the App in Android(of course with different credentials).

What I already found is this similar issue, but appending the charset "charset=utf-8", did not solve the issue for me unfortunately. Switching to the amplify package is currently not an option. Can anybody give me a hint?

I am using react-native: 0.67.2, agnostic-aws-signature: 1.0.6 and axios: 0.24.0

答:
I got this solved now by doing the following:

Setup cloudwatch to log the access events like this: Setting up CloudWatch logging for a REST API in API Gateway

Adding $context.error.message to be logged.

Trying to make the post request and checking the answer with the following result:

"error": "Signature not yet current: 20220206T163415Z is still later than 20220206T153916Z (20220206T153416Z + 5 min.)",

Looks like the Simulator used a different time zone, so I could resolve it with setting the clock and time zone manually.


问:
JavaScript Sorting Multidimensional JSON
I have this JSON string:

```<code>{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}
</code>```

if I do

```<code>alert(testJSON.widgets.length);
</code>```

I get 3, however if I do

```<code>alert(testJSON.widgets.column1.length);
</code>```

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

```<code>testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });
</code>```

So I can then do a $.each() via jquery

答:
If you want to be able to access like you mentioned, you need to lay it out like this:

```<code>{
"widgets": {
    "column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ],
    "column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ],
    "column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]
    }
}
</code>```

No need to wrap the columns in an array.

Body:
I have this JSON string:

{
"widgets":[
    {"column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ]},
    {"column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ]},
    {"column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]}
]}

if I do

alert(testJSON.widgets.length);

I get 3, however if I do

alert(testJSON.widgets.column1.length);

I get "testJSON.widgets.column3 is undefined" as an error.

What I am ultimately attempting to do is take each column1-3 and sort them by weight. Through something like

testJSON.widgets.column1.sort(function(a,b) { return parseFloat(a.weight) - parseFloat(b.weight) });

So I can then do a $.each() via jquery

Body:
If you want to be able to access like you mentioned, you need to lay it out like this:

{
"widgets": {
    "column1":[
        {"weight":1, "bID":1, "hideMe":false, "collapse":false, "titleOf":"Test 1", "colorOf":"color-blue", "theFunction":"functionName"},
        {"weight":2, "bID":2, "hideMe":false, "collapse":false, "titleOf":"Test 2", "colorOf":"color-red", "theFunction":"functionName"},
        {"weight":3, "bID":3, "hideMe":false, "collapse":true, "titleOf":"Test 3", "colorOf":"color-yellow", "theFunction":"functionName"}
    ],
    "column2":[
        {"weight":1, "bID":4, "hideMe":false, "collapse":false, "titleOf":"Test 4", "colorOf":"color-white", "theFunction":"functionName"},
        {"weight":3, "bID":5, "hideMe":false, "collapse":false, "titleOf":"Test 5", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":6, "hideMe":false, "collapse":true, "titleOf":"Test 6", "colorOf":"color-green", "theFunction":"functionName"}
    ],
    "column3":[
        {"weight":3, "bID":7, "hideMe":false, "collapse":false, "titleOf":"Test 7", "colorOf":"color-green", "theFunction":"functionName"},
        {"weight":2, "bID":8, "hideMe":false, "collapse":true, "titleOf":"Test 8", "colorOf":"color-yellow", "theFunction":"functionName"},
        {"weight":1, "bID":9, "hideMe":false, "collapse":false, "titleOf":"Test 9", "colorOf":"color-white", "theFunction":"functionName"},
    ]
    }
}

No need to wrap the columns in an array.


问:
Find No of Rows Having Value less than the value of present row
Imagine I have A table that looks like this:

id
value

1
2

2
4

3
1

4
0

5
0.2

I need to update the count_less_than column as the no of rows which have less value than current row value.

Output table would be like this:

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

what would be query???

答:
if your MySQL version support ROW_NUMBER window function

You can try to use ROW_NUMBER window function with subtraction one

Query #1

```<code>SELECT *,ROW_NUMBER() OVER(ORDER BY value) - 1 count_less_than
FROM T
ORDER BY ID;
</code>```

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

View on DB Fiddle

if your MySQL version didn't support ROW_NUMBER window function

you can try to use subquery with count to calculate number

Query #1

```<code>SELECT *,
       (SELECT COUNT(*)
       FROM T tt
       WHERE tt.value < t.value) count_less_than
FROM T t
ORDER BY ID;
</code>```

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

View on DB Fiddle

Body:
if your MySQL version support ROW_NUMBER window function

You can try to use ROW_NUMBER window function with subtraction one

Query #1

SELECT *,ROW_NUMBER() OVER(ORDER BY value) - 1 count_less_than
FROM T
ORDER BY ID;

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

View on DB Fiddle

if your MySQL version didn't support ROW_NUMBER window function

you can try to use subquery with count to calculate number

Query #1

SELECT *,
       (SELECT COUNT(*)
       FROM T tt
       WHERE tt.value < t.value) count_less_than
FROM T t
ORDER BY ID;

id
value
count_less_than

1
2
3

2
4
4

3
1
2

4
0
0

5
0.2
1

View on DB Fiddle


问:
Athena query return empty result because of timing issues
I'm trying to create and query the Athena table based on data located in S3, and it seems that there are some timing issues.

How can I know when all the partitions have been loaded to the table?

The following code returns an empty result -

```<code>athena_client.start_query_execution(QueryString=app_query_create_table,
                                    ResultConfiguration={'OutputLocation': output_location})

athena_client.start_query_execution(QueryString="MSCK REPAIR TABLE `{athena_db}`.`{athena_db_partition}`"
                .format(athena_db=athena_db, athena_db_partition=athena_db_partition),
            ResultConfiguration={'OutputLocation': output_location})

result = query.format(athena_db_partition=athena_db_partition, delta=delta, dt=dt)
</code>```

But when I add some delay, it works greate -

```<code>athena_client.start_query_execution(QueryString=app_query_create_table,
                                    ResultConfiguration={'OutputLocation': output_location})

athena_client.start_query_execution(QueryString="MSCK REPAIR TABLE `{athena_db}`.`{athena_db_partition}`"
                .format(athena_db=athena_db, athena_db_partition=athena_db_partition),
            ResultConfiguration={'OutputLocation': output_location})

time.sleep(3)

result = query.format(athena_db_partition=athena_db_partition, delta=delta, dt=dt)
</code>```

The following is the query for creating the table -

```<code>query_create_table = '''
            CREATE EXTERNAL TABLE `{athena_db}`.`{athena_db_partition}` (
                `time` string,
                `user_advertiser_id` string,
                `predictions` float
            ) PARTITIONED BY (
                dt string
            )
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
            WITH SERDEPROPERTIES (
                'serialization.format' = ',',
                'field.delim' = ','
            ) LOCATION 's3://{bucket}/path/'
            '''

app_query_create_table = query_create_table.format(bucket=bucket,
                                                   athena_db=athena_db,
                                                     athena_db_partition=athena_db_partition)
</code>```

I would love to get some help.

答:
The start_query_execution call only starts the query, it does not wait for it to complete. You must run get_query_execution periodically until the status of the execution is successful (or failed).

Not related to your problem per se, but if you create a table with CREATE TABLE … AS there is no need to add partitions with MSCK REPAIR TABLE … afterwards, there will be no new partitions after the table has just been created that way – because it will be created with all the partitions produced by the query.

Also, in general, avoid using MSCK REPAIR TABLE, it is slow and inefficient. There are many better ways to add partitions to a table, see https://athena.guide/articles/five-ways-to-add-partitions/

Body:
I'm trying to create and query the Athena table based on data located in S3, and it seems that there are some timing issues.

How can I know when all the partitions have been loaded to the table?

The following code returns an empty result -

athena_client.start_query_execution(QueryString=app_query_create_table,
                                    ResultConfiguration={'OutputLocation': output_location})

athena_client.start_query_execution(QueryString="MSCK REPAIR TABLE `{athena_db}`.`{athena_db_partition}`"
                .format(athena_db=athena_db, athena_db_partition=athena_db_partition),
            ResultConfiguration={'OutputLocation': output_location})

result = query.format(athena_db_partition=athena_db_partition, delta=delta, dt=dt)

But when I add some delay, it works greate -

athena_client.start_query_execution(QueryString=app_query_create_table,
                                    ResultConfiguration={'OutputLocation': output_location})

athena_client.start_query_execution(QueryString="MSCK REPAIR TABLE `{athena_db}`.`{athena_db_partition}`"
                .format(athena_db=athena_db, athena_db_partition=athena_db_partition),
            ResultConfiguration={'OutputLocation': output_location})

time.sleep(3)

result = query.format(athena_db_partition=athena_db_partition, delta=delta, dt=dt)

The following is the query for creating the table -

query_create_table = '''
            CREATE EXTERNAL TABLE `{athena_db}`.`{athena_db_partition}` (
                `time` string,
                `user_advertiser_id` string,
                `predictions` float
            ) PARTITIONED BY (
                dt string
            )
            ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe'
            WITH SERDEPROPERTIES (
                'serialization.format' = ',',
                'field.delim' = ','
            ) LOCATION 's3://{bucket}/path/'
            '''

app_query_create_table = query_create_table.format(bucket=bucket,
                                                   athena_db=athena_db,
                                                     athena_db_partition=athena_db_partition)

I would love to get some help.


问:
How can I convert JS to TS?
I read many articles about TypeScript and couldn't find anything. What type to set for elements X and Y? or how to convert the code to TS? thanks in advance for your help</p>
```<code>const x = document.getElementById("password-input");
const y = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }
</code>```

答:
With the ! sign you said that this element won't be null (if you are sure that element is in your HTML document), and as HTMLInputElemnt is for indicating your element type.

To read more about it, you can read this article.

```<code>const x = document.getElementById("password-input")! as HTMLInputElement;
const y = document.getElementById("img")! as HTMLInputElement;

function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }
</code>```

Title: How can I convert JS to TS?

Body:
I read many articles about TypeScript and couldn't find anything. What type to set for elements X and Y? or how to convert the code to TS? thanks in advance for your help

const x = document.getElementById("password-input");
const y = document.getElementById("img");
function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }

Body:
With the ! sign you said that this element won't be null (if you are sure that element is in your HTML document), and as HTMLInputElemnt is for indicating your element type.

To read more about it, you can read this article.

const x = document.getElementById("password-input")! as HTMLInputElement;
const y = document.getElementById("img")! as HTMLInputElement;

function showPass() {
            if (x.type === "password") {
            x.type = "text";
            y.src = "png"

        } else {
            x.type = "password";
            y.src = "png"
        }
    }


问:
Add + 1 every multiple of 10 in C#
I'm making an endless runner game with Unity and in this game for every 10 coins I collect, it increases the level by 1 with a maximum of 10. Currently, I'm doing this:

```<code>IF(coins >= 10 and coins < 20) level = 2
IF(coins >= 20 and coins <= 30) level = 3
</code>```

and so on till level 10.

But I'm sure that this code is badly written, I'm thinking in use the for statement but I'm a newbie to C#, any ideas?

答:
Use the modulo operator % to check if the number divided by 10 has the remainder of 0.

Example:

```<code>if (coins > 0 && coins % 10 == 0 && level < 10)
{
    ++level;
}
</code>```

In this example we also check if the player has at least one coin as 0 % 10 == 0 returns true and you don't want the player to level up if they don't have any coins. You could skip that if the player's initial level is 0, but I guess it would be 1.

When it comes to leveling up, use the unary operator ++ as it's generally a rule of thumb if you want to increment a value by 1.

Suggested reading:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators

https://stackoverflow.com/a/17525046/11412351

Title: Add + 1 every multiple of 10 in C#

Body:
I'm making an endless runner game with Unity and in this game for every 10 coins I collect, it increases the level by 1 with a maximum of 10. Currently, I'm doing this:

IF(coins >= 10 and coins < 20) level = 2
IF(coins >= 20 and coins <= 30) level = 3

and so on till level 10.

But I'm sure that this code is badly written, I'm thinking in use the for statement but I'm a newbie to C#, any ideas?

Body:
Use the modulo operator % to check if the number divided by 10 has the remainder of 0.

Example:

if (coins > 0 && coins % 10 == 0 && level < 10)
{
    ++level;
}

In this example we also check if the player has at least one coin as 0 % 10 == 0 returns true and you don't want the player to level up if they don't have any coins. You could skip that if the player's initial level is 0, but I guess it would be 1.

When it comes to leveling up, use the unary operator ++ as it's generally a rule of thumb if you want to increment a value by 1.

Suggested reading:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators

https://stackoverflow.com/a/17525046/11412351


问:
Unable to implement 'if int value >= 75' then proceed to next page logic
I am working on a certificate generation module where i want to generate certificate only if the input int value of 'percentage' is greater or equal to 75.

I want to implement a function which will able me to only show the certificate page only if the int percentage value is greater than or equal to 75 and execute that function in the submit button.

function which i am implementing in current state:

```<code>  void checkpercent(int a) {
    if (percentage >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }
</code>```

[In my current code i am able to access the certification page with any numerical value no matter less or more than 75]

but whatever method i am using to implement this logic either i am able to access the certification page with any value or not able to access the page at all.

Since course module is not complete yet which will provide my module the int percentage value i have added textfield which accepts value and converts the string value into integer called percentage for the time being[using "int.parse"].

the code is as follows:[I am having zero warnings,errors in my code while debugging, i am just not able to implement that logic properly.]

main.dart

```<code>import 'package:certi_gen_v68/cerstcreen.dart';
import 'package:flutter/material.dart';
import 'cerstcreen.dart';

TextEditingController unameController = TextEditingController();
TextEditingController cnameController = TextEditingController();
TextEditingController auth1Controller = TextEditingController();
TextEditingController auth2Controller = TextEditingController();
TextEditingController percentController = TextEditingController();
int percentage = int.parse(percentController.text);

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(
          title:
              'Input data [This is temporary screen till modules are integrated]'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void checkpercent(int a) {
    if (percentage >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: unameController,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Enter Full Name',
              ),
            ),
            TextField(
              controller: cnameController,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Enter Course Name',
              ),
            ),
            TextField(
              controller: auth1Controller,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Certification Authority 1',
              ),
            ),
            TextField(
              controller: auth2Controller,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Certification Authority 2',
              ),
            ),
            TextField(
              controller: percentController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Percentage',
              ),
            ),
            ElevatedButton(
              child: const Text('Submit'),
              onPressed: () {
                checkpercent(percentage);
              },
            ),
          ],
        ),
      ),
    );
  }
}

</code>```

certification screen is incomplete just added a few textlabels for now [i am just trying out new syntaxes and styles in certpage]

```<code>import 'package:flutter/material.dart';
import 'main.dart' as mainpage;

class CertScreen extends StatelessWidget {
  const CertScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            RichText(
              text: const TextSpan(
                text: 'home',
                style: TextStyle(fontStyle: FontStyle.italic),
                children: <TextSpan>[
                  TextSpan(
                      text: ' bold',
                      style: TextStyle(fontWeight: FontWeight.bold)),
                  TextSpan(text: ' world!'),
                ],
              ),
            ),
            Text(mainpage.unameController.text),
            Text(mainpage.percentage.toString())
          ],
        ),
      ),
    );
  }
}
</code>```

答:
You're not using the parameter a, you use percentage on the if statement.

```<code>void checkpercent(int a) {
    if (a >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }
</code>```

Also your int percentage = int.parse(percentController.text); at the start of main.dart should be called before the checkpercent function so it receives the latest value.

```<code>ElevatedButton(
          child: const Text('Submit'),
          onPressed: () {
            int percentage = int.parse(percentController.text);
            checkpercent(percentage);
          },
        ),
</code>```

Body:
I am working on a certificate generation module where i want to generate certificate only if the input int value of 'percentage' is greater or equal to 75.

I want to implement a function which will able me to only show the certificate page only if the int percentage value is greater than or equal to 75 and execute that function in the submit button.

function which i am implementing in current state:

  void checkpercent(int a) {
    if (percentage >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }

[In my current code i am able to access the certification page with any numerical value no matter less or more than 75]

but whatever method i am using to implement this logic either i am able to access the certification page with any value or not able to access the page at all.

Since course module is not complete yet which will provide my module the int percentage value i have added textfield which accepts value and converts the string value into integer called percentage for the time being[using "int.parse"].

the code is as follows:[I am having zero warnings,errors in my code while debugging, i am just not able to implement that logic properly.]

main.dart

import 'package:certi_gen_v68/cerstcreen.dart';
import 'package:flutter/material.dart';
import 'cerstcreen.dart';

TextEditingController unameController = TextEditingController();
TextEditingController cnameController = TextEditingController();
TextEditingController auth1Controller = TextEditingController();
TextEditingController auth2Controller = TextEditingController();
TextEditingController percentController = TextEditingController();
int percentage = int.parse(percentController.text);

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: const MyHomePage(
          title:
              'Input data [This is temporary screen till modules are integrated]'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void checkpercent(int a) {
    if (percentage >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: unameController,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Enter Full Name',
              ),
            ),
            TextField(
              controller: cnameController,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Enter Course Name',
              ),
            ),
            TextField(
              controller: auth1Controller,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Certification Authority 1',
              ),
            ),
            TextField(
              controller: auth2Controller,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Certification Authority 2',
              ),
            ),
            TextField(
              controller: percentController,
              keyboardType: TextInputType.number,
              decoration: const InputDecoration(
                border: InputBorder.none,
                labelText: 'Percentage',
              ),
            ),
            ElevatedButton(
              child: const Text('Submit'),
              onPressed: () {
                checkpercent(percentage);
              },
            ),
          ],
        ),
      ),
    );
  }
}

certification screen is incomplete just added a few textlabels for now [i am just trying out new syntaxes and styles in certpage]

import 'package:flutter/material.dart';
import 'main.dart' as mainpage;

class CertScreen extends StatelessWidget {
  const CertScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            RichText(
              text: const TextSpan(
                text: 'home',
                style: TextStyle(fontStyle: FontStyle.italic),
                children: <TextSpan>[
                  TextSpan(
                      text: ' bold',
                      style: TextStyle(fontWeight: FontWeight.bold)),
                  TextSpan(text: ' world!'),
                ],
              ),
            ),
            Text(mainpage.unameController.text),
            Text(mainpage.percentage.toString())
          ],
        ),
      ),
    );
  }
}

Body:
You're not using the parameter a, you use percentage on the if statement.

void checkpercent(int a) {
    if (a >= 75) {
      Navigator.push(
          context, MaterialPageRoute(builder: (context) => const CertScreen()));
    }
  }

Also your int percentage = int.parse(percentController.text); at the start of main.dart should be called before the checkpercent function so it receives the latest value.

ElevatedButton(
          child: const Text('Submit'),
          onPressed: () {
            int percentage = int.parse(percentController.text);
            checkpercent(percentage);
          },
        ),