问:
How to dynamically vertically align content in a div using transform?
I have a simple login screen with a title, input field and button. Once a user clicks the button, the assumption is that the they become authenticated and should move onto the next screen. There is an intermediate transition that I'm trying to implement, which clears the input field and button and translates the title into the center of the div.

Currently, I calculate the container's height and the inner content's height with useRef and then conditionally change the height of Container if the user is authenticated.

Right now, for Title I'm doing,

```<code>transform: translateY(${authenticated ? 42 : 0}px);
</code>```

But 42 could change in the future depending on stuff I might add or different screens that the user is viewing the page on.

Is there a better, more assuring way of doing this?

```<code>import * as React from "react";
import styled from "@emotion/styled";

const Container = styled.div`
  height: 100vh;
  display: grid;
  place-items: center;
`;

const Box = styled.div<{
  authenticated: boolean;
  containerHeight: number;
  innerContentHeight: number;
}>`
  ${({ authenticated, containerHeight, innerContentHeight }) => `
    border: 1px solid red;
    transition: 0.3s ease-in-out;
    width: 15rem;
    height: ${
      containerHeight
        ? `${
            authenticated
              ? containerHeight - innerContentHeight
              : containerHeight
          }px`
        : "auto"
    }
  `}
`;

const Title = styled.h2<{ authenticated: boolean }>`
  ${({ authenticated }) => `
    transform: translateY(${authenticated ? 42 : 0}px);
    margin-bottom: 6rem;
  `}
`;

const Input = styled.input``;

const Button = styled.button`
  width: 100%;
  margin-top: 1rem;
`;

export default function App() {
  const [containerHeight, setContainerHeight] = React.useState(0);
  const [innerContentHeight, setInnerContentHeight] = React.useState(0);

  const [authenticated, setAuthenticated] = React.useState(false);

  const handleRef = React.useCallback(
    (isContainer: boolean) => (ref: HTMLDivElement) => {
      if (!ref || (containerHeight && innerContentHeight)) return;

      const height = Math.ceil(ref.getBoundingClientRect().height);

      console.log("ref", ref);
      console.log("height", height);

      if (isContainer) {
        setContainerHeight(height);
      } else {
        setInnerContentHeight(height);
      }
    },
    [containerHeight, innerContentHeight]
  );

  const handleLogin = React.useCallback(() => {
    setAuthenticated(true);
  }, []);

  return (
    <Container>
      <Box
        ref={handleRef(true)}
        authenticated={authenticated}
        containerHeight={containerHeight}
        innerContentHeight={innerContentHeight}
      >
        <Title authenticated={authenticated}>Welcome</Title>
        {!authenticated && (
          <div ref={handleRef(false)}>
            <Input value={"test@test.com"} />
            <Button onClick={handleLogin}>Login</Button>
          </div>
        )}
      </Box>
    </Container>
  );
}
</code>```

Body:
I have a simple login screen with a title, input field and button. Once a user clicks the button, the assumption is that the they become authenticated and should move onto the next screen. There is an intermediate transition that I'm trying to implement, which clears the input field and button and translates the title into the center of the div.

Currently, I calculate the container's height and the inner content's height with useRef and then conditionally change the height of Container if the user is authenticated.

Right now, for Title I'm doing,

transform: translateY(${authenticated ? 42 : 0}px);

But 42 could change in the future depending on stuff I might add or different screens that the user is viewing the page on.

Is there a better, more assuring way of doing this?

import * as React from "react";
import styled from "@emotion/styled";

const Container = styled.div`
  height: 100vh;
  display: grid;
  place-items: center;
`;

const Box = styled.div<{
  authenticated: boolean;
  containerHeight: number;
  innerContentHeight: number;
}>`
  ${({ authenticated, containerHeight, innerContentHeight }) => `
    border: 1px solid red;
    transition: 0.3s ease-in-out;
    width: 15rem;
    height: ${
      containerHeight
        ? `${
            authenticated
              ? containerHeight - innerContentHeight
              : containerHeight
          }px`
        : "auto"
    }
  `}
`;

const Title = styled.h2<{ authenticated: boolean }>`
  ${({ authenticated }) => `
    transform: translateY(${authenticated ? 42 : 0}px);
    margin-bottom: 6rem;
  `}
`;

const Input = styled.input``;

const Button = styled.button`
  width: 100%;
  margin-top: 1rem;
`;

export default function App() {
  const [containerHeight, setContainerHeight] = React.useState(0);
  const [innerContentHeight, setInnerContentHeight] = React.useState(0);

  const [authenticated, setAuthenticated] = React.useState(false);

  const handleRef = React.useCallback(
    (isContainer: boolean) => (ref: HTMLDivElement) => {
      if (!ref || (containerHeight && innerContentHeight)) return;

      const height = Math.ceil(ref.getBoundingClientRect().height);

      console.log("ref", ref);
      console.log("height", height);

      if (isContainer) {
        setContainerHeight(height);
      } else {
        setInnerContentHeight(height);
      }
    },
    [containerHeight, innerContentHeight]
  );

  const handleLogin = React.useCallback(() => {
    setAuthenticated(true);
  }, []);

  return (
    <Container>
      <Box
        ref={handleRef(true)}
        authenticated={authenticated}
        containerHeight={containerHeight}
        innerContentHeight={innerContentHeight}
      >
        <Title authenticated={authenticated}>Welcome</Title>
        {!authenticated && (

            <Input value={"test@test.com"} />
            <Button onClick={handleLogin}>Login</Button>

        )}
      </Box>
    </Container>
  );
}


来源: stackexchange

问:
Helmet does not render nonce random value in Node.js-HBS
After 2nd day of trying:
the
scriptSrc: ["'self'", (req, res) => 'nonce-${res.locals.cspNonce}'],},
suppose to render nonce random value and blocks for security purpose rendering any other values.
E.g
I can render the random nonce value if I disable entire helmet (not just CSP helmet). Also I tried scriptSrc:["'self'", (req, res) => {res.render('index',{nonce:res.locals.cspNonce})}], that is not working too.
I tried to pass nonce by different methods (global.nonce or as function) to the index.js and commonly render it from index.js to layout.html :

 -- did not work!

Here is my app.js:

```<code>`const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
const indexRouter = require('./routes/index')
const hbs = require('hbs');
const helmet = require('helmet');
const crypto=require('crypto');
app.use(helmet());
var nonce=crypto.randomBytes(16).toString("hex");
app.use((req, res, next) => {res.locals.cspNonce = nonce;next();});

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],},
    },
  })
);
console.log(nonce);
//app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:res.locals.cspNonce});}); //not working, but title renders.
//app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:nonce});}); //not working`
</code>```

I am expecting:

```<code><head>
<script nonce="random_value===helmet_random_value" src="js/layout.js"></script>
</head>
all my attempts bring
<script nonce="" src="js/layout.js"></script>
</head>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
After 2nd day of trying:
the
scriptSrc: ["'self'", (req, res) => 'nonce-${res.locals.cspNonce}'],},
suppose to render nonce random value and blocks for security purpose rendering any other values.
E.g
I can render the random nonce value if I disable entire helmet (not just CSP helmet). Also I tried scriptSrc:["'self'", (req, res) => {res.render('index',{nonce:res.locals.cspNonce})}], that is not working too.
I tried to pass nonce by different methods (global.nonce or as function) to the index.js and commonly render it from index.js to layout.html :

 -- did not work!

Here is my app.js:

`const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
const indexRouter = require('./routes/index')
const hbs = require('hbs');
const helmet = require('helmet');
const crypto=require('crypto');
app.use(helmet());
var nonce=crypto.randomBytes(16).toString("hex");
app.use((req, res, next) => {res.locals.cspNonce = nonce;next();});

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],},
    },
  })
);
console.log(nonce);
//app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:res.locals.cspNonce});}); //not working, but title renders.
//app.get('/', function(req, res) {res.render('index',{title:'Welcome',nonce:nonce});}); //not working`

I am expecting:

all my attempts bring


问:
File being used by another process when using File.CopyTo method
This is the code for my windows form. The goal of the form is to be able to preview a pdf on the application and then chose a folder with a drop down that you would like to copy the file to (this is what a "house" refers to in the code). This is a little project for work to make it simpler to organize files that get sent to the company.  The listBox works populating with all the pdfs and the preview window works as well (this is the axAcroPDF component). But when hitting the send button to copy the file it says the file is being used by another process.

