问:
Tkinter : Window not opening when incrementing value,
I'm  making a BSOD simulator with a randomly progressing percentage.
What i'm trying to do is :

Make a variable called percentage and initialise it with a value of 0

Make a label with the text f"{percentage}% completed"

Make a variable called percentageIsAHundred and initialise it with a value of False

Works good. Output : 0% completed

Now to add the random steps :

Make a loop as long as percentageIsAHundred is false

Change the value of percentageText to f"{percentage}% completed" (to update it)

We do a win.after() (I've tried sleep and threading- don't work) and put the values 1000, and a function called steps

Check if the percentage value is above 100, If it returns true we set percentageText to 100% completed (otherwise it might be 106% or 104%) and set percentageIsAHundred to true, breaking the loop.

In the steps function we:

Increment the percentage variable by a random value in between 0 and 20

Should work? Nope.

No windows open and no errors appear in console. Commenting out the code works and returns to normal.

I have seen that this behaviour occurs at the steps() function, Although I may be wrong.

# Importing modules
from tkinter import *
import os
import random
import threading

# Initialising Tkinter window
win = Tk()

# Creating reboot function
def reboot(sec=50):
    os.system(f'echo "{sec} timer not confirmed"')

# Giving the window its iconic blue background.
win.config(bg="#0178d6")

# Making the window fullscreen
win.attributes("-fullscreen", True)

# Adding the emoticon ":("
emoticon = Label(win, text=":(", font="{Segoe UI} 100", bg="#0178d6", fg="#ffffff")
emoticon.place(x="50px", y="100px")

# Adding the text
text1 = Label(win, text="A problem has occurred and your PC needs to restart. We're just collecting some error information, then we'll restart for you.", font="{Segoe UI} 20", bg="#0178d6", fg="#ffffff")
text1.place(x="50px", y="259px")

# Adding the progress percentage
percentage = 0
percentageText = Label(win, text=f"{percentage}% complete", font="{Segoe UI} 20", bg="#0178d6", fg="#ffffff")
percentageText.place(x="50px", y="320px")
percentageIsAHundred = False

________________________________________________________

# This is the problematic code- Removing it seems to run the window normally but including it causes tkinter to not run with 0 errors

def steps(percentage=percentage) :
    percentage = percentage + random.randint(1, 20)
win.after(1000, steps)
while percentageIsAHundred == False :
    percentageText.config(text=f"{percentage}% complete")
    if percentage >= 100 :
        percentageText.config(text="100% complete")
        percentageIsAHundred = True
________________________________________________________

# Setting the mainloop
win.mainloop()
```

! My title may not be right because I can't think clear right now. !

答:
The percentage in steps() is local to that function.

If you want it to increase the value of the global percentage, you should mark it at such:

```<code>def steps():
    global percentage
    percentage += random.randint(1, 20)
    win.after(1000, steps)
    percentageText.config(text=f"{percentage}% complete")
    if percentage >= 100:
        percentageText.config(text="100% complete")
        win.quit()
</code>```

Also note that as a rule you should be careful with while and for loops in event handlers and after functions. If they take too long, they will inhibit event processing.

Also, your while loop is not indented, so it in not part of steps but part of the main module. In this case, since your your while loop runs before the mainloop, it prevents the tkinter mainloop from starting and your window from appearing. :-)

Body:
I'm  making a BSOD simulator with a randomly progressing percentage.
What i'm trying to do is :

Make a variable called percentage and initialise it with a value of 0

Make a label with the text f"{percentage}% completed"

Make a variable called percentageIsAHundred and initialise it with a value of False

Works good. Output : 0% completed

Now to add the random steps :

Make a loop as long as percentageIsAHundred is false

Change the value of percentageText to f"{percentage}% completed" (to update it)

We do a win.after() (I've tried sleep and threading- don't work) and put the values 1000, and a function called steps

Check if the percentage value is above 100, If it returns true we set percentageText to 100% completed (otherwise it might be 106% or 104%) and set percentageIsAHundred to true, breaking the loop.

In the steps function we:

Increment the percentage variable by a random value in between 0 and 20

Should work? Nope.

No windows open and no errors appear in console. Commenting out the code works and returns to normal.

I have seen that this behaviour occurs at the steps() function, Although I may be wrong.

# Importing modules
from tkinter import *
import os
import random
import threading

# Initialising Tkinter window
win = Tk()

# Creating reboot function
def reboot(sec=50):
    os.system(f'echo "{sec} timer not confirmed"')

# Giving the window its iconic blue background.
win.config(bg="#0178d6")

# Making the window fullscreen
win.attributes("-fullscreen", True)

# Adding the emoticon ":("
emoticon = Label(win, text=":(", font="{Segoe UI} 100", bg="#0178d6", fg="#ffffff")
emoticon.place(x="50px", y="100px")

# Adding the text
text1 = Label(win, text="A problem has occurred and your PC needs to restart. We're just collecting some error information, then we'll restart for you.", font="{Segoe UI} 20", bg="#0178d6", fg="#ffffff")
text1.place(x="50px", y="259px")

# Adding the progress percentage
percentage = 0
percentageText = Label(win, text=f"{percentage}% complete", font="{Segoe UI} 20", bg="#0178d6", fg="#ffffff")
percentageText.place(x="50px", y="320px")
percentageIsAHundred = False

________________________________________________________

# This is the problematic code- Removing it seems to run the window normally but including it causes tkinter to not run with 0 errors

def steps(percentage=percentage) :
    percentage = percentage + random.randint(1, 20)
win.after(1000, steps)
while percentageIsAHundred == False :
    percentageText.config(text=f"{percentage}% complete")
    if percentage >= 100 :
        percentageText.config(text="100% complete")
        percentageIsAHundred = True
________________________________________________________

# Setting the mainloop
win.mainloop()

! My title may not be right because I can't think clear right now. !

Body:
The percentage in steps() is local to that function.

If you want it to increase the value of the global percentage, you should mark it at such:

def steps():
    global percentage
    percentage += random.randint(1, 20)
    win.after(1000, steps)
    percentageText.config(text=f"{percentage}% complete")
    if percentage >= 100:
        percentageText.config(text="100% complete")
        win.quit()

Also note that as a rule you should be careful with while and for loops in event handlers and after functions. If they take too long, they will inhibit event processing.

Also, your while loop is not indented, so it in not part of steps but part of the main module. In this case, since your your while loop runs before the mainloop, it prevents the tkinter mainloop from starting and your window from appearing. :-)


来源: stackexchange

问:
How to fix `data-rbd-draggable-context-id` did not match. Server: "1" Client: "0"' with react-beautiful-dnd and next.js
When I try to use react-beautiful-dnd with next.js (or in general with server side rendering), after reorder items and refresh the page I get this error:

```<code>react-dom.development.js:88 Warning: Prop `data-rbd-draggable-context-id` did not match. Server: "1" Client: "0"
</code>```

And this (that depends on the first one):

```<code>react-beautiful-dnd.esm.js:39 react-beautiful-dndA setup problem was encountered.> Invariant failed: Draggable[id: 1]: Unable to find drag handle
</code>```

I try to use resetServerContext() to reset the server context counter, but it doesn't work as expected.

答:
I used this at the end of the nextjs page using b-dnd.

```<code>export async function getServerSideProps(context) {
  resetServerContext()
  return {props: { data : []}}
}
</code>```

and set this in next.config.js.

```<code>module.exports = {
  reactStrictMode: true,
};
</code>```

This works but I don't fully understand the implications if I'm honest.

ContentLicense: CC BY-SA 4.0

Body:
When I try to use react-beautiful-dnd with next.js (or in general with server side rendering), after reorder items and refresh the page I get this error:

react-dom.development.js:88 Warning: Prop `data-rbd-draggable-context-id` did not match. Server: "1" Client: "0"

And this (that depends on the first one):

react-beautiful-dnd.esm.js:39 react-beautiful-dndA setup problem was encountered.> Invariant failed: Draggable[id: 1]: Unable to find drag handle

I try to use resetServerContext() to reset the server context counter, but it doesn't work as expected.

Body:
I used this at the end of the nextjs page using b-dnd.

export async function getServerSideProps(context) {
  resetServerContext()
  return {props: { data : []}}
}

and set this in next.config.js.

module.exports = {
  reactStrictMode: true,
};

This works but I don't fully understand the implications if I'm honest.


问:
Get aks nodepool / vmss subnet ID
I created an aks using az cli with minimal parameters and specified a node-count and auto scaling. This created a nodepool and VMSS etc. and an accompanying vnet and subnet automatically.

How do I find out the created vnet and subnet using az cli?

```<code>az aks nodepool list --cluster-name aks -g rg-aks
</code>```

report vnetSubnetId and podSubnetId as null.

Using
az vmss list
does show the subnet but I haven't found any properties of the vmss linking it to the nodepool or aks cluster to enable finding it.

The autogenerated name is something like:
aks-nodepool1-15343534-vmss

Which I guess I could filter for along the lines of aks-nodepool1-*-vmss but that seems dodgy and flaky.

答:
I have tested in my environment

The VNET is created along with the VMSS in a different resource group which starts with MC_

To get the subnet ID, you can use the below script:

```<code>$CLUSTER_RESOURCE_GROUP = az aks show --resource-group RGName --name AKSClusterName --query nodeResourceGroup -o tsv
$VMSS_NAME = az vmss list -g $CLUSTER_RESOURCE_GROUP --query "[0].name"
az vmss show -g $CLUSTER_RESOURCE_GROUP -n $VMSS_NAME --query virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0].ipConfigurations[0].subnet.id
</code>```

Title: Get aks nodepool / vmss subnet ID

Body:
I created an aks using az cli with minimal parameters and specified a node-count and auto scaling. This created a nodepool and VMSS etc. and an accompanying vnet and subnet automatically.

How do I find out the created vnet and subnet using az cli?

az aks nodepool list --cluster-name aks -g rg-aks

report vnetSubnetId and podSubnetId as null.

Using
az vmss list
does show the subnet but I haven't found any properties of the vmss linking it to the nodepool or aks cluster to enable finding it.

The autogenerated name is something like:
aks-nodepool1-15343534-vmss

Which I guess I could filter for along the lines of aks-nodepool1-*-vmss but that seems dodgy and flaky.

Body:
I have tested in my environment

The VNET is created along with the VMSS in a different resource group which starts with MC_

To get the subnet ID, you can use the below script:

$CLUSTER_RESOURCE_GROUP = az aks show --resource-group RGName --name AKSClusterName --query nodeResourceGroup -o tsv
$VMSS_NAME = az vmss list -g $CLUSTER_RESOURCE_GROUP --query "[0].name"
az vmss show -g $CLUSTER_RESOURCE_GROUP -n $VMSS_NAME --query virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0].ipConfigurations[0].subnet.id


问:
animate move to the left and to the right?
I want is to move my pagination to the left and to the right after clicked on #prev_pag and #next_pag. how is it and solve my problem?

Eg:  http://jsfiddle.net/szVKD/5/

```<code>$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});
</code>```

答: This is a CSS issue. You need to set #pagination to position:relative; in order to animate the left css property.

ContentLicense: CC BY-SA 3.0

Body:
I want is to move my pagination to the left and to the right after clicked on #prev_pag and #next_pag. how is it and solve my problem?

Eg:  http://jsfiddle.net/szVKD/5/

$('#next_pag').click(function() {
        $('#pagination').animate({
            left: '-=100px'
        },
        500);
    });
    $('#prev_pag').click(function() {
        $('#pagination').animate({
            left: '+=100px'
        },
        500);
    });
});


问:
MultibodyPlant’s dynamics as part of a Python function/lambda constraint in a MathematicalProgram for direct collocation from scratch
I'm trying to implement direct collocation from scratch in a MathematicalProgram such that each constraint is a Python function, meaning that I can get the gradient of each constraint and cost with respect to their inputs. My goal is to use these gradients for a downstream task.

I'm converting the "Direct Collocation for the Pendulum" part of this notebook: https://github.com/RussTedrake/underactuated/blob/master/trajopt.ipynb to a MathematicalProgram. I've been able to convert the cost and constraints to lambdas instead of Formulas. For instance:

```<code>torque_limit = 3.0  # N*m.
u = dircol.input()
dircol.AddConstraintToAllKnotPoints(-torque_limit <= u[0])
dircol.AddConstraintToAllKnotPoints(u[0] <= torque_limit)
</code>```

becomes

```<code>torque_limit = 3.0  # N*m.
for n in range(N-1):
    constraint = prog.AddConstraint(lambda u: u, [-torque_limit], [torque_limit], [u[n][0]])
