问:
Incorporating Flash Messages into My Passport Authentication Strategies
I've watched tons of tutorials and read lots of articles on how to implement flash messages into a passport strat, so if Im the only way it seems to work is when I pass express-flash messages in as the 3rd argument for the done callback, like so:

passport.use(
  new LocalStrategy({ usernameField: "email", passReqToCallback: true }, (req, email, password, done) => {
    console.log(email);
    if (!email || !password)
      return done(null, false, req.flash('errors', 'Invalid Form'));
    User.findOne({ email })
      .then((user) => {
        if (!user)
          return done(null, false, req.flash('errors', 'User not found'));

        bcrypt
          .compare(password, user.password)
          .then((isMatch) => {
            if (!isMatch)
              return done(null, false, req.flash('errors', 'Invalid credentials'));

            return done(null, user, req.flash('success', `Welcome back!`));
          })
          .catch((err) => done(err, false));
      })
      .catch((err) => done(err, false));
  })
);```
</div>
</div>
</p>
<p>and then my auth handler:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>router.post('/passport',passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true,
successRedirect: '/api',
successFlash: true
}));</code>```

EJS Logic for errors

<% if (messages.errors) { %>

      <%= messages.errors %>

    <% } %> ```
</div>
</div>
</p>
<p>EJS Logic for Successful Login Redirect</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <%if(messages.success){%>
            <div class="alert alert-success alert-dismissible fade show">
                <%= messages.success %>
              </div>
        <%}%></code>```

Yet still, I'm only able to receive failure flashes, the success redirection flashes just won't appear.

On top of that, I hear this isn't even the correct way to use flash messages with passport. It's supposed to be done like this where the third argument of the done callback is a set of options where you can pass in a message, like so:

passport.use(
  new LocalStrategy({ usernameField: "email", passReqToCallback: true }, (req, email, password, done) => {
    console.log(email);
    if (!email || !password)
      return done(null, false, {message: 'Invalid Form'});
    User.findOne({ email })
      .then((user) => {
        if (!user)
          return done(null, false, {message: 'User not found'});

        bcrypt
          .compare(password, user.password)
          .then((isMatch) => {
            if (!isMatch)
              return done(null, false, {message: 'Invalid Credentials'});

            return done(null, user, {message: 'Welcome back!'});
          })
          .catch((err) => done(err, false));
      })
      .catch((err) => done(err, false));
  })
);```

Yet this way, I can't get anything to appear at all. If anyone knows what I'm doing wrong please lemme know.

Body:
I've watched tons of tutorials and read lots of articles on how to implement flash messages into a passport strat, so if Im the only way it seems to work is when I pass express-flash messages in as the 3rd argument for the done callback, like so:

passport.use(
  new LocalStrategy({ usernameField: "email", passReqToCallback: true }, (req, email, password, done) => {
    console.log(email);
    if (!email || !password)
      return done(null, false, req.flash('errors', 'Invalid Form'));
    User.findOne({ email })
      .then((user) => {
        if (!user)
          return done(null, false, req.flash('errors', 'User not found'));

        bcrypt
          .compare(password, user.password)
          .then((isMatch) => {
            if (!isMatch)
              return done(null, false, req.flash('errors', 'Invalid credentials'));

            return done(null, user, req.flash('success', `Welcome back!`));
          })
          .catch((err) => done(err, false));
      })
      .catch((err) => done(err, false));
  })
);

and then my auth handler:

router.post('/passport',passport.authenticate('local', {
failureRedirect: '/login',
failureFlash: true,
successRedirect: '/api',
successFlash: true
}));

EJS Logic for errors

<% if (messages.errors) { %>

      <%= messages.errors %>

    <% } %>

EJS Logic for Successful Login Redirect

 <%if(messages.success){%>

                <%= messages.success %>

        <%}%>

Yet still, I'm only able to receive failure flashes, the success redirection flashes just won't appear.

On top of that, I hear this isn't even the correct way to use flash messages with passport. It's supposed to be done like this where the third argument of the done callback is a set of options where you can pass in a message, like so:

passport.use(
  new LocalStrategy({ usernameField: "email", passReqToCallback: true }, (req, email, password, done) => {
    console.log(email);
    if (!email || !password)
      return done(null, false, {message: 'Invalid Form'});
    User.findOne({ email })
      .then((user) => {
        if (!user)
          return done(null, false, {message: 'User not found'});

        bcrypt
          .compare(password, user.password)
          .then((isMatch) => {
            if (!isMatch)
              return done(null, false, {message: 'Invalid Credentials'});

            return done(null, user, {message: 'Welcome back!'});
          })
          .catch((err) => done(err, false));
      })
      .catch((err) => done(err, false));
  })
);

Yet this way, I can't get anything to appear at all. If anyone knows what I'm doing wrong please lemme know.


来源: stackexchange

问:
How can I create a cron job which runs on a specific date and time in nodejs?
In my app every user will have a particular deliverydate when they buy a subscription so once they buy the subscription we will show an option saying "Remind me after" for reminding few things exactly 24 hours before the delivery date (A button on react frontend which calls remindmeafter API on nodejs)and I want to create a cron job for this use case.

So Far Here are my trials:

Initially I have tried node-schedule as they are supporting specific date and time based cron job and here is my code for the same.

const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))

const job = schedule.scheduleJob(date, function() {

  ejs.renderFile(emailUser, {
    data: MailObj
  }, (err, results) => {
    if (err) {
      logger.info('ERROR::::while sending reminder' + err);
    }
    emailApi.sendEmailApi(
      `Reminder `,
      'Reminder',
      results,
      subcriptiondata.email,
      'Mail sent failure',
      'Mail sent successfully',
      process.env.EMAIL_SENDER
    );
  });

})
```

<p>However I've then found on their documentation that node-schedule doesn't persist the data on server restart and which isn't suitable for my app.</p>
<ol start="2">
<li>I have then tried it using cron module and as per their documentation they also support date-based cron job and here is my code for it :</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))

const job = new CronJob(date, function() {

  ejs.renderFile(emailUser, {
    data: MailObj
  }, (err, results) => {
    if (err) {
      logger.info('ERROR::::while sending reminder' + err);
    }
    emailApi.sendEmailApi(
      `Scheduled Reminder `,
      'Scheduled Reminder',
      results,
      subcriptiondata.email,
      'Mail sent failure',
      'Mail sent successfully',
      process.env.EMAIL_SENDER
    );
  });

}, null, true, 'America/Toronto');
</code>```

I have deployed and tried both the codes however none of them are working as I'm not receiving any emails for the scheduled date.It would be great if someone here can help me with this on what I'm doing wrong here and I would prefer the second one i.e, using cron module as it persists server restarts.

Update: I have tried with every 5 mins trigger an email instead of specific date and I did received emails in this case.

ContentLicense: CC BY-SA 4.0

Body:
In my app every user will have a particular deliverydate when they buy a subscription so once they buy the subscription we will show an option saying "Remind me after" for reminding few things exactly 24 hours before the delivery date (A button on react frontend which calls remindmeafter API on nodejs)and I want to create a cron job for this use case.

So Far Here are my trials:

Initially I have tried node-schedule as they are supporting specific date and time based cron job and here is my code for the same.

const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))

const job = schedule.scheduleJob(date, function() {

  ejs.renderFile(emailUser, {
    data: MailObj
  }, (err, results) => {
    if (err) {
      logger.info('ERROR::::while sending reminder' + err);
    }
    emailApi.sendEmailApi(
      `Reminder `,
      'Reminder',
      results,
      subcriptiondata.email,
      'Mail sent failure',
      'Mail sent successfully',
      process.env.EMAIL_SENDER
    );
  });

})

However I've then found on their documentation that node-schedule doesn't persist the data on server restart and which isn't suitable for my app.

I have then tried it using cron module and as per their documentation they also support date-based cron job and here is my code for it :

const date = new Date(moment(subcriptiondata.deliveryDate, 'DD-MM-YYYY').subtract(1, 'days').subtract(5, 'hours').add(30, 'seconds').tz('America/Toronto'))

const job = new CronJob(date, function() {

  ejs.renderFile(emailUser, {
    data: MailObj
  }, (err, results) => {
    if (err) {
      logger.info('ERROR::::while sending reminder' + err);
    }
    emailApi.sendEmailApi(
      `Scheduled Reminder `,
      'Scheduled Reminder',
      results,
      subcriptiondata.email,
      'Mail sent failure',
      'Mail sent successfully',
      process.env.EMAIL_SENDER
    );
  });

}, null, true, 'America/Toronto');

I have deployed and tried both the codes however none of them are working as I'm not receiving any emails for the scheduled date.It would be great if someone here can help me with this on what I'm doing wrong here and I would prefer the second one i.e, using cron module as it persists server restarts.

Update: I have tried with every 5 mins trigger an email instead of specific date and I did received emails in this case.


问:
Insert a bulk of records into the Postgresql DB using Sails.js and Waterline ORM
I need to insert a bulk of records into the Postgresql database using the Sails.js framework and the Waterline ORM. I have a file with 100k records of users and their links:

```<code>// users.txt
line 1 {"firstname":"name1","lastname":"last1","email":"test1@gmail.com","phone":"+3801","links":[1]}
line 2 {"firstname":"name2","lastname":"last2","email":"test2@gmail.com","phone":"+3802","links":[2]}
line 3 {"firstname":"name3","lastname":"last3","email":"test3@gmail.com","phone":"+3803","links":[3]}
...

// links.txt
line 1 {"url":"http://linkedin.com/1","socialNetwork":3,"user":1}
line 2 {"url":"http://facebook.com/2","socialNetwork":2,"user":2}
line 3 {"url":"http://twitter.com/3","socialNetwork":1,"user":3}
...
</code>```

I have the users model and the links model, with the many-to-many associations:

```<code>// User.js
module.exports = {
  tableName: 'users',
  attributes: {
  firstname: {
      type: 'string',
      required: true,
    },
  lastname: {
      type: 'string',
      required: true,
    },
  email: {
      type: 'string',
      required: true,
      unique: true,
    },
  phone: {
      type: 'string',
      unique: true,
   },
  links: {
      collection: 'link',
      via: 'user',
    },
  },
};

