问:
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
Im trying to fix this error that I keep getting when I run /help, and don't know what I did wrong, I tried to do what I could with the error, but im getting annoyed at this point.

My error:

```<code>/app/slashCommands/Miscellaneous/help.js:138
   const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
                         ^
  TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
</code>```

Code:

```<code>const { MessageEmbed, Message, Client } = require("discord.js");
const { readdirSync } = require("fs");
const client = require("../../index");
const config = require("../../botconfig");
const create_menu = require("../../models/helpMenu.js");
const prefixSchema = require("../../models/prefix");

module.exports = {
  name: "help",
  description: "Displays all available command categories!",
  aliases: ["h"],
  usage: "<command> or <category>",
  run: async (client, interaction, args, db) => {
    const data = await prefixSchema.findOne({ Guild: interaction.guild.id });

    if (data) {
      let categories = [];
      let cots = [];

      if (!args[0]) {
        let ignored = ["Giveaway", "Owner"];

        const emoji = {
          Action: "",
          Admin: "",
          Birthday: "",
          Economy: "",
          Fun: "",
          Giveaway: "",
          Image: "",
          Minigame: "",
          Miscellaneous: "⚙",
          Moderation: "",
          Owner: "",
          Ticket: "",
        };

        let cmdCategory = [];

        readdirSync("./commands/").forEach((dir) => {
          if (ignored.includes(dir)) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          if (ignored.includes(dir)) return;

          const name = `${emoji[dir]} - ${dir}`;

          let categoryName = dir;

          let categoryDir = new Object();

          categoryDir = {
            name: name,
            value: "",
            inline: true,
          };

          categories.push(categoryDir);
          cmdCategory.push(categoryName);
        });

        const embed = new MessageEmbed()
          .setTitle("__Crimson's Help Menu__")
          .setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`${data.Prefix}\``)
          .setThumbnail(client.user.displayAvatarURL())
          .addFields(categories)
          .setColor("#EE1C25")
          .setFooter("Navigate through the embeds using the provided menu below", interaction.user.displayAvatarURL())
          .setTimestamp();

        let menus = create_menu(cmdCategory);
        return interaction.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
            const menuID = menus.sid;

            const select = async (interaction) => {
              if (interaction.customId != menuID) return;

              let { values } = interaction;

              let value = values[0];

              let commands2 = [];

              readdirSync("./commands/").forEach((dir) => {
                if (dir.toLowerCase() !== value.toLowerCase()) return;
                const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

                const cmds = commands.map((command) => {
                  let file = require(`../../commands/${dir}/${command}`);

                  if (!file.name) return "No command name.";

                  let name = file.name.replace(".js", "");

                  if (client.commands.get(name).hidden) return;

                  let emoji = client.commands.get(name).emoji;
                  let emoji2 = emoji ? `${emoji} ` : "• ";

                  let obj = { cname: `${emoji2}\`${name}\`` };

                  return obj;
                });

                let dota = new Object();

                cmds.map((co) => {
                  if (co == undefined) return;

                  dota = {
                    name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
                    value: "",
                    inline: true,
                  };
                  commands2.push(dota);
                });

                cots.push(dir.toLowerCase());
              });

              if (cots.includes(value.toLowerCase())) {
                const cmdEmbed = new MessageEmbed()
                  .setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
                  .addFields(commands2)
                  .setColor("#EE1C25");

                await interaction.deferUpdate();

                return interaction.editReply({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
              }
            };

            const filter = (interaction) => {
              if (interaction.user.id === interaction.user.id) return true;
              return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> You cannot use this menu.", ephemeral: true });
            };

            const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
            collector.on("collect", select);
            collector.on("end", () => null);
          });
      } else {
        let commands2 = [];

        readdirSync("./commands/").forEach((dir) => {
          if (dir.toLowerCase() !== args[0].toLowerCase()) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          const cmds = commands.map((command) => {
            let file = require(`../../commands/${dir}/${command}`);

            if (!file.name) return "Unable to find requested command";

            let name = file.name.replace(".js", "");

            if (client.commands.get(name).hidden) return;

            let emoji = client.commands.get(name).emoji;
            let emoji2 = emoji ? `${emoji} ` : "";

            let obj = { cname: `${emoji2}\`${name}\`` };

            return obj;
          });

          let dota = new Object();

          cmds.map((co) => {
            if (co == undefined) return;

            dota = {
              name: `${cmds.length === 0 ? "In progress..." : "• " + co.cname}`,
              value: "",
              inline: true,
            };
            commands2.push(dota);
          });

          cots.push(dir.toLowerCase());
        });

        const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

        if (cots.includes(args[0].toLowerCase())) {
          const cmdEmbed = new MessageEmbed()
            .setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
            .addFields(commands2)
            .setColor("#EE1C25");
          return interaction.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
        }

        if (!command) {
          const noCmdEmbed = new MessageEmbed()
            .setTitle("Unknown Command/Category")
            .setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
            .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
            .setTimestamp()
            .setColor("#EE1C25");
          return await interaction.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
        }

        const cmdDetailsEmbed = new MessageEmbed()
          .setThumbnail(client.user.displayAvatarURL())
          .setDescription(`**Command:** \`${command.name}\``)
          .addFields(
            {
              name: "Usage",
              value: command.usage
                ? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
                : "`No usage for this command`",
            },
            {
              name: "Description",
              value: command.description
                ? `\`\`\`${command.description}\`\`\``
                : "`No description for this command`",
            },
            {
              name: "Aliases",
              value: command.aliases
                ? `\`\`\`${command.aliases.join(", ")}\`\`\``
                : "`No aliases for this command`",
            }
          )
          .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
          .setTimestamp()
          .setColor("#EE1C25");
        return await interaction.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
      }
    } else if (!data) {
      let categories = [];
      let cots = [];

      if (!args[0]) {
        let ignored = ["Giveaway", "Owner"];

        const emoji = {
          Action: "",
          Admin: "",
          Birthday: "",
          Economy: "",
          Fun: "",
          Giveaway: "",
          Image: "",
          Minigame: "",
          Miscellaneous: "⚙",
          Moderation: "",
          Owner: "",
          Ticket: "",
        };

        let cmdCategory = [];

        readdirSync("./commands/").forEach((dir) => {
          if (ignored.includes(dir)) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          if (ignored.includes(dir)) return;

          const name = `${emoji[dir]} - ${dir}`;

          let categoryName = dir;

          let categoryDir = new Object();

          categoryDir = {
            name: name,
            value: "",
            inline: true,
          };

          categories.push(categoryDir);
          cmdCategory.push(categoryName);
        });

        const embed = new MessageEmbed()
          .setTitle("__Crimson's Help Menu__")
          .setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`none\``)
          .setThumbnail(client.user.displayAvatarURL())
          .addFields(categories)
          .setColor("#EE1C25")
          .setFooter("Navigate through the embeds using the provided menu below", interaction.user.displayAvatarURL())
          .setTimestamp();

        let menus = create_menu(cmdCategory);
        return interaction.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
            const menuID = menus.sid;

            const select = async (interaction) => {
              if (interaction.customId != menuID) return;

              let { values } = interaction;

              let value = values[0];

              let commands2 = [];

              readdirSync("./commands/").forEach((dir) => {
                if (dir.toLowerCase() !== value.toLowerCase()) return;
                const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

                const cmds = commands.map((command) => {
                  let file = require(`../../commands/${dir}/${command}`);

                  if (!file.name) return "No command name.";

                  let name = file.name.replace(".js", "");

                  if (client.commands.get(name).hidden) return;

                  let emoji = client.commands.get(name).emoji;
                  let emoji2 = emoji ? `${emoji} ` : "• ";

                  let obj = { cname: `${emoji2}\`${name}\`` };

                  return obj;
                });

                let dota = new Object();

                cmds.map((co) => {
                  if (co == undefined) return;

                  dota = {
                    name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
                    value: "",
                    inline: true,
                  };
                  commands2.push(dota);
                });

                cots.push(dir.toLowerCase());
              });

              if (cots.includes(value.toLowerCase())) {
                const cmdEmbed = new MessageEmbed()
                  .setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
                  .addFields(commands2)
                  .setColor("#EE1C25");

                await interaction.deferUpdate();

                return interaction.editReply({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
              }
            };

            const filter = (interaction) => {
              if (interaction.user.id === interaction.user.id) return true;
              return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> You cannot use this menu.", ephemeral: true });
            };

            const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
            collector.on("collect", select);
            collector.on("end", () => null);
          });
      } else {
        let commands2 = [];

        readdirSync("./commands/").forEach((dir) => {
          if (dir.toLowerCase() !== args[0].toLowerCase()) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          const cmds = commands.map((command) => {
            let file = require(`../../commands/${dir}/${command}`);

            if (!file.name) return "Unable to find requested command";

            let name = file.name.replace(".js", "");

            if (client.commands.get(name).hidden) return;

            let emoji = client.commands.get(name).emoji;
            let emoji2 = emoji ? `${emoji} ` : "";

            let obj = { cname: `${emoji2}\`${name}\`` };

            return obj;
          });

          let dota = new Object();

          cmds.map((co) => {
            if (co == undefined) return;

            dota = {
              name: `${cmds.length === 0 ? "In progress..." : "• " + co.cname}`,
              value: "",
              inline: true,
            };
            commands2.push(dota);
          });

          cots.push(dir.toLowerCase());
        });

        const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

        if (cots.includes(args[0].toLowerCase())) {
          const cmdEmbed = new MessageEmbed()
            .setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
            .addFields(commands2)
            .setColor("#EE1C25");
          return interaction.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
        }

        if (!command) {
          const noCmdEmbed = new MessageEmbed()
            .setTitle("Unknown Command/Category")
            .setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
            .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
            .setTimestamp()
            .setColor("#EE1C25");
          return await interaction.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
        }

        const cmdDetailsEmbed = new MessageEmbed()
          .setThumbnail(client.user.displayAvatarURL())
          .setDescription(`**Command:** \`${command.name}\``)
          .addFields(
            {
              name: "Usage",
              value: command.usage
                ? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
                : "`No usage for this command`",
            },
            {
              name: "Description",
              value: command.description
                ? `\`\`\`${command.description}\`\`\``
                : "`No description for this command`",
            },
            {
              name: "Aliases",
              value: command.aliases
                ? `\`\`\`${command.aliases.join(", ")}\`\`\``
                : "`No aliases for this command`",
            })
          .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
          .setTimestamp()
          .setColor("#EE1C25");
        return await interaction.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
      }
    }
  },
};
</code>```

答:
Without seeing your code there's not much we can help you with, but from the error I would assume that msg is undefined.
Try logging msg before creating the collector, if it returns undefined, there's your problem.

Body:
Im trying to fix this error that I keep getting when I run /help, and don't know what I did wrong, I tried to do what I could with the error, but im getting annoyed at this point.

My error:

/app/slashCommands/Miscellaneous/help.js:138
   const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
                         ^
  TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')

Code:

const { MessageEmbed, Message, Client } = require("discord.js");
const { readdirSync } = require("fs");
const client = require("../../index");
const config = require("../../botconfig");
const create_menu = require("../../models/helpMenu.js");
const prefixSchema = require("../../models/prefix");

module.exports = {
  name: "help",
  description: "Displays all available command categories!",
  aliases: ["h"],
  usage: "<command> or <category>",
  run: async (client, interaction, args, db) => {
    const data = await prefixSchema.findOne({ Guild: interaction.guild.id });

    if (data) {
      let categories = [];
      let cots = [];

      if (!args[0]) {
        let ignored = ["Giveaway", "Owner"];

        const emoji = {
          Action: "",
          Admin: "",
          Birthday: "",
          Economy: "",
          Fun: "",
          Giveaway: "",
          Image: "",
          Minigame: "",
          Miscellaneous: "⚙",
          Moderation: "",
          Owner: "",
          Ticket: "",
        };

        let cmdCategory = [];

        readdirSync("./commands/").forEach((dir) => {
          if (ignored.includes(dir)) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          if (ignored.includes(dir)) return;

          const name = `${emoji[dir]} - ${dir}`;

          let categoryName = dir;

          let categoryDir = new Object();

          categoryDir = {
            name: name,
            value: "",
            inline: true,
          };

          categories.push(categoryDir);
          cmdCategory.push(categoryName);
        });

        const embed = new MessageEmbed()
          .setTitle("__Crimson's Help Menu__")
          .setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`${data.Prefix}\``)
          .setThumbnail(client.user.displayAvatarURL())
          .addFields(categories)
          .setColor("#EE1C25")
          .setFooter("Navigate through the embeds using the provided menu below", interaction.user.displayAvatarURL())
          .setTimestamp();

        let menus = create_menu(cmdCategory);
        return interaction.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
            const menuID = menus.sid;

            const select = async (interaction) => {
              if (interaction.customId != menuID) return;

              let { values } = interaction;

              let value = values[0];

              let commands2 = [];

              readdirSync("./commands/").forEach((dir) => {
                if (dir.toLowerCase() !== value.toLowerCase()) return;
                const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

                const cmds = commands.map((command) => {
                  let file = require(`../../commands/${dir}/${command}`);

                  if (!file.name) return "No command name.";

                  let name = file.name.replace(".js", "");

                  if (client.commands.get(name).hidden) return;

                  let emoji = client.commands.get(name).emoji;
                  let emoji2 = emoji ? `${emoji} ` : "• ";

                  let obj = { cname: `${emoji2}\`${name}\`` };

                  return obj;
                });

                let dota = new Object();

                cmds.map((co) => {
                  if (co == undefined) return;

                  dota = {
                    name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
                    value: "",
                    inline: true,
                  };
                  commands2.push(dota);
                });

                cots.push(dir.toLowerCase());
              });

              if (cots.includes(value.toLowerCase())) {
                const cmdEmbed = new MessageEmbed()
                  .setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
                  .addFields(commands2)
                  .setColor("#EE1C25");

                await interaction.deferUpdate();

                return interaction.editReply({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
              }
            };

            const filter = (interaction) => {
              if (interaction.user.id === interaction.user.id) return true;
              return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> You cannot use this menu.", ephemeral: true });
            };

            const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
            collector.on("collect", select);
            collector.on("end", () => null);
          });
      } else {
        let commands2 = [];

        readdirSync("./commands/").forEach((dir) => {
          if (dir.toLowerCase() !== args[0].toLowerCase()) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          const cmds = commands.map((command) => {
            let file = require(`../../commands/${dir}/${command}`);

            if (!file.name) return "Unable to find requested command";

            let name = file.name.replace(".js", "");

            if (client.commands.get(name).hidden) return;

            let emoji = client.commands.get(name).emoji;
            let emoji2 = emoji ? `${emoji} ` : "";

            let obj = { cname: `${emoji2}\`${name}\`` };

            return obj;
          });

          let dota = new Object();

          cmds.map((co) => {
            if (co == undefined) return;

            dota = {
              name: `${cmds.length === 0 ? "In progress..." : "• " + co.cname}`,
              value: "",
              inline: true,
            };
            commands2.push(dota);
          });

          cots.push(dir.toLowerCase());
        });

        const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

        if (cots.includes(args[0].toLowerCase())) {
          const cmdEmbed = new MessageEmbed()
            .setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
            .addFields(commands2)
            .setColor("#EE1C25");
          return interaction.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
        }

        if (!command) {
          const noCmdEmbed = new MessageEmbed()
            .setTitle("Unknown Command/Category")
            .setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
            .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
            .setTimestamp()
            .setColor("#EE1C25");
          return await interaction.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
        }

        const cmdDetailsEmbed = new MessageEmbed()
          .setThumbnail(client.user.displayAvatarURL())
          .setDescription(`**Command:** \`${command.name}\``)
          .addFields(
            {
              name: "Usage",
              value: command.usage
                ? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
                : "`No usage for this command`",
            },
            {
              name: "Description",
              value: command.description
                ? `\`\`\`${command.description}\`\`\``
                : "`No description for this command`",
            },
            {
              name: "Aliases",
              value: command.aliases
                ? `\`\`\`${command.aliases.join(", ")}\`\`\``
                : "`No aliases for this command`",
            }
          )
          .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
          .setTimestamp()
          .setColor("#EE1C25");
        return await interaction.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
      }
    } else if (!data) {
      let categories = [];
      let cots = [];

      if (!args[0]) {
        let ignored = ["Giveaway", "Owner"];

        const emoji = {
          Action: "",
          Admin: "",
          Birthday: "",
          Economy: "",
          Fun: "",
          Giveaway: "",
          Image: "",
          Minigame: "",
          Miscellaneous: "⚙",
          Moderation: "",
          Owner: "",
          Ticket: "",
        };

        let cmdCategory = [];

        readdirSync("./commands/").forEach((dir) => {
          if (ignored.includes(dir)) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          if (ignored.includes(dir)) return;

          const name = `${emoji[dir]} - ${dir}`;

          let categoryName = dir;

          let categoryDir = new Object();

          categoryDir = {
            name: name,
            value: "",
            inline: true,
          };

          categories.push(categoryDir);
          cmdCategory.push(categoryName);
        });

        const embed = new MessageEmbed()
          .setTitle("__Crimson's Help Menu__")
          .setDescription(`>>> Default Prefix: \`${config.defaultPrefix}\`\nServer Prefix: \`none\``)
          .setThumbnail(client.user.displayAvatarURL())
          .addFields(categories)
          .setColor("#EE1C25")
          .setFooter("Navigate through the embeds using the provided menu below", interaction.user.displayAvatarURL())
          .setTimestamp();

        let menus = create_menu(cmdCategory);
        return interaction.reply({ embeds: [embed], components: menus.smenu, allowedMentions: { repliedUser: true } }).then((msg) => {
            const menuID = menus.sid;

            const select = async (interaction) => {
              if (interaction.customId != menuID) return;

              let { values } = interaction;

              let value = values[0];

              let commands2 = [];

              readdirSync("./commands/").forEach((dir) => {
                if (dir.toLowerCase() !== value.toLowerCase()) return;
                const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

                const cmds = commands.map((command) => {
                  let file = require(`../../commands/${dir}/${command}`);

                  if (!file.name) return "No command name.";

                  let name = file.name.replace(".js", "");

                  if (client.commands.get(name).hidden) return;

                  let emoji = client.commands.get(name).emoji;
                  let emoji2 = emoji ? `${emoji} ` : "• ";

                  let obj = { cname: `${emoji2}\`${name}\`` };

                  return obj;
                });

                let dota = new Object();

                cmds.map((co) => {
                  if (co == undefined) return;

                  dota = {
                    name: `${cmds.length === 0 ? "Processing..." : co.cname}`,
                    value: "",
                    inline: true,
                  };
                  commands2.push(dota);
                });

                cots.push(dir.toLowerCase());
              });

              if (cots.includes(value.toLowerCase())) {
                const cmdEmbed = new MessageEmbed()
                  .setTitle(`__${value.charAt(0) + value.slice(1)} Commands__`)
                  .addFields(commands2)
                  .setColor("#EE1C25");

                await interaction.deferUpdate();

                return interaction.editReply({ embeds: [cmdEmbed], components: menus.smenu, allowedMentions: { repliedUser: true } });
              }
            };

            const filter = (interaction) => {
              if (interaction.user.id === interaction.user.id) return true;
              return interaction.reply({ content: "<:CL_VoteCross:781265541804720148> You cannot use this menu.", ephemeral: true });
            };

            const collector = msg.createMessageComponentCollector({ filter, componentType: "SELECT_MENU" });
            collector.on("collect", select);
            collector.on("end", () => null);
          });
      } else {
        let commands2 = [];

        readdirSync("./commands/").forEach((dir) => {
          if (dir.toLowerCase() !== args[0].toLowerCase()) return;
          const commands = readdirSync(`./commands/${dir}/`).filter((file) => file.endsWith(".js"));

          const cmds = commands.map((command) => {
            let file = require(`../../commands/${dir}/${command}`);

            if (!file.name) return "Unable to find requested command";

            let name = file.name.replace(".js", "");

            if (client.commands.get(name).hidden) return;

            let emoji = client.commands.get(name).emoji;
            let emoji2 = emoji ? `${emoji} ` : "";

            let obj = { cname: `${emoji2}\`${name}\`` };

            return obj;
          });

          let dota = new Object();

          cmds.map((co) => {
            if (co == undefined) return;

            dota = {
              name: `${cmds.length === 0 ? "In progress..." : "• " + co.cname}`,
              value: "",
              inline: true,
            };
            commands2.push(dota);
          });

          cots.push(dir.toLowerCase());
        });

        const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));

        if (cots.includes(args[0].toLowerCase())) {
          const cmdEmbed = new MessageEmbed()
            .setTitle(`__${args[0].charAt(0) + args[0].slice(1)} commands__`)
            .addFields(commands2)
            .setColor("#EE1C25");
          return interaction.reply({ embeds: [cmdEmbed], allowedMentions: { repliedUser: true } });
        }

        if (!command) {
          const noCmdEmbed = new MessageEmbed()
            .setTitle("Unknown Command/Category")
            .setDescription(`The command or category you are trying to find is not in our database, if you think this is a mistake.. please let us know!\n\n\n**Options**\n\`\`\`${config.defaultPrefix}help <category name>\`\`\` \`\`\`${config.defaultPrefix}help <command name>\`\`\``)
            .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
            .setTimestamp()
            .setColor("#EE1C25");
          return await interaction.reply({ embeds: [noCmdEmbed], allowedMentions: { repliedUser: true } });
        }

        const cmdDetailsEmbed = new MessageEmbed()
          .setThumbnail(client.user.displayAvatarURL())
          .setDescription(`**Command:** \`${command.name}\``)
          .addFields(
            {
              name: "Usage",
              value: command.usage
                ? `\`\`\`${config.defaultPrefix}${command.name} ${command.usage}\`\`\``
                : "`No usage for this command`",
            },
            {
              name: "Description",
              value: command.description
                ? `\`\`\`${command.description}\`\`\``
                : "`No description for this command`",
            },
            {
              name: "Aliases",
              value: command.aliases
                ? `\`\`\`${command.aliases.join(", ")}\`\`\``
                : "`No aliases for this command`",
            })
          .setFooter(`Command Requested by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true }))
          .setTimestamp()
          .setColor("#EE1C25");
        return await interaction.reply({ embeds: [cmdDetailsEmbed], allowedMentions: { repliedUser: true } });
      }
    }
  },
};


来源: stackexchange

问:
NLP: how can I transform a string into a sequence of numbers that represent it's label
I'm a beginner and I am trying to figure out how to approach an NLP problem. All help is much appreciated.

How can I transform a string into a label.

For example if I have the string " I liked this movie very much" and its label is {positive: 1} I would like to make the entire string represent this label. It should look something like this: "I like this movie very much" --> 1 1 1 1 1 1 . Each "1" representing a word from the sentence that's labeled as positive.

I am not sure where to start. I did extensive research online and couldn't find anything to help me get this done or even started. Any links and/or code suggestions are much appreciated.

答:
If I understand your question correctly, you have a an input data structure along the lines of

```<code>reviews = [
    ('I liked this movie very much', 1), # positive sentiment
    ('I hated this movie', 0) # negative sentiment
]
</code>```

To assign each word in the string with the same value as the whole string, you need to split the string. You can save the data in a new list structure. Try something like:

```<code>split_sentences = []
for sentence, sentiment in reviews:
    split_sentence = sentence.split()
    split_sentences.append([(word, sentiment) for word in split_sentence])
</code>```

Your output of split_sentences will be

```<code>[[('I', 1), ('liked', 1), ('this', 1), ('movie', 1), ('very', 1), ('much', 1)],
 [('I', 0), ('hated', 0), ('this', 0), ('movie', 0)]]
</code>```

If you literally just need a list of one label per word (substring), you can do

```<code>>>> for sentence, sentiment in reviews:
...     split_sentence = sentence.split()
...     sentiment_per_word = [sentiment for word in split_sentence]
...     print(sentiment_per_word)
...
[1, 1, 1, 1, 1, 1] # "I liked this movie very much"
[0, 0, 0, 0] # "I hated this movie"

</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I understand your question correctly, you have a an input data structure along the lines of

reviews = [
    ('I liked this movie very much', 1), # positive sentiment
    ('I hated this movie', 0) # negative sentiment
]

To assign each word in the string with the same value as the whole string, you need to split the string. You can save the data in a new list structure. Try something like:

split_sentences = []
for sentence, sentiment in reviews:
    split_sentence = sentence.split()
    split_sentences.append([(word, sentiment) for word in split_sentence])

Your output of split_sentences will be

[[('I', 1), ('liked', 1), ('this', 1), ('movie', 1), ('very', 1), ('much', 1)],
 [('I', 0), ('hated', 0), ('this', 0), ('movie', 0)]]

If you literally just need a list of one label per word (substring), you can do

>>> for sentence, sentiment in reviews:
...     split_sentence = sentence.split()
...     sentiment_per_word = [sentiment for word in split_sentence]
...     print(sentiment_per_word)
...
[1, 1, 1, 1, 1, 1] # "I liked this movie very much"
[0, 0, 0, 0] # "I hated this movie"


问:
Unable to build Jenkins script
I have selenium/python frame that I would like to push and use with jenkins.

However, while trying to build the script I get following error:

```<code>Started by user Dusan Kovacevic
Running as SYSTEM
Building in workspace /Users/dusandev/.jenkins/workspace/SeleniumBase
The recommended git tool is: NONE
using credential somecredentials
> git rev-parse --resolve-git-dir
/Users/dusandev/.jenkins/workspace/SeleniumBase/.git # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/StreamFlow-Finance/automated-web-
tests.git # timeout=10
Fetching upstream changes from https://github.com/StreamFlow-Finance/automated-web-
tests.git
> git --version # timeout=10
> git --version # 'git version 2.34.1'
using GIT_ASKPASS to set credentials
> git fetch --tags --force --progress -- https://github.com/StreamFlow-
Finance/automated-web-tests.git +refs/heads/*:refs/remotes/origin/* # timeout=10
> git rev-parse refs/remotes/origin/main^{commit} # timeout=10
Checking out Revision 82fe529ff81267aebb97098fb92e4401abfe0462
(refs/remotes/origin/main)
> git config core.sparsecheckout # timeout=10
> git checkout -f 82fe529ff81267aebb97098fb92e4401abfe0462 # timeout=10
Commit message: "Add files via upload"
> git rev-list --no-walk 82fe529ff81267aebb97098fb92e4401abfe0462 # timeout=10
[SeleniumBase] $ /bin/sh -xe
/var/folders/nb/qbb9ctrn3rb68w54m_yyyqhh0000gn/T/shiningpanda17442261483823605080.sh
+ python -m venv env
+ call ./env/Scripts/activate.bat
/var/folders/nb/qbb9ctrn3rb68w54m_yyyqhh0000gn/T/shiningpanda17442261483823605080.sh:
line 3: call: command not found
Build step 'Custom Python Builder' marked build as failure
Finished: FAILURE
</code>```

Here is what I have under build command in Jenkins:

```<code>python -m venv env
call ./env/Scripts/activate.bat
pip install -r requirements.txt
sbase install chromedriver latest
pytest --headless
</code>```

What I'm trying to do is set up remote testing capabilities. Other teammates being able to run tests whenever they want.

Any help is appreciated and thank you in advance.

答:
Perhaps in order to call a .bat file from a Jenkins script, you need to write it like below.</p>
```<code>start cmd.exe /c ./env/Scripts/activate.bat
</code>```

Title: Unable to build Jenkins script

Body:
I have selenium/python frame that I would like to push and use with jenkins.

However, while trying to build the script I get following error:

Started by user Dusan Kovacevic
Running as SYSTEM
Building in workspace /Users/dusandev/.jenkins/workspace/SeleniumBase
The recommended git tool is: NONE
using credential somecredentials
> git rev-parse --resolve-git-dir
/Users/dusandev/.jenkins/workspace/SeleniumBase/.git # timeout=10
Fetching changes from the remote Git repository
> git config remote.origin.url https://github.com/StreamFlow-Finance/automated-web-
tests.git # timeout=10
Fetching upstream changes from https://github.com/StreamFlow-Finance/automated-web-
tests.git
> git --version # timeout=10
> git --version # 'git version 2.34.1'
using GIT_ASKPASS to set credentials
> git fetch --tags --force --progress -- https://github.com/StreamFlow-
Finance/automated-web-tests.git +refs/heads/*:refs/remotes/origin/* # timeout=10
> git rev-parse refs/remotes/origin/main^{commit} # timeout=10
Checking out Revision 82fe529ff81267aebb97098fb92e4401abfe0462
(refs/remotes/origin/main)
> git config core.sparsecheckout # timeout=10
> git checkout -f 82fe529ff81267aebb97098fb92e4401abfe0462 # timeout=10
Commit message: "Add files via upload"
> git rev-list --no-walk 82fe529ff81267aebb97098fb92e4401abfe0462 # timeout=10
[SeleniumBase] $ /bin/sh -xe
/var/folders/nb/qbb9ctrn3rb68w54m_yyyqhh0000gn/T/shiningpanda17442261483823605080.sh
+ python -m venv env
+ call ./env/Scripts/activate.bat
/var/folders/nb/qbb9ctrn3rb68w54m_yyyqhh0000gn/T/shiningpanda17442261483823605080.sh:
line 3: call: command not found
Build step 'Custom Python Builder' marked build as failure
Finished: FAILURE

Here is what I have under build command in Jenkins:

python -m venv env
call ./env/Scripts/activate.bat
pip install -r requirements.txt
sbase install chromedriver latest
pytest --headless

What I'm trying to do is set up remote testing capabilities. Other teammates being able to run tests whenever they want.

Any help is appreciated and thank you in advance.

Body:
Perhaps in order to call a .bat file from a Jenkins script, you need to write it like below.

start cmd.exe /c ./env/Scripts/activate.bat


问:
Rename the public folder to public_html in laravel
I use Laravel and Vuejs in my project.In my project, I changed the name of the public folder to public_html. When I run the "npm run watch" command, the public folder is created again, which is a problem for me.

in AppServiceProvider

```<code>class AppServiceProvider extends ServiceProvider
   {
   /**
   * Register any application services.
   *
   * @return void
   */
  public function register()
   {
    $this->app->bind('path.public',function (){
        return base_path().'/public_html';
    });
   }

  /**
   * Bootstrap any application services.
   *
   * @return void
   */
   public function boot()
   {
    //
   }
 }