</code>```

This means I can use ExtractGradient with that constraint:

```<code>ExtractGradient(constraint.evaluator().Eval(InitializeAutoDiff(arbitrary_u_vector)))
</code>```

The one constraint I have not been able to turn into a Python lambda/function is the constraint for Pendulum's dynamics, since that is implemented inside the black box of DirectCollocation. I've read the C++ for DirectCollocation, but I haven't been able to figure it out.

What would it take to either reimplement trajectory optimization's dynamics constraint in Python as a function/lambda or access the dynamics constraint's gradient in Python in some other way? I would like to be able to do this for an arbitrary MultibodyPlant, say Quadrotor or Acrobot, not just Pendulum.

答:
It should definitely be possible to implement the DirectCollocation constraint in python.  This notebook has a bunch of relevant examples of using python functions as constraints; it could help.  But it should be a fairly straightforward port of the DirectCollocationConstraint::Eval you've found in C++.

But you can also always get the gradients from the constraints that are being added by DirectCollocation.  That class is just a helper class that makes it easier to set up the MathematicalProgram for you.  You can still get that program back out and evaluate any of the constraints individually if you like.  I'm not convinced you get anything by reimplementing it yourself, and will certainly have worse performance in python.

Body:
I'm trying to implement direct collocation from scratch in a MathematicalProgram such that each constraint is a Python function, meaning that I can get the gradient of each constraint and cost with respect to their inputs. My goal is to use these gradients for a downstream task.

I'm converting the "Direct Collocation for the Pendulum" part of this notebook: https://github.com/RussTedrake/underactuated/blob/master/trajopt.ipynb to a MathematicalProgram. I've been able to convert the cost and constraints to lambdas instead of Formulas. For instance:

torque_limit = 3.0  # N*m.
u = dircol.input()
dircol.AddConstraintToAllKnotPoints(-torque_limit <= u[0])
dircol.AddConstraintToAllKnotPoints(u[0] <= torque_limit)

becomes

torque_limit = 3.0  # N*m.
for n in range(N-1):
    constraint = prog.AddConstraint(lambda u: u, [-torque_limit], [torque_limit], [u[n][0]])

This means I can use ExtractGradient with that constraint:

ExtractGradient(constraint.evaluator().Eval(InitializeAutoDiff(arbitrary_u_vector)))

The one constraint I have not been able to turn into a Python lambda/function is the constraint for Pendulum's dynamics, since that is implemented inside the black box of DirectCollocation. I've read the C++ for DirectCollocation, but I haven't been able to figure it out.

What would it take to either reimplement trajectory optimization's dynamics constraint in Python as a function/lambda or access the dynamics constraint's gradient in Python in some other way? I would like to be able to do this for an arbitrary MultibodyPlant, say Quadrotor or Acrobot, not just Pendulum.


问:
I have got this error when I try to make post request in postman " { "success": false, "error": "user.matchPassword is not a function" }
I have received this in postman when I try to run login route. I have used mongodb atlas and nodejs 14.17.0 version. Please help me to fix this error. This code was fond in YouTube tutorial. That code work for him but It is not working for me.
{
"success": false,
"error": "user.matchPassword is not a function"
}

Schema file

```<code>const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
//-------------------------------------------------------------------------------------

//------------- User Schema -------------
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, 'Please provide username'],
  },
  email: {
    type: String,
    required: [true, 'Please provide email address'],
    unique: true,

  },
  password: {
    type: String,
    required: [true, 'Please add a password'],
    minlength: 6,
    select: false,
  },
  resetPasswordToken: String,
  resetPasswordExpire: Date,
})

//------------- password encription before saving the schema  -------------
UserSchema.pre('save', async function (next) {
  if (!this.isModified('password')) {
    next()
  }

  const salt = await bcrypt.genSalt(10)
  this.password = await bcrypt.hash(this.password, salt)
  next()
})

//------------- password checking for login  -------------
UserSchema.methods.matchPassword = async function (password) {
  return await bcrypt.compare(password, this.password)
}

const User = mongoose.model('User', UserSchema)

module.exports = User
</code>```

Loginrouter function This is my login router function

```<code>//------------- Login route -------------
exports.login = async (req, res, next) => {
  const { email, password } = req.body

  if (!email || !password) {
    res
      .status(400)
      .json({ success: false, error: 'Please provide email and paswword.' })
  }
  try {
    const user = User.findOne({ email }).select('+password')
    if (!user) {
      res.status(404).json({ success: false, error: 'Invalid credentials.' })
    }

    const isMatch = await user.matchPassword(password)

    if (!isMatch) {
      res.status(404).json({ success: false, error: 'Invalid credentials' })
    }

    res.status(200).json({ success: true, token: '12646dfsdhf' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
</code>```

}

答:
Inside your Login Router function.

```<code>try {
    const user = await User.findOne({ email }).select('+password')
}
</code>```

Just add the await keyword for finding the user with the required fields.

Body:
I have received this in postman when I try to run login route. I have used mongodb atlas and nodejs 14.17.0 version. Please help me to fix this error. This code was fond in YouTube tutorial. That code work for him but It is not working for me.
{
"success": false,
"error": "user.matchPassword is not a function"
}

Schema file

const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
//-------------------------------------------------------------------------------------

//------------- User Schema -------------
const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: [true, 'Please provide username'],
  },
  email: {
    type: String,
    required: [true, 'Please provide email address'],
    unique: true,

  },
  password: {
    type: String,
    required: [true, 'Please add a password'],
    minlength: 6,
    select: false,
  },
  resetPasswordToken: String,
  resetPasswordExpire: Date,
})

//------------- password encription before saving the schema  -------------
UserSchema.pre('save', async function (next) {
  if (!this.isModified('password')) {
    next()
  }

  const salt = await bcrypt.genSalt(10)
  this.password = await bcrypt.hash(this.password, salt)
  next()
})

//------------- password checking for login  -------------
UserSchema.methods.matchPassword = async function (password) {
  return await bcrypt.compare(password, this.password)
}

const User = mongoose.model('User', UserSchema)

module.exports = User

Loginrouter function This is my login router function

//------------- Login route -------------
exports.login = async (req, res, next) => {
  const { email, password } = req.body

  if (!email || !password) {
    res
      .status(400)
      .json({ success: false, error: 'Please provide email and paswword.' })
  }
  try {
    const user = User.findOne({ email }).select('+password')
    if (!user) {
      res.status(404).json({ success: false, error: 'Invalid credentials.' })
    }

    const isMatch = await user.matchPassword(password)

    if (!isMatch) {
      res.status(404).json({ success: false, error: 'Invalid credentials' })
    }

    res.status(200).json({ success: true, token: '12646dfsdhf' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }

}

Body:
Inside your Login Router function.

try {
    const user = await User.findOne({ email }).select('+password')
}

Just add the await keyword for finding the user with the required fields.


问:
How to delete message in discord.py in python 3.10 (nothing else works)
I have tried anything in the internet and nothing works. My code:

@bot.command()
async def bug(ctx, bug):
    deleted_message_id = ctx.id
    await ctx.channel.send(str(deleted_message_id))
    await ctx.send(ctx.author.mention+", you're bug report hs been reported!")
```

I use python version 3.10

答:
To delete a message use the .delete() method.

@client.event
async def on_message(message):
    await message.channel.send("Deleting message!")
    await asyncio.sleep(3) #optional - sleeps for 3 seconds
    await message.delete()
```
<p>If you want to delete a message the bot sent after x amount of time you can use the delete_after kwarg.</p>
<pre class="lang-py prettyprint-override"><code>@client.command()
async def foo(ctx):
    await ctx.send("This message will be deleted in 2 seconds", delete_after=2)
</code>```

Body:
I have tried anything in the internet and nothing works. My code:

@bot.command()
async def bug(ctx, bug):
    deleted_message_id = ctx.id
    await ctx.channel.send(str(deleted_message_id))
    await ctx.send(ctx.author.mention+", you're bug report hs been reported!")

I use python version 3.10

Body:
To delete a message use the .delete() method.

@client.event
async def on_message(message):
    await message.channel.send("Deleting message!")
    await asyncio.sleep(3) #optional - sleeps for 3 seconds
    await message.delete()

If you want to delete a message the bot sent after x amount of time you can use the delete_after kwarg.

@client.command()
async def foo(ctx):
    await ctx.send("This message will be deleted in 2 seconds", delete_after=2)


问:
How to use facebook signup and login or connect into my asp.net site?
can any one give me a best example site URL to using how to use facebook connect or facebook signup into my site or facebook login with asp.net site?

actually my requirement is that when i registered into my asp.net site by using facebook at that time we want to get facebook user's username (emailid) from facebook and firstname and last name also with user image.

答:
use facebook javascript SDK because by using javascript SDK you can do anythin on facebook easily.
I am given you some code example to do this

```<code><script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root">
    </div>
    <script type="text/javascript">
        FB.init({
            appId: '012341352533212',
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true, // parse XFBML
            channelUrl: 'http://www.xyz.com/channel.html', // channel.html file
            oauth: true // enable OAuth 2.0
        });
    </script>
</code>```

this code call your facebook application

```<code> <script type="text/javascript">
        function facebookLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    FB.api('/me', function (response) {
                        jQuery('#txtFirstName').val(response.first_name);
                        jQuery('#txtLastName').val(response.last_name);
                        jQuery('#txtEmail').val(response.email);
                        jQuery('#hdfUID').val(response.id);
                        //                        FB.logout(function (response) {
                        //                        });
                    });
                } else {
                    jQuery('#txtFirstName').val('');
                    jQuery('#txtLastName').val('');
                    jQuery('#txtEmail').val('');
                    jQuery('#hdfUID').val('');
                }
            }, { scope: 'email' });
            return false;
        }
    </script>
</code>```

and this code call login page of facebook and it response you get back userid, first name. last name and email of the particular user and by using jquery save these values in textbox or hiddenfield and get these values on server side code page.

Body:
use facebook javascript SDK because by using javascript SDK you can do anythin on facebook easily.
I am given you some code example to do this

<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<div id="fb-root">
    </div>
    <script type="text/javascript">
        FB.init({
            appId: '012341352533212',
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true, // parse XFBML
            channelUrl: 'http://www.xyz.com/channel.html', // channel.html file
            oauth: true // enable OAuth 2.0
        });
    </script>

this code call your facebook application

 <script type="text/javascript">
        function facebookLogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    FB.api('/me', function (response) {
                        jQuery('#txtFirstName').val(response.first_name);
                        jQuery('#txtLastName').val(response.last_name);
                        jQuery('#txtEmail').val(response.email);
                        jQuery('#hdfUID').val(response.id);
                        //                        FB.logout(function (response) {
                        //                        });
                    });
                } else {
                    jQuery('#txtFirstName').val('');
                    jQuery('#txtLastName').val('');
                    jQuery('#txtEmail').val('');
                    jQuery('#hdfUID').val('');
                }
            }, { scope: 'email' });
            return false;
        }
    </script>