// Link.js

module.exports = {
  tableName: 'links',
  schema: false,
  attributes: {
  url: {
      type: 'string',
      required: true,
      unique: true,
    },
  socialNetwork: {
      model: 'socialnetwork',
    },
  user: {
      collection: 'user',
      via: 'links',
    },
  },
};
</code>```

and an endpoint to generate the records and save them to the database. I've tried to read the data from the file synchronously and then insert it into the database with chunks of 10k records, 10 times:

```<code>generateUsers: async (req, res) => {
    const links = readFileSync('./api/db/links.txt').toString().replace(/\r\n/g, '\n').split('\n');
    const users = readFileSync('./api/db/users.txt').toString().replace(/\r\n/g, '\n').split('\n');

    const mappedL = links.map((l) => JSON.parse(l));
    const mappedU = users.map((l) => JSON.parse(l));

    await sails.getDatastore().transaction(async (db) => {
      const chunk = links.length > 10000 ? 10000 : links.length;

      for (let i = 0; i < users.length; i += chunk) {
        let chunkArray = mappedL.slice(i, i + chunk);
        Link.createEach(chunkArray).usingConnection(db) ;

        chunkArray = mappedU.slice(i, i + chunk);
        await User.createEach(chunkArray).usingConnection(db);
      }
    });
    return res.ok(users.length + ' users were generated and inserted.');
</code>```

But that takes a long time to insert... and I have no idea, to be honest, how to manage this (via Sails.js and Waterline ORM). I've thought about doing it via streams (reading from the file and simultaneously inserting it into the database), but I couldn't figure out how. I would appreciate any help, thank you!

Body:
I need to insert a bulk of records into the Postgresql database using the Sails.js framework and the Waterline ORM. I have a file with 100k records of users and their links:

// users.txt
line 1 {"firstname":"name1","lastname":"last1","email":"test1@gmail.com","phone":"+3801","links":[1]}
line 2 {"firstname":"name2","lastname":"last2","email":"test2@gmail.com","phone":"+3802","links":[2]}
line 3 {"firstname":"name3","lastname":"last3","email":"test3@gmail.com","phone":"+3803","links":[3]}
...

// links.txt
line 1 {"url":"http://linkedin.com/1","socialNetwork":3,"user":1}
line 2 {"url":"http://facebook.com/2","socialNetwork":2,"user":2}
line 3 {"url":"http://twitter.com/3","socialNetwork":1,"user":3}
...

I have the users model and the links model, with the many-to-many associations:

// User.js
module.exports = {
  tableName: 'users',
  attributes: {
  firstname: {
      type: 'string',
      required: true,
    },
  lastname: {
      type: 'string',
      required: true,
    },
  email: {
      type: 'string',
      required: true,
      unique: true,
    },
  phone: {
      type: 'string',
      unique: true,
   },
  links: {
      collection: 'link',
      via: 'user',
    },
  },
};

// Link.js

module.exports = {
  tableName: 'links',
  schema: false,
  attributes: {
  url: {
      type: 'string',
      required: true,
      unique: true,
    },
  socialNetwork: {
      model: 'socialnetwork',
    },
  user: {
      collection: 'user',
      via: 'links',
    },
  },
};

and an endpoint to generate the records and save them to the database. I've tried to read the data from the file synchronously and then insert it into the database with chunks of 10k records, 10 times:

generateUsers: async (req, res) => {
    const links = readFileSync('./api/db/links.txt').toString().replace(/\r\n/g, '\n').split('\n');
    const users = readFileSync('./api/db/users.txt').toString().replace(/\r\n/g, '\n').split('\n');

    const mappedL = links.map((l) => JSON.parse(l));
    const mappedU = users.map((l) => JSON.parse(l));

    await sails.getDatastore().transaction(async (db) => {
      const chunk = links.length > 10000 ? 10000 : links.length;

      for (let i = 0; i < users.length; i += chunk) {
        let chunkArray = mappedL.slice(i, i + chunk);
        Link.createEach(chunkArray).usingConnection(db) ;

        chunkArray = mappedU.slice(i, i + chunk);
        await User.createEach(chunkArray).usingConnection(db);
      }
    });
    return res.ok(users.length + ' users were generated and inserted.');

But that takes a long time to insert... and I have no idea, to be honest, how to manage this (via Sails.js and Waterline ORM). I've thought about doing it via streams (reading from the file and simultaneously inserting it into the database), but I couldn't figure out how. I would appreciate any help, thank you!


问:
Can I directly replace @RunWith(PowerMockRunner.class) with @RunWith(MockitoJunitRunner.class)
@RunWith(PowerMockRunner.class) is not working with Eclemma and it is  showing 0% coverage for the classes annotated with @RunWith(PowerMockRunner.class)
If I replace @RunWith(PowerMockRunner.class) with @RunWith(MockitoJunitRunner.class) the code coverage is showing correctly.
If I replace @RunWith(PowerMockRunner.class) with @RunWith(MockitoJunitRunner.class) will it impact on existing test cases.
If this approach does not work then let me know an alternate option for @RunWith(PowerMockRunner.class)

Tried to get solution for @RunWith(PowerMockRunner.class) but no luck


问:
Combining HTML/JavaScript/Node - Bug in using the prompt function to retrieve input when using the fetch module
Using the fetch module in VS Code, is preventing the use of the prompt function when trying to input information through the HTML browser.

Details:

When using the fetch module in a recent script i.e.

```<code>import fetch from "node-fetch";
</code>```

I found that when I tried to retrieve user input using the prompt function it failed and returned the following error:

```<code>Uncaught SyntaxError SyntaxError: Cannot use import statement outside a module
</code>```

From looking around I read that you need to change the script call from:

```<code><script type='text/javascript' src='test.js'></script>
</code>```

to:

```<code><script type='module' src='test.js'></script>
</code>```

This removed the error message but still failed to bring the prompt when running the HTML page. Only by removing the import line will the prompt function run as expected.

Does anyone know why this is happening and know how to resolve this?

Body:
Using the fetch module in VS Code, is preventing the use of the prompt function when trying to input information through the HTML browser.

Details:

When using the fetch module in a recent script i.e.

import fetch from "node-fetch";

I found that when I tried to retrieve user input using the prompt function it failed and returned the following error:

Uncaught SyntaxError SyntaxError: Cannot use import statement outside a module

From looking around I read that you need to change the script call from:

to:

This removed the error message but still failed to bring the prompt when running the HTML page. Only by removing the import line will the prompt function run as expected.

Does anyone know why this is happening and know how to resolve this?


问:
Antd some row properties are not reactive, is it bug or feature, or the code is wrong?
I'm trying to implement the dynamic Row's properties and found justify and align are not updated when the props are updated. Not sure why, maybe something is wrong with the code?

```<code>import React, { useState } from "react";
import "./index.css";
import { Col, Row, Button, Select } from "antd";
const App = () => {
  const [justify, setjustify] = useState("end");
  return (
    <>
      {justify}
      <Select
        value={justify}
        options={[
          { value: "start", label: "start" },
          { value: "end", label: "end" }
        ]}
        onChange={(val) => {
          setjustify(val);
        }}
      />
      <Row justify={justify} style={{ height: "150px" }} align="bottom">
        <Button type="primary">button1</Button>
        <Button type="primary">button</Button>
      </Row>
    </>
  );
};
export default App;
</code>```

The justify property is changed only on the load, not dynamically. I mean the row is not updated on the property's change.

The code to play with is here: https://codesandbox.io/s/grid-sort-antd-5-0-7-forked-85qlli?file=/demo.js:0-662

Body:
I'm trying to implement the dynamic Row's properties and found justify and align are not updated when the props are updated. Not sure why, maybe something is wrong with the code?

import React, { useState } from "react";
import "./index.css";
import { Col, Row, Button, Select } from "antd";
const App = () => {
  const [justify, setjustify] = useState("end");
  return (
    <>
      {justify}
      <Select
        value={justify}
        options={[
          { value: "start", label: "start" },
          { value: "end", label: "end" }
        ]}
        onChange={(val) => {
          setjustify(val);
        }}
      />
      <Row justify={justify} style={{ height: "150px" }} align="bottom">
        <Button type="primary">button1</Button>
        <Button type="primary">button</Button>
      </Row>
    </>
  );
};
export default App;

The justify property is changed only on the load, not dynamically. I mean the row is not updated on the property's change.

The code to play with is here: https://codesandbox.io/s/grid-sort-antd-5-0-7-forked-85qlli?file=/demo.js:0-662


问:
Estimote Proximity Beacons are not being detected on Android App
I am using a modified version of a template app provided within the Estimote Cloud and I want "Toasts" to be displayed when entering/exiting zones. However, these Toasts are not being displayed

MainActivity

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, 2);
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);

    proximityContentAdapter = new ProximityContentAdapter(this);
    List<ProximityContent> nearbyContent = new ArrayList<>(1);
    proximityContentAdapter.setNearbyContent(nearbyContent);
    GridView gridView = findViewById(R.id.gridView);
    gridView.setAdapter(proximityContentAdapter);

    ProximityObserver proximityObserver = new ProximityObserverBuilder(getApplicationContext(), ((MyApplication) getApplication()).cloudCredentials)
            .withBalancedPowerMode()
            .onError(new Function1<Throwable, Unit>() {
                @Override
                public Unit invoke(Throwable throwable) {
                    Toast.makeText(getApplicationContext(), "POE " + throwable, Toast.LENGTH_LONG).show();
                    return null;
                }
            })
            .build();

    ProximityZone venueZone =
            new ProximityZoneBuilder()
                    .forTag("desk")
                    .inFarRange()
                    .onEnter(new Function1<ProximityZoneContext, Unit>() {
                        @Override public Unit invoke(ProximityZoneContext proximityContext) {
                            Toast.makeText(getApplicationContext(),"OnEnter", Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .onExit(new Function1<ProximityZoneContext, Unit>() {
                        @Override
                        public Unit invoke(ProximityZoneContext proximityContext) {
                            Toast.makeText(getApplicationContext(),"OnExit", Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .onContextChange(new Function1<Set<? extends ProximityZoneContext>, Unit>() {
                        @Override
                        public Unit invoke(Set<? extends ProximityZoneContext> contexts) {
                            Toast.makeText(getApplicationContext(),"OnContextChanged",
Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .build();

    RequirementsWizardFactory
            .createEstimoteRequirementsWizard()
            .fulfillRequirements(this,
                    new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            Log.d("app", "requirements fulfilled");
                            proximityObserver.startObserving(venueZone);
                            return null;
                        }
                    },
                    new Function1<List<? extends Requirement>, Unit>() {
                        @Override
                        public Unit invoke(List<? extends Requirement> requirements) {
                            Log.e("app", "requirements missing: " + requirements);
                            Toast.makeText(MainActivity.this, "requirements missing: " + requirements, Toast.LENGTH_LONG).show();
                            return null;
                        }
                    },
                    new Function1<Throwable, Unit>() {
                        @Override
                        public Unit invoke(Throwable throwable) {
                            Log.e("app", "requirements error: " + throwable);
                            Toast.makeText(MainActivity.this, "requirements error: " + throwable, Toast.LENGTH_LONG).show();
                            return null;
                        }
                    });
}
</code>```

Furthermore, no errors are being thrown!

I've attempted only using a single beacon and removing the batteries to test if the onExit method, within the ProximityZone object, would work, but nothing.

I'm testing on a real device, Galaxy A53 5G using Android 12.

It may be also worth noting that when this application is running in the background the official Estimote app is unable to detect nearby beacons either.

Body:
I am using a modified version of a template app provided within the Estimote Cloud and I want "Toasts" to be displayed when entering/exiting zones. However, these Toasts are not being displayed

MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = ActivityMainBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.BLUETOOTH_SCAN}, 2);
    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);

    proximityContentAdapter = new ProximityContentAdapter(this);
    List<ProximityContent> nearbyContent = new ArrayList<>(1);
    proximityContentAdapter.setNearbyContent(nearbyContent);
    GridView gridView = findViewById(R.id.gridView);
    gridView.setAdapter(proximityContentAdapter);

    ProximityObserver proximityObserver = new ProximityObserverBuilder(getApplicationContext(), ((MyApplication) getApplication()).cloudCredentials)
            .withBalancedPowerMode()
            .onError(new Function1<Throwable, Unit>() {
                @Override
                public Unit invoke(Throwable throwable) {
                    Toast.makeText(getApplicationContext(), "POE " + throwable, Toast.LENGTH_LONG).show();
                    return null;
                }
            })
            .build();

    ProximityZone venueZone =
            new ProximityZoneBuilder()
                    .forTag("desk")
                    .inFarRange()
                    .onEnter(new Function1<ProximityZoneContext, Unit>() {
                        @Override public Unit invoke(ProximityZoneContext proximityContext) {
                            Toast.makeText(getApplicationContext(),"OnEnter", Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .onExit(new Function1<ProximityZoneContext, Unit>() {
                        @Override
                        public Unit invoke(ProximityZoneContext proximityContext) {
                            Toast.makeText(getApplicationContext(),"OnExit", Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .onContextChange(new Function1<Set<? extends ProximityZoneContext>, Unit>() {
                        @Override
                        public Unit invoke(Set<? extends ProximityZoneContext> contexts) {
                            Toast.makeText(getApplicationContext(),"OnContextChanged",
Toast.LENGTH_LONG).show();
                            return null;
                        }
                    })
                    .build();

    RequirementsWizardFactory
            .createEstimoteRequirementsWizard()
            .fulfillRequirements(this,
                    new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            Log.d("app", "requirements fulfilled");
                            proximityObserver.startObserving(venueZone);
                            return null;
                        }
                    },
                    new Function1<List<? extends Requirement>, Unit>() {
                        @Override
                        public Unit invoke(List<? extends Requirement> requirements) {
                            Log.e("app", "requirements missing: " + requirements);
                            Toast.makeText(MainActivity.this, "requirements missing: " + requirements, Toast.LENGTH_LONG).show();
                            return null;
                        }
                    },
                    new Function1<Throwable, Unit>() {
                        @Override
                        public Unit invoke(Throwable throwable) {
                            Log.e("app", "requirements error: " + throwable);
                            Toast.makeText(MainActivity.this, "requirements error: " + throwable, Toast.LENGTH_LONG).show();
                            return null;
                        }
                    });
}

Furthermore, no errors are being thrown!

I've attempted only using a single beacon and removing the batteries to test if the onExit method, within the ProximityZone object, would work, but nothing.

I'm testing on a real device, Galaxy A53 5G using Android 12.

It may be also worth noting that when this application is running in the background the official Estimote app is unable to detect nearby beacons either.


问:
Duplicate headers while running API regression tests
how are you?

I'm having trouble running my automated API test suite.

Problem:

When I run the API tests within a JUnit5 suite class, I noticed that with each test run, the Header of my request is duplicated or even tripled. This results in the failure of further tests.

The strange thing is that the tests that fail in this run work normally when run individually.

```<code>private static RequestSpecification reqSpec;
private static ResponseSpecification respSpec;

@BeforeAll
public static void setup(){

    baseURI = BASE_URI;
    port = PORT;

    reqSpec = new RequestSpecBuilder()
            .log(LogDetail.ALL)
            .setContentType(CONTENT_TYPE)
            .setAccept("application/json")
            .build();

    respSpec = new ResponseSpecBuilder()
            .expectResponseTime(lessThan(TIMEOUT))
            .log(LogDetail.ALL)
            .build();

    requestSpecification = reqSpec;
    responseSpecification = respSpec;
}
</code>```

In the code above, center the RequestSpecification in a @BeforeAll for each test case.

```<code>
</code>```
```<code>package tests.booker;

import core.BaseRequestSpecification;
import entities.PayLoads;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
public class CreateBooking extends BaseRequestSpecification {

    private final String RESOURCE_BOOKER_ID = "booking";

    @Test
    @DisplayName("Listar IDs de Bookings")
    public void listarIDsDeBooking() {

                given()
                    .body(PayLoads.criarNewBooking())
                    .pathParams("recurso", RESOURCE_BOOKER_ID)
                .when()
                    .post("/{recurso}")
                .then()
                    .statusCode(HttpStatus.SC_OK);
    }
}
</code>```
```<code>Request method: POST
Request URI:    https://restful-booker.herokuapp.com:443/booking
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    recurso=booking
Headers:        Accept=application/json
                Content-Type=application/json
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "firstname": "Rafael",
    "lastname": "Pereira",
    "totalprice": 350,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2022-01-01",
        "checkout": "2022-09-08"
    },
    "additionalneeds": "Breakfast"
}
Request method: POST
Request URI:    https://restful-booker.herokuapp.com:443/booking
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    recurso=booking
Headers:        Accept=application/json
                Content-Type=application/json
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "firstname": "Rafael",
    "lastname": "Pereira",
    "totalprice": 350,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2022-01-01",
        "checkout": "2022-09-08"
    },
    "additionalneeds": "Breakfast"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 202
Etag: W/"ca-SeG/svUxAe31ACn85hvsVDB4nWM"
Date: Sun, 18 Dec 2022 03:34:57 GMT
Via: 1.1 vegur

{
    "bookingid": 1897,
    "booking": {
        "firstname": "Rafael",
        "lastname": "Pereira",
        "totalprice": 350,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2022-01-01",
            "checkout": "2022-09-08"
        },
        "additionalneeds": "Breakfast"
    }
}

</code>```

looking at the console output, they noticed that the API header is assembled a second time. this occurs with the other tests in the suite.

A similar problem: Duplicate headers are added at runtime in Rest assured

Body:
how are you?

I'm having trouble running my automated API test suite.

Problem:

When I run the API tests within a JUnit5 suite class, I noticed that with each test run, the Header of my request is duplicated or even tripled. This results in the failure of further tests.

The strange thing is that the tests that fail in this run work normally when run individually.

private static RequestSpecification reqSpec;
private static ResponseSpecification respSpec;

@BeforeAll
public static void setup(){

    baseURI = BASE_URI;
    port = PORT;

    reqSpec = new RequestSpecBuilder()
            .log(LogDetail.ALL)
            .setContentType(CONTENT_TYPE)
            .setAccept("application/json")
            .build();

    respSpec = new ResponseSpecBuilder()
            .expectResponseTime(lessThan(TIMEOUT))
            .log(LogDetail.ALL)
            .build();

    requestSpecification = reqSpec;
    responseSpecification = respSpec;
}

In the code above, center the RequestSpecification in a @BeforeAll for each test case.

package tests.booker;

import core.BaseRequestSpecification;
import entities.PayLoads;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
public class CreateBooking extends BaseRequestSpecification {

    private final String RESOURCE_BOOKER_ID = "booking";

    @Test
    @DisplayName("Listar IDs de Bookings")
    public void listarIDsDeBooking() {

                given()
                    .body(PayLoads.criarNewBooking())
                    .pathParams("recurso", RESOURCE_BOOKER_ID)
                .when()
                    .post("/{recurso}")
                .then()
                    .statusCode(HttpStatus.SC_OK);
    }
}

Request method: POST
Request URI:    https://restful-booker.herokuapp.com:443/booking
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    recurso=booking
Headers:        Accept=application/json
                Content-Type=application/json
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "firstname": "Rafael",
    "lastname": "Pereira",
    "totalprice": 350,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2022-01-01",
        "checkout": "2022-09-08"
    },
    "additionalneeds": "Breakfast"
}
Request method: POST
Request URI:    https://restful-booker.herokuapp.com:443/booking
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    recurso=booking
Headers:        Accept=application/json
                Content-Type=application/json
Cookies:        <none>
Multiparts:     <none>
Body:
{
    "firstname": "Rafael",
    "lastname": "Pereira",
    "totalprice": 350,
    "depositpaid": true,
    "bookingdates": {
        "checkin": "2022-01-01",
        "checkout": "2022-09-08"
    },
    "additionalneeds": "Breakfast"
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 202
Etag: W/"ca-SeG/svUxAe31ACn85hvsVDB4nWM"
Date: Sun, 18 Dec 2022 03:34:57 GMT
Via: 1.1 vegur

{
    "bookingid": 1897,
    "booking": {
        "firstname": "Rafael",
        "lastname": "Pereira",
        "totalprice": 350,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2022-01-01",
            "checkout": "2022-09-08"
        },
        "additionalneeds": "Breakfast"
    }
}

looking at the console output, they noticed that the API header is assembled a second time. this occurs with the other tests in the suite.

A similar problem: Duplicate headers are added at runtime in Rest assured


问:
How to change size of pixel square using createImageData in html canvas?
I need to draw some pixels which gonna be palette colors for my character. I done this but it is too small because it is 1:1. How can I change size of it, to be much bigger without losing quality? I have an array where I am holding data about RGB color about every single pixel. I just want to draw it much bigger, like 4x times bigger. 1 pixel should be square 2x2.

Here is my code:

```<code>// palette is an array[256] of objects RGB

function drawPalette(palette) {
    const palWidth = 8;
    const palHeight = 32;
    document.getElementById('palette-canvas').width = palWidth;
    document.getElementById('palette-canvas').height = palHeight;

    var canvas = document.querySelector('#palette-canvas');
    var context = canvas.getContext('2d');

    var image = context.createImageData(canvas.width, canvas.height);
    var data = image.data;

    var x = 0;
    var y = 0;
    palette.rgba.forEach(color => {
        if (y == palHeight) {
            return;
        }
        drawPixel(x, y, color);
        x++;
        if (x == palWidth) {
            x = 0;
            y++;
        }
    });
    swapBuffer();

    function drawPixel(x, y, color) {
        var roundedX = Math.round(x);
        var roundedY = Math.round(y);

        var index = 4 * (canvas.width * roundedY + roundedX);
        data[index + 0] = color.r;
        data[index + 1] = color.g;
        data[index + 2] = color.b;
        data[index + 3] = 255;
    }

    function swapBuffer() {
        context.putImageData(image, 0, 0);
    }
}
</code>```

This is how its looks like. It is valid but size is 1:1. Look left bottom corner

This is how it should be.

Body:
I need to draw some pixels which gonna be palette colors for my character. I done this but it is too small because it is 1:1. How can I change size of it, to be much bigger without losing quality? I have an array where I am holding data about RGB color about every single pixel. I just want to draw it much bigger, like 4x times bigger. 1 pixel should be square 2x2.

Here is my code:

// palette is an array[256] of objects RGB

function drawPalette(palette) {
    const palWidth = 8;
    const palHeight = 32;
    document.getElementById('palette-canvas').width = palWidth;
    document.getElementById('palette-canvas').height = palHeight;

    var canvas = document.querySelector('#palette-canvas');
    var context = canvas.getContext('2d');

    var image = context.createImageData(canvas.width, canvas.height);
    var data = image.data;

    var x = 0;
    var y = 0;
    palette.rgba.forEach(color => {
        if (y == palHeight) {
            return;
        }
        drawPixel(x, y, color);
        x++;
        if (x == palWidth) {
            x = 0;
            y++;
        }
    });
    swapBuffer();

    function drawPixel(x, y, color) {
        var roundedX = Math.round(x);
        var roundedY = Math.round(y);

        var index = 4 * (canvas.width * roundedY + roundedX);
        data[index + 0] = color.r;
        data[index + 1] = color.g;
        data[index + 2] = color.b;
        data[index + 3] = 255;
    }

    function swapBuffer() {
        context.putImageData(image, 0, 0);
    }
}

This is how its looks like. It is valid but size is 1:1. Look left bottom corner

This is how it should be.


问:
I'm trying to open a new project for the first time in React and I installed node.js and I get this error:

C:\Users\user\Desktop\נעמי תכנות\react\app_nomy>npx create-react-app app_nomy
npm ERR! code ETIMEDOUT
npm ERR! syscall connect
npm ERR! errno ETIMEDOUT
npm ERR! network request to https://registry.npmjs.org/create-react-app failed, reason: connect ETIMEDOUT 2606:4700::6810:1123:443
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\user\AppData\Local\npm-cache_logs\2022-12-17T19_17_13_700Z-debug-0.log

I have tried all kinds of operations of deleting the proxy and resetting it and nothing helps me. I would really appreciate it if someone could go through it step by step with me and try to help me


问:
Why is @pytest.fixture passed as an argument to tests but not used
Below is a test file for the Streamlink library. I was reading the test files to understand how testing is done and found a confusing set up for the tests. The test set up a series of @pytest.fixtures to help with testing. The assert_live fixture below is defined and passed into some tests, but never called at all. I dont think this is a mistake because a similar pattern is found throughout the file. I read the docs for fixtures but couldn't find anything that mentions this functionality. I got excited when they talked about using yeild inside a fixture but that turned not to touch on the subject either. Google was even less helpful. I am at a loss, but I am very interested in contributing to this library and need to understand how it works and how they test. Test is at the bottom of the code below. Thank you in advance!

```<code> # Other fixtures for context/continuity
 @pytest.fixture
def mocker(self):
    # The built-in requests_mock fixture is bad when trying to reference the following constants or classes
    with requests_mock.Mocker() as mocker:
        mocker.register_uri(requests_mock.ANY, requests_mock.ANY, exc=requests_mock.exceptions.InvalidRequest)
        yield mocker

@pytest.fixture
def mock(self, request, mocker: requests_mock.Mocker):
    mock = mocker.post("https://gql.twitch.tv/gql", **getattr(request, "param", {"json": {}}))
    yield mock
    assert mock.called_once
    payload = mock.last_request.json()  # type: ignore[union-attr]
    assert tuple(sorted(payload.keys())) == ("extensions", "operationName", "variables")
    assert payload.get("operationName") == "PlaybackAccessToken"
    assert payload.get("extensions") == {
        "persistedQuery": {
            "sha256Hash": "0828119ded1c13477966434e15800ff57ddacf13ba1911c129dc2200705b0712",
            "version": 1,
        },
    }
# The confusing fixture
@pytest.fixture
def assert_live(self, mock):
    yield
    assert mock.last_request.json().get("variables") == {  # type: ignore[union-attr]
        "isLive": True,
        "isVod": False,
        "login": "channelname",
        "vodID": "",
        "playerType": "embed",
    }

# The confusing test
# note that assert_live is passed as an arg but is not actually used.
@pytest.mark.parametrize("plugin,mock", [
    (
        [("api-header", [("Authorization", "OAuth invalid-token")])],
        {
            "status_code": 401,
            "json": {"error": "Unauthorized", "status": 401, "message": "The \"Authorization\" token is invalid."},
        },
    ),
], indirect=True)
def test_auth_failure(self, caplog: pytest.LogCaptureFixture, plugin: Twitch, mock: requests_mock.Mocker, assert_live):
    with pytest.raises(NoStreamsError) as cm:
        plugin._access_token(True, "channelname")
    assert str(cm.value) == "No streams found on this URL: https://twitch.tv/channelname"
    assert mock.last_request._request.headers["Authorization"] == "OAuth invalid-token"  # type: ignore[union-attr]
    assert [(record.levelname, record.module, record.message) for record in caplog.records] == [
        ("error", "twitch", "Unauthorized: The \"Authorization\" token is invalid."),
    ]
</code>```

Body:
Below is a test file for the Streamlink library. I was reading the test files to understand how testing is done and found a confusing set up for the tests. The test set up a series of @pytest.fixtures to help with testing. The assert_live fixture below is defined and passed into some tests, but never called at all. I dont think this is a mistake because a similar pattern is found throughout the file. I read the docs for fixtures but couldn't find anything that mentions this functionality. I got excited when they talked about using yeild inside a fixture but that turned not to touch on the subject either. Google was even less helpful. I am at a loss, but I am very interested in contributing to this library and need to understand how it works and how they test. Test is at the bottom of the code below. Thank you in advance!

 # Other fixtures for context/continuity
 @pytest.fixture
def mocker(self):
    # The built-in requests_mock fixture is bad when trying to reference the following constants or classes
    with requests_mock.Mocker() as mocker:
        mocker.register_uri(requests_mock.ANY, requests_mock.ANY, exc=requests_mock.exceptions.InvalidRequest)
        yield mocker

@pytest.fixture
def mock(self, request, mocker: requests_mock.Mocker):
    mock = mocker.post("https://gql.twitch.tv/gql", **getattr(request, "param", {"json": {}}))
    yield mock
    assert mock.called_once
    payload = mock.last_request.json()  # type: ignore[union-attr]
    assert tuple(sorted(payload.keys())) == ("extensions", "operationName", "variables")
    assert payload.get("operationName") == "PlaybackAccessToken"
    assert payload.get("extensions") == {
        "persistedQuery": {
            "sha256Hash": "0828119ded1c13477966434e15800ff57ddacf13ba1911c129dc2200705b0712",
            "version": 1,
        },
    }
# The confusing fixture
@pytest.fixture
def assert_live(self, mock):
    yield
    assert mock.last_request.json().get("variables") == {  # type: ignore[union-attr]
        "isLive": True,
        "isVod": False,
        "login": "channelname",
        "vodID": "",
        "playerType": "embed",
    }

# The confusing test
# note that assert_live is passed as an arg but is not actually used.
@pytest.mark.parametrize("plugin,mock", [
    (
        [("api-header", [("Authorization", "OAuth invalid-token")])],
        {
            "status_code": 401,
            "json": {"error": "Unauthorized", "status": 401, "message": "The \"Authorization\" token is invalid."},
        },
    ),
], indirect=True)
def test_auth_failure(self, caplog: pytest.LogCaptureFixture, plugin: Twitch, mock: requests_mock.Mocker, assert_live):
    with pytest.raises(NoStreamsError) as cm:
        plugin._access_token(True, "channelname")
    assert str(cm.value) == "No streams found on this URL: https://twitch.tv/channelname"
    assert mock.last_request._request.headers["Authorization"] == "OAuth invalid-token"  # type: ignore[union-attr]
    assert [(record.levelname, record.module, record.message) for record in caplog.records] == [
        ("error", "twitch", "Unauthorized: The \"Authorization\" token is invalid."),
    ]


问:
VSCode Code Actions not working with Rust
I'm using VSCode with rust-analyzer. I can get the Code Actions menu to show up, but clicking on the items does nothing. How can I fix this?

Everything else works fine. It's only the Code Actions that aren't doing anything.

I've already tried updating/reinstalling VSCode, rust-analyzer, and Rust.


问:
JavaFX Scene builder - more objects without Scene builder
I created a GUI in Scenebuilder. 2 rectangles. A circle should be displayed for a KeyEvent. The circle is not displayed (playShoot()). Can objects be inserted without Scenebuilder? I think yes, but how?  Do you have an idea?

Controller Class

```<code>public class PlayAnonymController{

    @FXML
    private Rectangle PLAYER;

    @FXML
    private Label gamoverLabel;

    @FXML
    private Label scoreLabel;

  //Variablen
    public enum Direction {
        LEFT, RIGHT, SPACE, NONE
    }

    double cX;

    public static List<Circle> bullets = new ArrayList<>();

    @FXML
    public void movePlayer(KeyEvent event) throws IOException{
        KeyCode key = event.getCode();  // keyboard code for the pressed key
//        System.out.println("Key Pressed: " + key);  // for testing
            switch (event.getCode()) {
            case LEFT:
                moveLeft();
              break;
            case RIGHT:
                moveRight();
               break;
            case SPACE:
                playerShoot();
                break;
            }
    }

    public void playerShoot() {

    System.out.println("Test");
    Circle circle = new Circle(50, 50, 50);
    circle.setFill(Color.RED);
    }

    void moveLeft() {
        PLAYER.setTranslateX(cX-=10);
    }

    void moveRight() {
        PLAYER.setTranslateX(cX+=10);
    }
}
</code>```

My FXML file from Scenebuilder. At the bottom of   the circle should be visible after a KeyEvent.

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.shape.Rectangle?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.PlayAnonymController">
   <top>
      <BorderPane prefHeight="37.0" prefWidth="600.0" BorderPane.alignment="CENTER">
         <left>
            <Label fx:id="scoreLabel" text="Label" BorderPane.alignment="CENTER" />
         </left>
         <center>
            <Label fx:id="gamoverLabel" text="Label" BorderPane.alignment="CENTER" />
         </center>
      </BorderPane>
   </top>
   <bottom>
      <Label text="Move: Pfeiltaste links / recht. Schießen Space." BorderPane.alignment="CENTER" />
   </bottom>
   <center>
      <Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
         <children>
            <Rectangle fx:id="PLAYER" arcHeight="5.0" arcWidth="5.0" fill="#000911" height="5.0" layoutX="280.0" layoutY="305.0" onKeyPressed="#movePlayer" stroke="BLACK" strokeType="INSIDE" width="40.0" />
         </children>
      </Pane>
   </center>
</BorderPane>
</code>```

Body:
I created a GUI in Scenebuilder. 2 rectangles. A circle should be displayed for a KeyEvent. The circle is not displayed (playShoot()). Can objects be inserted without Scenebuilder? I think yes, but how?  Do you have an idea?

Controller Class

public class PlayAnonymController{

    @FXML
    private Rectangle PLAYER;

    @FXML
    private Label gamoverLabel;

    @FXML
    private Label scoreLabel;

  //Variablen
    public enum Direction {
        LEFT, RIGHT, SPACE, NONE
    }

    double cX;

    public static List<Circle> bullets = new ArrayList<>();

    @FXML
    public void movePlayer(KeyEvent event) throws IOException{
        KeyCode key = event.getCode();  // keyboard code for the pressed key
//        System.out.println("Key Pressed: " + key);  // for testing
            switch (event.getCode()) {
            case LEFT:
                moveLeft();
              break;
            case RIGHT:
                moveRight();
               break;
            case SPACE:
                playerShoot();
                break;
            }
    }

    public void playerShoot() {

    System.out.println("Test");
    Circle circle = new Circle(50, 50, 50);
    circle.setFill(Color.RED);
    }

    void moveLeft() {
        PLAYER.setTranslateX(cX-=10);
    }

    void moveRight() {
        PLAYER.setTranslateX(cX+=10);
    }
}

My FXML file from Scenebuilder. At the bottom of   the circle should be visible after a KeyEvent.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.shape.Rectangle?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controller.PlayAnonymController">
   <top>
      <BorderPane prefHeight="37.0" prefWidth="600.0" BorderPane.alignment="CENTER">
         <left>

         </left>

      </BorderPane>
   </top>
   <bottom>

   </bottom>

      <Pane prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER">
         <children>
            <Rectangle fx:id="PLAYER" arcHeight="5.0" arcWidth="5.0" fill="#000911" height="5.0" layoutX="280.0" layoutY="305.0" onKeyPressed="#movePlayer" stroke="BLACK" strokeType="INSIDE" width="40.0" />
         </children>
      </Pane>

</BorderPane>


问:
How do you make a variable change from one class to another in Kivy?
I am building a simple game using Kivy. I have two classes, Result() and Game(), where both are inheriting from 'Screen'. The Game Class has a function that calculates the the result of the game and produces a message which I want to display on the Result Screen which contains a label and the screen gets displayed after the result is calculated.
My KV file:

```<code><Result>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Result Screen"
        Label:
            id: result_label
</code>```

Using the id of the Label, 'result_label', I thought using would work `

```<code>Result().ids.result_label.text = "message"
</code>```

`
I tried confirming this using:

```<code>print(Result().ids)
</code>```

And yes it tells me that indeed the id does exist and so i expected that the previous block of code would change the text of the label to "message", but it just shows a Label with no text, and there is no error. So how would you change the text of a label from outside the class?

Body:
I am building a simple game using Kivy. I have two classes, Result() and Game(), where both are inheriting from 'Screen'. The Game Class has a function that calculates the the result of the game and produces a message which I want to display on the Result Screen which contains a label and the screen gets displayed after the result is calculated.
My KV file:

<Result>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Result Screen"
        Label:
            id: result_label

Using the id of the Label, 'result_label', I thought using would work `

Result().ids.result_label.text = "message"

`
I tried confirming this using:

print(Result().ids)

And yes it tells me that indeed the id does exist and so i expected that the previous block of code would change the text of the label to "message", but it just shows a Label with no text, and there is no error. So how would you change the text of a label from outside the class?


问:
Python + NNI | Why am I getting a "free(): invalid pointer Aborted (core dumped)" error?
I am trying to use Microsoft/NNI for NAS, but I got this error:

```<code>free(): invalid pointer
Aborted (core dumped)
</code>```

This is my code:

```<code>import torch
import torch.nn.functional as F
import nni.retiarii.nn.pytorch as nn
from nni.retiarii import model_wrapper

@model_wrapper      # this decorator should be put on the out most
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(self.conv2(x), 2)
        x = torch.flatten(self.dropout1(x), 1)
        x = self.fc2(self.dropout2(F.relu(self.fc1(x))))
        output = F.log_softmax(x, dim=1)
        return output
</code>```

I ran this code on Ubuntu 20.04
python = 3.8

Body:
I am trying to use Microsoft/NNI for NAS, but I got this error:

free(): invalid pointer
Aborted (core dumped)

This is my code:

import torch
import torch.nn.functional as F
import nni.retiarii.nn.pytorch as nn
from nni.retiarii import model_wrapper

@model_wrapper      # this decorator should be put on the out most
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.max_pool2d(self.conv2(x), 2)
        x = torch.flatten(self.dropout1(x), 1)
        x = self.fc2(self.dropout2(F.relu(self.fc1(x))))
        output = F.log_softmax(x, dim=1)
        return output

I ran this code on Ubuntu 20.04
python = 3.8


问:
How do i add (android and apple) files on mobile pygame Replit
I was looking for a way to code on the go and I found replit which has many programming languages, the one I found and I use is pygame. Everything (so far) has been working fine except I don’t know how to load my (both android and apple) files in to the system so I can easily upload sprites or anything else

Because this is more of a technical problem I haven’t been able to do anything other then ask the community but they were no responses.


问:
BigQuery Internal Error with `pageToken` when running in GCP
I run into this error with BigQuery:

```<code>"An internal error occurred and the request could not be completed. This is usually caused by a transient issue. Retrying the job with back-off as described in the BigQuery SLA should solve the problem: https://cloud.google.com/bigquery/sla. If the error continues to occur please contact support at https://cloud.google.com/support. Error: 5034996"
</code>```

Two application use the same way with pageToken to paginate trough big result sets.

run query with initital startIndex: 0, maxResults: 10

get result together with pageToken

send to client

... some time may pass ...

request "next page": use pageToken together with maxResults: 10 to get the next result

repeat from 3.

NodeJS 16, @google-cloud/bigquery 6.0.3

Locally (Windows 10), for both application every thing works, pagination with pageToken returns results quite fast (<5s). All steps 1 to 6 and requesting multiple next pages one after another works, even tested that the pageToken still works after 60min+.

Production Cloud has problems: the initial query works always, but as soon as a pageToken is given, the query fails after ~15s+, even when "requested the next page directly (1-5s. delay) after getting the first page". Steps 1 to 3 work, but requesting next page fails nearly most time, it's very rare that it doesn't fail.

Production uses Google Cloud Functions and Google Cloud Run to serve the applications.

One application is an internal experiment, this application uses the same dataset + table when running locally and when running in "production".

The other application uses the same dataset but different tables for local/production - and is in another Google Cloud project than the first application.

Thus project-level quotas or e.g. different table setups locally/prod shouldn't cause the issue here (hopefully).

Example code used:

```<code>const [rows, , jobQueryResults] = await (job.getQueryResults(
    ('maxResults' in paginate ?
        {
            // there seems to be no need to give the startIndex again / but tested it also with giving a stable `0` index; atm. as soon as a pageToken is given the `startIndex` is omitted
            startIndex: paginate.pageToken ? undefined : paginate.startIndex,
            maxResults: paginate.maxResults,
            pageToken: paginate.pageToken,
        } : undefined) as QueryResultsOptions,
) as Promise<QueryRowsResponse>)
</code>```

What wonders me is that the pageToken isn't shown in the log of the failure, the maxResults is visible:

Edit

The error suggests some SLA problem, one of the GCP projects only include experimentals (non public) applications, thus any traffic/usage can be easily monitored.

The monitoring for BigQuery in that project shows roughly 1 job per 1 second when testing it, job 1+2 where "load without pageToken" -> 3 used the pageToken from 2 and run into an error, the retries must happen from BigQuery side, there is nothing implemented from my side (using only the official BigQuery package).

Body:
I run into this error with BigQuery:

"An internal error occurred and the request could not be completed. This is usually caused by a transient issue. Retrying the job with back-off as described in the BigQuery SLA should solve the problem: https://cloud.google.com/bigquery/sla. If the error continues to occur please contact support at https://cloud.google.com/support. Error: 5034996"

Two application use the same way with pageToken to paginate trough big result sets.

run query with initital startIndex: 0, maxResults: 10

get result together with pageToken

send to client

... some time may pass ...

request "next page": use pageToken together with maxResults: 10 to get the next result

repeat from 3.

NodeJS 16, @google-cloud/bigquery 6.0.3

Locally (Windows 10), for both application every thing works, pagination with pageToken returns results quite fast (<5s). All steps 1 to 6 and requesting multiple next pages one after another works, even tested that the pageToken still works after 60min+.

Production Cloud has problems: the initial query works always, but as soon as a pageToken is given, the query fails after ~15s+, even when "requested the next page directly (1-5s. delay) after getting the first page". Steps 1 to 3 work, but requesting next page fails nearly most time, it's very rare that it doesn't fail.

Production uses Google Cloud Functions and Google Cloud Run to serve the applications.

One application is an internal experiment, this application uses the same dataset + table when running locally and when running in "production".

The other application uses the same dataset but different tables for local/production - and is in another Google Cloud project than the first application.

Thus project-level quotas or e.g. different table setups locally/prod shouldn't cause the issue here (hopefully).

Example code used:

const [rows, , jobQueryResults] = await (job.getQueryResults(
    ('maxResults' in paginate ?
        {
            // there seems to be no need to give the startIndex again / but tested it also with giving a stable `0` index; atm. as soon as a pageToken is given the `startIndex` is omitted
            startIndex: paginate.pageToken ? undefined : paginate.startIndex,
            maxResults: paginate.maxResults,
            pageToken: paginate.pageToken,
        } : undefined) as QueryResultsOptions,
) as Promise<QueryRowsResponse>)

What wonders me is that the pageToken isn't shown in the log of the failure, the maxResults is visible:

Edit

The error suggests some SLA problem, one of the GCP projects only include experimentals (non public) applications, thus any traffic/usage can be easily monitored.

The monitoring for BigQuery in that project shows roughly 1 job per 1 second when testing it, job 1+2 where "load without pageToken" -> 3 used the pageToken from 2 and run into an error, the retries must happen from BigQuery side, there is nothing implemented from my side (using only the official BigQuery package).


问:
Callback on dash_leaflet to print range of current map
How can I trigger a callback-event when zooming (in or out) in dash_leaflet which gives me the current range of the shown map (the minimal/maximal x/y position)?

Here a minimal working example with a callback which gives me the center, but not the x/y range.

```<code>import dash
import dash_leaflet as dl
import dash_html_components as html
import json

from dash.dependencies import Output, Input, State

app = dash.Dash()
app.layout = html.Div([
dl.Map(dl.TileLayer(), style={'width': '1000px', 'height': '500px'}, id="map"),
html.Div(id="output1"), html.Div(id="output2"), html.Div(id="output3")
])

@app.callback(Output("output1", "children"), [Input("map", "zoom")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

@app.callback(Output("output2", "children"), [Input("map", "center")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

@app.callback(Output("output3", "children"), [Input("map", "viewport")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

if __name__ == '__main__':
        app.run_server()
</code>```

Body:
How can I trigger a callback-event when zooming (in or out) in dash_leaflet which gives me the current range of the shown map (the minimal/maximal x/y position)?

Here a minimal working example with a callback which gives me the center, but not the x/y range.

import dash
import dash_leaflet as dl
import dash_html_components as html
import json

from dash.dependencies import Output, Input, State

app = dash.Dash()
app.layout = html.Div([
dl.Map(dl.TileLayer(), style={'width': '1000px', 'height': '500px'}, id="map"),
html.Div(id="output1"), html.Div(id="output2"), html.Div(id="output3")
])

@app.callback(Output("output1", "children"), [Input("map", "zoom")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

@app.callback(Output("output2", "children"), [Input("map", "center")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

@app.callback(Output("output3", "children"), [Input("map", "viewport")])
def func(viewport):
        print(viewport)
        return json.dumps(viewport)

if __name__ == '__main__':
        app.run_server()


问:
UMQTT.simple function to check client.ping() call back
I am trying to get my head around UMQTT.simple. I am looking to handle instances in which my server might disconnect for a reboot. I want to check whether the client is connected, and if not, wait some period and try to reconnect.The guidance seems to be to use client.ping() for this (How to check Micropython umqtt client is connected?).

For the MQTT.paho client I see there is a way to access ping responses in the logs function (see here: http://www.steves-internet-guide.com/mqtt-keep-alive-by-example/). For UMQTT the docs indicate that ping response is handled automatically by wait_msg(): Ping server (response is automatically handled by wait_msg() (https://mpython.readthedocs.io/en/master/library/mPython/umqtt.simple.html). There does not appear to be any analogous logs function mentioned in the UMQTT.simple docs.

This is confounding for a couple of reasons:

If i use client.wait_msg() how do I call client.ping()? client.wait_msg() is a blocking function, so I can't make the ping. The system just disconnects when the keepalive time is reached.

If I call client.check_msg(), and client.ping() intermittently, I can't access the callback. My callback function doesn't have parameters to access pingresponse (params are f(topic, msg) in the docs).

The way I am solving this for now is to set a bunch of try-except calls on my client.connect and then connect-subscribe functions, but its quite verbose. Is this the way to handle or can i take advantage of the pingresponse in UMQTT.simple?

Below is a sample of the code i am running:

```<code>#Set broker variables and login credentials
#Connect to the network

#write the subscribe call back
def sub_cb(topic, msg):
    print((topic, msg))

#write a function that handles connecting and subscribing
def connect_and_subscribe():
    global CLIENT_NAME, BROKER_IP, USER, PASSWORD, TOPIC
    client = MQTTClient(client_id=CLIENT_NAME,
                    server=BROKER_IP,
                    user=USER,
                    password=PASSWORD,
                    keepalive=60)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(TOPIC)
    print('Connected to MQTT broker at: %s, subscribed to %s topic' % (BROKER_IP, TOPIC))
    return(client) #return the client so that i can do stuff with it

client = connect_and_subscribe()

#Check messages
now = time.time()
while True:
    try:
        client.check_msg()
    except OSError as message_error: #except if disconnected and check_msg() fails
        if message_error == -1:
            time.sleep(30) #wait for reboot
            try:
                client = connect_and_subscribe() #Try connect again to the server
            except OSError as connect_error: #If the server is still down
                time.sleep(30) #wait and try again
                try:
                    client = connect_and_subscribe()
                except:
                    quit() #Quite so that i don't get stuck in a loop
    time.sleep(0.1)
    if time.time() - now > 80: #ping to keepalive (60 * 1.5)
        client.ping()
        now = time.time() #reset the timer
</code>```

Body:
I am trying to get my head around UMQTT.simple. I am looking to handle instances in which my server might disconnect for a reboot. I want to check whether the client is connected, and if not, wait some period and try to reconnect.The guidance seems to be to use client.ping() for this (How to check Micropython umqtt client is connected?).

For the MQTT.paho client I see there is a way to access ping responses in the logs function (see here: http://www.steves-internet-guide.com/mqtt-keep-alive-by-example/). For UMQTT the docs indicate that ping response is handled automatically by wait_msg(): Ping server (response is automatically handled by wait_msg() (https://mpython.readthedocs.io/en/master/library/mPython/umqtt.simple.html). There does not appear to be any analogous logs function mentioned in the UMQTT.simple docs.

This is confounding for a couple of reasons:

If i use client.wait_msg() how do I call client.ping()? client.wait_msg() is a blocking function, so I can't make the ping. The system just disconnects when the keepalive time is reached.

If I call client.check_msg(), and client.ping() intermittently, I can't access the callback. My callback function doesn't have parameters to access pingresponse (params are f(topic, msg) in the docs).

The way I am solving this for now is to set a bunch of try-except calls on my client.connect and then connect-subscribe functions, but its quite verbose. Is this the way to handle or can i take advantage of the pingresponse in UMQTT.simple?

Below is a sample of the code i am running:

#Set broker variables and login credentials
#Connect to the network

#write the subscribe call back
def sub_cb(topic, msg):
    print((topic, msg))

#write a function that handles connecting and subscribing
def connect_and_subscribe():
    global CLIENT_NAME, BROKER_IP, USER, PASSWORD, TOPIC
    client = MQTTClient(client_id=CLIENT_NAME,
                    server=BROKER_IP,
                    user=USER,
                    password=PASSWORD,
                    keepalive=60)
    client.set_callback(sub_cb)
    client.connect()
    client.subscribe(TOPIC)
    print('Connected to MQTT broker at: %s, subscribed to %s topic' % (BROKER_IP, TOPIC))
    return(client) #return the client so that i can do stuff with it

client = connect_and_subscribe()

#Check messages
now = time.time()
while True:
    try:
        client.check_msg()
    except OSError as message_error: #except if disconnected and check_msg() fails
        if message_error == -1:
            time.sleep(30) #wait for reboot
            try:
                client = connect_and_subscribe() #Try connect again to the server
            except OSError as connect_error: #If the server is still down
                time.sleep(30) #wait and try again
                try:
                    client = connect_and_subscribe()
                except:
                    quit() #Quite so that i don't get stuck in a loop
    time.sleep(0.1)
    if time.time() - now > 80: #ping to keepalive (60 * 1.5)
        client.ping()
        now = time.time() #reset the timer


问:
How to decode dynamic key from JSON using retrofit - Kotlin
I'm stuck decoding a dynamic value from a json file with kotlin

```<code>{
    "values": {
        "16694990259825982nLJ": {
            "id": "16694990259825982nLJ",
            "createdAt": "2022-11-26T21:43:45.982Z",
            "name": "Some Text",
            "owner": "xxxx@xxxx.xx",
            "category": "Some Text",
            "description": "Some Text.",
            "template_id": "Some Text",
            "last_update": "2022-11-27T00:11:51.863Z",
            "users": [
                "xxxx@xxxx.xx"
            ]
        }
    }
}
</code>```

Here's my data class :

```<code>@Serializable
data class WorkflowsTest(
    @field:SerializedName("values")
    val values: Map<String, Id>
)

@Serializable
data class Id(

    @field:SerializedName("owner")
    val owner: String? = null,

    @field:SerializedName("createdAt")
    val createdAt: String? = null,

    @field:SerializedName("last_update")
    val lastUpdate: String? = null,

    @field:SerializedName("name")
    val name: String? = null,

    @field:SerializedName("description")
    val description: String? = null,

    @field:SerializedName("template_id")
    val templateId: String? = null,

    @field:SerializedName("id")
    val id: String? = null,

    @field:SerializedName("category")
    val category: String? = null,

    @field:SerializedName("users")
    val users: List<String?>? = null
)
</code>```

This is my ApiResponse data class when fetching Data from GET HTTP URL :

```<code>@Serializable
data class ApiResponse(
    @Transient
    val success: Boolean? = null,
    val message: String? = null,
    val values: WorkflowsTest? = null,
    val status: Int,
    @Transient
    val error: Exception? = null
)
</code>```

And this is my retrofit provider network from network module

```<code>@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}
</code>```

Logs that I get when I get the response back :
ApiResponse(success=null, message=null, **values=WorkflowsTest(values=null)**, status=1, error=null)

as you can see values are null no matter what I do, status = 1 means the request is 200 OK, success, error and message are transient and manipulated for snackbar messages.

Test on main function :

```<code>fun main() {
    val jsonString = """
        {
    "values": {
        "16694990259825982nLJ": {
            "id": "16694990259825982nLJ",
            "createdAt": "2022-11-26T21:43:45.982Z",
            "name": "Some Text",
            "owner": "xxxx@xxxx.xx",
            "category": "Some Text",
            "description": "Some Text.",
            "template_id": "Some Text",
            "last_update": "2022-11-27T00:11:51.863Z",
            "users": [
                "xxxx@xxxx.xx"
            ]
        }
    }
}"""

    val jsonTest: WorkflowsTest =
        Gson().fromJson(jsonString, WorkflowsTest::class.java)

    println(jsonTest)
}
</code>```

print result works fine :

WorkflowsTest(values={16694990259825982nLJ=Id(owner=xxxx@xxxx.xx, createdAt=2022-11-26T21:43:45.982Z, lastUpdate=2022-11-27T00:11:51.863Z, name=Some Text, description=Some Text., templateId=Some Text, id=16694990259825982nLJ, category=Some Text, users=[xxxx@xxxx.xx])})

```<code>
> **UPDATE**

I solved the issue by only changing the Api response data class :

Old :

    @Serializable
    data class ApiResponse(
        @Transient
        val success: Boolean? = null,
        val message: String? = null,
        val values: WorkflowsTest? = null,
        val status: Int,
        @Transient
        val error: Exception? = null

to the new one (focus on the values field) :

    @Serializable
    data class ApiResponse(
        @Transient
        val success: Boolean? = null,
        val message: String? = null,
        val values: Map<String, Id>? = null,
        val status: Int,
        @Transient
        val error: Exception? = null
    )

and magically it works.
</code>```

Body:
I'm stuck decoding a dynamic value from a json file with kotlin

{
    "values": {
        "16694990259825982nLJ": {
            "id": "16694990259825982nLJ",
            "createdAt": "2022-11-26T21:43:45.982Z",
            "name": "Some Text",
            "owner": "xxxx@xxxx.xx",
            "category": "Some Text",
            "description": "Some Text.",
            "template_id": "Some Text",
            "last_update": "2022-11-27T00:11:51.863Z",
            "users": [
                "xxxx@xxxx.xx"
            ]
        }
    }
}

Here's my data class :

@Serializable
data class WorkflowsTest(
    @field:SerializedName("values")
    val values: Map<String, Id>
)

@Serializable
data class Id(

    @field:SerializedName("owner")
    val owner: String? = null,

    @field:SerializedName("createdAt")
    val createdAt: String? = null,

    @field:SerializedName("last_update")
    val lastUpdate: String? = null,

    @field:SerializedName("name")
    val name: String? = null,

    @field:SerializedName("description")
    val description: String? = null,

    @field:SerializedName("template_id")
    val templateId: String? = null,

    @field:SerializedName("id")
    val id: String? = null,

    @field:SerializedName("category")
    val category: String? = null,

    @field:SerializedName("users")
    val users: List<String?>? = null
)

This is my ApiResponse data class when fetching Data from GET HTTP URL :

@Serializable
data class ApiResponse(
    @Transient
    val success: Boolean? = null,
    val message: String? = null,
    val values: WorkflowsTest? = null,
    val status: Int,
    @Transient
    val error: Exception? = null
)

And this is my retrofit provider network from network module

@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
}

Logs that I get when I get the response back :
ApiResponse(success=null, message=null, **values=WorkflowsTest(values=null)**, status=1, error=null)

as you can see values are null no matter what I do, status = 1 means the request is 200 OK, success, error and message are transient and manipulated for snackbar messages.

Test on main function :

fun main() {
    val jsonString = """
        {
    "values": {
        "16694990259825982nLJ": {
            "id": "16694990259825982nLJ",
            "createdAt": "2022-11-26T21:43:45.982Z",
            "name": "Some Text",
            "owner": "xxxx@xxxx.xx",
            "category": "Some Text",
            "description": "Some Text.",
            "template_id": "Some Text",
            "last_update": "2022-11-27T00:11:51.863Z",
            "users": [
                "xxxx@xxxx.xx"
            ]
        }
    }
}"""

    val jsonTest: WorkflowsTest =
        Gson().fromJson(jsonString, WorkflowsTest::class.java)

    println(jsonTest)
}

print result works fine :

WorkflowsTest(values={16694990259825982nLJ=Id(owner=xxxx@xxxx.xx, createdAt=2022-11-26T21:43:45.982Z, lastUpdate=2022-11-27T00:11:51.863Z, name=Some Text, description=Some Text., templateId=Some Text, id=16694990259825982nLJ, category=Some Text, users=[xxxx@xxxx.xx])})

> **UPDATE**

I solved the issue by only changing the Api response data class :

Old :

    @Serializable
    data class ApiResponse(
        @Transient
        val success: Boolean? = null,
        val message: String? = null,
        val values: WorkflowsTest? = null,
        val status: Int,
        @Transient
        val error: Exception? = null

to the new one (focus on the values field) :

    @Serializable
    data class ApiResponse(
        @Transient
        val success: Boolean? = null,
        val message: String? = null,
        val values: Map<String, Id>? = null,
        val status: Int,
        @Transient
        val error: Exception? = null
    )

and magically it works.


问:
node and npm are both updated already
I have node and npm are both updated already but when I install npx create-strapi-app@latest filename, im getting this message: enter image description here

been waiting for few hours already and tried the steps above, still the same even if vscode is already in admin mode. Any solution for this?

Title: node and npm are both updated already


问:
The variable in the request in the mybatis mapper is not replaced
The variable in the request in the mybatis mapper is not replaced.
In the case of "select" queries, everything is fine, but I need to be able to create a table by name.

```<code>import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface TableMapper {
    @Update("""
        create table if not exists #{name}
        (table_name varchar(50) NOT NULL,
        update_date varchar(20) NOT NULL)
        """)
    void createTableByName(@Param("name") String name);
}
</code>```

What am I doing wrong? Or is this approach not possible when using mybatis?

In logs:

```<code>The error occurred while setting parameters
SQL: create table if not exists ? (table_name varchar(50) NOT NULL, update_date varchar(20) NOT NULL)
</code>```

The variable passed to the method is neither empty nor null.

The list of fields in the table itself is not important, only the possibility of creating a table by a given name.

Body:
The variable in the request in the mybatis mapper is not replaced.
In the case of "select" queries, everything is fine, but I need to be able to create a table by name.

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface TableMapper {
    @Update("""
        create table if not exists #{name}
        (table_name varchar(50) NOT NULL,
        update_date varchar(20) NOT NULL)
        """)
    void createTableByName(@Param("name") String name);
}

What am I doing wrong? Or is this approach not possible when using mybatis?

In logs:

The error occurred while setting parameters
SQL: create table if not exists ? (table_name varchar(50) NOT NULL, update_date varchar(20) NOT NULL)

The variable passed to the method is neither empty nor null.

The list of fields in the table itself is not important, only the possibility of creating a table by a given name.


问:
.net core with selenium how to run in some server/cloud
I'm trying to run a project with .net core API running selenium.
Locally all works but the issue is when I need to deploy in some server, because the server doesn't have a chrome driver installed.
I hear about phantomjs but the project is discontinued, so I can't use it.

I tried to run my application using docker images on Heroku and I added two Buildpacks:

https://github.com/heroku/heroku-buildpack-chromedriver

https://github.com/heroku/heroku-buildpack-google-chrome

And the variables:

CHROMEDRIVER_PATH = /app/.chromedriver/bin/chromedriver

GOOGLE_CHROME_BIN = /app/.apt/usr/bin/google-chrome

But I believe the Heroku is not running the buildpack when I deploy my image because I'm receiving the following error:

"OpenQA.Selenium.DriverServiceNotFoundException: The file /app/.chromedriver/bin/chromedriver /chromedriver does not exist. The driver can be downloaded at http://chromedriver.storage.googleapis.com/index.html"

I have two questions:
what I'm doing wrong in heroku ?

And have other options can I try to follow where I'll be able to execute selenium ?


问:
Sorting/Optimization problem with rows in a pandas dataframe
the dataframe: df is a pre-processed(masked, sorted) dataframe, the result of several masks and iterations of processing.   This is noted here to provide insight into the index numbers (or row names).  The unmasked, original df includes many, many rows.  One of the columns, labeled, 'qty' is composed of integers.  The currently sorted arrangement of rows matters, with the first row being more 'suitable' for inclusion in the final answer than the next lower row, and so on, down through the entire vector of rows.

The optimization goal is to find the smallest number of rows in which the sum of their 'qty' integers equals target_qty, with the constraint that rows higher in the list(closer to index=0) are a better fit than rows lower down in the list(index=large_integer).  The output result should be a tuple containing the row index (or row 'name') of whatever combination of rows produces the optimal outcome.

The best outcome is to identify one row that had 'qty' = target_qty.  If no single row meets that condition, then the next best outcome is to identify any two rows where the sum of 'qty' equals target_qty.  If that condition can't be met, then identify any three rows where the sum of their 'qty' elements equals target_qty, or the best 4 rows, or 5 rows, or ....

import pandas as pd
import itertools
df = pd.DataFrame( {'qty': [2, 4, 3, 7, 5, 4, 9]  }, index=[744,823,844,855,901,917,922]  )
target_qty = 14
# expected answer:  resulting_index_tuple = ([823, 844, 855],x), where [the tuple] contains each of the row 'names', and where x = a subsequent calculation to be provided based on items from rows 823, 844, and 855.
```
<p>I've included an import of itertools, which was used to try this:</p>
<pre class="lang-py prettyprint-override"><code>
# Get all possible combinations of [any three] indices
indices = list(itertools.combinations(df.index, 3))

# Find the combination whose sum of 'qty' values equals the target_qty
# this doesn't work ...
for index_tuple in indices:
    if df.loc[index_tuple, 'qty'].sum() == target_qty:
        break

print(index_tuple)
# ... index_tuple to be subsequently used to produce 'resulting_index_tuple' as noted above.
</code>```

My idea was to loop this entire 'for index_tuple...' snippet within a control loop that would replace the '3' in

```<code>indices = list(itertools.combinations(df.index, 3))
</code>```

with an iterator which would expand the row count upward from 1 as needed.  In other words, the '3' above would be replaced with 'x', where x increments to x+1 as the algorithm hunts for the minimum number of rows to complete the search.  But I can address that loop later.  For now, I know there is a combination of three rows in this sample df which will result in their qty's summing to  target_qty, and I only want to get this inner loop to work.

Another constraint of the larger, overall problem include the fact that df includes a number or rows that always equals or exceeds target_qty, so that even if the 'qty' field of each row were '1', an eventual solution could be found simply by gathering enough rows.  In other words, there is always an eventual number of rows in which the sum of their 'qty' equals target_qty.

For the record, the itertools idea and above-noted 'for index_tuple...' loop was the result of me asking chat gpt-3 about this optimization problem.  It's answer looks like almost-executable pseudo-code, but alas, it doesn't run.  I sense that it is close, and I'm sure it will do better once it gets to read what some of you wizards come up with.  Any guidance is appreciated.

Body:
the dataframe: df is a pre-processed(masked, sorted) dataframe, the result of several masks and iterations of processing.   This is noted here to provide insight into the index numbers (or row names).  The unmasked, original df includes many, many rows.  One of the columns, labeled, 'qty' is composed of integers.  The currently sorted arrangement of rows matters, with the first row being more 'suitable' for inclusion in the final answer than the next lower row, and so on, down through the entire vector of rows.

The optimization goal is to find the smallest number of rows in which the sum of their 'qty' integers equals target_qty, with the constraint that rows higher in the list(closer to index=0) are a better fit than rows lower down in the list(index=large_integer).  The output result should be a tuple containing the row index (or row 'name') of whatever combination of rows produces the optimal outcome.

The best outcome is to identify one row that had 'qty' = target_qty.  If no single row meets that condition, then the next best outcome is to identify any two rows where the sum of 'qty' equals target_qty.  If that condition can't be met, then identify any three rows where the sum of their 'qty' elements equals target_qty, or the best 4 rows, or 5 rows, or ....

import pandas as pd
import itertools
df = pd.DataFrame( {'qty': [2, 4, 3, 7, 5, 4, 9]  }, index=[744,823,844,855,901,917,922]  )
target_qty = 14
# expected answer:  resulting_index_tuple = ([823, 844, 855],x), where [the tuple] contains each of the row 'names', and where x = a subsequent calculation to be provided based on items from rows 823, 844, and 855.

I've included an import of itertools, which was used to try this:

# Get all possible combinations of [any three] indices
indices = list(itertools.combinations(df.index, 3))

# Find the combination whose sum of 'qty' values equals the target_qty
# this doesn't work ...
for index_tuple in indices:
    if df.loc[index_tuple, 'qty'].sum() == target_qty:
        break

print(index_tuple)
# ... index_tuple to be subsequently used to produce 'resulting_index_tuple' as noted above.

My idea was to loop this entire 'for index_tuple...' snippet within a control loop that would replace the '3' in

indices = list(itertools.combinations(df.index, 3))

with an iterator which would expand the row count upward from 1 as needed.  In other words, the '3' above would be replaced with 'x', where x increments to x+1 as the algorithm hunts for the minimum number of rows to complete the search.  But I can address that loop later.  For now, I know there is a combination of three rows in this sample df which will result in their qty's summing to  target_qty, and I only want to get this inner loop to work.

Another constraint of the larger, overall problem include the fact that df includes a number or rows that always equals or exceeds target_qty, so that even if the 'qty' field of each row were '1', an eventual solution could be found simply by gathering enough rows.  In other words, there is always an eventual number of rows in which the sum of their 'qty' equals target_qty.

For the record, the itertools idea and above-noted 'for index_tuple...' loop was the result of me asking chat gpt-3 about this optimization problem.  It's answer looks like almost-executable pseudo-code, but alas, it doesn't run.  I sense that it is close, and I'm sure it will do better once it gets to read what some of you wizards come up with.  Any guidance is appreciated.


问:
Fridump3 process not found
Trying to run fridump3. However it says, it cant find the given procees:

```<code>python3 fridump3.py -u -s sg.vp.owasp_mobile.omtg_android

        ______    _     _
        |  ___|  (_)   | |
        | |_ _ __ _  __| |_   _ _ __ ___  _ __
        |  _| '__| |/ _` | | | | '_ ` _ \| '_ \
        | | | |  | | (_| | |_| | | | | | | |_) |
        \_| |_|  |_|\__,_|\__,_|_| |_| |_| .__/
                                         | |
                                         |_|

unable to find process with name 'sg.vp.owasp_mobile.omtg_android'

</code>```
```<code>frida-ps -Uia

 3942  Attack me if u can                 sg.vp.owasp_mobile.omtg_android
20164  Firefox                            org.mozilla.firefox
 8090  Games                              com.oneplus.gamespace
 2939  Settings                           com.android.settings
 8232  Sieve                              com.mwr.example.sieve
21126  drozer Agent                       com.mwr.dz

</code>```

As you can see in the first line the process is running and has PID 3942. Why fridump3 cant find the process?

Googled and checed fridump's github page, reinstalled it

Title: Fridump3 process not found

Body:
Trying to run fridump3. However it says, it cant find the given procees:

python3 fridump3.py -u -s sg.vp.owasp_mobile.omtg_android

        ______    _     _
        |  ___|  (_)   | |
        | |_ _ __ _  __| |_   _ _ __ ___  _ __
        |  _| '__| |/ _` | | | | '_ ` _ \| '_ \
        | | | |  | | (_| | |_| | | | | | | |_) |
        \_| |_|  |_|\__,_|\__,_|_| |_| |_| .__/
                                         | |
                                         |_|

unable to find process with name 'sg.vp.owasp_mobile.omtg_android'

frida-ps -Uia

 3942  Attack me if u can                 sg.vp.owasp_mobile.omtg_android
20164  Firefox                            org.mozilla.firefox
 8090  Games                              com.oneplus.gamespace
 2939  Settings                           com.android.settings
 8232  Sieve                              com.mwr.example.sieve
21126  drozer Agent                       com.mwr.dz

As you can see in the first line the process is running and has PID 3942. Why fridump3 cant find the process?

Googled and checed fridump's github page, reinstalled it


问:
htt_proxy and https_proxy setup minikube
i am a beginner i don't know how to fill these proxyname and port in this where can i get this
to solve the below issue
after running minikube start --driver-docker
after some googling i found out that i need to add proxy env so that pod can access internet
enter image description here
but how do i know what to put in place of proxy name and port?

i tried scrolling through all github issues tried it using virtual machine also using hyper v but issue still persist