问:
RuntimeError: memory access out of bounds for Discord Bot [Node.JS] using Distube NPM Module
I have made music commands for my discord bot using the distube NPM module.
The issue i am facing is that sometimes ( this doesn't happen always ) and its not with a specific command, it occurs randomly with any music command under distube.

This is the error that i am facing.

```<code>26.08 00:11:45 [Bot] Startup wasm://wasm/0010d1fa:1
26.08 00:11:45 [Bot] Startup ^
26.08 00:11:45 [Bot] Startup RuntimeError: memory access out of bounds
26.08 00:11:45 [Bot] Startup at <anonymous>:wasm-function[268]:0x2177a
26.08 00:11:45 [Bot] Startup at <anonymous>:wasm-function[267]:0x21732
26.08 00:11:45 [Bot] Startup at OpusScriptHandler$_decode [as _decode] (eval at Db (/node_modules/opusscript/build/opusscript_native_wasm.js:1:1), <anonymous>:11:10)
26.08 00:11:45 [Bot] Startup at OpusScript.decode (/node_modules/opusscript/index.js:80:28)
26.08 00:11:45 [Bot] Startup at Decoder._decode (/node_modules/prism-media/src/opus/Opus.js:64:25)
26.08 00:11:45 [Bot] Startup at Decoder._transform (/node_modules/prism-media/src/opus/Opus.js:189:20)
26.08 00:11:45 [Bot] Startup at Decoder.Transform._read (internal/streams/transform.js:205:10)
26.08 00:11:45 [Bot] Startup at Decoder.Transform._write (internal/streams/transform.js:193:12)
26.08 00:11:45 [Bot] Startup at writeOrBuffer (internal/streams/writable.js:358:12)
26.08 00:11:45 [Bot] Startup at Decoder.Writable.write (internal/streams/writable.js:303:10)
26.08 00:11:45 [Bot] Startup at Encoder.ondata (internal/streams/readable.js:719:22)
26.08 00:11:45 [Bot] Startup at Encoder.emit (events.js:315:20)
26.08 00:11:45 [Bot] Startup at addChunk (internal/streams/readable.js:309:12)
26.08 00:11:45 [Bot] Startup at readableAddChunk (internal/streams/readable.js:284:9)
26.08 00:11:45 [Bot] Startup at Encoder.Readable.push (internal/streams/readable.js:223:10)
26.08 00:11:45 [Bot] Startup at Encoder.Transform.push (internal/streams/transform.js:166:32)
26.08 00:11:45 [Bot] Startup npm ERR! code ELIFECYCLE
26.08 00:11:45 [Bot] Startup npm ERR! errno 1
26.08 00:11:45 [Bot] Startup npm ERR! index@1.0.0 start: `node index.js`
26.08 00:11:45 [Bot] Startup npm ERR! Exit status 1
26.08 00:11:45 [Bot] Startup npm ERR!
26.08 00:11:45 [Bot] Startup npm ERR! Failed at the index@1.0.0 start script.
26.08 00:11:45 [Bot] Startup npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
26.08 00:11:45 [Bot] Startup npm ERR! A complete log of this run can be found in:
26.08 00:11:45 [Bot] Startup npm ERR!     /tmp/npm/_logs/2021-08-26T04_11_45_714Z-debug.log
26.08 00:11:46 [PebbleHost] Server shut down (running)
26.08 00:11:46 [PebbleHost] Server stopped
26.08 00:11:58 [PebbleHost] Received start command
26.08 00:11:58 [PebbleHost] Starting server!
</code>```

This is the code for the music commands.

```<code>const DisTube = require('distube'),
  config = {
    prefix: "x",
  };

// Create a new DisTube
const distube = new DisTube(client, {
  searchSongs: true,
  emitNewSongOnly: true
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on("message", async(message) => {
  if (message.author.bot) return;
  if (!message.content.startsWith(config.prefix)) return;
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift();

  if (command == "play")
    distube.play(message, args.join(" "));

  if (["repeat", "loop"].includes(command))
    distube.setRepeatMode(message, parseInt(args[0]));

  if (command == "loop" || command == "repeat") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Song has been Looped!')

    message.channel.send(exampleEmbed);
  }

  if (command == "stop") {
    distube.stop(message);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Bot has left the voice channel!')

    message.channel.send(exampleEmbed);
  }
  if (command == "skip") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Song has been skipped!')

    message.channel.send(exampleEmbed);
  }

  if (command == "skip")
    distube.skip(message);

  if (command == "volume")
    distube.setVolume(message, args[0]);
  if (command == "volume") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Volume has been set to ${args[0]}% `)

    message.channel.send(exampleEmbed);
  }

  if (command == "jump")
    distube.jump(message, parseInt(args[0] - 1));

  if (command == "shuffle")
    distube.shuffle(message);

  if (command == "shuffle") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Queue has been shuffled!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "pause")
    distube.pause(message);

  if (command == "pause") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Current Song has been paused!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "resume")
    distube.resume(message);

  if (command == "resume") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Current Song has been resumed!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "queue") {
    let queue = distube.getQueue(message);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Queue')
      .setDescription(queue.songs.map((song, id) =>
        `**${id + 1}**) ${song.name} - \`${song.formattedDuration}\``).slice(0, 10).join("\n"))

    message.channel.send(exampleEmbed);
  }

  if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`, `reverse`, `surround`, `earwax`].includes(command)) {
    let filter = distube.setFilter(message, command);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Filter')
      .setDescription(filter || 'Off')

    message.channel.send(exampleEmbed);
  }
});

// Queue status template
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;

// DisTube event listeners, more in the documentation page
distube

  .on("playSong", (message, queue, song) =>
    message.channel.send(
      `Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`
    ))
  .on("addSong", (message, queue, song) => message.channel.send(
    `Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
  ))
  .on("playList", (message, queue, playlist, song) => message.channel.send(
    `Play \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
  ))
  .on("addList", (message, queue, playlist) => message.channel.send(
    `Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
  ))
  // DisTubeOptions.searchSongs = true
  .on("searchResult", (message, result) => {
    let i = 0;
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Choose an option from below')
      .setDescription(`${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n\n*Enter anything else or wait 60 seconds to cancel*`)
    message.channel.send(exampleEmbed);

  })
  // DisTubeOptions.searchSongs = true
  .on("searchCancel", (message) => message.channel.send(`Searching canceled`))
  .on("error", (message, e) => {
    console.error(e)
    message.channel.send("An error encountered: " + e);
  });
</code>```

答:
Due to opusscript package. Uninstall it and install @discordjs/opus instead.

npm uninstall opusscript
npm install @discordjs/opus
```