and this code call login page of facebook and it response you get back userid, first name. last name and email of the particular user and by using jquery save these values in textbox or hiddenfield and get these values on server side code page.


问:
How to construct the data frame such that the "species" column has the actual species names (setosa etc)
```<code>import sklearn.datasets as data
iris = data.load_iris()
import pandas as pd
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])

iris_df['species'] = iris['filename']
iris_df
</code>```

in species name there's iris.csv showing but i need actual species names (setosa etc).

答:
You can solve this with list comprehensions:

Replace the last 2-lines with:

iris_df['species'] = iris['target']
    #species column is filled with 0,1,2 (class indexes)
iris_df['species'] = iris_df['species'].replace({i:k for i,k in enumerate(iris['target_names'])})
    #here we replace the indexes with strings
    # 0 replaced with 'setosa', 1 with 'versicolor'
```
<p>output would be:</p>
```   sepal length (cm)  sepal width (cm)  ...  petal width (cm)    species
0                  5.1               3.5  ...               0.2     setosa
1                  4.9               3.0  ...               0.2     setosa
2                  4.7               3.2  ...               0.2     setosa
3                  4.6               3.1  ...               0.2     setosa
4                  5.0               3.6  ...               0.2     setosa
..                 ...               ...  ...               ...        ...
145                6.7               3.0  ...               2.3  virginica
146                6.3               2.5  ...               1.9  virginica
147                6.5               3.0  ...               2.0  virginica
148                6.2               3.4  ...               2.3  virginica
149                5.9               3.0  ...               1.8  virginica
```

Body:
import sklearn.datasets as data
iris = data.load_iris()
import pandas as pd
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])

iris_df['species'] = iris['filename']
iris_df

in species name there's iris.csv showing but i need actual species names (setosa etc).

Body:
You can solve this with list comprehensions:

Replace the last 2-lines with:

iris_df['species'] = iris['target']
    #species column is filled with 0,1,2 (class indexes)
iris_df['species'] = iris_df['species'].replace({i:k for i,k in enumerate(iris['target_names'])})
    #here we replace the indexes with strings
    # 0 replaced with 'setosa', 1 with 'versicolor'

output would be:

   sepal length (cm)  sepal width (cm)  ...  petal width (cm)    species
0                  5.1               3.5  ...               0.2     setosa
1                  4.9               3.0  ...               0.2     setosa
2                  4.7               3.2  ...               0.2     setosa
3                  4.6               3.1  ...               0.2     setosa
4                  5.0               3.6  ...               0.2     setosa
..                 ...               ...  ...               ...        ...
145                6.7               3.0  ...               2.3  virginica
146                6.3               2.5  ...               1.9  virginica
147                6.5               3.0  ...               2.0  virginica
148                6.2               3.4  ...               2.3  virginica
149                5.9               3.0  ...               1.8  virginica


问:
How should i use grep in docker-compose healthcheck?
I'm trying to add healthcheck for my docker app by grep the curl result.
When i run into docker container:

```<code>curl -sS http://nginx | grep -c works > /dev/null
echo $?
</code>```

I getting 0 and everything seems fine, but if I'm trying to add it into docker-compose

```<code>version: "3.8"

services:
  php:
    build: .
    volumes:
     - ./www:/var/www
    healthcheck:
     test: ["CMD", "curl", "-sS", "http://nginx | grep", "-c", "works > /dev/null"]
     interval: 5s
     timeout: 5s
     retries: 5
  nginx:
    image: "nginx:latest"
    ports:
     - "8080:80"
    volumes:
     - ./nginx:/etc/nginx/conf.d
     - ./www:/var/www
    links:
     - php
</code>```

and check it by docker-compose ps it has status "unhealthy". What am I doing wrong?

答:
Healthcheck can be specified either in shell form, or as an EXEC array (like you have done).

The exec array doesn't support most shell functionality, like using pipes.

I expect it will work fine if you specify it in shell form. I.e.

```<code>    healthcheck:
     test: curl -sS http://nginx | grep -c works > /dev/null
</code>```

Or wrap it in ["CMD", "/bin/sh", "-c", "curl -sS ..."].

Body:
I'm trying to add healthcheck for my docker app by grep the curl result.
When i run into docker container:

curl -sS http://nginx | grep -c works > /dev/null
echo $?

I getting 0 and everything seems fine, but if I'm trying to add it into docker-compose

version: "3.8"

services:
  php:
    build: .
    volumes:
     - ./www:/var/www
    healthcheck:
     test: ["CMD", "curl", "-sS", "http://nginx | grep", "-c", "works > /dev/null"]
     interval: 5s
     timeout: 5s
     retries: 5
  nginx:
    image: "nginx:latest"
    ports:
     - "8080:80"
    volumes:
     - ./nginx:/etc/nginx/conf.d
     - ./www:/var/www
    links:
     - php

and check it by docker-compose ps it has status "unhealthy". What am I doing wrong?

Body:
Healthcheck can be specified either in shell form, or as an EXEC array (like you have done).

The exec array doesn't support most shell functionality, like using pipes.

I expect it will work fine if you specify it in shell form. I.e.

    healthcheck:
     test: curl -sS http://nginx | grep -c works > /dev/null

Or wrap it in ["CMD", "/bin/sh", "-c", "curl -sS ..."].


问:
GCP GCS (Google Cloud Storage) object-level retention policy
Is it possible to define retention policy for individual file in a GCS bucket?

For example, if the bucket is set to have minimum retention of 1 year:

Is it possible for "file A" retention policy set to 2 years and "file B" set to 5 years?

If yes, is it done using prefixes (like AWS S3)? Can I immediately set to x number of year for the file?

答: This could be done with an object hold, which effectively excludes objects from the retention policy.</p>


问:
How to use the default font size selector with custom Quill toolbar?
The normal/default Quill editor uses this kind of size editor:

I am building a custom toolbar using the tools provided by Quill. That looks like this:

```<code>        const toolbarOptions = [
            [
                { font: ['Lato,sans-serif'] },
            ],
            ['size'],
            ['bold', 'italic', 'underline'],
            ['link'],
            ['clean'],
        ];