```<code>public partial class Form1 : Form { public Form1() { InitializeComponent();
}
    string selectedPDF = "";
    string selectedHouse = "";
    DirectoryInfo currentPDF;
    private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.Filter = "PDF Files(*.pdf) |*.pdf;";
        openFileDialog1.ShowDialog();
        if(openFileDialog1.FileName != null)
        {
            axAcroPDF1.LoadFile(openFileDialog1.FileName);
        }

    }

    private void refreshBTN_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\bkamide\Desktop\ExamplePDFS");
        FileInfo[] smFiles = dinfo.GetFiles("*.pdf");
        foreach (FileInfo fi in smFiles)
        {
            pdfList.Items.Add(Path.GetFileName(fi.Name));

        }
    }
    private void pdfList_SelectedIndexChanged(object sender, EventArgs e)
    {
        string firstSelectedItem = pdfList.SelectedItem.ToString();
        selectedPDF = firstSelectedItem;
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\bkamide\Desktop\ExamplePDFS\" + firstSelectedItem);
        currentPDF = dinfo;
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        openFileDialog1.Reset();
        axAcroPDF1.EndInit();
        var sourceFile = new FileInfo(currentPDF.FullName);
        var dest = Path.Combine(@"C:\Users\bkamide\Desktop\ExamplePDFS\", selectedHouse, sourceFile.FullName);
        sourceFile.CopyTo(dest, true);

    }

    private void cbHouse_SelectedIndex(object sender, EventArgs e)
    {
        selectedHouse = cbHouse.SelectedIndex.ToString();

    }
}
</code>```

I tried in the send method to reset the openFileDialog and axAcroPDF (not sure if I did that right) to see if those were the processes that could be using the file. I also tried restarting my computer to make sure nothing in the background was using it as well. I also did try the using method but I was not quite sure how to implement it within this.

Body:
This is the code for my windows form. The goal of the form is to be able to preview a pdf on the application and then chose a folder with a drop down that you would like to copy the file to (this is what a "house" refers to in the code). This is a little project for work to make it simpler to organize files that get sent to the company.  The listBox works populating with all the pdfs and the preview window works as well (this is the axAcroPDF component). But when hitting the send button to copy the file it says the file is being used by another process.

public partial class Form1 : Form { public Form1() { InitializeComponent();
}
    string selectedPDF = "";
    string selectedHouse = "";
    DirectoryInfo currentPDF;
    private void button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.Filter = "PDF Files(*.pdf) |*.pdf;";
        openFileDialog1.ShowDialog();
        if(openFileDialog1.FileName != null)
        {
            axAcroPDF1.LoadFile(openFileDialog1.FileName);
        }

    }

    private void refreshBTN_Click(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\bkamide\Desktop\ExamplePDFS");
        FileInfo[] smFiles = dinfo.GetFiles("*.pdf");
        foreach (FileInfo fi in smFiles)
        {
            pdfList.Items.Add(Path.GetFileName(fi.Name));

        }
    }
    private void pdfList_SelectedIndexChanged(object sender, EventArgs e)
    {
        string firstSelectedItem = pdfList.SelectedItem.ToString();
        selectedPDF = firstSelectedItem;
        DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\bkamide\Desktop\ExamplePDFS\" + firstSelectedItem);
        currentPDF = dinfo;
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        openFileDialog1.Reset();
        axAcroPDF1.EndInit();
        var sourceFile = new FileInfo(currentPDF.FullName);
        var dest = Path.Combine(@"C:\Users\bkamide\Desktop\ExamplePDFS\", selectedHouse, sourceFile.FullName);
        sourceFile.CopyTo(dest, true);

    }

    private void cbHouse_SelectedIndex(object sender, EventArgs e)
    {
        selectedHouse = cbHouse.SelectedIndex.ToString();

    }
}

I tried in the send method to reset the openFileDialog and axAcroPDF (not sure if I did that right) to see if those were the processes that could be using the file. I also tried restarting my computer to make sure nothing in the background was using it as well. I also did try the using method but I was not quite sure how to implement it within this.


问:
MassTransit JobConsumer
We recently discovered that a couple of our long-running consumers were starting to bomb out after upgrading our rabbitmq version. This was due to a 30min ack timeout that rabbitmq added in newer versions. Looking through some examples and recommendations online, we noticed that MassTransit has JobConsumers for longer running consumers. We've refactored our consumers to use this new JobConsumer with an in-memory repository for the different Job sagas (JobType, JobAttempt, and JobState) for the time-being. The in-memory repository is temporary until we can set aside some time to move this to a backing state machine database.

This works for the most part on about 3/4 jobs that we've moved over. There is one job, however, that we are still running into issues with. What we've noticed is that every time we do a deployment, this job will run fine the first time, but then doesn't run again unless we do another deployment.

What we've found in the logs are these messages that pop up after the first run -
"The AttemptCompleted event is not handled during the Faulted state for the JobStateMachine state machine"
"MassTransit.JobService.Components.StateMachines.JobSaga(cecd0c80-e9ca-4c94-98d1-e496ce0afc9f) Saga exception on receipt of MassTransit.Contracts.JobService.JobAttemptCompleted: Not accepted in state Faulted | The AttemptCompleted event is not handled during the Faulted state for the JobStateMachine state machine"

Our configuration below. Thanks in advance.

```<code>IRabbitMqBusFactoryConfigurator RegisterAdditionalRabbitMQSettings(IRabbitMqBusFactoryConfigurator rabbitMqBusFactoryConfigurator,
    IBusRegistrationContext busRegistrationContext)
{
    rabbitMqBusFactoryConfigurator.UseDelayedMessageScheduler();

    var options = new ServiceInstanceOptions()
        .EnableJobServiceEndpoints();

    rabbitMqBusFactoryConfigurator.ServiceInstance(options, instance =>
    {
        instance.ConfigureJobServiceEndpoints(serviceConfigurator =>
        {
            serviceConfigurator.FinalizeCompleted = true;
            serviceConfigurator.ConfigureSagaRepositories(busRegistrationContext);

        });

        instance.ConfigureEndpoints(busRegistrationContext);
    });
    return rabbitMqBusFactoryConfigurator;
}

IServiceCollectionBusConfigurator RegisterAdditionalSagaStorageSettings(
    IServiceCollectionBusConfigurator serviceCollectionBusConfigurator)
{
    serviceCollectionBusConfigurator.AddDelayedMessageScheduler();
    serviceCollectionBusConfigurator.AddSagaRepository<JobSaga>().InMemoryRepository();
    serviceCollectionBusConfigurator.AddSagaRepository<JobTypeSaga>().InMemoryRepository();
    serviceCollectionBusConfigurator.AddSagaRepository<JobAttemptSaga>().InMemoryRepository();

    return serviceCollectionBusConfigurator;
}
</code>```

Title: MassTransit JobConsumer

Body:
We recently discovered that a couple of our long-running consumers were starting to bomb out after upgrading our rabbitmq version. This was due to a 30min ack timeout that rabbitmq added in newer versions. Looking through some examples and recommendations online, we noticed that MassTransit has JobConsumers for longer running consumers. We've refactored our consumers to use this new JobConsumer with an in-memory repository for the different Job sagas (JobType, JobAttempt, and JobState) for the time-being. The in-memory repository is temporary until we can set aside some time to move this to a backing state machine database.

This works for the most part on about 3/4 jobs that we've moved over. There is one job, however, that we are still running into issues with. What we've noticed is that every time we do a deployment, this job will run fine the first time, but then doesn't run again unless we do another deployment.

What we've found in the logs are these messages that pop up after the first run -
"The AttemptCompleted event is not handled during the Faulted state for the JobStateMachine state machine"
"MassTransit.JobService.Components.StateMachines.JobSaga(cecd0c80-e9ca-4c94-98d1-e496ce0afc9f) Saga exception on receipt of MassTransit.Contracts.JobService.JobAttemptCompleted: Not accepted in state Faulted | The AttemptCompleted event is not handled during the Faulted state for the JobStateMachine state machine"

Our configuration below. Thanks in advance.

IRabbitMqBusFactoryConfigurator RegisterAdditionalRabbitMQSettings(IRabbitMqBusFactoryConfigurator rabbitMqBusFactoryConfigurator,
    IBusRegistrationContext busRegistrationContext)
{
    rabbitMqBusFactoryConfigurator.UseDelayedMessageScheduler();

    var options = new ServiceInstanceOptions()
        .EnableJobServiceEndpoints();

    rabbitMqBusFactoryConfigurator.ServiceInstance(options, instance =>
    {
        instance.ConfigureJobServiceEndpoints(serviceConfigurator =>
        {
            serviceConfigurator.FinalizeCompleted = true;
            serviceConfigurator.ConfigureSagaRepositories(busRegistrationContext);

        });

        instance.ConfigureEndpoints(busRegistrationContext);
    });
    return rabbitMqBusFactoryConfigurator;
}

IServiceCollectionBusConfigurator RegisterAdditionalSagaStorageSettings(
    IServiceCollectionBusConfigurator serviceCollectionBusConfigurator)
{
    serviceCollectionBusConfigurator.AddDelayedMessageScheduler();
    serviceCollectionBusConfigurator.AddSagaRepository<JobSaga>().InMemoryRepository();
    serviceCollectionBusConfigurator.AddSagaRepository<JobTypeSaga>().InMemoryRepository();
    serviceCollectionBusConfigurator.AddSagaRepository<JobAttemptSaga>().InMemoryRepository();

    return serviceCollectionBusConfigurator;
}


问:
Why Pyspark is turning off my Computer with heavy computation?
I am running this script:

```<code>import pyspark
import random

sc = pyspark.SparkContext(appName="Pi")

num_samples = 100000000

def inside(p):
  x, y = random.random(), random.random()
  return x*x + y*y < 1

count = sc.parallelize(range(0, num_samples)).filter(inside).count()
pi = 4 * count / num_samples
print(pi)
sc.stop()
</code>```

And it's working without any issues.

If I increase the num_samples variable to 1000000000 for example, after like 2 seconds my computer shutdown completely.

cpu: amd 5950x
64gb RAM
gpu: RTX 3070 TI

Anyone knows why this is happening?

Body:
I am running this script:

import pyspark
import random

sc = pyspark.SparkContext(appName="Pi")

num_samples = 100000000

def inside(p):
  x, y = random.random(), random.random()
  return x*x + y*y < 1

count = sc.parallelize(range(0, num_samples)).filter(inside).count()
pi = 4 * count / num_samples
print(pi)
sc.stop()

And it's working without any issues.

If I increase the num_samples variable to 1000000000 for example, after like 2 seconds my computer shutdown completely.

cpu: amd 5950x
64gb RAM
gpu: RTX 3070 TI

Anyone knows why this is happening?


问:
Pass as onChange parameter all the HTML content of a div in React for a useState
I would like to be able to save the entire content of the div. As the "element" parameter, you can enter any HTML content. If there is a change to that HTML, it is simply updated by saving it with its useStat.
In the line , how could I pass the HTML content of the "div" tag itself as a parameter?</p>
```<code>const ElementoPaginacion = ({element}) =>{
    const [content, saveElement] = useState(element);

    const saveData = (newData) =>{
        saveElement(newData);
    }
    return(
        <div onChange={saveData}>
            {element}
        </div>
    )
}
</code>```

Body:
I would like to be able to save the entire content of the div. As the "element" parameter, you can enter any HTML content. If there is a change to that HTML, it is simply updated by saving it with its useStat.
In the line , how could I pass the HTML content of the "div" tag itself as a parameter?

const ElementoPaginacion = ({element}) =>{
    const [content, saveElement] = useState(element);

    const saveData = (newData) =>{
        saveElement(newData);
    }
    return(

            {element}

    )
}


问:
Marmap: get shortest distance from point to isobath over water only
I am aware that I can use the dist2isobath function to extract the shortest distance from a point, e.g., a tide gauge location to an isobath (say the -200m) but that will NOT bypass land pixel. Is it possible to extract the shortest distance to the isobath but only "over water"? In other words, I am looking for an effective/approximate way to extract the width of the continental shelf at a particular point. I can only extract the distance only including over land pixels so far.