Body:
I have made music commands for my discord bot using the distube NPM module.
The issue i am facing is that sometimes ( this doesn't happen always ) and its not with a specific command, it occurs randomly with any music command under distube.

This is the error that i am facing.

26.08 00:11:45 [Bot] Startup wasm://wasm/0010d1fa:1
26.08 00:11:45 [Bot] Startup ^
26.08 00:11:45 [Bot] Startup RuntimeError: memory access out of bounds
26.08 00:11:45 [Bot] Startup at <anonymous>:wasm-function[268]:0x2177a
26.08 00:11:45 [Bot] Startup at <anonymous>:wasm-function[267]:0x21732
26.08 00:11:45 [Bot] Startup at OpusScriptHandler$_decode [as _decode] (eval at Db (/node_modules/opusscript/build/opusscript_native_wasm.js:1:1), <anonymous>:11:10)
26.08 00:11:45 [Bot] Startup at OpusScript.decode (/node_modules/opusscript/index.js:80:28)
26.08 00:11:45 [Bot] Startup at Decoder._decode (/node_modules/prism-media/src/opus/Opus.js:64:25)
26.08 00:11:45 [Bot] Startup at Decoder._transform (/node_modules/prism-media/src/opus/Opus.js:189:20)
26.08 00:11:45 [Bot] Startup at Decoder.Transform._read (internal/streams/transform.js:205:10)
26.08 00:11:45 [Bot] Startup at Decoder.Transform._write (internal/streams/transform.js:193:12)
26.08 00:11:45 [Bot] Startup at writeOrBuffer (internal/streams/writable.js:358:12)
26.08 00:11:45 [Bot] Startup at Decoder.Writable.write (internal/streams/writable.js:303:10)
26.08 00:11:45 [Bot] Startup at Encoder.ondata (internal/streams/readable.js:719:22)
26.08 00:11:45 [Bot] Startup at Encoder.emit (events.js:315:20)
26.08 00:11:45 [Bot] Startup at addChunk (internal/streams/readable.js:309:12)
26.08 00:11:45 [Bot] Startup at readableAddChunk (internal/streams/readable.js:284:9)
26.08 00:11:45 [Bot] Startup at Encoder.Readable.push (internal/streams/readable.js:223:10)
26.08 00:11:45 [Bot] Startup at Encoder.Transform.push (internal/streams/transform.js:166:32)
26.08 00:11:45 [Bot] Startup npm ERR! code ELIFECYCLE
26.08 00:11:45 [Bot] Startup npm ERR! errno 1
26.08 00:11:45 [Bot] Startup npm ERR! index@1.0.0 start: `node index.js`
26.08 00:11:45 [Bot] Startup npm ERR! Exit status 1
26.08 00:11:45 [Bot] Startup npm ERR!
26.08 00:11:45 [Bot] Startup npm ERR! Failed at the index@1.0.0 start script.
26.08 00:11:45 [Bot] Startup npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
26.08 00:11:45 [Bot] Startup npm ERR! A complete log of this run can be found in:
26.08 00:11:45 [Bot] Startup npm ERR!     /tmp/npm/_logs/2021-08-26T04_11_45_714Z-debug.log
26.08 00:11:46 [PebbleHost] Server shut down (running)
26.08 00:11:46 [PebbleHost] Server stopped
26.08 00:11:58 [PebbleHost] Received start command
26.08 00:11:58 [PebbleHost] Starting server!

This is the code for the music commands.

const DisTube = require('distube'),
  config = {
    prefix: "x",
  };

// Create a new DisTube
const distube = new DisTube(client, {
  searchSongs: true,
  emitNewSongOnly: true
});

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on("message", async(message) => {
  if (message.author.bot) return;
  if (!message.content.startsWith(config.prefix)) return;
  const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
  const command = args.shift();

  if (command == "play")
    distube.play(message, args.join(" "));

  if (["repeat", "loop"].includes(command))
    distube.setRepeatMode(message, parseInt(args[0]));

  if (command == "loop" || command == "repeat") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Song has been Looped!')

    message.channel.send(exampleEmbed);
  }

  if (command == "stop") {
    distube.stop(message);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Bot has left the voice channel!')

    message.channel.send(exampleEmbed);
  }
  if (command == "skip") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Song has been skipped!')

    message.channel.send(exampleEmbed);
  }

  if (command == "skip")
    distube.skip(message);

  if (command == "volume")
    distube.setVolume(message, args[0]);
  if (command == "volume") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Volume has been set to ${args[0]}% `)

    message.channel.send(exampleEmbed);
  }

  if (command == "jump")
    distube.jump(message, parseInt(args[0] - 1));

  if (command == "shuffle")
    distube.shuffle(message);

  if (command == "shuffle") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Queue has been shuffled!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "pause")
    distube.pause(message);

  if (command == "pause") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Current Song has been paused!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "resume")
    distube.resume(message);

  if (command == "resume") {
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle(`Current Song has been resumed!`)

    message.channel.send(exampleEmbed);
  }

  if (command == "queue") {
    let queue = distube.getQueue(message);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Queue')
      .setDescription(queue.songs.map((song, id) =>
        `**${id + 1}**) ${song.name} - \`${song.formattedDuration}\``).slice(0, 10).join("\n"))

    message.channel.send(exampleEmbed);
  }

  if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`, `reverse`, `surround`, `earwax`].includes(command)) {
    let filter = distube.setFilter(message, command);
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Current Filter')
      .setDescription(filter || 'Off')

    message.channel.send(exampleEmbed);
  }
});

// Queue status template
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;

// DisTube event listeners, more in the documentation page
distube

  .on("playSong", (message, queue, song) =>
    message.channel.send(
      `Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`
    ))
  .on("addSong", (message, queue, song) => message.channel.send(
    `Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
  ))
  .on("playList", (message, queue, playlist, song) => message.channel.send(
    `Play \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
  ))
  .on("addList", (message, queue, playlist) => message.channel.send(
    `Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
  ))
  // DisTubeOptions.searchSongs = true
  .on("searchResult", (message, result) => {
    let i = 0;
    const exampleEmbed = new Discord.MessageEmbed()
      .setColor('#9966CC')
      .setTitle('Choose an option from below')
      .setDescription(`${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n\n*Enter anything else or wait 60 seconds to cancel*`)
    message.channel.send(exampleEmbed);

  })
  // DisTubeOptions.searchSongs = true
  .on("searchCancel", (message) => message.channel.send(`Searching canceled`))
  .on("error", (message, e) => {
    console.error(e)
    message.channel.send("An error encountered: " + e);
  });


来源: stackexchange

问:
SQL Statement to Retrieve All New Customers in a Specific Month
I have an ecommerce MySQL database that stores order information in the table 'orders'

I need to select all NEW customers for the month of March. Customers do not have to register to order, so I'm working simply with the customer email and the date time of the order. So select all customer emails that don't feature at all in previous months.

The database table has about 100k rows, and I'm looking for an efficient query.

I'm not too good with SQL (you can probably tell!), but this is what I have...

```<code>SELECT distinct(user_email) FROM orders
WHERE order_datetime > '2011-03-01 00:00:00'
      AND order_datetime < '2011-03-31 23:59:59'
      AND user_email NOT IN (
          SELECT user_email FROM orders
          WHERE order_datetime < '2011-03-01 00:00:00')
GROUP BY user_email
</code>```

Is that a really convoluted way of doing things? :) Please let me know if there's a more speed efficient way...

Thanks, Rich

答:
How about this:

```<code> SELECT user_email
 FROM orders
 GROUP BY user_email
 HAVING MIN(order_datetime) BETWEEN '2011-03-01' AND '2011-03-31 23:59:59';
</code>```

the first order being in March is checked in the HAVING clause.

having an index on order_datetime will help.

ContentLicense: CC BY-SA 3.0

Body:
I have an ecommerce MySQL database that stores order information in the table 'orders'

I need to select all NEW customers for the month of March. Customers do not have to register to order, so I'm working simply with the customer email and the date time of the order. So select all customer emails that don't feature at all in previous months.

The database table has about 100k rows, and I'm looking for an efficient query.

I'm not too good with SQL (you can probably tell!), but this is what I have...

SELECT distinct(user_email) FROM orders
WHERE order_datetime > '2011-03-01 00:00:00'
      AND order_datetime < '2011-03-31 23:59:59'
      AND user_email NOT IN (
          SELECT user_email FROM orders
          WHERE order_datetime < '2011-03-01 00:00:00')
GROUP BY user_email

Is that a really convoluted way of doing things? :) Please let me know if there's a more speed efficient way...

Thanks, Rich

Body:
How about this:

 SELECT user_email
 FROM orders
 GROUP BY user_email
 HAVING MIN(order_datetime) BETWEEN '2011-03-01' AND '2011-03-31 23:59:59';

the first order being in March is checked in the HAVING clause.

having an index on order_datetime will help.


问:
Adding double quotes to a variable when creating a csv file in python
```<code>    DudeNumber = 12
    with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file,quotechar = "'")
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", DudeNumber ])
</code>```

Output:

```<code>Linus Torvalds, 12
</code>```

Desired output:

```<code>Linus Torvalds, "12"
</code>```

DudeNumber wont always be a number, how do I make so I'm able to add quotes to the variable. Tried changing the quotechar but that didn't works. Not too sure on what to do. Using python 3 on Visual Studio Code

答:
You can use f-strings -

```<code>writer.writerow([1, "Linus Torvalds", f'"{DudeNumber}"' ])
</code>```

This would wrap the DudeNumber with " and it would be written to the csv.

```<code>>>> a = 5
>>> print(f'"{a}"')
"5"
>>> print(f"{a}")
5
>>> print('"' + str(a) + '"')
"5"
>>> print('"{}"'.format(a))
"5"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
    DudeNumber = 12
    with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file,quotechar = "'")
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", DudeNumber ])

Output:

Linus Torvalds, 12

Desired output:

Linus Torvalds, "12"

DudeNumber wont always be a number, how do I make so I'm able to add quotes to the variable. Tried changing the quotechar but that didn't works. Not too sure on what to do. Using python 3 on Visual Studio Code

Body:
You can use f-strings -

writer.writerow([1, "Linus Torvalds", f'"{DudeNumber}"' ])

This would wrap the DudeNumber with " and it would be written to the csv.

>>> a = 5
>>> print(f'"{a}"')
"5"
>>> print(f"{a}")
5
>>> print('"' + str(a) + '"')
"5"
>>> print('"{}"'.format(a))
"5"


问:
MariaDB: how to update column based on modification of another column in the same table
original question: Create a way to update a staff member's password when their username is modified. Assume the staff member's password should be the result of the expression

I have staff table that has a Trigger. the Trigger will update staff.password every time the staff.username is modified. but so far no success

答:
```<code>BEGIN
if(old.username != new.username)
    THEN UPDATE staff.password
    set new.password = MD5(new.username);

    end if;