</code>```

['size'] is invalid syntax, as nothing shows on the toolbar if you use that:

If I alter the 'size' array to be [{ size: ['10px', '12px' ... }] etc, the dropdown ends up looking like this:

How can I use the default size that comes with the editor in a custom configuration of options?

答:
You can override the editor's CSS to change the content of the labels and font sizes. The custom style will take precedence when added after the stylesheet. I left the default values commented in the snippet below.

const toolbarOptions = [
    [
        { font: ['Lato,sans-serif'] },
    ],
    [{ 'size': ['small', false, 'large', 'huge'] }],

    ['bold', 'italic', 'underline'],
    ['link'],
    ['clean'],
];

const quill = new Quill('#editor', {
    theme: 'snow',
    modules: {
        toolbar: toolbarOptions
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

<style>
 .ql-container {
    box-sizing: border-box;
    font-family: Helvetica, Arial, sans-serif;
    /* font-size: 13px; */
    font-size: 12px;
    height: 100%;
    margin: 0px;
    position: relative;
  }

  .ql-editor .ql-size-small {
    /* font-size: 0.75em; */
    font-size: 10px;
  }

  .ql-editor .ql-size-large {
    /* font-size: 1.5em; */
    font-size: 14px;
  }

  .ql-editor .ql-size-huge {
    /* font-size: 2.5em; */
    font-size: 16px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    /* content: 'Normal'; */
    content: '12px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
    /* content: 'Small'; */
    content: '10px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
    /* content: 'Large'; */
    content: '14px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
    /* content: 'Huge'; */
    content: '16px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
    font-size: 10px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
    /* font-size: 18px; */
    font-size: 14px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
    /* font-size: 32px; */
    font-size: 16px;
  }
</style>

<div id="editor">
  <p>Hello World!</p>
  <p>Some initial <strong>bold</strong> text</p>
  <p><br></p>
</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script></code>```

Body:
The normal/default Quill editor uses this kind of size editor:

I am building a custom toolbar using the tools provided by Quill. That looks like this:

        const toolbarOptions = [
            [
                { font: ['Lato,sans-serif'] },
            ],
            ['size'],
            ['bold', 'italic', 'underline'],
            ['link'],
            ['clean'],
        ];

['size'] is invalid syntax, as nothing shows on the toolbar if you use that:

If I alter the 'size' array to be [{ size: ['10px', '12px' ... }] etc, the dropdown ends up looking like this:

How can I use the default size that comes with the editor in a custom configuration of options?

Body:
You can override the editor's CSS to change the content of the labels and font sizes. The custom style will take precedence when added after the stylesheet. I left the default values commented in the snippet below.

const toolbarOptions = [
    [
        { font: ['Lato,sans-serif'] },
    ],
    [{ 'size': ['small', false, 'large', 'huge'] }],

    ['bold', 'italic', 'underline'],
    ['link'],
    ['clean'],
];

const quill = new Quill('#editor', {
    theme: 'snow',
    modules: {
        toolbar: toolbarOptions
    }
});

<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">

<style>
 .ql-container {
    box-sizing: border-box;
    font-family: Helvetica, Arial, sans-serif;
    /* font-size: 13px; */
    font-size: 12px;
    height: 100%;
    margin: 0px;
    position: relative;
  }

  .ql-editor .ql-size-small {
    /* font-size: 0.75em; */
    font-size: 10px;
  }

  .ql-editor .ql-size-large {
    /* font-size: 1.5em; */
    font-size: 14px;
  }

  .ql-editor .ql-size-huge {
    /* font-size: 2.5em; */
    font-size: 16px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    /* content: 'Normal'; */
    content: '12px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
    /* content: 'Small'; */
    content: '10px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
    /* content: 'Large'; */
    content: '14px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
    /* content: 'Huge'; */
    content: '16px';
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
    font-size: 10px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
    /* font-size: 18px; */
    font-size: 14px;
  }

  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
    /* font-size: 32px; */
    font-size: 16px;
  }
</style>

<div id="editor">
  <p>Hello World!</p>
  <p>Some initial <strong>bold</strong> text</p>
  <p><br></p>
</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>


问:
Selenium does not find existing elements that can be found by the browser aba elements and by using js in console
I'm trying to automate the bet365 casino, I know they have tools to block bots.

link :https://casino.bet365.com/Play/LiveRoulette

I can't handle anything that's inside the div class="app-container", at least by selenium. But I find these elements using JavaScript in the browser console.

```<code>import undetected_chromedriver as UChrome
from webdriver_manager.chrome import ChromeDriverManager

UChrome.install(ChromeDriverManager().install())

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

driver = UChrome.Chrome()
driver.get('https://www.bet365.com/#/HO/')
</code>```

after login

```<code>driver.get('https://casino.bet365.com/Play/LiveRoulette')

locator = (By.XPATH,'//*[contains(@class, "second-dozen")]')
</code>```

I try
probably the selectors should be a little different

```<code>driver.execute_script('return document.getElementsByClassName("roulette-table-cell roulette-table-cell_side-first-dozen roulette-table-cell_group-dozen")[0].getBoundingClientRect()')
</code>```

Try

```<code>driver.find_element(locator[0], locator[1])
</code>```

but I recive this:     raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//*[contains(text(), "PAR")])[1]"}
(Session info: chrome=96.0.4664.110)
Stacktrace:
0 0x55f8fa1bcee3

1 0x55f8f9c8a608

2 0x55f8f9cc0aa1

答:
You probably missing a delay / wait.

Redirecting to the inner page with

driver.get('https://casino.bet365.com/Play/LiveRoulette')
```
<p>It takes some time to make all the elements loaded there, you can not access elements immediately.<br />
The recommended way to do that is to use to use Expected Conditions explicit waits, something like this:</p>
<pre class="lang-py prettyprint-override"><code>import undetected_chromedriver as UChrome
from webdriver_manager.chrome import ChromeDriverManager

UChrome.install(ChromeDriverManager().install())

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

driver = UChrome.Chrome()
wait = WebDriverWait(driver, 20)
driver.get('https://www.bet365.com/#/HO/')
#perform the login here
driver.get('https://casino.bet365.com/Play/LiveRoulette')

locator = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '//*[contains(@class, "second-dozen")]')))
</code>```

I see you are also basically missing the driver.find_element method.

This:

(By.XPATH,'//*[contains(@class, "second-dozen")]')
```

will not return a web element.

Also make sure that element is not inside the iframe.

Body:
I'm trying to automate the bet365 casino, I know they have tools to block bots.

link :https://casino.bet365.com/Play/LiveRoulette

I can't handle anything that's inside the div class="app-container", at least by selenium. But I find these elements using JavaScript in the browser console.

import undetected_chromedriver as UChrome
from webdriver_manager.chrome import ChromeDriverManager

UChrome.install(ChromeDriverManager().install())

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

driver = UChrome.Chrome()
driver.get('https://www.bet365.com/#/HO/')

after login

driver.get('https://casino.bet365.com/Play/LiveRoulette')

locator = (By.XPATH,'//*[contains(@class, "second-dozen")]')

I try
probably the selectors should be a little different

driver.execute_script('return document.getElementsByClassName("roulette-table-cell roulette-table-cell_side-first-dozen roulette-table-cell_group-dozen")[0].getBoundingClientRect()')

Try

driver.find_element(locator[0], locator[1])

but I recive this:     raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(//*[contains(text(), "PAR")])[1]"}
(Session info: chrome=96.0.4664.110)
Stacktrace:
0 0x55f8fa1bcee3

1 0x55f8f9c8a608

2 0x55f8f9cc0aa1

Body:
You probably missing a delay / wait.

Redirecting to the inner page with

driver.get('https://casino.bet365.com/Play/LiveRoulette')

It takes some time to make all the elements loaded there, you can not access elements immediately.

The recommended way to do that is to use to use Expected Conditions explicit waits, something like this:

import undetected_chromedriver as UChrome
from webdriver_manager.chrome import ChromeDriverManager

UChrome.install(ChromeDriverManager().install())

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

driver = UChrome.Chrome()
wait = WebDriverWait(driver, 20)
driver.get('https://www.bet365.com/#/HO/')
#perform the login here
driver.get('https://casino.bet365.com/Play/LiveRoulette')

locator = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '//*[contains(@class, "second-dozen")]')))

I see you are also basically missing the driver.find_element method.

This:

(By.XPATH,'//*[contains(@class, "second-dozen")]')

will not return a web element.

Also make sure that element is not inside the iframe.


问:
Add multiple values including a range to a rails select dropdown
I have a dropdown in my rails app where I want users to be able to select from a range of numbers as well as the value "Still Attending".

Could someone help me work this out. I have the range working fine but when I add

```<code>, "Still Attending"
</code>```

It stops working.

```<code><%= select(:year, '', options_for_select(2021.downto(1950), "Still Attending"), { prompt: "Select Year" }, class: "input border border-grey-light text-sm mt-2 w-full") %>
</code>```

答:
Assuming you want "Still Attending" to be the first choice, you can make it the first element in the options array.

```<code><%= select(:year, '', options_for_select(["Still Attending"] + 2021.downto(1950).to_a), { prompt: "Select Year" }, class: "input border border-grey-light text-sm mt-2 w-full") %>
</code>```

The second argument in options_for_select is just to set the current "selected" option, it's not a new option in its own right.

Body:
I have a dropdown in my rails app where I want users to be able to select from a range of numbers as well as the value "Still Attending".

Could someone help me work this out. I have the range working fine but when I add

, "Still Attending"

It stops working.

<%= select(:year, '', options_for_select(2021.downto(1950), "Still Attending"), { prompt: "Select Year" }, class: "input border border-grey-light text-sm mt-2 w-full") %>

Body:
Assuming you want "Still Attending" to be the first choice, you can make it the first element in the options array.

<%= select(:year, '', options_for_select(["Still Attending"] + 2021.downto(1950).to_a), { prompt: "Select Year" }, class: "input border border-grey-light text-sm mt-2 w-full") %>

The second argument in options_for_select is just to set the current "selected" option, it's not a new option in its own right.


问:
can't access class in same package
```<code>Project directory:
 Project
 -[other directories]
 -bin
 --A.java
 --B.java
</code>```

Class A source code:

```<code>package bin;
public class A{
 public static void main(String[] args){
  B use=new B("Hello");
  use.run();
 }
}
</code>```

Class B source code:

```<code>package bin;
public class B{
 static String x=null;
 public B(String text){
  x=text;
 }
 public static void run(){
  System.out.println(x);
 }
}
</code>```

There was no error when I compiled B.java, when I tried to compile A.java, I got:

```<code>A.java:4: error: cannot find symbol
     B use=new B("Hello");
  symbol:   class B
  location: class A
search.java:4: error: cannot find symbol
     B use=new B("Hello");
           ^
  symbol:   class B
  location: class A