问:
HERE Maps OAuth URLs for a ZOHO CRM Extension
Tried checking documentation for a few days and contacted support - Looks like GET URLs for OAuth are not available (like Google API 'https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.google.com/m8/feeds`) for HERE Maps. I need the below URLs. Does anyone have luck with the below?

Request Token URL - Should accept GET

Access Token URL

Refresh Token URL

Revoke Token URL

https://account.api.here.com/oauth2/token accepts only POST per my knowledge.

Example Google API URLs

```<code>Request Token URL:
https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.google.com/m8/feeds
Access Token URL:
https://www.googleapis.com/oauth2/v4/token
Refresh Token URL:
https://www.googleapis.com/oauth2/v4/token
</code>```

Lowkey: My aim is to validate the address - But I'm offering this as an extension - so I'd like to allow respective users to generate their own Keys/Tokens.

Below is the screenshot of ZOHO Configuration form:

Body:
Tried checking documentation for a few days and contacted support - Looks like GET URLs for OAuth are not available (like Google API 'https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.google.com/m8/feeds`) for HERE Maps. I need the below URLs. Does anyone have luck with the below?

Request Token URL - Should accept GET

Access Token URL

Refresh Token URL

Revoke Token URL

https://account.api.here.com/oauth2/token accepts only POST per my knowledge.

Example Google API URLs

Request Token URL:
https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.google.com/m8/feeds
Access Token URL:
https://www.googleapis.com/oauth2/v4/token
Refresh Token URL:
https://www.googleapis.com/oauth2/v4/token

Lowkey: My aim is to validate the address - But I'm offering this as an extension - so I'd like to allow respective users to generate their own Keys/Tokens.

Below is the screenshot of ZOHO Configuration form:


问:
GKE Unable to Access webpage
I have simple container created with below code

```<code>FROM nginx:1.22-alpine
COPY src/html /usr/share/nginx/html
CMD [ "nginx", "-g", "daemon off;" ]
</code>```

Its working fine on the local machine but when deployed to GKE and trying to access the external ip   getting below error on the log

Can you please advise

Trying to get the webpage similar to one getting on the local machine

Title: GKE Unable to Access webpage

Body:
I have simple container created with below code

FROM nginx:1.22-alpine
COPY src/html /usr/share/nginx/html
CMD [ "nginx", "-g", "daemon off;" ]

Its working fine on the local machine but when deployed to GKE and trying to access the external ip   getting below error on the log

Can you please advise

Trying to get the webpage similar to one getting on the local machine


问:
Py4JJavaError while calling .fit() in pyspark RandomForestClassifier
Im trying to run a RandomForestClassifier model on my dataset and below error pops up.Anyone knows a solution? Im using Spark version 3.3.1 and Python version 3.8.

```<code>    model_df = output.select(["features","OrderMonth"])
    train_df, test_df = model_df.randomSplit([0.7,0.3])

    from pyspark.ml.classification import RandomForestClassifier

    rfc = RandomForestClassifier(numTrees=10, labelCol="OrderMonth").fit(train_df)

    rf_pred = rfc.transform(test_df)
    rf_pred.show()
</code>```

Py4JJavaError Traceback (most recent call last)
<ipython-input-56-5ed675f09e07> in <module>
7 from pyspark.ml.classification import RandomForestClassifier
8
----> 9 rfc = RandomForestClassifier(numTrees=10, labelCol="OrderMonth").fit(train_df)#change n_e to a bigger number
10
11 #rfc.fit(X_train,y_train)

Body:
Im trying to run a RandomForestClassifier model on my dataset and below error pops up.Anyone knows a solution? Im using Spark version 3.3.1 and Python version 3.8.

    model_df = output.select(["features","OrderMonth"])
    train_df, test_df = model_df.randomSplit([0.7,0.3])

    from pyspark.ml.classification import RandomForestClassifier

    rfc = RandomForestClassifier(numTrees=10, labelCol="OrderMonth").fit(train_df)

    rf_pred = rfc.transform(test_df)
    rf_pred.show()

Py4JJavaError Traceback (most recent call last)
<ipython-input-56-5ed675f09e07> in <module>
7 from pyspark.ml.classification import RandomForestClassifier
8
----> 9 rfc = RandomForestClassifier(numTrees=10, labelCol="OrderMonth").fit(train_df)#change n_e to a bigger number
10
11 #rfc.fit(X_train,y_train)


问:
Refresh DB Query in Global - Shiny
I have a shiny app that will be hosted on a server at my work. I use a global file to connect to a postgres DB and query the appropriate data. When I update the database with new data or changes I would like to have those changes be reflected in shiny app.

I know in order for that to happen I would need to move the database queries into the server as reactive expressions or have the IT personel set the app to redeploy every couple days, which would affect my caching. I have many queries and worried about performance issues if the queries are executed on fresh inputs in reactive statements.

Is there a work around to have the global.R file refresh manually or automatically once it is deployed?

Mostly curious about the questions below

**I have seen examples by creating an actionButton and using session$reload() as stated here. Does restarting the session reload the global? for all users or only that user?

Or is another option using a restart.txt file with an action button as stated here**

Title: Refresh DB Query in Global - Shiny


问:
Start foreground service without popping up a notification in android
An android foreground service needs a notification, which is fine, but I would rather have it go directly to the notification background without first obscuring the UI for 3 seconds.

Is there a combination of settings for the notification builder and or the notification channel, which will give me the small icon in the notification bar as well as the notification, when expanding the notification list, but without showing a notification on top of the ui for about three seconds?

My issue is not that I want to hide anything, but rather that the application is in use by the user after the foreground service is being started, so the popup is annoying.


问:
nodejs flash message disappears from request
I am trying to post a flash message after authenticating but for some reason the req.flash() loses its value after a redirect.

The code starts when the user asks for a GET on '/'. Here's the code:

```<code>const express = require('express');
const session = require('express-session');
const cookie = require('cookie');
const methodOverride = require('method-override')
const passport = require('passport');
const localStrategy = require ('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const flash = require('express-flash');
const fs = require('fs');
const config = require('./config.js');
const db = require('./db.js');
const log = require('./logger.js');
const crypto = require('crypto');
var app = express();
const server = require('http').createServer(app);
const build_version = fs.readFileSync("minorBuild.txt").toString();
process.on('UnhandledPromiseRejectionWarning', function(err) {
    log.error({ section: "UnhandledPromiseRejectionWarningr", err: err, uid: '1', orgId: '1' });
});
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(cookieParser(config.cookieSecret));
app.use(flash());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(session({   name: 'sid',
                    secret: config.sessionSecret,
                    cookie: { maxAge: config.sessionCookieMaxAge, domain: 'localhost:3000' },
                    resave: true,
                    saveUninitialized: true
                }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
app.use(methodOverride('_method'))

app.get('/', function(req, res, next) {
    if (req.isAuthenticated()) {
        res.redirect('/dashboard');
    } else {
            res.render('index', { messages: req.flash("error") });
        })
    }
});
</code>```

Once the user POSTS username and password, the data is sent to this function:

```<code>app.post('/login', function(req, res, next){
    passport.authenticate('local', function(err, user, info){
        var redirectUrl = '/';

        if (!user) {
            req.flash('error', info.messages);
            return res.redirect('/');
        }
        if (req.session.redirectUrl) {
            redirectUrl = req.session.redirectUrl;
            req.session.redirectUrl = null;
        }

        req.logIn(user, function(err){
            if (err) {
                return next(err);
            }
        });

        res.redirect(redirectUrl);
    })(req, res, next);
});
</code>```

The data is authenticated here and the message is set on incorrect auth:

```<code>async function authenticateUser (email, password, done)  {
    await db.getParticipantByEmail(email)
    .then(async (getEmailResult) => {
        if (getEmailResult === undefined) {
            return done(null, false, { messages: "Incorrect Username and/or Password" });
        }
    });
}
</code>```

Using the debugger I see the message come back to /login in the info.messages. In this line in the '/login' function:

```<code>if (!user) {
    req.flash('error', info.messages);     //I see the message show up here
    return res.redirect('/');
}
</code>```

After the redirect to '/' req.flash('error') is empty.

```<code>res.render('index', { messages: req.flash("error") });  //req.flash("error") is empty here
</code>```

I have no idea why this is. What am I missing?

Body:
I am trying to post a flash message after authenticating but for some reason the req.flash() loses its value after a redirect.

The code starts when the user asks for a GET on '/'. Here's the code:

const express = require('express');
const session = require('express-session');
const cookie = require('cookie');
const methodOverride = require('method-override')
const passport = require('passport');
const localStrategy = require ('passport-local').Strategy;
const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const flash = require('express-flash');
const fs = require('fs');
const config = require('./config.js');
const db = require('./db.js');
const log = require('./logger.js');
const crypto = require('crypto');
var app = express();
const server = require('http').createServer(app);
const build_version = fs.readFileSync("minorBuild.txt").toString();
process.on('UnhandledPromiseRejectionWarning', function(err) {
    log.error({ section: "UnhandledPromiseRejectionWarningr", err: err, uid: '1', orgId: '1' });
});
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(cookieParser(config.cookieSecret));
app.use(flash());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
app.use(session({   name: 'sid',
                    secret: config.sessionSecret,
                    cookie: { maxAge: config.sessionCookieMaxAge, domain: 'localhost:3000' },
                    resave: true,
                    saveUninitialized: true
                }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static('public'));
app.use(methodOverride('_method'))

app.get('/', function(req, res, next) {
    if (req.isAuthenticated()) {
        res.redirect('/dashboard');
    } else {
            res.render('index', { messages: req.flash("error") });
        })
    }
});

Once the user POSTS username and password, the data is sent to this function:

app.post('/login', function(req, res, next){
    passport.authenticate('local', function(err, user, info){
        var redirectUrl = '/';

        if (!user) {
            req.flash('error', info.messages);
            return res.redirect('/');
        }
        if (req.session.redirectUrl) {
            redirectUrl = req.session.redirectUrl;
            req.session.redirectUrl = null;
        }

        req.logIn(user, function(err){
            if (err) {
                return next(err);
            }
        });

        res.redirect(redirectUrl);
    })(req, res, next);
});

The data is authenticated here and the message is set on incorrect auth:

async function authenticateUser (email, password, done)  {
    await db.getParticipantByEmail(email)
    .then(async (getEmailResult) => {
        if (getEmailResult === undefined) {
            return done(null, false, { messages: "Incorrect Username and/or Password" });
        }
    });
}

Using the debugger I see the message come back to /login in the info.messages. In this line in the '/login' function:

if (!user) {
    req.flash('error', info.messages);     //I see the message show up here
    return res.redirect('/');
}

After the redirect to '/' req.flash('error') is empty.

res.render('index', { messages: req.flash("error") });  //req.flash("error") is empty here

I have no idea why this is. What am I missing?


问:
Im having trouble with rendering a table in react due to setState being async
```<code>render() {
        return(
            <div>
                <SelectBox responseClick={this.getTeams.bind(this)}/>
                <table>

                    <th>Points</th>
                    <th>Goals Delta</th>
                    <th>Name</th>

                    {
                        this.state.teams.map((team) => {
                            return(
                                <tr>
                                    <td>
                                        {team.points}
                                    </td>
                                    <td>
                                        {team.goalsDelta}
                                    </td>
                                    <td>
                                        {team.name}
                                    </td>
                                </tr>
                            )
                        })
                    }
                </table>
                {

                }
            </div>
        )
    }
</code>```

SelectBox sends me the selected league id when pressed (its a button)

```<code>getTeams = (currentLeagueId) => {

            axios.get("https://app.seker.live/fm1/teams/" + currentLeagueId)
                .then((response) => {
                    this.tempTeams = []
                    response.data.map((item) => {
                        console.log(item.name)
                        axios.get("https://app.seker.live/fm1/history/" + currentLeagueId + "/" + item.id)
                            .then((response) => {
                                let tempPoints = 0
                                let delta = 0
                                response.data.forEach(game => {
                                    let goalsScored = 0
                                    let goalsConceded = 0
                                    let home

                                    if (game.homeTeam.id === item.id) {
                                        home = true
                                    }else {
                                        home = false
                                    }
                                    game.goals.forEach(goal => {
                                        if (goal.home === home) {
                                            goalsScored++
                                            delta++
                                        } else {
                                            goalsConceded++
                                            delta--
                                        }
                                    })

                                    if (goalsScored > goalsConceded) {
                                        tempPoints+=3
                                    } else if (goalsScored === goalsConceded) {
                                        tempPoints++
                                    }
                                })
                                this.tempTeams.push({
                                    name : item.name,
                                    id : item.id,
                                    points : tempPoints,
                                    goalsDelta : delta
                                })
                            })
                    })
                    this.setState({
                        teams: this.tempTeams,
                    })
                })
        }
</code>```

this is getTeams that is ran when the button is pressed, now im getting the array of names i logged them to the console all are there but for some reason it does not render the table, i suspect it is because setState is async but I do not know how to get around it i know there is a callback option for setState but i dont know how to put render in it so it will update after the setState

Body:
render() {
        return(

                <SelectBox responseClick={this.getTeams.bind(this)}/>

                    Points
                    Goals Delta
                    Name

                    {
                        this.state.teams.map((team) => {
                            return(

                                        {team.points}

                                        {team.goalsDelta}

                                        {team.name}

                            )
                        })
                    }

                {

                }

        )
    }

SelectBox sends me the selected league id when pressed (its a button)

getTeams = (currentLeagueId) => {

            axios.get("https://app.seker.live/fm1/teams/" + currentLeagueId)
                .then((response) => {
                    this.tempTeams = []
                    response.data.map((item) => {
                        console.log(item.name)
                        axios.get("https://app.seker.live/fm1/history/" + currentLeagueId + "/" + item.id)
                            .then((response) => {
                                let tempPoints = 0
                                let delta = 0
                                response.data.forEach(game => {
                                    let goalsScored = 0
                                    let goalsConceded = 0
                                    let home

                                    if (game.homeTeam.id === item.id) {
                                        home = true
                                    }else {
                                        home = false
                                    }
                                    game.goals.forEach(goal => {
                                        if (goal.home === home) {
                                            goalsScored++
                                            delta++
                                        } else {
                                            goalsConceded++
                                            delta--
                                        }
                                    })

                                    if (goalsScored > goalsConceded) {
                                        tempPoints+=3
                                    } else if (goalsScored === goalsConceded) {
                                        tempPoints++
                                    }
                                })
                                this.tempTeams.push({
                                    name : item.name,
                                    id : item.id,
                                    points : tempPoints,
                                    goalsDelta : delta
                                })
                            })
                    })
                    this.setState({
                        teams: this.tempTeams,
                    })
                })
        }

this is getTeams that is ran when the button is pressed, now im getting the array of names i logged them to the console all are there but for some reason it does not render the table, i suspect it is because setState is async but I do not know how to get around it i know there is a callback option for setState but i dont know how to put render in it so it will update after the setState


问:
Displaying two SHAP beeswarm plots side by side in the same figure using matplotlib
I wonder how to place two independent SHAP beeswarm plots into the same figure but in different axes. I am using matplotlib version 3.4.2, shap version 0.39.0, and Python 3.8.2. I am trying using a single figure and two axes but realize that the beeswarm method does not handle the axis as parameter (error: TypeError: beeswarm() got an unexpected keyword argument 'ax').

I am aware of this related question, but this is different since I am using SHAP API. Any recommendation is welcome. Thanks in advance.

```<code>from matplotlib import pyplot as plt
import shap

fig, axes = plt.subplots(1, 2, figsize=(35, 7), gridspec_kw = {"wspace":1.0})

shap.plots.beeswarm(explainer_a(X_test_a), max_display=10, ax=axes[0])
shap.plots.beeswarm(explainer_b(X_test_b), max_display=10, ax=axes[1])

plt.show()
</code>```

Body:
I wonder how to place two independent SHAP beeswarm plots into the same figure but in different axes. I am using matplotlib version 3.4.2, shap version 0.39.0, and Python 3.8.2. I am trying using a single figure and two axes but realize that the beeswarm method does not handle the axis as parameter (error: TypeError: beeswarm() got an unexpected keyword argument 'ax').

I am aware of this related question, but this is different since I am using SHAP API. Any recommendation is welcome. Thanks in advance.

from matplotlib import pyplot as plt
import shap

fig, axes = plt.subplots(1, 2, figsize=(35, 7), gridspec_kw = {"wspace":1.0})

shap.plots.beeswarm(explainer_a(X_test_a), max_display=10, ax=axes[0])
shap.plots.beeswarm(explainer_b(X_test_b), max_display=10, ax=axes[1])

plt.show()


问:
How to Compare 2 columns to find cells that contain the same words and create a third column with the result in Python?
I need to compare 2 columns to find cells that contain the same words and create a third column with the result.
[![https://i.stack.imgur.com/EhDim.jpg%5C]]

i did that but it only compares cells in the same row and I need it to look for repeated values in the column .

```<code>import pandas as pd
import numpy as np

details = {
    'Column1': ['site.com/auto-new/car', 2, 30, 0],
    'Column2': ['site.com/auto/car', 1 , 25, 3]
}

df = pd.DataFrame(details)
df['NEW'] = np.where((df['Column1'].str.endswith('car')) & df['Column1'].str.contains('auto') & df['Column2'].str.endswith('car') & df['Column2'].str.contains('auto'), df['Column2'], np.nan)
print(df)
</code>```

I should to convert dataframe to array like this?https://stackoverflow.com/questions/13187778/convert-pandas-dataframe-to-numpy-array I need This [![enter image description here](https://i.stack.imgur.com/oK3Zl.jpg)](https://i.stack.imgur.com/oK3Zl.jpg)

Body:
I need to compare 2 columns to find cells that contain the same words and create a third column with the result.
[![https://i.stack.imgur.com/EhDim.jpg%5C]]

i did that but it only compares cells in the same row and I need it to look for repeated values in the column .

import pandas as pd
import numpy as np

details = {
    'Column1': ['site.com/auto-new/car', 2, 30, 0],
    'Column2': ['site.com/auto/car', 1 , 25, 3]
}

df = pd.DataFrame(details)
df['NEW'] = np.where((df['Column1'].str.endswith('car')) & df['Column1'].str.contains('auto') & df['Column2'].str.endswith('car') & df['Column2'].str.contains('auto'), df['Column2'], np.nan)
print(df)

I should to convert dataframe to array like this?https://stackoverflow.com/questions/13187778/convert-pandas-dataframe-to-numpy-array I need This [![enter image description here](https://i.stack.imgur.com/oK3Zl.jpg)](https://i.stack.imgur.com/oK3Zl.jpg)


问:
How does $$ and $ in nasm translate to Gnu Assembler?
In NASM I can write jmp $ and use ($-$$), but what is the equivalent in GNU Assembler (GAS).


问:
Delay Animation On Page Load
I'm trying to show the color gradient for Text 1,2, and 3 after the animation has completed on load.

You are able to see that Text 2 and Text 3 have a gradient but the problem I'm having is delaying the color gradient for "Text 1" because it starts as soon as the page loads. So the gradient is so quick you can't even see it.

I have tired animation delay on Text 1 but it's still too fast.

I hope this makes sense if not please let me know in the comments or if there could be a better name for the question.

Here is source code:

```<code>```
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Sample

                Text 1Text 2
                Text 3

```
</code>```

Title: Delay Animation On Page Load

Body:
I'm trying to show the color gradient for Text 1,2, and 3 after the animation has completed on load.

You are able to see that Text 2 and Text 3 have a gradient but the problem I'm having is delaying the color gradient for "Text 1" because it starts as soon as the page loads. So the gradient is so quick you can't even see it.

I have tired animation delay on Text 1 but it's still too fast.

I hope this makes sense if not please let me know in the comments or if there could be a better name for the question.

Here is source code:

```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        *{
            font-family: "Poppins" "sans-serif";
        }
             h1 {
        margin: 0;

        color: #fff;
        letter-spacing: -0.03em;
      }

      .heading-line {
        line-height: 1;
        display: block;
        position: relative;
        text-align: center;
      }

      .heading-line::before {
        line-height: 1;
        display: block;
        position: absolute;
        color: #fff;
        pointer-events: none;
        width: 100%;
      }

      .heading-line-gradient {
        -webkit-text-fill-color: transparent;
        color: transparent;
        -webkit-background-clip: text;
        background-clip: text;
      }

      /* 1st heading gradient */
      @keyframes first_heading_gradient {

        0%,
        16.667% {
          opacity: 1;
        }

        33.333%,
        83.333% {
          opacity: 0;
        }

        100% {
          opacity: 1;
        }
      }

      /* 1st heading white text */
      @keyframes first_heading_white_text {

        0%,
        16.667% {
          opacity: 0;
        }

        25%,
        91.667% {
          opacity: 1;
        }

        100% {
          opacity: 0;
        }
      }

      @keyframes second_heading_gradient {

        0%,
        16.667% {
          opacity: 0;
        }

        33.333%,
        50% {
          opacity: 1;
        }

        66.667%,
        100% {
          opacity: 0;
        }
      }

      @keyframes second_heading_white_text {

        0%,
        25% {
          opacity: 1;
        }

        33.333%,
        50% {
          opacity: 0;
        }

        58.333%,
        100% {
          opacity: 1;
        }
      }

      @keyframes third_heading_gradient {

        0%,
        50% {
          opacity: 0;
        }

        66.667%,
        83.333% {
          opacity: 1;
        }

        100% {
          opacity: 0;
        }
      }

      @keyframes third_heading_white_text {

        0%,
        58.333% {
          opacity: 1;
        }

        66.667%,
        83.333% {
          opacity: 0;
        }

        91.667%,
        100% {
          opacity: 1;
        }
      }

      .heading-line-first>.heading-line-gradient {
        background-image: linear-gradient(to left, #ed8936, #ed64a6);
        animation-delay: 2s;
        animation: first_heading_gradient 4s ;
      }

      .heading-line-first::before {
        content: "Text 1";
        animation-delay: 2s;
        animation: first_heading_white_text 4s 2;
      }

      .heading-line-second>.heading-line-gradient {
        background-image: linear-gradient(to left, #38b2ac, #0bc5ea);
        animation: second_heading_gradient 4s ;
      }

      .heading-line-second::before {
        content: "Text 2";
        /* animation: second_heading_white_text 4s 2; */
      }

      .heading-line-third>.heading-line-gradient {
        background-image: linear-gradient(to left, #ecc94b, #48bb78);
        animation: third_heading_gradient 4s ;
      }

      .heading-line-third::before {
        content: "Text 3";
        /* animation: third_heading_white_text 4s 2; */
      }

      .tracking-in-expand {
    -webkit-animation: tracking-in-expand 0.7s cubic-bezier(0.215, 0.610, 0.355, 1.000) both;
            animation: tracking-in-expand 0.7s cubic-bezier(0.215, 0.610, 0.355, 1.000) both;

}
      /* ----------------------------------------------
 * Generated by Animista on 2023-1-4 16:26:19
 * Licensed under FreeBSD License.
 * See http://animista.net/license for more info.
 * w: http://animista.net, t: @cssanimista
 * ---------------------------------------------- */

/**
 * ----------------------------------------
 * animation tracking-in-expand
 * ----------------------------------------
 */
@-webkit-keyframes tracking-in-expand {
  0% {
    letter-spacing: -0.5em;
    opacity: 0;
  }
  40% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}
@keyframes tracking-in-expand {
  0% {
    letter-spacing: -0.5em;
    opacity: 0;
  }
  40% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}

.text-focus-in {
    -webkit-animation: text-focus-in 1s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
            animation: text-focus-in 1s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
}
/* ----------------------------------------------
 * Generated by Animista on 2023-1-4 16:46:36
 * Licensed under FreeBSD License.
 * See http://animista.net/license for more info.
 * w: http://animista.net, t: @cssanimista
 * ---------------------------------------------- */

/**
 * ----------------------------------------
 * animation text-focus-in
 * ----------------------------------------
 */
 @-webkit-keyframes text-focus-in {
  0% {
    -webkit-filter: blur(12px);
            filter: blur(12px);
    opacity: 0;
  }
  100% {
    -webkit-filter: blur(0px);
            filter: blur(0px);
    opacity: 1;
  }
}
@keyframes text-focus-in {
  0% {
    -webkit-filter: blur(12px);
            filter: blur(12px);
    opacity: 0;
  }
  100% {
    -webkit-filter: blur(0px);
            filter: blur(0px);
    opacity: 1;
  }
}

    </style>
</head>
<body>
    <!-- component style="background-color: #1a202c;"-->
<body>
     <header>

        <div class="w-full bg-cover bg-center " style="height:32rem; background-color:#1a202c;">
          <div class="flex items-center justify-center h-full w-full bg-gray-900 bg-opacity-50">
            <div class="text-center">
               <p class="text-8xl font-bold text-white tracking-in-expand">Sample</p>
              <h1 class="text-2xl font-normal text-focus-in">
                <span class="heading-line heading-line-first py-2"><span class="heading-line-gradient">Text 1</span></span><span class="heading-line heading-line-second py-2"><span class="heading-line-gradient">Text 2</span></span>
                <span class="heading-line heading-line-third py-2"><span class="heading-line-gradient">Text 3</span></span>
              </h1>

            </div>
          </div>
        </div>
      </header>

</body>
</html>```


问:
How can I use a fragment shader along with a geometry buffer array to create points in React-Three-Fiber
To clarify I am using React-Three-Fiber

I would like to create a bunch of points on the canvas, beforehand I was using buffered arrays of colors and positions to plot the points. Here is my attempt at getting it work with buffered positions and using shaderMaterial along with a fragmentShader

```<code>    <points>
        <bufferGeometry attach="geometry">
            <bufferAttribute
                attach="attributes-position"
                count={positions.length / 3}
                array={positions}
                itemSize={3}
                usage={THREE.DynamicDrawUsage}
            />
        </bufferGeometry>
        <shaderMaterial fragmentShader={fragmentShader}/>
    </points>
</code>```

I am able to use the shader with other geometries so I know the mistake is in the way I am trying to use points. Using pointsMaterial or meshStandardMaterial worked fine, could anyone help me understand how to go about using shaders with points in R3F?

Body:
To clarify I am using React-Three-Fiber

I would like to create a bunch of points on the canvas, beforehand I was using buffered arrays of colors and positions to plot the points. Here is my attempt at getting it work with buffered positions and using shaderMaterial along with a fragmentShader

    <points>
        <bufferGeometry attach="geometry">
            <bufferAttribute
                attach="attributes-position"
                count={positions.length / 3}
                array={positions}
                itemSize={3}
                usage={THREE.DynamicDrawUsage}
            />
        </bufferGeometry>
        <shaderMaterial fragmentShader={fragmentShader}/>
    </points>

I am able to use the shader with other geometries so I know the mistake is in the way I am trying to use points. Using pointsMaterial or meshStandardMaterial worked fine, could anyone help me understand how to go about using shaders with points in R3F?


问:
Live Preview of my code doesn't work with css
I try to use live preview of my code.I installed the Five Server extention on VsCode but when I open the live preview the page doesn't allow the use of the css file

Google error (Ctrl + Shift +I>Console): "Not allowed to load local resource: file:///C:/Users/giann/OneDrive/%CE%A5%CF%80%CE%BF%CE%BB%CE%BF%CE%B3%CE%B9%CF%83%CF%84%CE%AE%CF%82/code/code%20exercise/Exercise-6/styles/style.css"

I think that if I upload the file to a cloud service the page might recognise it but I don't know any


问:
Swift user online status updates but it repeats on cells that is not supposed to
I'm working on a chat app and I configured a function to check if a user is online. I'm able to see if another user is active or not, but, the issue I'm having is that if I scroll down (I'm using a UITableView) other users show as active and they are not. I placed the code inside the UITableViewCell class. Any suggestions as to what could be the problem are greatly appreciated. Here is my code:

UITableViewCell

```<code>func configureHomeFeedCell(member: Member) {
    profileImage.loadImage(with: member.imageURL)
    profileName.text = "\(member.name)" + ", " + "\(member.age)"

    checkUserOnlineStatus(with: member.documentId) { _ in }

}

func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
    let query = USERS_COLLECTION.document(userId).collection(IS_ONLINE)
    query.getDocuments { (snapshot, error) in
        if let error = error {
            print("ERROR..\(error.localizedDescription)")
        } else {
            snapshot?.documents.forEach({ diff in
                let isOnline = diff.get(USER_IS_ONLINE) as? Bool
                self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
                completion(isOnline!)
            })}}
        query.addSnapshotListener { (snapshot, error) in
            snapshot?.documentChanges.forEach { diff in
                let isOnline = diff.document.get(USER_IS_ONLINE) as? Bool
                if (diff.type == .modified) {
                    self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
                    completion(isOnline!)
                }}}
}
</code>```

** cellForRowAt**

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let hCell = homeFeedTableView.dequeueReusableCell(withIdentifier: "HomeFeedCell", for: indexPath) as! HomeFeedCell

        if !members.isEmpty {
            hCell.configureHomeFeedCell(member: members[indexPath.row])
        }

        hCell.selectionStyle = .none
        hCell.backgroundColor = UIColor.white

        return hCell
    }
</code>```

Updated Solution

Service Class

This function is to update the user's presence when online or not and it's called inside SceneDelegate

```<code>static func isUserOnline(bool: Bool) {
    guard let currentUID = Auth.auth().currentUser?.uid else { return }

    if !currentUID.isEmpty {
      let dictionary = [USER_IS_ONLINE: bool as Any,
             USER_LASTEST_ONLINE: Date().timeIntervalSince1970 as Any]

      USERS_COLLECTION.document(currentUID).getDocument { (document, error) in
        if let error = error {
          print("Error..\(error.localizedDescription)")
        } else {
          if document?.exists == true {
            USERS_COLLECTION.document(currentUID).updateData(dictionary)
          } else {
            USERS_COLLECTION.document(currentUID).updateData(dictionary)
          }}}}}

**SceneDelegate**

func sceneDidDisconnect(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

  func sceneDidBecomeActive(_ scene: UIScene) {
    Service.isUserOnline(bool: true)
  }

  func sceneWillResignActive(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

  func sceneDidEnterBackground(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

**This function is to monitor the user activity**

  static func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
    let query = USERS_COLLECTION.document(userId)

    query.getDocument { (document, error) in
      if let document = document, document.exists {
        let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
        completion(isOnline)
      }
    }
    query.addSnapshotListener { (document, error) in
      if let document = document, document.exists {
        let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
        completion(isOnline)
      }}}
</code>```

Calling the function inside the cell class

```<code>func configureHomeFeedCell(member: Member) {

 Service.checkUserOnlineStatus(with: member.documentId) { isOnline in
      self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
    } }
</code>```

Body:
I'm working on a chat app and I configured a function to check if a user is online. I'm able to see if another user is active or not, but, the issue I'm having is that if I scroll down (I'm using a UITableView) other users show as active and they are not. I placed the code inside the UITableViewCell class. Any suggestions as to what could be the problem are greatly appreciated. Here is my code:

UITableViewCell

func configureHomeFeedCell(member: Member) {
    profileImage.loadImage(with: member.imageURL)
    profileName.text = "\(member.name)" + ", " + "\(member.age)"

    checkUserOnlineStatus(with: member.documentId) { _ in }

}

func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
    let query = USERS_COLLECTION.document(userId).collection(IS_ONLINE)
    query.getDocuments { (snapshot, error) in
        if let error = error {
            print("ERROR..\(error.localizedDescription)")
        } else {
            snapshot?.documents.forEach({ diff in
                let isOnline = diff.get(USER_IS_ONLINE) as? Bool
                self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
                completion(isOnline!)
            })}}
        query.addSnapshotListener { (snapshot, error) in
            snapshot?.documentChanges.forEach { diff in
                let isOnline = diff.document.get(USER_IS_ONLINE) as? Bool
                if (diff.type == .modified) {
                    self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
                    completion(isOnline!)
                }}}
}

** cellForRowAt**

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let hCell = homeFeedTableView.dequeueReusableCell(withIdentifier: "HomeFeedCell", for: indexPath) as! HomeFeedCell

        if !members.isEmpty {
            hCell.configureHomeFeedCell(member: members[indexPath.row])
        }

        hCell.selectionStyle = .none
        hCell.backgroundColor = UIColor.white

        return hCell
    }

Updated Solution

Service Class

This function is to update the user's presence when online or not and it's called inside SceneDelegate

static func isUserOnline(bool: Bool) {
    guard let currentUID = Auth.auth().currentUser?.uid else { return }

    if !currentUID.isEmpty {
      let dictionary = [USER_IS_ONLINE: bool as Any,
             USER_LASTEST_ONLINE: Date().timeIntervalSince1970 as Any]

      USERS_COLLECTION.document(currentUID).getDocument { (document, error) in
        if let error = error {
          print("Error..\(error.localizedDescription)")
        } else {
          if document?.exists == true {
            USERS_COLLECTION.document(currentUID).updateData(dictionary)
          } else {
            USERS_COLLECTION.document(currentUID).updateData(dictionary)
          }}}}}

**SceneDelegate**

func sceneDidDisconnect(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

  func sceneDidBecomeActive(_ scene: UIScene) {
    Service.isUserOnline(bool: true)
  }

  func sceneWillResignActive(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

  func sceneDidEnterBackground(_ scene: UIScene) {
    Service.isUserOnline(bool: false)
  }

**This function is to monitor the user activity**

  static func checkUserOnlineStatus(with userId: String, completion: @escaping(Bool) -> Void) {
    let query = USERS_COLLECTION.document(userId)

    query.getDocument { (document, error) in
      if let document = document, document.exists {
        let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
        completion(isOnline)
      }
    }
    query.addSnapshotListener { (document, error) in
      if let document = document, document.exists {
        let isOnline = document.get(USER_IS_ONLINE) as? Bool ?? false
        completion(isOnline)
      }}}

Calling the function inside the cell class

func configureHomeFeedCell(member: Member) {

 Service.checkUserOnlineStatus(with: member.documentId) { isOnline in
      self.onlineViewStatus.backgroundColor = isOnline == true ? .green : .red
    } }


问:
My vue3 ref const is being reset as soon as I assign a value
I'm creating an app in Laravel 9 using Vue 3. I have a list that I would like to filter, based on the selection of a dropdown. To ensure the continuity of the selection, I store the value in a ref (gamekk). My code is working to a point: gamekk is updated with the selected value, my computed list filters on the value of gamekk, and the list is displayed. It's only there momentarily, though. Immediately after, gamekk is reset and the list disappears. I can confirm this by displaying gamekk in my page - the value appears then disappears. I don't reference gamekk anywhere else (I added the 'kk' to be sure').

My script is:

```<code><script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link, usePage } from '@inertiajs/inertia-vue3';
import PrimaryButton from '@/Components/PrimaryButton.vue';
import Dropdown from '@/Components/Dropdown.vue';
import DropdownLink from '@/Components/DropdownLink.vue';
import { Inertia } from '@inertiajs/inertia';
import {ref, reactive, computed} from 'vue';

const props = defineProps({
    categories: {
        type: Object,
        default: () => ({}),
    },
    games: {
        type: Object,
        default: () => ({})
    },
    languages: {
        type: Object,
        default: () => ({})
    }
});

const gamekk = ref();
const langFil = ref();
const cats = computed( () => {
    return usePage().props.value.categories.filter(cat =>
        (cat.game == gamekk.value)
    );
});

function filterCats(filter, name) {
    switch(filter) {
        case 'game':
            gamekk.value = name;
        break;
        case 'language':
            langFil.value = name;
        break;
    }
}

</script>
</code>```

I filter the list using:

```<code><div class="flex">
    Game
    <div class="hidden sm:flex sm:items-center sm:ml-6">
        <!-- Settings Dropdown -->
        <div class="ml-3 relative">
            <Dropdown align="right" width="48">
                <template #trigger>
                    <span class="inline-flex rounded-md">
                        <button type="button" class="inline-flex items-center px-3 border border-transparent text-lg leading-4 font-medium rounded-md text-gray-700 hover:text-gray-500 focus:outline-none transition ease-in-out duration-150">
                            <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                            </svg>
                        </button>
                    </span>
                </template>

                <template #content>
                    <DropdownLink v-for="game in $page.props.games" :key="game.id" @click="filterCats('game', game.name)">{{ game.name }}</DropdownLink>
                </template>
            </Dropdown>
        </div>
    </div>
</div>
</code>```

I've used refs in this way before without problem. What am I missing that might reset the value automatically?

Body:
I'm creating an app in Laravel 9 using Vue 3. I have a list that I would like to filter, based on the selection of a dropdown. To ensure the continuity of the selection, I store the value in a ref (gamekk). My code is working to a point: gamekk is updated with the selected value, my computed list filters on the value of gamekk, and the list is displayed. It's only there momentarily, though. Immediately after, gamekk is reset and the list disappears. I can confirm this by displaying gamekk in my page - the value appears then disappears. I don't reference gamekk anywhere else (I added the 'kk' to be sure').

My script is:

I filter the list using:

    Game

            <Dropdown align="right" width="48">
                <template #trigger>

                        <button type="button" class="inline-flex items-center px-3 border border-transparent text-lg leading-4 font-medium rounded-md text-gray-700 hover:text-gray-500 focus:outline-none transition ease-in-out duration-150">
                            <svg class="ml-2 -mr-0.5 h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                            </svg>
                        </button>

                </template>

                <template #content>
                    <DropdownLink v-for="game in $page.props.games" :key="game.id" @click="filterCats('game', game.name)">{{ game.name }}</DropdownLink>
                </template>
            </Dropdown>

I've used refs in this way before without problem. What am I missing that might reset the value automatically?


问:
hdiutil convert "Resource temporarily unavailable"
```<code>hdiutil detach disk9s2
"disk9" ejected.

hdiutil convert -format UDRW -o disk9s2/snolepinst.img /Users/jaygamel/Desktop/snolepinst.iso
hdiutil: convert failed - Resource temporarily unavailable
</code>```

I am not trained at this, but follow directions well.

I'm trying to make an install USB thumb drive for High Sierra. I have the .iso file and have tried many variations of the hdiutil convert with no success, getting No such directory until the last iteration, when I obtained "Resource temporarily unavailable." I am using a 2020 Intel Mac with Monterey 12.6.2 to do it. The usb is HFS+, the current Mac is APFS.

Here is debug:

```<code>hdiutil convert -format UDRW -o disk9s2/snolepinst.img /Users/jaygamel/Desktop/snolepinst.iso -debug         ─╯
DIIsInitialized: returning YES
DIIsInitialized: returning YES
DIBackingStoreNewWithCFURL: entry with
file:///Users/jaygamel/Desktop/snolepinst.iso
writeable: false
DIBackingStoreInstantiatorProbe: entry
file:///Users/jaygamel/Desktop/snolepinst.iso
writeable: false
DIBackingStoreInstantiatorProbe: probing interface 0 CBSDBackingStore
CBSDBackingStore::newProbe score 100 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  0, score      100, CBSDBackingStore
DIBackingStoreInstantiatorProbe: probing interface 1 CBundleBackingStore
CBundleBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  1, score    -1000, CBundleBackingStore
DIBackingStoreInstantiatorProbe: probing interface 2 CRAMBackingStore
CRAMBackingStore::probe: scheme "file": not ram: or ramdisk: scheme.
CRAMBackingStore::probe: score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  2, score    -1000, CRAMBackingStore
DIBackingStoreInstantiatorProbe: probing interface 3 CDevBackingStore
CDevBackingStore::newProbe: not /dev/disk or /dev/rdisk (/Users/jaygamel/Desktop/snolepinst.iso).
CDevBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  3, score    -1000, CDevBackingStore
DIBackingStoreInstantiatorProbe: probing interface 4 CCURLBackingStore
CCURLBackingStore::probe: scheme is: file
CCURLBackingStore::probe: not recognized URL scheme.
CCURLBackingStore::probe: score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  4, score    -1000, CCURLBackingStore
DIBackingStoreInstantiatorProbe: probing interface 5 CVectoredBackingStore
CVectoredBackingStore::newProbe not "vectored" scheme.
CVectoredBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  5, score    -1000, CVectoredBackingStore
DIBackingStoreInstantiatorProbe: selecting CBSDBackingStore
DIBackingStoreNewWithCFURL: CBSDBackingStore
CBSDBackingStore::setPermission: opening /Users/jaygamel/Desktop/snolepinst.iso
CBSDBackingStore::OpenLockFriendly: mapping flags 0x00000000 -> 0x00000014 (locks are MANDATORY)
CBSDBackingStore:OpenLockFriendly: could not open with lock 35
DIBackingStoreNewWithCFURL: instantiator returned 35
DIBackingStoreNewWithCFURL: returning 35
DIResolveURLToBackingStore: unable to resolve to any backing store class. 35.
DIResolveURLToDiskImage: resolving backing store/file encoding failed. 35.
convert: unable to recognize "/Users/jaygamel/Desktop/snolepinst.iso":
Resource temporarily unavailable.hdiutil: convert failed - Resource temporarily unavailable
</code>```

Body:
hdiutil detach disk9s2
"disk9" ejected.

hdiutil convert -format UDRW -o disk9s2/snolepinst.img /Users/jaygamel/Desktop/snolepinst.iso
hdiutil: convert failed - Resource temporarily unavailable

I am not trained at this, but follow directions well.

I'm trying to make an install USB thumb drive for High Sierra. I have the .iso file and have tried many variations of the hdiutil convert with no success, getting No such directory until the last iteration, when I obtained "Resource temporarily unavailable." I am using a 2020 Intel Mac with Monterey 12.6.2 to do it. The usb is HFS+, the current Mac is APFS.

Here is debug:

hdiutil convert -format UDRW -o disk9s2/snolepinst.img /Users/jaygamel/Desktop/snolepinst.iso -debug         ─╯
DIIsInitialized: returning YES
DIIsInitialized: returning YES
DIBackingStoreNewWithCFURL: entry with
file:///Users/jaygamel/Desktop/snolepinst.iso
writeable: false
DIBackingStoreInstantiatorProbe: entry
file:///Users/jaygamel/Desktop/snolepinst.iso
writeable: false
DIBackingStoreInstantiatorProbe: probing interface 0 CBSDBackingStore
CBSDBackingStore::newProbe score 100 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  0, score      100, CBSDBackingStore
DIBackingStoreInstantiatorProbe: probing interface 1 CBundleBackingStore
CBundleBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  1, score    -1000, CBundleBackingStore
DIBackingStoreInstantiatorProbe: probing interface 2 CRAMBackingStore
CRAMBackingStore::probe: scheme "file": not ram: or ramdisk: scheme.
CRAMBackingStore::probe: score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  2, score    -1000, CRAMBackingStore
DIBackingStoreInstantiatorProbe: probing interface 3 CDevBackingStore
CDevBackingStore::newProbe: not /dev/disk or /dev/rdisk (/Users/jaygamel/Desktop/snolepinst.iso).
CDevBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  3, score    -1000, CDevBackingStore
DIBackingStoreInstantiatorProbe: probing interface 4 CCURLBackingStore
CCURLBackingStore::probe: scheme is: file
CCURLBackingStore::probe: not recognized URL scheme.
CCURLBackingStore::probe: score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  4, score    -1000, CCURLBackingStore
DIBackingStoreInstantiatorProbe: probing interface 5 CVectoredBackingStore
CVectoredBackingStore::newProbe not "vectored" scheme.
CVectoredBackingStore::newProbe score -1000 for file:///Users/jaygamel/Desktop/snolepinst.iso
DIBackingStoreInstantiatorProbe: interface  5, score    -1000, CVectoredBackingStore
DIBackingStoreInstantiatorProbe: selecting CBSDBackingStore
DIBackingStoreNewWithCFURL: CBSDBackingStore
CBSDBackingStore::setPermission: opening /Users/jaygamel/Desktop/snolepinst.iso
CBSDBackingStore::OpenLockFriendly: mapping flags 0x00000000 -> 0x00000014 (locks are MANDATORY)
CBSDBackingStore:OpenLockFriendly: could not open with lock 35
DIBackingStoreNewWithCFURL: instantiator returned 35
DIBackingStoreNewWithCFURL: returning 35
DIResolveURLToBackingStore: unable to resolve to any backing store class. 35.
DIResolveURLToDiskImage: resolving backing store/file encoding failed. 35.
convert: unable to recognize "/Users/jaygamel/Desktop/snolepinst.iso":
Resource temporarily unavailable.hdiutil: convert failed - Resource temporarily unavailable


问:
I am busy creating a simple 2D game. Before the start I would like the players to fill in their names based on the colour of their choice
I am in the process of developing a very basic 2d style board game.

I would like the players to enter their names rather than have Player 1, 2, 3, 4 displayed on the screen. The names need to correlate with a specific colour. There are only four options (red, green, blue, yellow). One colour = One player.

I have the following code:

```<code># create a font object
font = pygame.font.Font(None, 36)

# create a dictionary to store the player names
player_names = {}

# create a list of player colors
player_colors = \['red', 'green', 'blue', 'yellow'\]

# create a loop to get the player names
for color in player_colors:
    # initialize the player name to an empty string
    player_names\[color\] = ''

    # wait for the player to enter their name
    while True:
        # display a prompt for the player to enter their name
        prompt_text = f'Enter name for {color} player: {player_names[color]}'
        prompt = font.render(prompt_text, True, (255, 255, 255))
        screen.fill((0, 0, 0))
        screen.blit(prompt, (100, 100))
        pygame.display.flip()

        # check for keyboard input
        keys = pygame.key.get_pressed()

        # process events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                # add the character to the player name
                if event.unicode.isalpha() or event.unicode.isdigit():
                    player_names[color] += event.unicode
                # delete the last character of the player name
                elif event.key == pygame.K_BACKSPACE:
                    player_names[color] = player_names[color][:-1]
                # end the loop when the player presses the enter key
                elif event.key == pygame.K_RETURN:
                    break

# main game loop
</code>```

Problem:

I cannot see the cursor when typing.

I enter the name Aaron. Push enter. Nothing happens.

If I incorrectly type my name I cannot correct it using backspace or the arrow key to move the cursor.

My desired outcome:

I would like to see a cursor so the player knows they can type even when it says type name.

When I am finished entering my name and push enter, I would like it to go to the next colour/player to enter their names.

I would like the players to edit errors before they move on.

How can I do this?

Body:
I am in the process of developing a very basic 2d style board game.

I would like the players to enter their names rather than have Player 1, 2, 3, 4 displayed on the screen. The names need to correlate with a specific colour. There are only four options (red, green, blue, yellow). One colour = One player.

I have the following code:

# create a font object
font = pygame.font.Font(None, 36)

# create a dictionary to store the player names
player_names = {}

# create a list of player colors
player_colors = \['red', 'green', 'blue', 'yellow'\]

# create a loop to get the player names
for color in player_colors:
    # initialize the player name to an empty string
    player_names\[color\] = ''

    # wait for the player to enter their name
    while True:
        # display a prompt for the player to enter their name
        prompt_text = f'Enter name for {color} player: {player_names[color]}'
        prompt = font.render(prompt_text, True, (255, 255, 255))
        screen.fill((0, 0, 0))
        screen.blit(prompt, (100, 100))
        pygame.display.flip()

        # check for keyboard input
        keys = pygame.key.get_pressed()

        # process events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                # add the character to the player name
                if event.unicode.isalpha() or event.unicode.isdigit():
                    player_names[color] += event.unicode
                # delete the last character of the player name
                elif event.key == pygame.K_BACKSPACE:
                    player_names[color] = player_names[color][:-1]
                # end the loop when the player presses the enter key
                elif event.key == pygame.K_RETURN:
                    break

# main game loop

Problem:

I cannot see the cursor when typing.

I enter the name Aaron. Push enter. Nothing happens.

If I incorrectly type my name I cannot correct it using backspace or the arrow key to move the cursor.

My desired outcome:

I would like to see a cursor so the player knows they can type even when it says type name.

When I am finished entering my name and push enter, I would like it to go to the next colour/player to enter their names.

I would like the players to edit errors before they move on.

How can I do this?


问:
interpolation of coordinates in python
I want to interpolate "missing" points on a heatmap that right now looks like this:

.

The csv file is simply a pair of coordinates on each line, separated by semicolons. For example, a single line looks like this:

0.2324;0.343434
```
<p>The <code>interpolation="sinc"</code> is not changing anything, the plot looks exactly the same with or without it e.g.:</p>
```a = plt.imshow(img, extent=extent, origin='lower', cmap="jet", interpolation="sinc")
```
<p>Here's my code:</p>
```import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
import csv

x = []
y = []

plik_csv = "plik.csv"

with open(plik_csv, 'r') as csvfile:
    lines = csv.reader(csvfile, delimiter=';')
    for row in lines:
        x.append(float(row[0]))
        y.append(-float(row[1]))

x_list=np.array(x)
y_list=np.array(y)

def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [min(x_list), max(x_list), min(y_list), max(y_list)]
    return heatmap.T, extent

print("wykres")
sigma = 40
img, extent = myplot(x, y, sigma)
a = plt.imshow(img, extent=extent, origin='lower', cmap="jet", interpolation="sinc")
plt.xlim([-0.4,0.7])
plt.ylim([-0.4,0])
for pos in ['right', 'top', 'bottom', 'left']:
    plt.gca().spines[pos].set_visible(False)

plt.colorbar(a)
plt.show()
```

Title: interpolation of coordinates in python

Body:
I want to interpolate "missing" points on a heatmap that right now looks like this:

.

The csv file is simply a pair of coordinates on each line, separated by semicolons. For example, a single line looks like this:

0.2324;0.343434

The interpolation="sinc" is not changing anything, the plot looks exactly the same with or without it e.g.:

a = plt.imshow(img, extent=extent, origin='lower', cmap="jet", interpolation="sinc")

Here's my code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
import csv

x = []
y = []

plik_csv = "plik.csv"

with open(plik_csv, 'r') as csvfile:
    lines = csv.reader(csvfile, delimiter=';')
    for row in lines:
        x.append(float(row[0]))
        y.append(-float(row[1]))

x_list=np.array(x)
y_list=np.array(y)

def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [min(x_list), max(x_list), min(y_list), max(y_list)]
    return heatmap.T, extent

print("wykres")
sigma = 40
img, extent = myplot(x, y, sigma)
a = plt.imshow(img, extent=extent, origin='lower', cmap="jet", interpolation="sinc")
plt.xlim([-0.4,0.7])
plt.ylim([-0.4,0])
for pos in ['right', 'top', 'bottom', 'left']:
    plt.gca().spines[pos].set_visible(False)

plt.colorbar(a)
plt.show()