END
</code>```


问:
Set new Value from mapping inside Map() and using reducer to return Boolean or Object to a specific new value using Javascript
I want to assign a new Value (let say this is a flag such as isActive) from an existing object. this is an example for the object I'm using to try:

```<code>let localValue = {
  "id": "019eadd3-2e71-4446-a195-69d849d88a43",
  "discount": {
      "code": "PFMQWERTY",
      "id": "019eadd3-2e71-4446-a195-69d849d88a43",
      "isActive": false
  },
  "discountId": "019eadd3-2e71-4446-a195-69d849d88a43",
  "discountRules": [
    {
      "id": "1-1",
      "type": "FIXED",
      "value": 30000,
      "package": {
        "id": "1-1-A",
        "name": "Package A",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-1-A-A",
            "code": "QWERTY",
            "expirationDate": "2034-02-28T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-2",
      "type": "FIXED",
      "value": 100000,
      "package": {
        "id": "1-2-A",
        "name": "Package B",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-2-A-A",
            "code": "KASH",
            "expirationDate": "2032-02-03T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-3",
      "type": "FIXED",
      "value": 15000,
      "package": {
        "id": "1-3-A",
        "name": "Package C",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-4",
      "type": "FIXED",
      "value": 180000,
      "package": {
        "id": "1-4-A",
        "name": "Package D",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-5",
      "type": "FIXED",
      "value": 15000,
      "package": {
        "id": "1-5-A",
        "name": "",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-6",
      "type": "FIXED",
      "value": 30003,
      "package": {
        "id": "1-6-A",
        "name": "Package E",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-6-A-A",
            "code": "QWERTY",
            "expirationDate": "2034-02-28T00:00:00+0000"
          },
          {
            "id": "1-6-A-B",
            "code": "KASH",
            "expirationDate": "2032-02-03T00:00:00+0000"
          },
          {
            "id": "1-6-A-C",
            "code": "ANT",
            "expirationDate": "2021-07-30T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-7",
      "type": "FIXED",
      "value": 5000,
      "package": {
        "id": "1-7-A",
        "name": "Package F",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    }
  ],
  "expirationDate": "28/02/2034 07:00:00",
  "totalPackagesShown": 2
}
</code>```

the goals I want to achieve is to check if there is the same code in discountRules.package.discountInApps.code === this.localValue.discount.code then return true, if failed then return false.

I can already find the way to set it using map() and some() like this:

```<code>this.localValue.discountRules = this.localValue.discountRules.map(
  rule => ({
    ...rule,
    isActive:
      rule.package &&
      rule.package.discountInApps &&
      rule.package.discountInApps.length !== 0
        ? rule.package.discountInApps.some(
            ruleItems =>
              ruleItems.code === this.localValue.discount.code
          )
        : false
  })
);
</code>```

but performance wise, is it better using map() and reducer() combination for this case or better stay using map() and some()? because I read it in here Array.prototype.reduce() it seems when using reducer can make an array reduce until it finds a value that I want (is my understanding correct?) so if it's true then...

is it better using this map() and reducer() (if its possible) or stay with map() and some() combination?
(I'm still failed to implement map() and reducer(), so can someone tell me how to use this (map() and reducer()) combination?)

Notes:
if by any chance there is a better way, I'm open for it

just in case, I'm already try to read this thread but still not quite understand as how to implement it in my case:

remove-object-from-array-using-javascript

答:
If you prefer performance, the traditional for loop would be the fastest.

For execution times, I get these

```<code>Map & Some: 27ms average
Map & Reduce: 32ms average
</code>```

You can use console.time() and console.timeEnd() to check for execution times.

The array Reduce method will run a callback function on each element of the supplied array and will return the calculated value from the callback (the value will be stored in the index of the element). If you want to use reduce with map, you can do something like this

```<code>localValue.discountRules = localValue.discountRules.map((rule) => ({
  ...rule,
  isActive:
    rule.package &&
    rule.package.discountInApps &&
    rule.package.discountInApps.length !== 0
      ? rule.package.discountInApps.reduce(
          (accumulatedValue, currentValue) =>
            accumulatedValue && currentValue.code === localValue.discount.code,
          true // this is the default initial value for the accumulatedValue
        )
      : false,
}));
</code>```

Alternatively, you can use optional chaining (?.) Like this

```<code>localValue.discountRules = localValue.discountRules.map((rule) => ({
  ...rule,
  isActive:
    rule?.package?.discountInApps?.some(
        (ruleItems) => ruleItems.code === localValue.discount.code
    )
}));
</code>```

(Do check out the supported browsers here).

Body:
I want to assign a new Value (let say this is a flag such as isActive) from an existing object. this is an example for the object I'm using to try:

let localValue = {
  "id": "019eadd3-2e71-4446-a195-69d849d88a43",
  "discount": {
      "code": "PFMQWERTY",
      "id": "019eadd3-2e71-4446-a195-69d849d88a43",
      "isActive": false
  },
  "discountId": "019eadd3-2e71-4446-a195-69d849d88a43",
  "discountRules": [
    {
      "id": "1-1",
      "type": "FIXED",
      "value": 30000,
      "package": {
        "id": "1-1-A",
        "name": "Package A",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-1-A-A",
            "code": "QWERTY",
            "expirationDate": "2034-02-28T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-2",
      "type": "FIXED",
      "value": 100000,
      "package": {
        "id": "1-2-A",
        "name": "Package B",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-2-A-A",
            "code": "KASH",
            "expirationDate": "2032-02-03T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-3",
      "type": "FIXED",
      "value": 15000,
      "package": {
        "id": "1-3-A",
        "name": "Package C",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-4",
      "type": "FIXED",
      "value": 180000,
      "package": {
        "id": "1-4-A",
        "name": "Package D",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-5",
      "type": "FIXED",
      "value": 15000,
      "package": {
        "id": "1-5-A",
        "name": "",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    },
    {
      "id": "1-6",
      "type": "FIXED",
      "value": 30003,
      "package": {
        "id": "1-6-A",
        "name": "Package E",
        "maxDiscountInApps": 3,
        "discountInApps": [
          {
            "id": "1-6-A-A",
            "code": "QWERTY",
            "expirationDate": "2034-02-28T00:00:00+0000"
          },
          {
            "id": "1-6-A-B",
            "code": "KASH",
            "expirationDate": "2032-02-03T00:00:00+0000"
          },
          {
            "id": "1-6-A-C",
            "code": "ANT",
            "expirationDate": "2021-07-30T00:00:00+0000"
          }
        ]
      }
    },
    {
      "id": "1-7",
      "type": "FIXED",
      "value": 5000,
      "package": {
        "id": "1-7-A",
        "name": "Package F",
        "maxDiscountInApps": 3,
        "discountInApps": []
      }
    }
  ],
  "expirationDate": "28/02/2034 07:00:00",
  "totalPackagesShown": 2
}

the goals I want to achieve is to check if there is the same code in discountRules.package.discountInApps.code === this.localValue.discount.code then return true, if failed then return false.

I can already find the way to set it using map() and some() like this:

this.localValue.discountRules = this.localValue.discountRules.map(
  rule => ({
    ...rule,
    isActive:
      rule.package &&
      rule.package.discountInApps &&
      rule.package.discountInApps.length !== 0
        ? rule.package.discountInApps.some(
            ruleItems =>
              ruleItems.code === this.localValue.discount.code
          )
        : false
  })
);

but performance wise, is it better using map() and reducer() combination for this case or better stay using map() and some()? because I read it in here Array.prototype.reduce() it seems when using reducer can make an array reduce until it finds a value that I want (is my understanding correct?) so if it's true then...

is it better using this map() and reducer() (if its possible) or stay with map() and some() combination?
(I'm still failed to implement map() and reducer(), so can someone tell me how to use this (map() and reducer()) combination?)

Notes:
if by any chance there is a better way, I'm open for it

just in case, I'm already try to read this thread but still not quite understand as how to implement it in my case:

remove-object-from-array-using-javascript

Body:
If you prefer performance, the traditional for loop would be the fastest.

For execution times, I get these

Map & Some: 27ms average
Map & Reduce: 32ms average

You can use console.time() and console.timeEnd() to check for execution times.

The array Reduce method will run a callback function on each element of the supplied array and will return the calculated value from the callback (the value will be stored in the index of the element). If you want to use reduce with map, you can do something like this

localValue.discountRules = localValue.discountRules.map((rule) => ({
  ...rule,
  isActive:
    rule.package &&
    rule.package.discountInApps &&
    rule.package.discountInApps.length !== 0
      ? rule.package.discountInApps.reduce(
          (accumulatedValue, currentValue) =>
            accumulatedValue && currentValue.code === localValue.discount.code,
          true // this is the default initial value for the accumulatedValue
        )
      : false,
}));

Alternatively, you can use optional chaining (?.) Like this

localValue.discountRules = localValue.discountRules.map((rule) => ({
  ...rule,
  isActive:
    rule?.package?.discountInApps?.some(
        (ruleItems) => ruleItems.code === localValue.discount.code
    )
}));

(Do check out the supported browsers here).


问:
sending file via WhatsApp from Windows application C#
I want send a pdf file from c# windows application via WhatsApp. How can I do that?
I khow its possible sending text messages by wa link but for attaching file like pdf I can't find anyway.</p>

答:
Because this question is too broad in terms of correct answer, I will post a few links, which might help you do what you asked ( depending on your needs ) :

https://www.twilio.com/docs/whatsapp/tutorial/send-and-receive-media-messages-twilio-api-whatsapp

https://whatsmate.github.io/2018-01-17-send-whatsapp-pdf-c-sharp-dot-net/

https://whatsmate.github.io/2018-01-23-send-whatsapp-pdf-group-c-sharp-dot-net/

https://developers.facebook.com/docs/whatsapp/api/media


问:
Use .indexof to Check for Multiple Strings with Array
I am attempting to embed a chat widget if utm_source=VALUE (any of these values)

Here is the surrounding code:

```<code>var ref1 = document.referrer;
IF STATEMENT HERE
  {
    alert("Welcome to Ellas Bubbles");
    s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
  }
</code>```

You can test it here: https://ellasbubbles.com

I have tried the following, which is only working on 'ccov':

```<code>if ((ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip') || (getcookie('track-page-1').indexOf('ccov')>-1) || (getcookie('track-page-1').indexOf('top10')>-1) || (getcookie('track-page-1').indexOf('cenf')>-1) || (getcookie('track-page-1').indexOf('aip')>-1)) > -1)
</code>```

I have also tried this:

```<code>  if ((ref1.indexOf('ccov' || 'top10' || 'cenf' || 'aip') || (getcookie('track-page-1').indexOf('ccov' || 'top10' || 'cenf' || 'aip')>-1)) > -1)
  {
    s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
  }
</code>```

Which is also only working on the first value, 'ccov'.

I have also tried this:

```<code>if ((ref1.indexOf('ccov', 'top10', 'cenf', 'aip') || (getcookie('track-page-1').indexOf('ccov', 'top10', 'cenf', 'aip')>-1)) > -1)
</code>```

Which is also only working on the first value

Is there a better way to go about this?

答:
I think your statements are incomplete. Before each || you need to condition to be satisfied. I’m writing on my phone so sorry this isn’t as specific but you need the >-1 before every ||. So instead of
X || Y < z
I think You need
X < z || y < z.</p>

Body:
I am attempting to embed a chat widget if utm_source=VALUE (any of these values)

Here is the surrounding code:

var ref1 = document.referrer;
IF STATEMENT HERE
  {
    alert("Welcome to Ellas Bubbles");
    s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
  }

You can test it here: https://ellasbubbles.com

I have tried the following, which is only working on 'ccov':

if ((ref1.indexOf('ccov') || ref1.indexOf('top10') || ref1.indexOf('cenf') || ref1.indexOf('aip') || (getcookie('track-page-1').indexOf('ccov')>-1) || (getcookie('track-page-1').indexOf('top10')>-1) || (getcookie('track-page-1').indexOf('cenf')>-1) || (getcookie('track-page-1').indexOf('aip')>-1)) > -1)

I have also tried this:

  if ((ref1.indexOf('ccov' || 'top10' || 'cenf' || 'aip') || (getcookie('track-page-1').indexOf('ccov' || 'top10' || 'cenf' || 'aip')>-1)) > -1)
  {
    s1.src='https://embed.tawk.to/620675459bd1f31184dc28c0/1frkjk5mj';
  }

Which is also only working on the first value, 'ccov'.

I have also tried this:

if ((ref1.indexOf('ccov', 'top10', 'cenf', 'aip') || (getcookie('track-page-1').indexOf('ccov', 'top10', 'cenf', 'aip')>-1)) > -1)

Which is also only working on the first value

Is there a better way to go about this?


问:
Registering COM objects on Windows 7
I am running Visual Studio in none administrative mode under Windows 7. Everything works well except for the COM registration every time i build my project. Does anyone know how to solve this?</p>

答:
You need amin privileges for the registration. Note however that the object needs to be registered only once, not every time you build it.

Just fire up a command prompt with admin privilege and type regsvr32 path/my.dll.
If it's an exe, you usually register it using path/my.exe /regserver but that depends on your framework.

Of course, if you add new objects to your COM DLL/EXE, you need to register it again.

Also, if you want to switch from debug to release build, you'll need to re-register the correct version (debug or release) since they stand in different directories.

Title: Registering COM objects on Windows 7


问:
Flutter release APK build - Intermittent white screen
My app works perfectly on the Android emulator. When I create a release APK I get this error:

Intermittently, the Scaffold content does not load. The Nav bar and drawer are visible, but not the central content.

This does not happen every time I open the app, only about 1/3 times, on average. There is no obvious pattern to this working or failing.

[✓] Flutter (Channel stable, v1.12.13+hotfix.7, on Mac OS X 10.11.6 15G22010,
    locale en)
    • Flutter version 1.12.13+hotfix.7 at /Applications/flutter
    • Framework revision 9f5ff2306b (3 days ago), 2020-01-26 22:38:26 -0800
    • Engine revision a67792536c
    • Dart version 2.7.0

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/dan/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling
      support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)
    • All Android licenses accepted.

[✗] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS
      development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin
        code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install:
        sudo gem install cocoapods

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 42.1.1
    • Dart plugin version 191.8593
    • Java version OpenJDK Runtime Environment (build
      1.8.0_202-release-1483-b49-5587405)

[✓] VS Code (version 1.41.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.7.1

[✓] Connected device (1 available)
    • klte • 5d3f96b0 • android-arm • Android 7.1.2 (API 25)

答: I have a similar case, the scaffold is not drawn, it is as if it were empty, for the moment the solution I found was to generate the apk but in debug mode, change flutter build apk --release to flutter build --debug .


问:
How do I add an integer to a string using Console.WriteLine?
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

```<code>Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();
</code>```

Outcome:

```<code>Checking 'Pi' value...
Pi value found. Pi =
</code>```

If you know anything I can try, please let me know.

答:
There are many ways to do this:

```<code>// placeholder
Console.WriteLine("Pi value found. Pi = {0}",Pi);

// concatenation
Console.WriteLine("Pi value found. Pi = " + Pi.ToString());

// interpolation
Console.WriteLine($"Pi value found. Pi = {Pi}");

// StringBuilder
var sb = new StringBuilder("Pi value found. Pi = ").Append(Pi);
Console.WriteLine(sb);

// multiple writes
Console.Write("Pi value found. Pi = ");
Console.WriteLine(Pi);
</code>```

Body:
I'm currently writing a program in C# and I'm practicing using integers. I'm trying to make it so the written line comes out with the int at the end. It doesn't give me the outcome I want though, and when I searched on Google it didn't give me the solution I was looking for.

Code:

Random rnd = new Random();
int Pi = rnd.Next(1,5);

Console.WriteLine("Checking 'Pi' value...");
Console.Beep(37,1000);
Console.WriteLine("Pi value found. Pi = ",Pi);
Console.ReadKey();

Outcome:

Checking 'Pi' value...
Pi value found. Pi =

If you know anything I can try, please let me know.

Body:
There are many ways to do this:

// placeholder
Console.WriteLine("Pi value found. Pi = {0}",Pi);

// concatenation
Console.WriteLine("Pi value found. Pi = " + Pi.ToString());

// interpolation
Console.WriteLine($"Pi value found. Pi = {Pi}");

// StringBuilder
var sb = new StringBuilder("Pi value found. Pi = ").Append(Pi);
Console.WriteLine(sb);

// multiple writes
Console.Write("Pi value found. Pi = ");
Console.WriteLine(Pi);


问:
tabBarOptions not applied to project (React Native)
I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.

I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.

MainContainer Class:

```<code>import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'

//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';

// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';

const Tab = createBottomTabNavigator();

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'black',
                    labelStyle: {paddingBottom: 10, fontSize: 10},
                    style: {padding: 10, height: 70},
                }}
                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}

</code>```

For reference here is my ToDoList class

```<code>import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';

export default function ToDoList() {
    const [task, setTask] = useState();
    const [taskItems, setTaskItems] = useState([]);

    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
    }

    const completeTask = (index) => {
        let itemsCopy = [...taskItems];
        itemsCopy.splice(index, 1);
        setTaskItems(itemsCopy)
    }

    return (
        <View style={styles.container}>
            {/* Scroll View when list gets longer than page */}
            <ScrollView contentContainerStyle={{
                flexGrow: 1
            }} keyboardShouldPersistTaps='handled'>

                {/*Today's Tasks */}
                <View style={styles.tasksWrapper}>
                    <Text style={styles.sectionTitle}>Today's Tasks</Text>
                    <View style={styles.items}>
                        {/* This is where the tasks will go*/}
                        {
                            taskItems.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                                        <Task text={item} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            {/* Write a task section */}
            {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
                <TouchableOpacity onPress={() => handleAddTask()}>
                    <View style={styles.addWrapper}>
                        <Text style={styles.addText}>+</Text>
                    </View>
                </TouchableOpacity>
            </KeyboardAvoidingView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#E8EAED',
    },
    tasksWrapper: {
        paddingTop: 20,
        paddingHorizontal: 20,
    },
    sectionTitle: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    items: {
        marginTop: 30,
    },
    writeTaskWrapper: {
        position: 'absolute',
        bottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    input: {
        paddingVertical: 15,
        width: 250,
        paddingHorizontal: 15,
        backgroundColor: '#FFF',
        borderRadius: 60,
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addWrapper: {
        width: 60,
        height: 60,
        backgroundColor: '#FFF',
        borderRadius: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addText: {

    },

});

</code>```

And my Calendar class

```<code>import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){

    return(
        <View>
            <Text>Calendar Will go here</Text>
        </View>
    )

}
</code>```

I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.

```<code>import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';

const Task = (props) => {
    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{props.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#FFF',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,

    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: .4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',

    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5
    },
});

export default Task;
</code>```

答:
What I ended up doing to solve this was to put the styling inside the screenOptions. I didn't want to do this because I wanted to separate the styling from the logic, but it solved the problem for me. See code below:

```<code>export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator

                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                               activeTintColor: 'tomato',
                               inactiveTintColor: 'black',
                               tabBarShowLabel: false,
                               tabBarStyle: {padding: 10, height: 100, backgroundColor: 'black'},
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}
</code>```

Body:
I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.

I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.

MainContainer Class:

import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'

//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';

// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';

const Tab = createBottomTabNavigator();

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'black',
                    labelStyle: {paddingBottom: 10, fontSize: 10},
                    style: {padding: 10, height: 70},
                }}
                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}

For reference here is my ToDoList class

import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';

export default function ToDoList() {
    const [task, setTask] = useState();
    const [taskItems, setTaskItems] = useState([]);

    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
    }

    const completeTask = (index) => {
        let itemsCopy = [...taskItems];
        itemsCopy.splice(index, 1);
        setTaskItems(itemsCopy)
    }

    return (
        <View style={styles.container}>
            {/* Scroll View when list gets longer than page */}
            <ScrollView contentContainerStyle={{
                flexGrow: 1
            }} keyboardShouldPersistTaps='handled'>

                {/*Today's Tasks */}
                <View style={styles.tasksWrapper}>
                    <Text style={styles.sectionTitle}>Today's Tasks</Text>
                    <View style={styles.items}>
                        {/* This is where the tasks will go*/}
                        {
                            taskItems.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                                        <Task text={item} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            {/* Write a task section */}
            {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
                <TouchableOpacity onPress={() => handleAddTask()}>
                    <View style={styles.addWrapper}>
                        <Text style={styles.addText}>+</Text>
                    </View>
                </TouchableOpacity>
            </KeyboardAvoidingView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#E8EAED',
    },
    tasksWrapper: {
        paddingTop: 20,
        paddingHorizontal: 20,
    },
    sectionTitle: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    items: {
        marginTop: 30,
    },
    writeTaskWrapper: {
        position: 'absolute',
        bottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    input: {
        paddingVertical: 15,
        width: 250,
        paddingHorizontal: 15,
        backgroundColor: '#FFF',
        borderRadius: 60,
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addWrapper: {
        width: 60,
        height: 60,
        backgroundColor: '#FFF',
        borderRadius: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addText: {

    },

});

And my Calendar class

import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){

    return(
        <View>
            <Text>Calendar Will go here</Text>
        </View>
    )

}

I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';

const Task = (props) => {
    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{props.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#FFF',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,

    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: .4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',

    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5
    },
});

export default Task;

Body:
What I ended up doing to solve this was to put the styling inside the screenOptions. I didn't want to do this because I wanted to separate the styling from the logic, but it solved the problem for me. See code below:

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator

                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                               activeTintColor: 'tomato',
                               inactiveTintColor: 'black',
                               tabBarShowLabel: false,
                               tabBarStyle: {padding: 10, height: 100, backgroundColor: 'black'},
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}


问:
Nightwatch - How can I CSS select a nested button with no unique identifiers on the button itself
In image 'UI' I need to select the second 'Setup' button on the page.

I've tried many different combinations of trying to select this element but have had no luck. I've seen some related posts but most talk about having 1 parent and 1 or 2 child elements. In this case I need to go along this path: li2/div2/div/a. I'm just unsure of how to string that together.

Xpath is not an option unfortunately as the id changes from session to session.

UI

Inspecting the DOM

For additional context, the other options in the ul (Google Auth & Voice Auth) are identical to the SMS li.

Ideally, I would want to do something like this, but I feel that I am way off:

```<code>selector: 'li[data-se$="SMS"] + a[class$="button link-button"]'
</code>```

答:
Why not select by the data attribute?

If you need to "click" on the button, you'll need to decide when that happens.  You could for example do it on page load:

const sms = document.querySelector("[data-se='SMS']");
const simulated_button_click = sms.getElementsByClassName('link-button')[0];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="simulated_button_click.click()">
...
<div class="enroll-factor-list">
    <ul class="list-content">
        <li data-se="GOOGLE_AUTH" class="enroll-factor-row clearfix">
            <div class="enroll-factor-icon-container">
                <div class="enroll-factor-button">
                    Setup
                </div>
            </div>
      </li>
      <li data-se="SMS" class="enroll-factor-row clearfix">
            <div class="enroll-factor-icon-container">
                <div class="enroll-factor-button">
                    Setup
                </div>
            </div>
      </li>
  </ul>
</div>
...
</body></code>```

Body:
In image 'UI' I need to select the second 'Setup' button on the page.

I've tried many different combinations of trying to select this element but have had no luck. I've seen some related posts but most talk about having 1 parent and 1 or 2 child elements. In this case I need to go along this path: li2/div2/div/a. I'm just unsure of how to string that together.

Xpath is not an option unfortunately as the id changes from session to session.

UI

Inspecting the DOM

For additional context, the other options in the ul (Google Auth & Voice Auth) are identical to the SMS li.

Ideally, I would want to do something like this, but I feel that I am way off:

selector: 'li[data-se$="SMS"] + a[class$="button link-button"]'

Body:
Why not select by the data attribute?

If you need to "click" on the button, you'll need to decide when that happens.  You could for example do it on page load:

const sms = document.querySelector("[data-se='SMS']");
const simulated_button_click = sms.getElementsByClassName('link-button')[0];

<body onload="simulated_button_click.click()">
...
<div class="enroll-factor-list">
    <ul class="list-content">
        <li data-se="GOOGLE_AUTH" class="enroll-factor-row clearfix">
            <div class="enroll-factor-icon-container">
                <div class="enroll-factor-button">
                    <a class="button link-button" href="#">Setup</a>
                </div>
            </div>
      </li>
      <li data-se="SMS" class="enroll-factor-row clearfix">
            <div class="enroll-factor-icon-container">
                <div class="enroll-factor-button">
                    <a class="button link-button" href="#">Setup</a>
                </div>
            </div>
      </li>
  </ul>
</div>
...
</body>


问:
MariaDB: temporary database and workaround for autocommit
I have a web page written in PHP (version 7.3.12), where an user can write any SQL statement and then execute it (I am using MariaDB version 10.4.10, included in XAMPP). When user writes DDL statements, most of them are unfortunately autocommited, hence there is no space for rollbacking a transaction. I don't want them to e.g. create 200 tables in a database that would wihtout any intervention persist in the database forever. Is there a way to workaround this problem?

Also I was wondering if besides temporary tables exists something like a temporary database? I was thinking about this, because if I could create some sort of a temporary database (that would be visible to session only), user can practically do anything without me worrying any leftovers would stay in the DB.

Thanks for any advice

答:
Data definition language (DDL) statements in MariaDB are not part of its transaction semantics, so there's no way to roll back DDL using ROLLBACK.

With the appropriate code in your php application, you can create a uuniquely named database for each user session, then drop it at the end of the session.  This is how the various database fiddle sites work.


问:
Count the amount of times a word is repeated
I'm pretty new to C# however I am trying to solve this question down below. Any way I can count that specific word each time even when its repeated twice in the same list element? I am trying to not use the Split() function. Thanks for the help</p>
```<code>string wordToSearch = "Pig";
List<string> sentences = new List<string>()
             {
                 "The animal I really dig,",
                 "Above all others is the pig.",
                 "Pigs are noble. Pigs are clever,",
                 "Pigs are courteous. However,",
                 "Now and then, to break this rule,",
                 "One meets a pig who is a fool.",
                 "What, for example, would you say,",
                 "If strolling through the woods one day,",
                 "Right there in front of you you saw",
                 "A pig who'd built his house of STRAW?",
                 "The Wolf who saw it licked his lips,",
                 "And said, 'That pig has had his chips.'",
                 "'Little pig, little pig, let me come in!'",
                 "'No, no, by the hairs on my chinny-chin-chin!'",
                 "'Then I'll huff and I'll puff and I'll blow your house in!'"
             };
foreach (string sentence in sentences)
{
    int count = 0;
    if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
    {
        count++;
        Console.WriteLine(sentence + " " + "[" + count + "]");

    }
    else
    {
        Console.WriteLine(sentence + " " + "[" + count + "]");
    }

}
</code>```

答:
Try this:</p>
```<code>foreach (string sentence in sentences)
            {
                int count = 0;
                if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
                {
                    string[] words = sentence.ToUpper().Replace(",", "").Replace(".", "").Split(Convert.ToChar(" "));
                    Console.WriteLine(sentence + " " + "[" + words.Where(s => s.Equals(wordToSearch.ToUpper())).Count().ToString() + "]");

                }
                else
                {
                    Console.WriteLine(sentence + " " + "[" + count + "]");
                }

            }
</code>```

Body:
I'm pretty new to C# however I am trying to solve this question down below. Any way I can count that specific word each time even when its repeated twice in the same list element? I am trying to not use the Split() function. Thanks for the help

string wordToSearch = "Pig";
List<string> sentences = new List<string>()
             {
                 "The animal I really dig,",
                 "Above all others is the pig.",
                 "Pigs are noble. Pigs are clever,",
                 "Pigs are courteous. However,",
                 "Now and then, to break this rule,",
                 "One meets a pig who is a fool.",
                 "What, for example, would you say,",
                 "If strolling through the woods one day,",
                 "Right there in front of you you saw",
                 "A pig who'd built his house of STRAW?",
                 "The Wolf who saw it licked his lips,",
                 "And said, 'That pig has had his chips.'",
                 "'Little pig, little pig, let me come in!'",
                 "'No, no, by the hairs on my chinny-chin-chin!'",
                 "'Then I'll huff and I'll puff and I'll blow your house in!'"
             };
foreach (string sentence in sentences)
{
    int count = 0;
    if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
    {
        count++;
        Console.WriteLine(sentence + " " + "[" + count + "]");

    }
    else
    {
        Console.WriteLine(sentence + " " + "[" + count + "]");
    }

}

Body:
Try this:

foreach (string sentence in sentences)
            {
                int count = 0;
                if (sentence.ToUpper().Contains(wordToSearch.ToUpper()))
                {
                    string[] words = sentence.ToUpper().Replace(",", "").Replace(".", "").Split(Convert.ToChar(" "));
                    Console.WriteLine(sentence + " " + "[" + words.Where(s => s.Equals(wordToSearch.ToUpper())).Count().ToString() + "]");

                }
                else
                {
                    Console.WriteLine(sentence + " " + "[" + count + "]");
                }

            }


问:
Why isn't the catch statement working for emoji reactions? | discord.js v13
So i'm trying to edit an embed when the user doesn't react with something like gameover you lost @user! only issue is, it's not editing at all and it's not even entering the catch statement it just keeps going into the then statement. I've done this method before and I'm currently using it for another command and works 100% correctly and I've just copied the code as is and still doesn't work and I don't understand why.

```<code>const testEmbed = new discord.MessageEmbed()
  .setColor('#FFFFFF')
  .setTitle("Test")
  .setDescription(`${message.author} was here!`)
  .addFields({
    name: `${message.author}`,
    value: `The name of the author`,
    inline: true
  }, {
    name: `${message.author.id}`,
    value: `The ID of the author`,
    inline: true
  })
  .setImage(`some link to some image`)

const reactEmbed = await message.channel.send({
  embeds: [testEmbed]
});
await reactEmbed.react("");
await reactEmbed.react("");

const filter = (reaction, user) => {
  return ["", ""].includes(reaction.emoji.name) && user.id === message.author.id;
}

reactEmbed.awaitReactions({
    filter,
    max: 1,
    time: 15000,
    error: ["time"]
  }).then(
    async(collected) => {
      const reaction = collected.first();
      console.log(`${reaction} i am in the then statement`);
    })
  .catch(async collected => {
    console.log(`${collected} im in the catch statement`)
    reactEmbed.reactions.removeAll();
    const reactEmbedEdited = new discord.MessageEmbed()
      .setTitle(`Gameover!`)
      .setColor('#000000')
      .addField('new Field', 'new Field')
    await reactEmbed.edit({
      embeds: [reactEmbedEdited]
    });
  })
</code>```

The output expected would be for the original embed sent to be edited into the new embed if no one reacts. However, when i test this command by running it, it sends the original embed, reacts then waits 15 seconds and prints the first statement i am in the then statement which completely makes no sense judging that it works perfectly fine in my other command and comparing them both there is no difference between them. So my questions are:

Why does it enter the then statement?

Why won't it enter the catch statement?

What is the issue with it and how can it be fixed?

I'm getting no errors just the console log output.

答:
You are missing an s in errors so:

reactEmbed.awaitReactions({
    filter,
    max: 1,
    time: 15000,
    errors: ["time"]
         ^
  }).then(...)
```

Body:
So i'm trying to edit an embed when the user doesn't react with something like gameover you lost @user! only issue is, it's not editing at all and it's not even entering the catch statement it just keeps going into the then statement. I've done this method before and I'm currently using it for another command and works 100% correctly and I've just copied the code as is and still doesn't work and I don't understand why.

const testEmbed = new discord.MessageEmbed()
  .setColor('#FFFFFF')
  .setTitle("Test")
  .setDescription(`${message.author} was here!`)
  .addFields({
    name: `${message.author}`,
    value: `The name of the author`,
    inline: true
  }, {
    name: `${message.author.id}`,
    value: `The ID of the author`,
    inline: true
  })
  .setImage(`some link to some image`)

const reactEmbed = await message.channel.send({
  embeds: [testEmbed]
});
await reactEmbed.react("");
await reactEmbed.react("");

const filter = (reaction, user) => {
  return ["", ""].includes(reaction.emoji.name) && user.id === message.author.id;
}

reactEmbed.awaitReactions({
    filter,
    max: 1,
    time: 15000,
    error: ["time"]
  }).then(
    async(collected) => {
      const reaction = collected.first();
      console.log(`${reaction} i am in the then statement`);
    })
  .catch(async collected => {
    console.log(`${collected} im in the catch statement`)
    reactEmbed.reactions.removeAll();
    const reactEmbedEdited = new discord.MessageEmbed()
      .setTitle(`Gameover!`)
      .setColor('#000000')
      .addField('new Field', 'new Field')
    await reactEmbed.edit({
      embeds: [reactEmbedEdited]
    });
  })

The output expected would be for the original embed sent to be edited into the new embed if no one reacts. However, when i test this command by running it, it sends the original embed, reacts then waits 15 seconds and prints the first statement i am in the then statement which completely makes no sense judging that it works perfectly fine in my other command and comparing them both there is no difference between them. So my questions are:

Why does it enter the then statement?

Why won't it enter the catch statement?

What is the issue with it and how can it be fixed?

I'm getting no errors just the console log output.


问:
How to add +9 hours on my jQuery script?
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

```<code>$end = mktime(16, 54, 0, 8, 18, 2011);
</code>```

and the copy it below

Countdown Script

```<code><script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);

$(document).ready(function() {
    $("#time").countdown({
        date: end_date,
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

答:
Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:

```<code>// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');
</code>```

and:

```<code>// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)
</code>```

Edit:

Since the OP said he wanted to use a TS from DB, here's the relevant code:

```<code>$date = strtotime('+9 hours', (int)$db_time);
</code>```

Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:

```<code>$db_time = strtotime($db_time);
</code>```

However, I urge you to check for alternative ways to parse the time.

Body:
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

$end = mktime(16, 54, 0, 8, 18, 2011);

and the copy it below

Countdown Script

Body:
Instead of playing the heroes by trying to do time Math (and even failing badly), you should rely on native methods, available to both PHP and JS:

// gets the time 9 hours from now
// you can give a 2nd parameter to specify when is "now"
$date = strtotime('+9 hours');

and:

// get the time right now
var date = new Date()
// add 9 hours, don't worry about jumping the 24hr boundary, JS resolves correctly.
date.setHours(date.getHours()+9)

Edit:

Since the OP said he wanted to use a TS from DB, here's the relevant code:

$date = strtotime('+9 hours', (int)$db_time);

Note: If $db_time is a formatted string, like "24 April 2011, 4:56 pm", you need to put the following code before the one above:

$db_time = strtotime($db_time);

However, I urge you to check for alternative ways to parse the time.


问:
How to use RenderTreeBuilder for RenderFragment<> in Blazor
I am implementing an EventCallback in a RenderFragment parameter to enable an external close button to fire an event within a custom component:

public RenderFragment<IElementInfo>? ContentTemplate { get; set; }
```
<p>Here is the interface:</p>
<pre class="lang-cs prettyprint-override"><code>public interface IElementInfo
{
    EventCallback CloseCallback { get; }
}
</code>```

And to use:

<ContentTemplate>
    <button type="button"
            @onclick="@(async () =>
              await RaiseCallback(context.CloseCallback))">
        Cancel
    </button>
</ContentTemplate>
```
<p><strong>[edit]</strong>
This is what the compiler generates for the above usage:</p>
<pre class="lang-cs prettyprint-override"><code>__builder.AddAttribute<ClosedEventArgs>(22, "Closed", RuntimeHelpers.TypeCheck<EventCallback<ClosedEventArgs>>(EventCallback.Factory.Create<ClosedEventArgs>((object) this, new Action(OnClosed))));
</code>```

[end edit]

There is more code that is needed to wire it all up. As it is it works.

What I am trying to do is add a simple method for passing a title and a razor component to wire-up using the RenderTreeBuilder manually. Here is a working version for a non-generic RenderFragment:

[edit]

public void Show(string? title, Type contentType)
{
    if (contentType.BaseType != typeof(ComponentBase))
        throw new ArgumentException
            ($"{contentType.FullName} must be a Blazor Component");

    RenderFragment content = x =>
    {
        x.OpenComponent(1, contentType);
        x.CloseComponent();
    };

    Show(new Options
    {
        HeaderText = title,
        ContentTemplate = content
     });
}

public void Show(Options options)
{
    Container container = new Container(options, _provider);
    _contents.Add(container);

    // notify new content
    OnUpdated?.Invoke();
}
```
<p>Sample usage:</p>
<pre class="lang-cs prettyprint-override"><code>Service.Show(
    "Sample Title",
    typeof(SampleRazorFile));
// where SampleRazorFile is a seperate razor file
</code>```

[end edit]

Where I am stumped is with changing with the RenderTreeBuilder for working with the generic RenderFragment<IElementInfo>.

[edit]

The question is regarding RenderTreeBuilder - can it return a Renderfragment<TValue> type?

[end edit]

There is next to no information out there on this specific task. Has anyone done anything like this and have any suggestions?

答:
I'm not absolutely sure of your context and if you have it right.  You don't set the "context" externally, you set it within the component and pass it to the external RenderFragment block.

Here's some code for a component to display the WeatherForecast rows in FetchData that demonstreates how to use the RenderFragment<> in a RenderFragment block.

```<code><h3>ListOfWeather</h3>
<table class="table">
    <thead>
        @this.HeaderTemplate
    </thead>
    @this.Rows
</table>

@code {
    [Parameter] public List<WeatherForecast> ForecastList { get; set; } = new List<WeatherForecast>();

    [Parameter] public RenderFragment<WeatherForecast>? ListRowTemplate { get; set; }

    [Parameter] public RenderFragment<WeatherForecast>? HeaderTemplate { get; set; }

    private RenderFragment Rows => (builder) =>
    {
        if (this.ListRowTemplate is null)
            return;

        builder.OpenElement(0, "tdbody");
        foreach (var forecast in ForecastList)
            builder.AddContent(2, this.ListRowTemplate(forecast));

        builder.CloseElement();
    };
}
</code>```

For reference FetchData looks like this:

```<code>@page "/fetchdata"

<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

<ListOfWeather ForecastList="this.Forecasts">
    <HeaderTemplate>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
        </tr>

    </HeaderTemplate>
    <ListRowTemplate>
        <tr>
            <td>@context.Date.ToShortDateString()</td>
            <td>@context.TemperatureC</td>
            <td>@context.TemperatureF</td>
            <td>@context.Summary</td>
            <td></td>
        </tr>
    </ListRowTemplate>
</ListOfWeather>

@code {
    private List<WeatherForecast> Forecasts = new List<WeatherForecast>();

    [Inject] private WeatherForecastService? service { get; set; }
    private WeatherForecastService Service => service!;

    protected override async Task OnInitializedAsync()
    {
        this.Forecasts = await Service.GetForecastAsync(DateTime.Now);
    }
}
</code>```

Body:
I am implementing an EventCallback in a RenderFragment parameter to enable an external close button to fire an event within a custom component:

public RenderFragment<IElementInfo>? ContentTemplate { get; set; }

Here is the interface:

public interface IElementInfo
{
    EventCallback CloseCallback { get; }
}

And to use:

<ContentTemplate>
    <button type="button"
            @onclick="@(async () =>
              await RaiseCallback(context.CloseCallback))">
        Cancel
    </button>
</ContentTemplate>

[edit]
This is what the compiler generates for the above usage:

__builder.AddAttribute<ClosedEventArgs>(22, "Closed", RuntimeHelpers.TypeCheck<EventCallback<ClosedEventArgs>>(EventCallback.Factory.Create<ClosedEventArgs>((object) this, new Action(OnClosed))));

[end edit]

There is more code that is needed to wire it all up. As it is it works.

What I am trying to do is add a simple method for passing a title and a razor component to wire-up using the RenderTreeBuilder manually. Here is a working version for a non-generic RenderFragment:

[edit]

public void Show(string? title, Type contentType)
{
    if (contentType.BaseType != typeof(ComponentBase))
        throw new ArgumentException
            ($"{contentType.FullName} must be a Blazor Component");

    RenderFragment content = x =>
    {
        x.OpenComponent(1, contentType);
        x.CloseComponent();
    };

    Show(new Options
    {
        HeaderText = title,
        ContentTemplate = content
     });
}

public void Show(Options options)
{
    Container container = new Container(options, _provider);
    _contents.Add(container);

    // notify new content
    OnUpdated?.Invoke();
}

Sample usage:

Service.Show(
    "Sample Title",
    typeof(SampleRazorFile));
// where SampleRazorFile is a seperate razor file

[end edit]

Where I am stumped is with changing with the RenderTreeBuilder for working with the generic RenderFragment<IElementInfo>.

[edit]

The question is regarding RenderTreeBuilder - can it return a Renderfragment<TValue> type?

[end edit]

There is next to no information out there on this specific task. Has anyone done anything like this and have any suggestions?

Body:
I'm not absolutely sure of your context and if you have it right.  You don't set the "context" externally, you set it within the component and pass it to the external RenderFragment block.

Here's some code for a component to display the WeatherForecast rows in FetchData that demonstreates how to use the RenderFragment<> in a RenderFragment block.

<h3>ListOfWeather</h3>
<table class="table">
    <thead>
        @this.HeaderTemplate
    </thead>
    @this.Rows
</table>

@code {
    [Parameter] public List<WeatherForecast> ForecastList { get; set; } = new List<WeatherForecast>();

    [Parameter] public RenderFragment<WeatherForecast>? ListRowTemplate { get; set; }

    [Parameter] public RenderFragment<WeatherForecast>? HeaderTemplate { get; set; }

    private RenderFragment Rows => (builder) =>
    {
        if (this.ListRowTemplate is null)
            return;

        builder.OpenElement(0, "tdbody");
        foreach (var forecast in ForecastList)
            builder.AddContent(2, this.ListRowTemplate(forecast));

        builder.CloseElement();
    };
}

For reference FetchData looks like this:

@page "/fetchdata"

<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

<ListOfWeather ForecastList="this.Forecasts">
    <HeaderTemplate>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
        </tr>

    </HeaderTemplate>
    <ListRowTemplate>
        <tr>
            <td>@context.Date.ToShortDateString()</td>
            <td>@context.TemperatureC</td>
            <td>@context.TemperatureF</td>
            <td>@context.Summary</td>
            <td></td>
        </tr>
    </ListRowTemplate>
</ListOfWeather>

@code {
    private List<WeatherForecast> Forecasts = new List<WeatherForecast>();

    [Inject] private WeatherForecastService? service { get; set; }
    private WeatherForecastService Service => service!;

    protected override async Task OnInitializedAsync()
    {
        this.Forecasts = await Service.GetForecastAsync(DateTime.Now);
    }
}


问:
AWS ECS CodePipeline build error REPOSITORY_URI
we wanna try CodePipeline with a image that we already have on ECR.

So we follow the steps on the documentation.

We have buildspec.yml like this:

```<code>phases:
  install:
    runtime-versions:
      nodejs: 10
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --no-include-email --region us-east-1)
      - REPOSITORY_URI=OUR_URL_FROM_ECR
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
      - echo $REPOSITORY_URI
      - echo $COMMIT_HASH
      - echo $IMAGE_TAG
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"Petr","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
artifacts:
    files: imagedefinitions.json
</code>```

We created a new pipeline flow, but when we push some changes we get this log:

```<code>[Container] 2019/11/07 23:30:49 Waiting for agent ping
[Container] 2019/11/07 23:30:51 Waiting for DOWNLOAD_SOURCE
[Container] 2019/11/07 23:30:52 Phase is DOWNLOAD_SOURCE
[Container] 2019/11/07 23:30:52 CODEBUILD_SRC_DIR=/codebuild/output/src386464501/src
[Container] 2019/11/07 23:30:52 YAML location is /codebuild/output/src386464501/src/buildspec.yml
[Container] 2019/11/07 23:30:52 No commands found for phase name: INSTALL
[Container] 2019/11/07 23:30:52 Processing environment variables
[Container] 2019/11/07 23:30:52 Moving to directory /codebuild/output/src386464501/src
[Container] 2019/11/07 23:30:52 Registering with agent
[Container] 2019/11/07 23:30:52 Phases found in YAML: 4
[Container] 2019/11/07 23:30:52  POST_BUILD: 6 commands
[Container] 2019/11/07 23:30:52  INSTALL: 0 commands
[Container] 2019/11/07 23:30:52  PRE_BUILD: 9 commands
[Container] 2019/11/07 23:30:52  BUILD: 4 commands
[Container] 2019/11/07 23:30:52 Phase complete: DOWNLOAD_SOURCE State: SUCCEEDED
[Container] 2019/11/07 23:30:52 Phase context status code:  Message:
[Container] 2019/11/07 23:30:52 Entering phase INSTALL
[Container] 2019/11/07 23:30:52 Running command echo "Installing Node.js version 10 ..."
Installing Node.js version 10 ...

[Container] 2019/11/07 23:30:52 Running command n 10.16.3
   installed : v10.16.3 (with npm 6.9.0)

[Container] 2019/11/07 23:31:02 Phase complete: INSTALL State: SUCCEEDED
[Container] 2019/11/07 23:31:02 Phase context status code:  Message:
[Container] 2019/11/07 23:31:02 Entering phase PRE_BUILD
[Container] 2019/11/07 23:31:02 Running command echo Logging in to Amazon ECR...
Logging in to Amazon ECR...

[Container] 2019/11/07 23:31:02 Running command aws --version
aws-cli/1.16.242 Python/3.6.8 Linux/4.14.143-91.122.amzn1.x86_64 exec-env/AWS_ECS_EC2 botocore/1.12.232

[Container] 2019/11/07 23:31:07 Running command $(aws ecr get-login --no-include-email --region us-east-1)
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

[Container] 2019/11/07 23:31:10 Running command REPOSITORY_URI=***********

[Container] 2019/11/07 23:31:10 Running command COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)

[Container] 2019/11/07 23:31:10 Running command IMAGE_TAG=${COMMIT_HASH:=latest}

[Container] 2019/11/07 23:31:10 Running command echo $REPOSITORY_URI
***********

[Container] 2019/11/07 23:31:10 Running command echo $COMMIT_HASH
88f8cfc

[Container] 2019/11/07 23:31:10 Running command echo $IMAGE_TAG
88f8cfc

[Container] 2019/11/07 23:31:10 Phase complete: PRE_BUILD State: SUCCEEDED
[Container] 2019/11/07 23:31:10 Phase context status code:  Message:
[Container] 2019/11/07 23:31:10 Entering phase BUILD
[Container] 2019/11/07 23:31:10 Running command echo Build started on `date`
Build started on Thu Nov 7 23:31:10 UTC 2019

[Container] 2019/11/07 23:31:10 Running command echo Building the Docker image...
Building the Docker image...

[Container] 2019/11/07 23:31:10 Running command docker build -t $REPOSITORY_URI:latest .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

[Container] 2019/11/07 23:31:10 Command did not exit successfully docker build -t $REPOSITORY_URI:latest . exit status 1
[Container] 2019/11/07 23:31:10 Phase complete: BUILD State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: docker build -t $REPOSITORY_URI:latest .. Reason: exit status 1
[Container] 2019/11/07 23:31:10 Entering phase POST_BUILD
[Container] 2019/11/07 23:31:10 Running command echo Build completed on `date`
Build completed on Thu Nov 7 23:31:10 UTC 2019

[Container] 2019/11/07 23:31:10 Running command echo Pushing the Docker images...
Pushing the Docker images...

[Container] 2019/11/07 23:31:10 Running command docker push $REPOSITORY_URI:latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

[Container] 2019/11/07 23:31:10 Command did not exit successfully docker push $REPOSITORY_URI:latest exit status 1
[Container] 2019/11/07 23:31:10 Phase complete: POST_BUILD State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: docker push $REPOSITORY_URI:latest. Reason: exit status 1
[Container] 2019/11/07 23:31:10 Expanding base directory path: .
[Container] 2019/11/07 23:31:10 Assembling file list
[Container] 2019/11/07 23:31:10 Expanding .
[Container] 2019/11/07 23:31:10 Expanding file paths for base directory .
[Container] 2019/11/07 23:31:10 Assembling file list
[Container] 2019/11/07 23:31:10 Expanding imagedefinitions.json
[Container] 2019/11/07 23:31:10 Skipping invalid file path imagedefinitions.json
[Container] 2019/11/07 23:31:10 Phase complete: UPLOAD_ARTIFACTS State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: CLIENT_ERROR Message: no matching artifact paths found
</code>```

We wanna know if we are missing something, we follow some steps from here:

https://aws.amazon.com/es/blogs/devops/build-a-continuous-delivery-pipeline-for-your-container-images-with-amazon-ecr-as-source/

Any advice?

答:
I ran into similar error. The fix is, this build project needs to build a Docker image therefore set Privilege Mode to true.

Privileged mode grants a build project's Docker container access.

Body:
we wanna try CodePipeline with a image that we already have on ECR.

So we follow the steps on the documentation.

We have buildspec.yml like this:

phases:
  install:
    runtime-versions:
      nodejs: 10
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --no-include-email --region us-east-1)
      - REPOSITORY_URI=OUR_URL_FROM_ECR
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
      - echo $REPOSITORY_URI
      - echo $COMMIT_HASH
      - echo $IMAGE_TAG
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"Petr","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
artifacts:
    files: imagedefinitions.json

We created a new pipeline flow, but when we push some changes we get this log:

[Container] 2019/11/07 23:30:49 Waiting for agent ping
[Container] 2019/11/07 23:30:51 Waiting for DOWNLOAD_SOURCE
[Container] 2019/11/07 23:30:52 Phase is DOWNLOAD_SOURCE
[Container] 2019/11/07 23:30:52 CODEBUILD_SRC_DIR=/codebuild/output/src386464501/src
[Container] 2019/11/07 23:30:52 YAML location is /codebuild/output/src386464501/src/buildspec.yml
[Container] 2019/11/07 23:30:52 No commands found for phase name: INSTALL
[Container] 2019/11/07 23:30:52 Processing environment variables
[Container] 2019/11/07 23:30:52 Moving to directory /codebuild/output/src386464501/src
[Container] 2019/11/07 23:30:52 Registering with agent
[Container] 2019/11/07 23:30:52 Phases found in YAML: 4
[Container] 2019/11/07 23:30:52  POST_BUILD: 6 commands
[Container] 2019/11/07 23:30:52  INSTALL: 0 commands
[Container] 2019/11/07 23:30:52  PRE_BUILD: 9 commands
[Container] 2019/11/07 23:30:52  BUILD: 4 commands
[Container] 2019/11/07 23:30:52 Phase complete: DOWNLOAD_SOURCE State: SUCCEEDED
[Container] 2019/11/07 23:30:52 Phase context status code:  Message:
[Container] 2019/11/07 23:30:52 Entering phase INSTALL
[Container] 2019/11/07 23:30:52 Running command echo "Installing Node.js version 10 ..."
Installing Node.js version 10 ...

[Container] 2019/11/07 23:30:52 Running command n 10.16.3
   installed : v10.16.3 (with npm 6.9.0)

[Container] 2019/11/07 23:31:02 Phase complete: INSTALL State: SUCCEEDED
[Container] 2019/11/07 23:31:02 Phase context status code:  Message:
[Container] 2019/11/07 23:31:02 Entering phase PRE_BUILD
[Container] 2019/11/07 23:31:02 Running command echo Logging in to Amazon ECR...
Logging in to Amazon ECR...

[Container] 2019/11/07 23:31:02 Running command aws --version
aws-cli/1.16.242 Python/3.6.8 Linux/4.14.143-91.122.amzn1.x86_64 exec-env/AWS_ECS_EC2 botocore/1.12.232

[Container] 2019/11/07 23:31:07 Running command $(aws ecr get-login --no-include-email --region us-east-1)
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

[Container] 2019/11/07 23:31:10 Running command REPOSITORY_URI=***********

[Container] 2019/11/07 23:31:10 Running command COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)

[Container] 2019/11/07 23:31:10 Running command IMAGE_TAG=${COMMIT_HASH:=latest}

[Container] 2019/11/07 23:31:10 Running command echo $REPOSITORY_URI
***********

[Container] 2019/11/07 23:31:10 Running command echo $COMMIT_HASH
88f8cfc

[Container] 2019/11/07 23:31:10 Running command echo $IMAGE_TAG
88f8cfc

[Container] 2019/11/07 23:31:10 Phase complete: PRE_BUILD State: SUCCEEDED
[Container] 2019/11/07 23:31:10 Phase context status code:  Message:
[Container] 2019/11/07 23:31:10 Entering phase BUILD
[Container] 2019/11/07 23:31:10 Running command echo Build started on `date`
Build started on Thu Nov 7 23:31:10 UTC 2019

[Container] 2019/11/07 23:31:10 Running command echo Building the Docker image...
Building the Docker image...

[Container] 2019/11/07 23:31:10 Running command docker build -t $REPOSITORY_URI:latest .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

[Container] 2019/11/07 23:31:10 Command did not exit successfully docker build -t $REPOSITORY_URI:latest . exit status 1
[Container] 2019/11/07 23:31:10 Phase complete: BUILD State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: docker build -t $REPOSITORY_URI:latest .. Reason: exit status 1
[Container] 2019/11/07 23:31:10 Entering phase POST_BUILD
[Container] 2019/11/07 23:31:10 Running command echo Build completed on `date`
Build completed on Thu Nov 7 23:31:10 UTC 2019

[Container] 2019/11/07 23:31:10 Running command echo Pushing the Docker images...
Pushing the Docker images...

[Container] 2019/11/07 23:31:10 Running command docker push $REPOSITORY_URI:latest
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

[Container] 2019/11/07 23:31:10 Command did not exit successfully docker push $REPOSITORY_URI:latest exit status 1
[Container] 2019/11/07 23:31:10 Phase complete: POST_BUILD State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: docker push $REPOSITORY_URI:latest. Reason: exit status 1
[Container] 2019/11/07 23:31:10 Expanding base directory path: .
[Container] 2019/11/07 23:31:10 Assembling file list
[Container] 2019/11/07 23:31:10 Expanding .
[Container] 2019/11/07 23:31:10 Expanding file paths for base directory .
[Container] 2019/11/07 23:31:10 Assembling file list
[Container] 2019/11/07 23:31:10 Expanding imagedefinitions.json
[Container] 2019/11/07 23:31:10 Skipping invalid file path imagedefinitions.json
[Container] 2019/11/07 23:31:10 Phase complete: UPLOAD_ARTIFACTS State: FAILED
[Container] 2019/11/07 23:31:10 Phase context status code: CLIENT_ERROR Message: no matching artifact paths found

We wanna know if we are missing something, we follow some steps from here:

https://aws.amazon.com/es/blogs/devops/build-a-continuous-delivery-pipeline-for-your-container-images-with-amazon-ecr-as-source/

Any advice?