</code>```

By the way, I am not using an IDE to compile this, I just edited the files with Geany and nano, then tried to compile them from the terminal with javac.

答:
As pointed out by @Alex, you are most likely executing javac command inside bin folder. The right way to compile the program in your situation is to run the javac command int project folder

```<code>javac bin/A.java
</code>```

and to run

```<code>java bin/A
</code>```

Title: can't access class in same package

Body:
Project directory:
 Project
 -[other directories]
 -bin
 --A.java
 --B.java

Class A source code:

package bin;
public class A{
 public static void main(String[] args){
  B use=new B("Hello");
  use.run();
 }
}

Class B source code:

package bin;
public class B{
 static String x=null;
 public B(String text){
  x=text;
 }
 public static void run(){
  System.out.println(x);
 }
}

There was no error when I compiled B.java, when I tried to compile A.java, I got:

A.java:4: error: cannot find symbol
     B use=new B("Hello");
  symbol:   class B
  location: class A
search.java:4: error: cannot find symbol
     B use=new B("Hello");
           ^
  symbol:   class B
  location: class A

By the way, I am not using an IDE to compile this, I just edited the files with Geany and nano, then tried to compile them from the terminal with javac.

Body:
As pointed out by @Alex, you are most likely executing javac command inside bin folder. The right way to compile the program in your situation is to run the javac command int project folder

javac bin/A.java

and to run

java bin/A


问:
Is there a way to manipulate rendered text in react component children?
I am trying to write a component that highlights text inside it's children recursively.

What I have been able to achieve, is to highlight the text only if it's explicitly provided in the body component, but I can't find a way to change the text of the component's render part.

Let's say I have the following HighlightText component:

(Note, that this is a concept component. The real component is much more complicated)

const HighlightText = ({highlight, children}) => {
    const regex = new RegExp(`(${regexEscape(highlight)})`, 'gi');
    return React.Children.map(children, child => {
        // Found a text, can highlight
        if (typeof child === 'string') {
            const text = child.trim();
            if (text) {
                return text.split(regex).filter(p => p).map((p, i) =>
                    regex.test(p) ? {p} : {p};
                );
            }
        }

        // If child is a react component, recurse through its children to find more text to highlight
        if (React.isValidElement(child)) {
            if (child.props && child.props.children) {
                return HighlightText({children: child.props.children, highlight});
            }
        }

        // Here I believe, should be another handling that handles the result of the render function to search for more text to highlight...

        // For any other cases, leave the child as is.
        return child;
    })
}
```
<p>And some component that renders something:</p>
<pre class="lang-js prettyprint-override"><code>const SomeContent = () => <div>content</div>;
</code>```

Now, I want to use the HighlightText component the following way:

ReactDOM.render(

    <HighlightText highlight="e">
        <SomeContent />

some paragraph

        nude text
    </HighlightText>

,document.body);
```
<p>The resulted DOM of the the above code is:</p>
<pre class="lang-html prettyprint-override"><code><div>content</div>
<p><span>som</span><mark>e</mark><span> paragraph</span></p>
<span>nud</span><mark>e</mark><span> t</span><mark>e</mark><span>xt</span>
</code>```

But I expect it to be:

content

some paragraph

nude text
```

Any suggestions on how to handle the rendered part of the child component?

答:
Eventually I managed to solve this problem using React.Context.

Not exactly as I expected, but I think it's even a better approach, because now I can decide what text to highlight.

It's similar to i18n and themes techniques in React. React.Context is best approach for these kind of text manipulations.

Body:
I am trying to write a component that highlights text inside it's children recursively.

What I have been able to achieve, is to highlight the text only if it's explicitly provided in the body component, but I can't find a way to change the text of the component's render part.

Let's say I have the following HighlightText component:

(Note, that this is a concept component. The real component is much more complicated)

const HighlightText = ({highlight, children}) => {
    const regex = new RegExp(`(${regexEscape(highlight)})`, 'gi');
    return React.Children.map(children, child => {
        // Found a text, can highlight
        if (typeof child === 'string') {
            const text = child.trim();
            if (text) {
                return text.split(regex).filter(p => p).map((p, i) =>
                    regex.test(p) ? {p} : {p};
                );
            }
        }

        // If child is a react component, recurse through its children to find more text to highlight
        if (React.isValidElement(child)) {
            if (child.props && child.props.children) {
                return HighlightText({children: child.props.children, highlight});
            }
        }

        // Here I believe, should be another handling that handles the result of the render function to search for more text to highlight...

        // For any other cases, leave the child as is.
        return child;
    })
}

And some component that renders something:

const SomeContent = () =>
content
;

Now, I want to use the HighlightText component the following way:

ReactDOM.render(

    <HighlightText highlight="e">
        <SomeContent />

some paragraph

        nude text
    </HighlightText>

,document.body);

The resulted DOM of the the above code is:

content

some paragraph

nude text

But I expect it to be:

content

some paragraph

nude text

Any suggestions on how to handle the rendered part of the child component?


问:
Accessing parent Javascript function from within iframe?
I'm trying to access a function that would update the JQuery UI progress bar located in the parent from within the iframe page. Every time somebody clicks on a link in the iframe page I want it to update the progress bar. I've searched around for answers, and using "window.parent.FunctionName()" is the solution that is given, but for some reason it doesn't seem to work in my situation? Any ideas?

UPDATE: It seems to work in safari, firefox, but not in chrome???

The function that I want to access in the parent page is:

```<code>var percentage = 0;

$('ul li a').one('click', updateBar);

function updateBar() {
    percentage += 8;
    $('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500)
    $('.middle').progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
    }
}
</code>```

The JQuery call that I'm calling from the iframe page is:

```<code>$('#sidenav ul li a').one('click', window.parent.updateBar);
</code>```

答:
be sure that jQuery is also embedded inside the frame

Your approach as it is should work, but the context where the function is executed is the parent window.
   If you like to execute the function using the frame as context, provide the context as argument:

```<code> function updateBar(context) {
    percentage += 8;
    $('.ui-progressbar-value',context).stop().animate({ width: percentage+"%" }, 500)
    $('.middle',context).progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value',context).stop().animate({ width: "100%"}, 500);
    }
}
</code>```

```<code>$('#sidenav ul li a').one('click', function(){window.parent.updateBar(document);});
</code>```

Body:
I'm trying to access a function that would update the JQuery UI progress bar located in the parent from within the iframe page. Every time somebody clicks on a link in the iframe page I want it to update the progress bar. I've searched around for answers, and using "window.parent.FunctionName()" is the solution that is given, but for some reason it doesn't seem to work in my situation? Any ideas?

UPDATE: It seems to work in safari, firefox, but not in chrome???

The function that I want to access in the parent page is:

var percentage = 0;

$('ul li a').one('click', updateBar);

function updateBar() {
    percentage += 8;
    $('.ui-progressbar-value').stop().animate({ width: percentage+"%" }, 500)
    $('.middle').progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value').stop().animate({ width: "100%"}, 500);
    }
}

The JQuery call that I'm calling from the iframe page is:

$('#sidenav ul li a').one('click', window.parent.updateBar);

Body:
be sure that jQuery is also embedded inside the frame

Your approach as it is should work, but the context where the function is executed is the parent window.
   If you like to execute the function using the frame as context, provide the context as argument:

 function updateBar(context) {
    percentage += 8;
    $('.ui-progressbar-value',context).stop().animate({ width: percentage+"%" }, 500)
    $('.middle',context).progressbar('option','value', percentage);

    if(percentage > 100) {
        $('ui-progressbar-value',context).stop().animate({ width: "100%"}, 500);
    }
}

$('#sidenav ul li a').one('click', function(){window.parent.updateBar(document);});


问:
a function to Print the summation of numbers between A and B inclusive that are divisible by X
Given three numbers A, B and X. Print the summation of numbers between A and B inclusive that are divisible by X.

Example :

Input :  5 20 5

Output : 50

Explanation: The numbers [5, 10, 15, 20] are dividable by 5 then the result: 5 + 10 + 15 + 20 = 50.

the problem on codeforces

This my Function :

```<code>long long int Divisability(long long int a, long long int b, long long int x) {
long long int sum = 0;
for (long long int i = a; i <= b; i++) {
    if (i % x == 0) {
        sum += i;
    }
}
return sum;}
</code>```

It works well with a small ranges but doesn't work with a big ranges like :

Input :   1 1000000000 1000000000.

my function causes a "Time limit exceeded".

I need another algorithm to solve this problem.

答:
Why do you run over all numbers and check if they are divisible?

You can simply take the first number, divisible by x, and step further using step x, something like:

```<code>long long int first_number;
a%x == 0 ? first_number = a : first_number = a + x - a%x;

for (long long int i = first_number; i <= b; i+=x)
    sum += i; // no need for checking divisibility by x
</code>```

Remark: I have written the "formula" of first_number by heart without testing, there might be some errors in it. Please test first.

Body:
Given three numbers A, B and X. Print the summation of numbers between A and B inclusive that are divisible by X.

Example :

Input :  5 20 5

Output : 50

Explanation: The numbers [5, 10, 15, 20] are dividable by 5 then the result: 5 + 10 + 15 + 20 = 50.

the problem on codeforces

This my Function :

long long int Divisability(long long int a, long long int b, long long int x) {
long long int sum = 0;
for (long long int i = a; i <= b; i++) {
    if (i % x == 0) {
        sum += i;
    }
}
return sum;}

It works well with a small ranges but doesn't work with a big ranges like :

Input :   1 1000000000 1000000000.

my function causes a "Time limit exceeded".

I need another algorithm to solve this problem.

Body:
Why do you run over all numbers and check if they are divisible?

You can simply take the first number, divisible by x, and step further using step x, something like:

long long int first_number;
a%x == 0 ? first_number = a : first_number = a + x - a%x;

for (long long int i = first_number; i <= b; i+=x)
    sum += i; // no need for checking divisibility by x

Remark: I have written the "formula" of first_number by heart without testing, there might be some errors in it. Please test first.


问:
How to implement cookie authentication with Sveltekit & Supabase?
I'm fairly new to both SvelteKit & Supabase and have done a bit of experimentation on my own, but I would like to know what is the best way to implement user authentication with both of these technologies.

I currently have the following in my __layout.svelte file so that every page on my web application will have access to the session but I'm not sure how to implement persistent user authentication with a cookie.

If anyone can guide me and future users that would be awesome!