</code>```

and in my server.php code:

```<code><?php

/**
* Laravel - A PHP Framework For Web Artisans
*
* @package  Laravel
* @author   Taylor Otwell <taylor@laravel.com>
*/

$uri = urldecode(
  parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

 // This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
 if ($uri !== '/' && file_exists(__DIR__ . '/public_html' . $uri)) {
  return false;
 }

 require_once __DIR__ . '/public_html/index.php';
</code>```

and in webpack.mix.js

```<code>const mix = require('laravel-mix');

 /*
 |-------------------------------------------------------------
 | Mix Asset Management
 |------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build
    steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

  mix.js('resources/js/app.js', 'public_html/js')
    .sass('resources/sass/app.scss', 'public_html/css');
</code>```

Does anyone know how to fix this problem so that the public folder is not re-created?

答: You can do that by calling mix.setPublicPath("your-public-path") in your webpack.mix.js

Body:
I use Laravel and Vuejs in my project.In my project, I changed the name of the public folder to public_html. When I run the "npm run watch" command, the public folder is created again, which is a problem for me.

in AppServiceProvider

class AppServiceProvider extends ServiceProvider
   {
   /**
   * Register any application services.
   *
   * @return void
   */
  public function register()
   {
    $this->app->bind('path.public',function (){
        return base_path().'/public_html';
    });
   }

  /**
   * Bootstrap any application services.
   *
   * @return void
   */
   public function boot()
   {
    //
   }
 }