```<code><script>
  import supabase from "$lib/api";
  import { page, session } from '$app/stores';
  import { browser } from '$app/env';

    if(browser){
      $session = supabase.auth.session();
      supabase.auth.onAuthStateChange((event, sesh) => {
        $session = sesh;
      });
    }
</script>
</code>```

答:
It is definitely not clear how to do this. I tried to make it easy and put it into a user readable store:

export const user = readable<any>(null, (set) => {

    set(supabase.auth.user());
    const unsubscribe = supabase.auth.onAuthStateChange((_, session) => {
        session ? set(session.user) : set(null);
    });
    return () => {
        unsubscribe.data.unsubscribe();
    }
});
```

Now you can just use $user anywhere to get the session, or see if there is a session.

J

Body:
It is definitely not clear how to do this. I tried to make it easy and put it into a user readable store:

export const user = readable<any>(null, (set) => {

    set(supabase.auth.user());
    const unsubscribe = supabase.auth.onAuthStateChange((_, session) => {
        session ? set(session.user) : set(null);
    });
    return () => {
        unsubscribe.data.unsubscribe();
    }
});

Now you can just use $user anywhere to get the session, or see if there is a session.

J


问:
can c++ using cin to read one digit like scanf
does c++ have similar measure like scanf("%1d) read only one digit in cin >>

or only #include <cstdin> and use scanf

I try to use setw() but it seem to use in string

答:
Here, take a look at this method

```<code>#include <iostream>

int main(){

    std::cout << "Enter a number : ";
    std::string input;
    std::getline(std::cin, input);

    int num = input[0] - 48; // converting char to int by ASCII values
    // int num = input[0] - '0';  can also be used
    cout << num;

    return 0;
}
</code>```

Even if many digits are entered as input, the program only accepts the first digit.

Body:
Here, take a look at this method

#include <iostream>

int main(){

    std::cout << "Enter a number : ";
    std::string input;
    std::getline(std::cin, input);

    int num = input[0] - 48; // converting char to int by ASCII values
    // int num = input[0] - '0';  can also be used
    cout << num;

    return 0;
}

Even if many digits are entered as input, the program only accepts the first digit.


问:
Canvas problem with double click single click?
I have a canvas on which on doubleclick event I create a box object. On box object I want to assign a click event but the problem that occurs is since box gets drawn in canvas. The single click is also registered with canvas and a next click creates another box.</p>

答:
How are you handling each? You dont want to have a click handler and dblclick handler assigned to the same element.

Personally I would assign a click handler, check bounds of where the user is clicking to see if its within the created rect on the canvas, and do what you need. For double clicking I would set some sort of time threshold in the click event to find out if it was a double click or not.


问:
How to avoid god components in Angular?
I am experimenting with Angular. In classical fashion I have separated the template, styles and component into 3 different files.

The component file contains different functions.

Some are triggered by events (e.g. button clicks) from the template, some are not.

Some functions are async, some are not.

Some open modal dialogs, some don't.

Some execute file operations, others don't.

Some functions are high-level and return their result through the snackbar, others don't.

This tends to make component class become a god object, how can this be avoided? And also, how can I avoid the sheer mix of functions? I can export functions to other files, but that means that objects passed to the constructor of the component need to be forwarded which doesn't look like the way to go:

import { doSomething } './helper';

[...]

class Foo Component {
    doSomething(this.snackBar,  <-- smelly code
                     "X", 1, 2, 3)
```

答:
Don't hold the state of the components inside of the components, hold it in a state management library.

By doing this you don't need to pass this.snackBar because there is nothing to be done upon, no mutation of the actual component. Anything that should be done in doSomething can be done in the action that will be called.

Whether its rxjs, ngrx, ngxs (note the examples I'll use are ngxs) or whatever library of your choice.

So you'll have this type of code to execute button an action:

```<code>public doSomething(): void {
   this.store.dispatch(new DoSomeThingCommand("X", 1, 2, 3));
}
</code>```

and to retrieve the actual state you can use reducers:

```<code>@Select(state => state.someState.isSomethingDone)
public isSomethingDone$: Observable<boolean>
</code>```

So in this way the only mutation you are going to have is in the store, rather than the components thus avoiding any dependency on the actual components.

Title: How to avoid god components in Angular?

Body:
Don't hold the state of the components inside of the components, hold it in a state management library.

By doing this you don't need to pass this.snackBar because there is nothing to be done upon, no mutation of the actual component. Anything that should be done in doSomething can be done in the action that will be called.

Whether its rxjs, ngrx, ngxs (note the examples I'll use are ngxs) or whatever library of your choice.

So you'll have this type of code to execute button an action:

public doSomething(): void {
   this.store.dispatch(new DoSomeThingCommand("X", 1, 2, 3));
}

and to retrieve the actual state you can use reducers:

@Select(state => state.someState.isSomethingDone)
public isSomethingDone$: Observable<boolean>

So in this way the only mutation you are going to have is in the store, rather than the components thus avoiding any dependency on the actual components.


问:
AWS Lambda Provisioning Business Logic
In AWS Lambda, there is no need of provisioning done by us. But I was wondering how AWS Lambda might be provisioning machines to run for the requests. Is it creating a EC2 server for each request and execute the request and then kill the server? Or it keeps some EC2 servers always on to serve the request by executing the lambda function? If its doing the former point, then I am wondering it would also affect performance of AWS Lambda to serve the request. Can anyone guide me on this?</p>

答:
Lambdas run inside of a docker-like container, on EC2 servers (using Firecracker) that are highly, highly optimized. AWS has thousands of servers running full time to serve all of the Lambda functions that are running.

A cold start Lambda (one that's never been run before) starts up in a few seconds, depending on how big it is. An EC2 server takes 30+ seconds to startup. If it had to startup an EC2 server, you'd never be able to use a Lambda through API gateway (because API Gateway has a 30 second timeout). But obviously you can.

If you want your Lambdas to startup super duper fast (100ms), use Provisioned Concurrency.

Title: AWS Lambda Provisioning Business Logic


问:
Getting the Data in snapshot.val() but not able to treat it
I was making an app and had to fetch data from Realtime Database. I am getting the data in snapshot.val() like this

```<code>►{xz0ezxzrpkb:{…}}
▼xz0ezxzrpkb:{blood_group:"B+",cause:"Random Cause",created_on:"08-02-2022",email:"example@gmail.com",location:"Random Location",message:"Random Message",name:"Any_Name",phone_number:"+91 *********"}
</code>```

And Now I want to access this data. When I am trying snapshot.val()[0].email   and

snapshot.val().[0].email I am Getting

```<code>undefined (2)
</code>```

So, I am working in React Native and this is the code

```<code>db.ref('/requests/').on('value', (snapshot) => {
       console.log(snapshot.val())
       console.log(snapshot.val()[0].email)
       console.log(snapshot.val().[0].email)
});
</code>```

The nodes of database are as follows:

Please help me out.

答:
While the approach in Dharmaraj's answer works, I recommend using Firebase's built-in forEach operation, since that ensures that you process the results in the same order the database returns them:

```<code>db.ref('/requests/').on('value', (snapshot) => {
  snapshot.forEach((childSnapshot) => {
     console.log(childSnapshot.key)                  // "xz0ezxzrpkb"
     console.log(childSnapshot.val())                // {blood_group:"B+",cause:"Random Cause", ...
     console.log(childSnapshot.val().email)          // "example@gmail.com"
     console.log(childSnapshot.child('email').val()) // "example@gmail.com"
  })
})
</code>```

Body:
I was making an app and had to fetch data from Realtime Database. I am getting the data in snapshot.val() like this

►{xz0ezxzrpkb:{…}}
▼xz0ezxzrpkb:{blood_group:"B+",cause:"Random Cause",created_on:"08-02-2022",email:"example@gmail.com",location:"Random Location",message:"Random Message",name:"Any_Name",phone_number:"+91 *********"}

And Now I want to access this data. When I am trying snapshot.val()[0].email   and

snapshot.val().[0].email I am Getting

undefined (2)

So, I am working in React Native and this is the code

db.ref('/requests/').on('value', (snapshot) => {
       console.log(snapshot.val())
       console.log(snapshot.val()[0].email)
       console.log(snapshot.val().[0].email)
});

The nodes of database are as follows:

Please help me out.

Body:
While the approach in Dharmaraj's answer works, I recommend using Firebase's built-in forEach operation, since that ensures that you process the results in the same order the database returns them:

db.ref('/requests/').on('value', (snapshot) => {
  snapshot.forEach((childSnapshot) => {
     console.log(childSnapshot.key)                  // "xz0ezxzrpkb"
     console.log(childSnapshot.val())                // {blood_group:"B+",cause:"Random Cause", ...
     console.log(childSnapshot.val().email)          // "example@gmail.com"
     console.log(childSnapshot.child('email').val()) // "example@gmail.com"
  })
})


问:
tensorflow: how to reload from a saved checkpoint and do incremental change
I have checkpoint from a pre-trained model A but not its graph-building code. Now I want to reload model A and add sub-graph B to it to get final model C. It's like that C = A + B.  However, since model A is very well trained I don't want to train it in C. I only want to train sub-graph B in C. In other words, sub-graph A only participate in prediction phase(forward propagation) but not training phase(backward propagation), and sub-graph B participate both phase and is what I want to train. The aim is that with the help of sub-graph B, now model C will outperform model A.

How can this be achieved? I guess this may be related to saver/restore but I don't know how to get all things work together. Any code snippet will be greatly appreciated.

I'm using tensorflow 1.12

答:
Well, what you want to do is quite a typical machine learning use case, and it can be achieved in a few manners.

If you just have a saved checkpoint but not source code of the pre-trained model, after loading the model from checkpoint, you need to :

Clear tf.GraphKeys.TRAINABLE_VARIABLES collection to make variables
from ckpt non-trainable by the fine tuning model

Clear tf.GraphKeys.GLOBAL_VARIABLES collection to make variables
from ckpt not re-initialized by the fine tuning model

And then build and train the fine tuning model, as usual.

The code below is tested with TensorFlow 1.12

import os
import shutil
import tensorflow as tf
import numpy as np
from absl import logging, app, flags

flags.DEFINE_string('pre_train_model_checkpoint_path', '/tmp/pre_train_model', '')
FLAGS = flags.FLAGS

def train_and_save_pre_train_model():
    # model: y = w*x + b
    x = tf.placeholder(tf.float32, shape=(None), name='x')
    y_true = tf.placeholder(tf.float32, shape=(None), name='y')
    w = tf.get_variable('w', shape=())
    b = tf.get_variable('b', shape=())
    y = w*x + b
    y_pred = tf.identity(y, 'y_pred')
    loss = tf.losses.mean_squared_error(y_true, y_pred)
    train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss, global_step=tf.train.get_or_create_global_step())
    sess = tf.Session()
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        x_val = np.random.rand(128)
        y_val = x_val * 2.0 - 1.0 # to make w=2.0 and b=-1.0
        sess.run(train_op, {x: x_val, y_true: y_val})
    saver = tf.train.Saver()
    shutil.rmtree(FLAGS.pre_train_model_checkpoint_path)
    os.makedirs(FLAGS.pre_train_model_checkpoint_path)
    save_path = os.path.join(FLAGS.pre_train_model_checkpoint_path, 'ckpt')
    saver.save(sess, save_path, global_step=100)
    return sess.run((w, b));

def main(_):
    w_val, b_val = train_and_save_pre_train_model()
    # to check if pre train model is trained as expected
    logging.info('w_val={}, b_val={}'.format(w_val, b_val))

    # load pre train model
    tf.reset_default_graph()
    meta_file = os.path.join(FLAGS.pre_train_model_checkpoint_path, 'ckpt-100.meta')
    saver = tf.train.import_meta_graph(meta_file)
    save_path = os.path.join(FLAGS.pre_train_model_checkpoint_path, 'ckpt-100')
    sess = tf.Session()
    saver.restore(sess, save_path)
    x = tf.get_default_graph().get_tensor_by_name('x:0')
    y_pred = tf.get_default_graph().get_tensor_by_name('y_pred:0')
    w = tf.get_default_graph().get_tensor_by_name('w:0')
    b = tf.get_default_graph().get_tensor_by_name('b:0')

    # to make variable from ckpt non-trainable by fine tuning model
    tf.get_collection_ref(tf.GraphKeys.TRAINABLE_VARIABLES).clear()
    # to make variable from ckpt not re-initialized by fine tuning model
    tf.get_collection_ref(tf.GraphKeys.GLOBAL_VARIABLES).clear()

    # build fine-tuning model: y2 = w2*y + b2
    w2 = tf.get_variable('w2', shape=())
    b2 = tf.get_variable('b2', shape=())
    y2_pred = w2*y_pred + b2
    y2_true = tf.placeholder(tf.float32, shape=(None), name='y2')
    loss = tf.losses.mean_squared_error(y2_true, y2_pred)
    train_op = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss, global_step=tf.train.get_or_create_global_step())
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        x_val = np.random.rand(128)
        y2_val = (x_val * w_val + b_val) * 10.0 + 1.0 # to make w2=10.0 and b2=1.0
        sess.run(train_op, {x: x_val, y2_true: y2_val})
    w2_val, b2_val = sess.run((w2, b2))
    logging.info('w2_val={}, b2_val={}'.format(w2_val, b2_val))

    # assert w and b is not trained
    w_val_after_fine_tuning, b_val_after_fine_tuning = sess.run((w, b))
    logging.info('w_val_after_fine_tuning={}, b_val_after_fine_tuning={}'.format(w_val_after_fine_tuning, b_val_after_fine_tuning))
    assert(w_val == w_val_after_fine_tuning)
    assert(b_val == b_val_after_fine_tuning)
    logging.info('all good')

if __name__ == '__main__':
    app.run(main)

```


问:
How to activate duplicate feature on my new activity in moodle?
I created a new activity on Moodle but I found that duplicate feature isn't working .
is there any way to solve these problem .
after searching i found that i have to add backup folder in the folder of my activity
but i don't know if that true or not</p>

答:
You will need to populate the backup files for your plugin - see details at https://docs.moodle.org/dev/Backup_API

Your PLUGINNAME_supports() function in lib.php will also need to return true for FEATURE_BACKUP_MOODLE2

I usually start with something like mod_forum in the core code and use that as the basis for my activity plugin backup & restore code.


问:
Java Gradle Eclipse - UTF-8 symbols showing before build in IDE but not after build
i'm fairly new to coding and currently im trying to build my first fat JAR with gradle in eclipse. My project generates a HTML file with data i get from a JSON file. some of the strings in there use UTF-8 symbols/emojis. I managed to get them into my java objects with "Jackson" and by using the getBytes() method for the strings. When i generate the HTML from those objects in eclipse they show up the right way (when opened in browser outside of eclipse).
The problem occurs, when i build the fat jar with "gradlew jar" (i had to make some changes in build.gradle to jar to make it contain the dependencies).
Everything works fine, besides the UTF-8 symbols not showing, instead i get a "?", like the encoding is not set right.
So i think the problem is encoding settings in gradle.

What i tried so far is adding this to gradlew.bat:

```<code>set GRADLE_OPTS=-Dfile.encoding=utf-8
</code>```

this to build.gradle :

```<code>tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}
</code>```

and  this to gradle.Properties

```<code>systemProp.file.encoding=utf-8
</code>```

like mentioned in this thread Show UTF-8 text properly in Gradle

None of those seem to help. Any ideas? Im stuck, struggle to find a solution.

答:
-Dfile.encoding=UTF-8 sets the default encoding used at runtime when running your compiled code, e.g. java -Dfile.encoding=UTF-8 -jar .... Don't mix it up with the encoding that is used by the Java compiler to read the .java files: javac -encoding ....

To avoid to set it on the command line, you can set it also programmatically via System.setProperty("file.encoding", "UTF-8");. But better set the encoding where it used, e.g. instead of BufferedWriter writer= Files.newBufferedWriter(path); use BufferedWriter writer= Files.newBufferedWriter(path, StandardCharsets.UTF_8);.

Body:
i'm fairly new to coding and currently im trying to build my first fat JAR with gradle in eclipse. My project generates a HTML file with data i get from a JSON file. some of the strings in there use UTF-8 symbols/emojis. I managed to get them into my java objects with "Jackson" and by using the getBytes() method for the strings. When i generate the HTML from those objects in eclipse they show up the right way (when opened in browser outside of eclipse).
The problem occurs, when i build the fat jar with "gradlew jar" (i had to make some changes in build.gradle to jar to make it contain the dependencies).
Everything works fine, besides the UTF-8 symbols not showing, instead i get a "?", like the encoding is not set right.
So i think the problem is encoding settings in gradle.

What i tried so far is adding this to gradlew.bat:

set GRADLE_OPTS=-Dfile.encoding=utf-8

this to build.gradle :

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

and  this to gradle.Properties

systemProp.file.encoding=utf-8

like mentioned in this thread Show UTF-8 text properly in Gradle

None of those seem to help. Any ideas? Im stuck, struggle to find a solution.


问:
Pattern matching record types
Let's consider the following Point record type:

```<code>type Point = { x:int; y:int }
</code>```

I'd like to make a predicate that tells me whether a given Point is in a valid region.

```<code>let insideBounds p =
  let notInside c = c < 0 || c > 100
  match p with
  | {x=i; y=_} when notInside i -> false
  | {x=_; y=j} when notInside j -> false
  | _                           -> true
</code>```

This works, yet I wonder if there's an  alternative way of achieving the same result having as insideBounds signature

```<code>let insideBounds {x=i; y=j}
</code>```

instead, still making use of pattern matching?

答:
Sure.

```<code>type Point = { x:int; y:int }

let insideBounds {x=i; y=j} =
  let notInside c = c < 0 || c > 100
  not (notInside i || notInside j)
</code>```

I'd recommend inverting your logic to make it clearer:

```<code>let insideBounds {x=i; y=j} =
  let isInside c = c >= 0 && c <= 100
  isInside i && isInside j
</code>```

As a general rule, it's better for boolean functions/properties, etc to be affirmative. That way, negation retains it's negativity, so to speak.

Title: Pattern matching record types

Body:
Let's consider the following Point record type:

type Point = { x:int; y:int }

I'd like to make a predicate that tells me whether a given Point is in a valid region.

let insideBounds p =
  let notInside c = c < 0 || c > 100
  match p with
  | {x=i; y=_} when notInside i -> false
  | {x=_; y=j} when notInside j -> false
  | _                           -> true

This works, yet I wonder if there's an  alternative way of achieving the same result having as insideBounds signature

let insideBounds {x=i; y=j}

instead, still making use of pattern matching?

Body:
Sure.

type Point = { x:int; y:int }

let insideBounds {x=i; y=j} =
  let notInside c = c < 0 || c > 100
  not (notInside i || notInside j)

I'd recommend inverting your logic to make it clearer:

let insideBounds {x=i; y=j} =
  let isInside c = c >= 0 && c <= 100
  isInside i && isInside j

As a general rule, it's better for boolean functions/properties, etc to be affirmative. That way, negation retains it's negativity, so to speak.


问:
The filter does not clear the previously selected countries. When i try to make a new selection the previous does not erase and list the old one too
```<code><!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Playground!</title>
    <!-- Setup for mobile device screen physical width -->
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <div>
      <select
        id="originCountry"
        onchange="onCountrySelect('origin', this.value)"
      >
        <option>Origin Country</option>
      </select>
      <select
        id="departureCountry"
        onchange="onCountrySelect('destination', this.value)"
        style="margin-left: 60px"
      >
        <option>Destination Country</option>
      </select>
    </div>
    <div>
      <select id="originCity">
        <option>Departure City</option>
      </select>
      <select id="destinationCity" style="margin-left: 60px">
        <option>Arrival City</option>
      </select>
    </div>
    <script>
      const countries = ["US", "RO"];
      const cities = [
        { name: "Las Vegas", country: "US" },
        { name: "Boston", country: "US" },
        { name: "New York", country: "US" },
        { name: "Cluj", country: "RO" },
        { name: "Timisoara", country: "RO" },
        { name: "Arad", country: "RO" },
      ];
      function appendOptionsToSelect(element, list) {
        for (var i = 0; i < list.length; i++) {
          var opt = list[i];
          var el = document.createElement("option");
          el.textContent = opt;
          el.value = opt;
          element.appendChild(el);
        }
      }
      // create select for Origin Country & populate options
      const originCountryElm = document.getElementById("originCountry");
      appendOptionsToSelect(originCountryElm, countries);
      // create select for Destination Country & populate options
      const destinationCountryElm = document.getElementById("departureCountry");
      appendOptionsToSelect(destinationCountryElm, countries);
      // create select for Origin/Destination Cities
      const originCitiesElm = document.getElementById("originCity");
      const destinationCitiesElm = document.getElementById("destinationCity");
      function onCountrySelect(countryType, newValue) {
        console.log(
          "Selected country is of type",
          countryType,
          "with name: ",
          newValue
        );
        // get only cities from that country
        const matchingCities = cities
          .filter((item) => item.country === newValue)
          .map((item) => item.name);
</code>```

todo - remove existing options before assiging new ones. The filter does not clear the previously selected countries. When i try to make a new selection the previous does not erase and list the old one too and when i try to make a new select it goes indefinitly and will list the same selection again and again

```<code>        if (countryType === "origin") {

          appendOptionsToSelect(originCitiesElm, matchingCities);
        } else {
          appendOptionsToSelect(destinationCitiesElm, matchingCities);
        }
      }
    </script>
  </body>