and in my server.php code:

<?php

/**
* Laravel - A PHP Framework For Web Artisans
*
* @package  Laravel
* @author   Taylor Otwell <taylor@laravel.com>
*/

$uri = urldecode(
  parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

 // This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
 if ($uri !== '/' && file_exists(__DIR__ . '/public_html' . $uri)) {
  return false;
 }

 require_once __DIR__ . '/public_html/index.php';

and in webpack.mix.js

const mix = require('laravel-mix');

 /*
 |-------------------------------------------------------------
 | Mix Asset Management
 |------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build
    steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

  mix.js('resources/js/app.js', 'public_html/js')
    .sass('resources/sass/app.scss', 'public_html/css');

Does anyone know how to fix this problem so that the public folder is not re-created?


问:
Error: Provider configuration not present
Im trying to update terraform version from 0.12 to 0.13. While updating the terraform I came across on an issue during plan

```<code>Error: Provider configuration not present

To work with
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription
its original provider configuration at provider["registry.terraform.io/-/aws"]
is required, but it has been removed. This occurs when a provider
configuration is removed while objects created by that provider still exist in
the state. Re-add the provider configuration to destroy
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription,
after which you can remove the provider configuration again.
</code>```

Could someone please help?

答:
Most of the time you'll have a global.tf file in your directory that lists some things that might not actually be resources. This is where you'd normally have a block like this:

```<code>provider "aws" {
  region     = "REGION"
  access_key = "my-access-key"
  secret_key = "my-secret-key"
}
</code>```

Looks like that block, whatever file it was in, got deleted. Add it back and then try again. Note you'll need to change REGION to whatever region you put your resources in. In lieu of access_key and secret_key, some people use a profile and put it in ~/.aws/credentials.

Body:
Im trying to update terraform version from 0.12 to 0.13. While updating the terraform I came across on an issue during plan

Error: Provider configuration not present

To work with
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription
its original provider configuration at provider["registry.terraform.io/-/aws"]
is required, but it has been removed. This occurs when a provider
configuration is removed while objects created by that provider still exist in
the state. Re-add the provider configuration to destroy
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription,
after which you can remove the provider configuration again.

Could someone please help?

Body:
Most of the time you'll have a global.tf file in your directory that lists some things that might not actually be resources. This is where you'd normally have a block like this:

provider "aws" {
  region     = "REGION"
  access_key = "my-access-key"
  secret_key = "my-secret-key"
}

Looks like that block, whatever file it was in, got deleted. Add it back and then try again. Note you'll need to change REGION to whatever region you put your resources in. In lieu of access_key and secret_key, some people use a profile and put it in ~/.aws/credentials.


问:
How to display in Flask certain input fields depending on the value of variables
Have a good day!

I would be very grateful and grateful for help on an issue that I have been thinking about for a long time.

How to display certain input fields depending on the value of variables

Flask Bootstrap's form
input group
multiple inputs
custom forms

Input groups include support for custom selects and custom file inputs. Browser default versions of these are not supported.

I want to display a form for entries of various information.
Form, for example, from 20 different elements for entering, 15-25 different fields for entering any information.

I have 25 different variables, 25 variables can take on a value, a value - either zero (0) or one (1).

Each variable corresponds to a certain field in the form for entering any information.

And I need that if one of the above variable, for example, is equal to zero (0), then I do not display the corresponding field in the form for entering any information.

The number of fields may vary.
form text

```<code><label for="inputPassword5" class="form-label">Password</label>
<input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock">
<div id="passwordHelpBlock" class="form-text">
  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.
</div>
</code>```

答:
Typically for logic similar to this you would use a Rules Based Engine. I have found a similar topic:

Python Rule Based Engine

Without relying on one of the Rules Based Engines such as Clips, it may require a number of nested if-statements which would not be very pythonic.

Unfortunately without using one of these solutions, you may be looking to develop a service which would act as a rules engine.

You could alternatively store each input as a 0 or 1 and create a string of 25 characters similar to a bitmap, and compare each result against a dictionary like below:

```<code>results_dict = {
   "1": "Field A",
   "2": "Field B"
}

def check_string(some_string):
    """
    :param some_string: a string of length 25 i.e. 0100000100000010000100001
    """
    count = 1
    show_variable_list = []
    for character in some_string:
        print(character)
        if character == "1":
            print(True)
            show_variable_list.append(results_dict.get(str(count)))

        count += 1
    return show_variable_list

fields_to_show = check_string("1100")
</code>```

Then based on the items stored in the fields_to_show, you may be able to do something clever with what to display!

Hope this helps and good luck!

Body:
Have a good day!

I would be very grateful and grateful for help on an issue that I have been thinking about for a long time.

How to display certain input fields depending on the value of variables

Flask Bootstrap's form
input group
multiple inputs
custom forms

Input groups include support for custom selects and custom file inputs. Browser default versions of these are not supported.

I want to display a form for entries of various information.
Form, for example, from 20 different elements for entering, 15-25 different fields for entering any information.

I have 25 different variables, 25 variables can take on a value, a value - either zero (0) or one (1).

Each variable corresponds to a certain field in the form for entering any information.

And I need that if one of the above variable, for example, is equal to zero (0), then I do not display the corresponding field in the form for entering any information.

The number of fields may vary.
form text

Password
<input type="password" id="inputPassword5" class="form-control" aria-describedby="passwordHelpBlock">

  Your password must be 8-20 characters long, contain letters and numbers, and must not contain spaces, special characters, or emoji.

Body:
Typically for logic similar to this you would use a Rules Based Engine. I have found a similar topic:

Python Rule Based Engine

Without relying on one of the Rules Based Engines such as Clips, it may require a number of nested if-statements which would not be very pythonic.

Unfortunately without using one of these solutions, you may be looking to develop a service which would act as a rules engine.

You could alternatively store each input as a 0 or 1 and create a string of 25 characters similar to a bitmap, and compare each result against a dictionary like below:

results_dict = {
   "1": "Field A",
   "2": "Field B"
}

def check_string(some_string):
    """
    :param some_string: a string of length 25 i.e. 0100000100000010000100001
    """
    count = 1
    show_variable_list = []
    for character in some_string:
        print(character)
        if character == "1":
            print(True)
            show_variable_list.append(results_dict.get(str(count)))

        count += 1
    return show_variable_list

fields_to_show = check_string("1100")

Then based on the items stored in the fields_to_show, you may be able to do something clever with what to display!

Hope this helps and good luck!


问:
How to dynamically access JSON data?
I have a React Child component that looks like this:

```<code>const SingleProject =(props)=>{
    let data = projectData.VARIABLE_FROM_PROPS.projectDetails;
    let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar;

    useEffect(() => {
        console.log(props);
    }, []);
    return (<></>);
</code>```

How can I use the value in props: props.pathname to get the projectDetails data.

Basically, if props.pathname is golly then I need to be able to get the data from projectData.golly.projectDetails.

答:
You can simply do projectData[VARIABLE_FROM_PROPS]["projectDetails"]

or

projectData[VARIABLE_FROM_PROPS].projectDetails

Title: How to dynamically access JSON data?

Body:
I have a React Child component that looks like this:

const SingleProject =(props)=>{
    let data = projectData.VARIABLE_FROM_PROPS.projectDetails;
    let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar;

    useEffect(() => {
        console.log(props);
    }, []);
    return (<></>);

How can I use the value in props: props.pathname to get the projectDetails data.

Basically, if props.pathname is golly then I need to be able to get the data from projectData.golly.projectDetails.


问:
Key of children required based on self length > 1
I have an rules array, that contains rules. Theses rules need to be groupped (groupId) if they are more than 1.

```<code>"rules": {
  "type": "array",
  "items": { "$ref": "#/rule" }
},

"rule": {
    "type": "object",
    "additionalProperties": false,
    "required": ["keepValue"],
    "properties": {
      "groupId": { "type": ["number", "string"] },
      "keepValue": { "type": "boolean" }
    }
</code>```

When rules.length > 1 I want groupId to be mandatory. How do I do that ?

答:
You can use the if/then keywords for the conditional and minItems for the array length assertion.

{
  "if": {
    "type": "array",
    "minItems": 2
  },
  "then": {
    "items": { "required": ["groupId"] }
  }
}
```

Body:
I have an rules array, that contains rules. Theses rules need to be groupped (groupId) if they are more than 1.

"rules": {
  "type": "array",
  "items": { "$ref": "#/rule" }
},

"rule": {
    "type": "object",
    "additionalProperties": false,
    "required": ["keepValue"],
    "properties": {
      "groupId": { "type": ["number", "string"] },
      "keepValue": { "type": "boolean" }
    }

When rules.length > 1 I want groupId to be mandatory. How do I do that ?


问:
Java: is a Lists's generic type parameter covariant or contravariant when consuming?
I'm a little bit confused about covariance and contravariance. Do we say that in Java something is generally contravariant when we use ? super X.

Now reading my book I understood the following concept:

this is contravariant:

```<code>method(Predicate<? super X> pred)
</code>```

but this one it's covariant:

```<code>method(List<? super X> list)  //And then we use add for a list of course
</code>```

This concept is not written explicitly exactly how I'm asking to you so I want to know, is this definition correct? If yes, why the first one is contravariant and the last one covariant if both are using super keyword?

答:
We don’t often talk about variance in Java, people generally just apply PECS.

Both your examples are identical in terms of variance, as it does not matter what are the actual method definitions inside Predicate or List to evaluate their variance.

So what is it here?

Well let’s say we have Cat extends Animal and method(List<? super Cat> list) (or the same with Predicate). This method would accept List<? super Cat>, List<Cat>, List<Animal> or even List<? super Animal or List<Object> as argument, i.e. List whose generic type is a supertype of Cat.

Using the ≤ notation (see also this answer), we see that ? super inverses the relationship: Cat ≤ Animal implies List<Animal> ≤ List<? super Cat>, so this is contravariance as the types get swapped.

Conversely, List<Cat> ≤ List<? extends Animal>, i.e. you can assign a value of type List<Cat> to a variable/parameter of type List<? extends Animal>. As it does not swap the types (Cat ≤ Animal), this is covariance. (see also How would contravariance be used in Java generics?)

Citing the same Wikipedia article’s section on use-site variance annotations (wildcards) (as in Java):

wildcard types are covariant in their upper bounds (and also contravariant in their lower bounds). In total, given a wildcard type like C<? extends T>, there are three ways to form a subtype: by specializing the class C, by specifying a tighter bound T, or by replacing the wildcard ? with a specific type.

(you can replace C<? extends T> with C<? super T> in the above, it just makes T a lower bound instead of an upper bound).

Body:
I'm a little bit confused about covariance and contravariance. Do we say that in Java something is generally contravariant when we use ? super X.

Now reading my book I understood the following concept:

this is contravariant:

method(Predicate<? super X> pred)

but this one it's covariant:

method(List<? super X> list)  //And then we use add for a list of course

This concept is not written explicitly exactly how I'm asking to you so I want to know, is this definition correct? If yes, why the first one is contravariant and the last one covariant if both are using super keyword?


问:
Syntax error when using Delimiters with Aurora Serverless MySQL 5.6
I'm using Aurora Serverless MySQL 5.6 to create the following trigger which will update one table when data is inserted into another table but am receiving syntax errors, specifically around the Delimiter keyword.

```<code>DELIMITER $$
CREATE TRIGGER Create_Media_Like_Trigger AFTER INSERT ON MediaLike
FOR EACH ROW
BEGIN
    IF NEW.likeType = 'LIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes + 1
        WHERE Media.mediaId = NEW.mediaId;
    ELSEIF NEW.likeType = 'DISLIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes - 1
        WHERE Media.mediaId = NEW.mediaId;
    ENDIF;
END $$
DELIMITER ;
</code>```

Like I said above, I am receiving syntax errors near DELIMITER, is this issue AWS specific and how can I fix it?

UPDATE with error messages:

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'DELIMITER $$ CREATE TRIGGER Create_Media_Like_Trigger
AFTER INSERT ON MediaLike ' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'ELSEIF NEW.likeType = 'DISLIKE' THEN UPDATE Media SET
Media.numLikes = Media.num' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'END $$' at line 1
</code>```

答:
After quite a while of messing with the DELIMITER keyword, I found the following works.

DROP FUNCTION sf_CheckUser;
DELIMITER / /
CREATE FUNCTION db1.sf_CheckUser (
    userUUID VARCHAR(255),
    groupUUID VARCHAR(255),
    requiredTHING INT
) RETURNS TINYINT(1)
BEGIN
DECLARE permit TINYINT(1);

  -- BODY OF FUNCTION

END / / DELIMITER;```

Body:
I'm using Aurora Serverless MySQL 5.6 to create the following trigger which will update one table when data is inserted into another table but am receiving syntax errors, specifically around the Delimiter keyword.

DELIMITER $$
CREATE TRIGGER Create_Media_Like_Trigger AFTER INSERT ON MediaLike
FOR EACH ROW
BEGIN
    IF NEW.likeType = 'LIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes + 1
        WHERE Media.mediaId = NEW.mediaId;
    ELSEIF NEW.likeType = 'DISLIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes - 1
        WHERE Media.mediaId = NEW.mediaId;
    ENDIF;
END $$
DELIMITER ;

Like I said above, I am receiving syntax errors near DELIMITER, is this issue AWS specific and how can I fix it?

UPDATE with error messages:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'DELIMITER $$ CREATE TRIGGER Create_Media_Like_Trigger
AFTER INSERT ON MediaLike ' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'ELSEIF NEW.likeType = 'DISLIKE' THEN UPDATE Media SET
Media.numLikes = Media.num' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'END $$' at line 1


问:
Postman scripts : "pm is not defined"
I try to write a Pre-request script in Postman. I want to to make a request so I try to use pm.sendRequest. For example :

```<code>pm.sendRequest('http://example.com', function (err, res) {
    //...
});
</code>```

But I get this error :

There was an error in evaluating the Pre-request Script: pm is not defined

I'm on Windows 10. I just updated the extension.

How do I access pm?

答:
For extension version, you can use following pattern:

tests["Status code is 200"] = responseCode.code === 200;

ContentLicense: CC BY-SA 3.0

Title: Postman scripts : "pm is not defined"

Body:
I try to write a Pre-request script in Postman. I want to to make a request so I try to use pm.sendRequest. For example :

pm.sendRequest('http://example.com', function (err, res) {
    //...
});

But I get this error :

There was an error in evaluating the Pre-request Script: pm is not defined

I'm on Windows 10. I just updated the extension.

How do I access pm?


问:
Use active record to find a record by month and day, ignoring year and time
I have a model (Entries) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00, will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.

RoR 3.0.9 / Ruby 1.9.2p290

答:
Assume RDBMS is MySQL and you have form with combobox to select month and/or date_of_months, may be you could make a named_scope, for example :

```<code>scope :by_date_or_month, lambda { |date, month| {:conditions => ["DAYOFMONTH(created_at) = ? or MONTH(created_at) = ?", date, month]}}
</code>```

Test from IRB :

```<code>Model.by_date_or_month(31,8)
Model.by_date_or_month(nil,8)
</code>```

Body:
Assume RDBMS is MySQL and you have form with combobox to select month and/or date_of_months, may be you could make a named_scope, for example :

scope :by_date_or_month, lambda { |date, month| {:conditions => ["DAYOFMONTH(created_at) = ? or MONTH(created_at) = ?", date, month]}}

Test from IRB :

Model.by_date_or_month(31,8)
Model.by_date_or_month(nil,8)


问:
IQueryable Adding OR Conditions to the chain of queries
How can i Chain EF queries with OR condition

Right now i am chaining or building the query like below and this is ended up adding AND conditions

```<code>              if (model.EMailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail)
                                        );
                }

                if (model.MailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPMail)
                                    );
                }

                if (model.PhoneChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)
                                    );
                }
</code>```

How can we add OR conditions to this chain

答:
```<code>bool anyEmails = model.EMailChoices?.Any() == true;
bool anyMails = model.MailChoices?.Any() == true;
bool anyPhones = model.PhoneChoices?.Any() == true;

if(anyEmails || anyMails || anyPhones)
{
     query = query.Where(
         c => (anyEmails && model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyMails && model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail))
           || (anyPhones && model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)));
}
</code>```

Body:
How can i Chain EF queries with OR condition

Right now i am chaining or building the query like below and this is ended up adding AND conditions

              if (model.EMailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.EMailChoices.Contains(c.Contact.CommunicationPreferences.TPEMail)
                                        );
                }

                if (model.MailChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.MailChoices.Contains(c.Contact.CommunicationPreferences.TPMail)
                                    );
                }

                if (model.PhoneChoices?.Count() > 0)
                {
                    query = query.Where(
                                        c => model.PhoneChoices.Contains(c.Contact.CommunicationPreferences.TPTelephone)
                                    );
                }

How can we add OR conditions to this chain


问:
Changing index in array / collection Laravel/Php
Hello i would like to change my array / collection index to its value.
I have something like this
enter image description here

Is it possible in each array to change :
"date" : 2021-01-01T00:00:00.000000Z

to 2021-01-01T00:00:00.000000Z : 100.00

Thanks for your help

答:
I don't know what your original data is (array or Collection), but you can change it with array_map or map

$array['ENFERMERIA'] = array_map(
    function ($item) {
        return [
            'send' => $item['send'],
            'open_date' => $item['open_date'],
            'name' => $item['name'],
            $item['date'] => $item['rate']
        ];
    },
    $array['ENFERMERIA']
);
```


问:
Snakemake on SLURM: retry attempt counter does not change
I have a workflow rule with varying time requirements for a slurm cluster. I decorated the workflow as per documentation to increase the slurm time limit for resubmitted jobs (my cluster config.yaml has the arg restart-times: 3), look for resources.time:

example_1:

```<code>rule run_toolx:
    ...
    resources:
        cpus=config["smk_params"]["threads"] * config["smk_params"]["thread_factor"],
        mem_mb=4000,
        time=lambda wildcards, attempt: ( 3 * ( attempt ** 2 ))
    threads:
        config["smk_params"]["threads"] * config["smk_params"]["thread_factor"]
    log:
        "logs/{sample}_toolX.log"
    shell:
        """
        echo "Queueing toolX job with a timelimit of {resources.time} minutes."
        toolX --threads {threads} | tee {log} 2> {log}
        """
</code>```

When I review my snakemake log file for the echo, I find three job submissions with the line: "Queueing toolX job with a timelimit of 3 minutes.". I expected a time limit increase of 3, 12, 27 minutes. This is backed by the slurm logs where each submitted job requests only "00:03:00" computing time on the nodes. When the job hits this timelimit, the slurm manager interrupts it as expected:

output_1:

```<code>       JobID    JobName  Partition  AllocCPUS      State    Elapsed  Timelimit ExitCode
------------ ---------- ---------- ---------- ---------- ---------- ---------- --------
4983483      snakejob.+     normal          6    TIMEOUT   00:03:15   00:03:00      0:0
4983483.bat+      batch                     6  CANCELLED   00:03:16                0:15
4983904      snakejob.+     normal          6    TIMEOUT   00:03:03   00:03:00      0:0
4983904.bat+      batch                     6  CANCELLED   00:03:04                0:15
4984740      snakejob.+     normal          6    TIMEOUT   00:03:03   00:03:00      0:0
4984740.bat+      batch                     6  CANCELLED   00:03:04                0:15
</code>```

Apparently, either my lambda function does not work or the variable attempt is not a counter.

Thanks for sharing a thought.

Edit_1:

with config["smk_params"]["threads"]=2 and config["smk_params"]["thread_factor"]=3 , so the math for resources.cpus works

This tutorial uses the same notation as my in example above.

The attempt parameter was introduced with [4.1.0] - 2017-09-26. I am using snakemake 6.15.1.

I am using the slurm job submission scripts from Snakemake-Profiles.

some tutorials and posts use 'int(attempt)', this does not solve above problem

Edit_2: Reproducable Example for succesful attempt usage

reprex_1:

```<code>shell.executable("bash")

localrules: all

rule all:
    input:
        "success.txt"

rule run_toolX:
    output:
        "success.txt",
    resources:
        cpus=1,
        mem_mb=100,
        time=lambda wildcards, input, threads, attempt: ( 3 * ( attempt ** 2 ))
    shell:
        """
        echo "Queueing run_quast with a timelimit of {resources.time} minutes."
        sleep 4m
        echo "Queueing run_quast with a timelimit of {resources.time} minutes." > {output}
        """
</code>```

yielding:

output_2:

```<code>4985470      snakejob.+     normal          1    TIMEOUT   00:03:16   00:03:00      0:0
4985470.bat+      batch                     1  CANCELLED   00:03:17                0:15
4985477      snakejob.+     normal          1  COMPLETED   00:04:08   00:12:00      0:0
4985477.bat+      batch                     1  COMPLETED   00:04:08                 0:0
</code>```

Experience: I first tried it with a one-minute setup, which was working to my suprise, and then tested the exact same lambda function as in my complex rule resulting in the error. The same slurm profile was used for both examples.

It's quirky.

Edit_3: testing all variations of the notation

my reprex works with or without, respectively:

int(attempt)

int( lambda ... )

lambda wildcards, input, threads, attempt: ...

lambda wildcards, attempt: ...

Edit_4: embedding the reprex in the complex workflow

I am converging with reprex_1 to the setup/environment of the non-functional rule:

reprex_1 works within complex workflow with all rule only pulling reprex_1 rule output

with all rule only pulling example_1 rule output and the resources of example_1 the counter is broken

Next culprit to test: example_1 is a grouped rule. Maybe rule grouping disables the attempt counter.

答:
One possible problem is that the submitted script doesn't use the time option appropriately. Can you check your profile script's cluster option?

This is an incomplete string, but the key idea is to show that the time option should reference the appropriate option in resources:

cluster: "sbatch --parsable -t {resources.time}"
```
<p>As a debugging experiment, you could also try starting with a specific attempt number:</p>
<pre class="lang-sh prettyprint-override"><code>snakemake -s Snakefile -j 1 --attempt 3 -n
</code>```

If this doesn't modify the submission characteristics, then there is a problem with snakemake handling of attempt (as opposed to a problem during job submission to SLURM).

Body:
I have a workflow rule with varying time requirements for a slurm cluster. I decorated the workflow as per documentation to increase the slurm time limit for resubmitted jobs (my cluster config.yaml has the arg restart-times: 3), look for resources.time:

example_1:

rule run_toolx:
    ...
    resources:
        cpus=config["smk_params"]["threads"] * config["smk_params"]["thread_factor"],
        mem_mb=4000,
        time=lambda wildcards, attempt: ( 3 * ( attempt ** 2 ))
    threads:
        config["smk_params"]["threads"] * config["smk_params"]["thread_factor"]
    log:
        "logs/{sample}_toolX.log"
    shell:
        """
        echo "Queueing toolX job with a timelimit of {resources.time} minutes."
        toolX --threads {threads} | tee {log} 2> {log}
        """

When I review my snakemake log file for the echo, I find three job submissions with the line: "Queueing toolX job with a timelimit of 3 minutes.". I expected a time limit increase of 3, 12, 27 minutes. This is backed by the slurm logs where each submitted job requests only "00:03:00" computing time on the nodes. When the job hits this timelimit, the slurm manager interrupts it as expected:

output_1:

       JobID    JobName  Partition  AllocCPUS      State    Elapsed  Timelimit ExitCode
------------ ---------- ---------- ---------- ---------- ---------- ---------- --------
4983483      snakejob.+     normal          6    TIMEOUT   00:03:15   00:03:00      0:0
4983483.bat+      batch                     6  CANCELLED   00:03:16                0:15
4983904      snakejob.+     normal          6    TIMEOUT   00:03:03   00:03:00      0:0
4983904.bat+      batch                     6  CANCELLED   00:03:04                0:15
4984740      snakejob.+     normal          6    TIMEOUT   00:03:03   00:03:00      0:0
4984740.bat+      batch                     6  CANCELLED   00:03:04                0:15

Apparently, either my lambda function does not work or the variable attempt is not a counter.

Thanks for sharing a thought.

Edit_1:

with config["smk_params"]["threads"]=2 and config["smk_params"]["thread_factor"]=3 , so the math for resources.cpus works

This tutorial uses the same notation as my in example above.

The attempt parameter was introduced with [4.1.0] - 2017-09-26. I am using snakemake 6.15.1.

I am using the slurm job submission scripts from Snakemake-Profiles.

some tutorials and posts use 'int(attempt)', this does not solve above problem

Edit_2: Reproducable Example for succesful attempt usage

reprex_1:

shell.executable("bash")

localrules: all

rule all:
    input:
        "success.txt"

rule run_toolX:
    output:
        "success.txt",
    resources:
        cpus=1,
        mem_mb=100,
        time=lambda wildcards, input, threads, attempt: ( 3 * ( attempt ** 2 ))
    shell:
        """
        echo "Queueing run_quast with a timelimit of {resources.time} minutes."
        sleep 4m
        echo "Queueing run_quast with a timelimit of {resources.time} minutes." > {output}
        """

yielding:

output_2:

4985470      snakejob.+     normal          1    TIMEOUT   00:03:16   00:03:00      0:0
4985470.bat+      batch                     1  CANCELLED   00:03:17                0:15
4985477      snakejob.+     normal          1  COMPLETED   00:04:08   00:12:00      0:0
4985477.bat+      batch                     1  COMPLETED   00:04:08                 0:0

Experience: I first tried it with a one-minute setup, which was working to my suprise, and then tested the exact same lambda function as in my complex rule resulting in the error. The same slurm profile was used for both examples.

It's quirky.

Edit_3: testing all variations of the notation

my reprex works with or without, respectively:

int(attempt)

int( lambda ... )

lambda wildcards, input, threads, attempt: ...

lambda wildcards, attempt: ...

Edit_4: embedding the reprex in the complex workflow

I am converging with reprex_1 to the setup/environment of the non-functional rule:

reprex_1 works within complex workflow with all rule only pulling reprex_1 rule output

with all rule only pulling example_1 rule output and the resources of example_1 the counter is broken

Next culprit to test: example_1 is a grouped rule. Maybe rule grouping disables the attempt counter.

Body:
One possible problem is that the submitted script doesn't use the time option appropriately. Can you check your profile script's cluster option?

This is an incomplete string, but the key idea is to show that the time option should reference the appropriate option in resources:

cluster: "sbatch --parsable -t {resources.time}"

As a debugging experiment, you could also try starting with a specific attempt number:

snakemake -s Snakefile -j 1 --attempt 3 -n

If this doesn't modify the submission characteristics, then there is a problem with snakemake handling of attempt (as opposed to a problem during job submission to SLURM).


问:
DebounceTime after first value in RxJS
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

```<code>throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-
</code>```

DebounceTime

```<code>debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------
</code>```

What I want

```<code>debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------
</code>```

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

答:
Here's a custom operator that (as far s I can tell) does what you're after.

The two key insights here are:

Use connect so that you can subscribe to the source twice, once to ignore emissions with exhaustMap and another to inspect and debounce emissions with switchMap

Create an internal token so that you know when to exit without a debounced emission. (Insures that from your example above, the 4 is still emitted).

function throttleDebounceTime<T>(interval: number): MonoTypeOperatorFunction<T> {
  // Use this token's memory address as a nominal token
  const resetToken = {};

  return connect(s$ => s$.pipe(
    exhaustMap(a => s$.pipe(
      startWith(resetToken),
      switchMap(b => timer(interval).pipe(mapTo(b))),
      take(1),
      filter<T>(c => c !== resetToken),
      startWith(a)
    ))
  ));
}
```
<p>example:</p>
```of(1,2,3,4).pipe(
  throttleDebounceTime(500)
).subscribe(console.log);

// 1 [...0.5s wait] 4
```

Title: DebounceTime after first value in RxJS

Body:
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-

DebounceTime

debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------

What I want

debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

Body:
Here's a custom operator that (as far s I can tell) does what you're after.

The two key insights here are:

Use connect so that you can subscribe to the source twice, once to ignore emissions with exhaustMap and another to inspect and debounce emissions with switchMap

Create an internal token so that you know when to exit without a debounced emission. (Insures that from your example above, the 4 is still emitted).

function throttleDebounceTime<T>(interval: number): MonoTypeOperatorFunction<T> {
  // Use this token's memory address as a nominal token
  const resetToken = {};

  return connect(s$ => s$.pipe(
    exhaustMap(a => s$.pipe(
      startWith(resetToken),
      switchMap(b => timer(interval).pipe(mapTo(b))),
      take(1),
      filter<T>(c => c !== resetToken),
      startWith(a)
    ))
  ));
}

example:

of(1,2,3,4).pipe(
  throttleDebounceTime(500)
).subscribe(console.log);

// 1 [...0.5s wait] 4


问:
Android Studio stuck on loading devices
I'm currently running Android Studio Bumblebee 2021.1.1 in windows 10.
The problem I have is each time I start android studio the device list is stuck in loading devices.

I tried these solutions

android studio device list stuck on loading/51101178

android device list showing in android studio got stuck/65177069

The soulutions provided in the threads sometimes work and sometimes don't but the real problem is even if I did fix it in the run time,  The next time I open android studio it's still there.

I already tried updating android studio to latest version, reinstalling android studio, deleting all the caches and plugins and resetting it to default. Completely Deleting Sdk folder and downloading again. But nothing helped I don't know where this problem could be originate from

答:
After hours of research and try and error I finally figured out what was going on.
Turns out my adb configuration was conflicting with genymotion's. Nothing could have done at the side of android studio. I went to the genymotion settings ADB tab and changed from Use Genymotion Android Tools to Use custom Android SDK Tools and it went away at last

Title: Android Studio stuck on loading devices


问:
Error trying to remove a namespace from an XML in Mule 4
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

```<code>Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
</code>```

Mule flow :

```<code><flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>
</code>```

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

```<code>#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]
</code>```

Please assist me to resolve this issue.

答:
If you use string operations to work with XML, chances are you are doing it wrong. In other programming languages you should use the existing libraries and frameworks to process XML. In Mule you should use DataWeave transformations. This one is a little bit intuitive because it requires using the seldom used namespace selector. The selector returns the namespace URL, not the name. I created this simple function to remove a namespace from the output:

%dw 2.0
output application/xml
fun removeNamespace(element,namespaceName) =
  element mapObject (value, key) ->
            (if (key.# as String == namespaceName) (key as String) else (key)) @((key.@)) : (
                if (value is Object) removeNamespace(value, namespaceName)                             else value
            )
---
removeNamespace(payload, "http://schemas.xmlsoap.org/soap/envelope/")
```

Body:
I see the error like "Trying to write END_DOCUMENT when document has no root" while I replace all the payload env and xmlns with "".

It throws error :

Message               : "Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document, while writing Xml.
Trace:
  at main (Unknown)" evaluating expression: "payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")".
Element               : map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload)
Element DSL           : <set-payload value="#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]" doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc"></set-payload>
Error type            : MULE:EXPRESSION
FlowStack             : at map_requestFlow(map_requestFlow/processors/0 @ map_request:map_request.xml:13 (Set Payload))

  (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)

Mule flow :

<flow name="map_requestFlow" doc:id="21d0d652-3766-47ed-95aa-a451f62c5776" >
        <http:listener doc:name="Listener" doc:id="7312114b-2857-40b3-98cd-f52b628b3a28" config-ref="HTTP_Listener_config" path="/map"/>
        <set-payload value='#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]' doc:name="Set Payload" doc:id="7db57e88-dbd4-4a09-ba05-ea37fb9586fc" />
        <logger level="INFO" doc:name="Logger" doc:id="21051f39-bb9f-412c-af73-f65051317757" message="#[payload]"/>
</flow>

Input payload : https://github.com/Manikandan99/Map_request/blob/main/soap_request.xml

Expected output : https://github.com/Manikandan99/Map_request/blob/main/soap_response.xml

I am trying to replace payload using

#[payload.replaceAll("env:","").replaceAll("xmlns=\"http://decisionresearch.com/RateMaker\"","")]

Please assist me to resolve this issue.


问:
React Native CLI Android installation error
I am new to react native, I was trying to follow an example on how to launch react native app with react native CLI but I keep getting this error in my CMD.

```<code>C:\React Native Workspace\RN-CLI\FirstCli>npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 863 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon (subsequent builds will be faster)

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\React Native Workspace\RN-CLI\FirstCli\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\React Native Workspace\RN-CLI\FirstCli\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s

    at makeError (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\execa\index.js:174:9)
    at C:\React Native Workspace\RN-CLI\FirstCli\node_modules\execa\index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.
</code>```

I need help with resolving these issues.

答:
Assuming that you already have the Android SDK installed, you need to create a file named local.properties at the root of you Android project your-react-native-project-android/ and you should also add it to .gitignore if you are using git.

The file must indicate the path of the SDK on your computer, for macOS for example

local.properties

```<code>## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Tue Oct 26 14:02:40 CEST 2021
sdk.dir=/Users/username/Library/Android/sdk
</code>```

If you never installed the SDK, you need to start here

Body:
I am new to react native, I was trying to follow an example on how to launch react native app with react native CLI but I keep getting this error in my CMD.

C:\React Native Workspace\RN-CLI\FirstCli>npx react-native run-android
info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag.
Jetifier found 863 file(s) to forward-jetify. Using 12 workers...
info Starting JS server...
'adb' is not recognized as an internal or external command,
operable program or batch file.
info Launching emulator...
error Failed to launch emulator. Reason: No emulators found as an output of `emulator -list-avds`.
warn Please launch an emulator manually or connect a device. Otherwise app may fail to launch.
info Installing the app...
Starting a Gradle Daemon (subsequent builds will be faster)

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\React Native Workspace\RN-CLI\FirstCli\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at 'C:\React Native Workspace\RN-CLI\FirstCli\android\local.properties'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 10s

    at makeError (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\execa\index.js:174:9)
    at C:\React Native Workspace\RN-CLI\FirstCli\node_modules\execa\index.js:278:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async runOnAllDevices (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
    at async Command.handleAction (C:\React Native Workspace\RN-CLI\FirstCli\node_modules\@react-native-community\cli\build\index.js:192:9)
info Run CLI with --verbose flag for more details.

I need help with resolving these issues.

Body:
Assuming that you already have the Android SDK installed, you need to create a file named local.properties at the root of you Android project your-react-native-project-android/ and you should also add it to .gitignore if you are using git.

The file must indicate the path of the SDK on your computer, for macOS for example

local.properties

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Tue Oct 26 14:02:40 CEST 2021
sdk.dir=/Users/username/Library/Android/sdk

If you never installed the SDK, you need to start here