</html>
</code>```

答:
You were on the right track, you just needed to clear out the previous options before appending the new options.

I've added a new function to clear out previous options and it needs to be called before appending the new options.

function clearOptions(selectElement) {
   const len = selectElement.options.length - 1;
   for(let i = len; i >= 1; i--) {
      selectElement.remove(i);
   }
}

function onCountrySelect(countryType, newValue) {
  console.log(
    "Selected country is of type",
    countryType,
    "with name: ",
    newValue
  );
  // get only cities from that country
  const matchingCities = cities
    .filter((item) => item.country === newValue)
    .map((item) => item.name);

  if (countryType === "origin") {
    clearOptions(originCitiesElm);
    appendOptionsToSelect(originCitiesElm, matchingCities);
  } else {
    clearOptions(destinationCitiesElm);
    appendOptionsToSelect(destinationCitiesElm, matchingCities);
  }
}
```

Body:
<!DOCTYPE html>

    <title>Bootstrap Playground!</title>

    <meta name="viewport" content="width=device-width, initial-scale=1" />

      <select
        id="originCountry"
        onchange="onCountrySelect('origin', this.value)"
      >
        <option>Origin Country</option>
      </select>
      <select
        id="departureCountry"
        onchange="onCountrySelect('destination', this.value)"
        style="margin-left: 60px"
      >
        <option>Destination Country</option>
      </select>

      <select id="originCity">
        <option>Departure City</option>
      </select>
      <select id="destinationCity" style="margin-left: 60px">
        <option>Arrival City</option>
      </select>


问:
What happens to abandoned coroutine in Lua
I wonder what happens with the coroutine in this example:

```<code>function powersOfTwo(i)
    coroutine.yield(i)
    powersOfTwo(2*i)
end

function iterator()
    return coroutine.wrap(function () powersOfTwo(1) end)
end

for power in iterator() do
    print(power)
    if power > 1000 then break end
end
</code>```

The coroutine does not finish its code. Is it garbage collected?

答:
The coroutine does not finish its code. Is it garbage collected?

Yes, it is garbage-collected as there are no references to the coroutine left after the loop has finished execution. The fact that this involves a coroutine doesn't make a difference; if iterator() returned a closure, it would be garbage-collected all the same.

You can verify this by using collectgarbage:

-- Declare functions, which won't be garbage-collected as they're in the global table
function collectgarbage_full()
    for _ = 1, 10 do -- Run multiple cycles to ensure that all garbage is collected even if the generational GC of Lua 5.2 or later is used
        collectgarbage"collect"
    end
end
function powersOfTwo(i)
    coroutine.yield(i)
    powersOfTwo(2*i)
end
function iterator()
    return coroutine.wrap(function() powersOfTwo(1) end)
end
-- Count non-garbage used memory
collectgarbage_full()
local used = collectgarbage"count"
-- Now use the iterator, creating a garbage coroutine
for power in iterator() do
    print(power)
    if power > 1000 then break end
end
-- Collect garbage, compare used memory against used memory before the garbage coroutine
collectgarbage_full()
if used < collectgarbage"count" then
    error"Garbage coroutine was not collected!"
end
print"Coroutine was garbage-collected."
```
<p>You should see the following output:</p>
```1
2
4
8
16
32
64
128
256
512
1024
Coroutine was garbage-collected.
```

Body:
I wonder what happens with the coroutine in this example:

function powersOfTwo(i)
    coroutine.yield(i)
    powersOfTwo(2*i)
end

function iterator()
    return coroutine.wrap(function () powersOfTwo(1) end)
end

for power in iterator() do
    print(power)
    if power > 1000 then break end
end

The coroutine does not finish its code. Is it garbage collected?

Body:
The coroutine does not finish its code. Is it garbage collected?

Yes, it is garbage-collected as there are no references to the coroutine left after the loop has finished execution. The fact that this involves a coroutine doesn't make a difference; if iterator() returned a closure, it would be garbage-collected all the same.

You can verify this by using collectgarbage:

-- Declare functions, which won't be garbage-collected as they're in the global table
function collectgarbage_full()
    for _ = 1, 10 do -- Run multiple cycles to ensure that all garbage is collected even if the generational GC of Lua 5.2 or later is used
        collectgarbage"collect"
    end
end
function powersOfTwo(i)
    coroutine.yield(i)
    powersOfTwo(2*i)
end
function iterator()
    return coroutine.wrap(function() powersOfTwo(1) end)
end
-- Count non-garbage used memory
collectgarbage_full()
local used = collectgarbage"count"
-- Now use the iterator, creating a garbage coroutine
for power in iterator() do
    print(power)
    if power > 1000 then break end
end
-- Collect garbage, compare used memory against used memory before the garbage coroutine
collectgarbage_full()
if used < collectgarbage"count" then
    error"Garbage coroutine was not collected!"
end
print"Coroutine was garbage-collected."

You should see the following output:

1
2
4
8
16
32
64
128
256
512
1024
Coroutine was garbage-collected.


问:
Save Theme Primary Color and Theme Brightness, and load on startup Flutter
I am using this code to switch between light mode and dark mode and choose the primary color.
Works well, but it doesn't save nor load on app restart. How to fix that?</p>

答:
You're not storing the data anywhere. You can either use flutter_secure_storage, shared_preferences, or any other package you want.

You can achieve it by storing the ThemeMode in the device, when you're updating the value, then loading it on startup, and when you load you can simply update the Provider's value


问:
Count divisors of each element of an array
Looks like I was wrong somewhere that made the program not run.

The input consists of a count and then that many numbers; the output is the number of divisors (including 1 and itself) for each element of the array.

Sample:

```<code>input 3 16 17 18
output 5 2 6
</code>```

Code:

```<code>#include <bits/stdc++.h>
using namespace std;
int countDivisors(int a[], int n) {
     int cnt = 0;
     for(int j = 1; j <= sqrt(a[i]); j++) {
        if(a[i] % j == 0) {
          if(a[i] % j == j) {
            cnt++;
          }
          else {
             cnt = cnt + 2;
          }
      }
 }
 return cnt;
}

int main() {
    int n, i = 0;
    cin >> n;
    int a[n];
    for(;i < n; i++) {
        cin >> a[i];
    }
    cout << " " << countDivisors(a, n);
    return 0;
}
</code>```

答:
```<code>public class Solution {
    public ArrayList<Integer> solve(ArrayList<Integer> A) {

        ArrayList<Integer> result= new ArrayList<Integer>();

        for(int i=0; i<A.size(); i++){

            int count= getDivisorsCount(A.get(i));

            result.add(count);
        }

        return result;

    }

    public int getDivisorsCount(int num){

        int count=0;
        for(int i=1; i*i <= num ; i++){
            if(num % i==0){
                count++;
                if( i !=num/i){
                    count++;
                }
            }
        }

        return count;
    }
}
</code>```

Body:
Looks like I was wrong somewhere that made the program not run.

The input consists of a count and then that many numbers; the output is the number of divisors (including 1 and itself) for each element of the array.

Sample:

input 3 16 17 18
output 5 2 6

Code:

#include <bits/stdc++.h>
using namespace std;
int countDivisors(int a[], int n) {
     int cnt = 0;
     for(int j = 1; j <= sqrt(a[i]); j++) {
        if(a[i] % j == 0) {
          if(a[i] % j == j) {
            cnt++;
          }
          else {
             cnt = cnt + 2;
          }
      }
 }
 return cnt;
}

int main() {
    int n, i = 0;
    cin >> n;
    int a[n];
    for(;i < n; i++) {
        cin >> a[i];
    }
    cout << " " << countDivisors(a, n);
    return 0;
}


问:
take data from edit text in kotlin
I have some edittext boxes (input type = phone) in a fragment. I need to get the value from them and store them in a variable called totalincome and pass this value to another fragment which has a textview. how to do this in the kotlin way. I'm a beginner.

is this the right way
etincome.toString().toInt()

答:
if input type you have phone , data type the variable must string</p>
```<code>editText.text.toString()
</code>```

Title: take data from edit text in kotlin

Body:
if input type you have phone , data type the variable must string

editText.text.toString()


问:
How to know if chat between 2 users is active in Firebase Realtime Database?
I have a chat feature in my app where I am sending push notification to users but I've come across a problem as I don't want to send the push if 2 users are already chatting with each other. How can I know if the chat is active between the 2 users? And how to know if someone has closed the chat session?

Would really appreciate the help.

Cheers!!

答:
Okay so here the deal.

Let suppose there are two Users, A & B.
User A has entered the Chat screen, at the same time a [Map:bool] will be send to the firestore that "IsActive_A: true". (This is for User A, Use similar field for UserB).

and when the User A leaves the Chat, Or click the back button or onDispose method is called. the same function of sending [Map:bool] will be send to there firestream with value equal to false.

This is all i can give you right now, if you want further explaination please share some related code!