问:
My Dynamic cart attributes - second attribute is showing the same value for every order
I have two dynamic dropdowns on my cart page for collecting cart attributes - the first is to select your state, and the second dropdown is a list of facilities in that state. Everything looks great on the front end. The first dropdown for states works and saves the information perfectly. The second dropdown, with the facilities looks good on the frontend, but saves the incorrect value each time - the second dropdown always saves the same value - 3108.

I load these using three files - my secondary dropdowns are now loaded in one html file, as it is too large to load in the cart-template.liquid file.

cart-template.liquid:

```<code>
    <div> <p class="cart-attribute" id="PrisonDropdownCart" >
              <label><b>Please select</b> the state and name of the prison facility you are ordering for.</label><br>
                <label style="display:none;">State</label>
              <select required class="required states" id="state" name="attributes[state]">
                <option value="" disabled="" selected=""{% if cart.attributes["state"] == "Disabled" %} selected{% endif %}>Please Select a State</option>
                <option value="Alabama" {% if cart.attributes["state"] == "Alabama" %} selected{% endif %}>Alabama</option>
                <option value="Alaska" {% if cart.attributes["state"] == "Alaska" %} selected{% endif %}>Alaska</option>
                <option value="Arizona" {% if cart.attributes["state"] == "Arizona" %} selected{% endif %}>Arizona</option>
                <option value="Arkansas" {% if cart.attributes["state"] == "Arkansas" %} selected{% endif %}>Arkansas</option>
                <option value="California" {% if cart.attributes["state"] == "California" %} selected{% endif %}>California</option>
                <option value="Colorado" {% if cart.attributes["state"] == "Colorado" %} selected{% endif %}>Colorado</option>
                <option value="Connecticut" {% if cart.attributes["state"] == "Connecticut" %} selected{% endif %}>Connecticut</option>
                <option value="Delaware" {% if cart.attributes["state"] == "Delaware" %} selected{% endif %}>Delaware</option>
                <option value="District of Columbia" {% if cart.attributes["state"] == "District of Columbia" %} selected{% endif %}>District of Columbia</option>
                <option value="Florida" {% if cart.attributes["state"] == "Florida" %} selected{% endif %}>Florida</option>
                <option value="Georgia" {% if cart.attributes["state"] == "Georgia" %} selected{% endif %}>Georgia</option>
                <option value="Hawaii" {% if cart.attributes["state"] == "Hawaii" %} selected{% endif %}>Hawaii</option>
                <option value="Idaho" {% if cart.attributes["state"] == "Idaho" %} selected{% endif %}>Idaho</option>
                <option value="Illinois" {% if cart.attributes["state"] == "Illinois" %} selected{% endif %}>Illinois</option>
                <option value="Indiana" {% if cart.attributes["state"] == "Indiana" %} selected{% endif %}>Indiana</option>
                <option value="Iowa" {% if cart.attributes["state"] == "Iowa" %} selected{% endif %}>Iowa</option>
                <option value="Kansas" {% if cart.attributes["state"] == "Kansas" %} selected{% endif %}>Kansas</option>
                <option value="Kentucky" {% if cart.attributes["state"] == "Kentucky" %} selected{% endif %}>Kentucky</option>
                <option value="Louisiana" {% if cart.attributes["state"] == "Louisiana" %} selected{% endif %}>Louisiana</option>
                <option value="Maine" {% if cart.attributes["state"] == "Maine" %} selected{% endif %}>Maine</option>
                <option value="Maryland" {% if cart.attributes["state"] == "Maryland" %} selected{% endif %}>Maryland</option>
                <option value="Massachusetts" {% if cart.attributes["state"] == "Massachusetts" %} selected{% endif %}>Massachusetts</option>
                <option value="Michigan" {% if cart.attributes["state"] == "Michigan" %} selected{% endif %}>Michigan</option>
                <option value="Minnesota" {% if cart.attributes["state"] == "Minnesota" %} selected{% endif %}>Minnesota</option>
                <option value="Mississippi" {% if cart.attributes["state"] == "Mississippi" %} selected{% endif %}>Mississippi</option>
                <option value="Missouri" {% if cart.attributes["state"] == "Missouri" %} selected{% endif %}>Missouri</option>
                <option value="Montana" {% if cart.attributes["state"] == "Montana" %} selected{% endif %}>Montana</option>
                <option value="Nebraska" {% if cart.attributes["state"] == "Nebraska" %} selected{% endif %}>Nebraska</option>
                <option value="Nevada" {% if cart.attributes["state"] == "Nevada" %} selected{% endif %}>Nevada</option>
                <option value="New Hampshire" {% if cart.attributes["state"] == "New Hampshire" %} selected{% endif %}>New Hampshire</option>
                <option value="New Jersey" {% if cart.attributes["state"] == "New Jersey" %} selected{% endif %}>New Jersey</option>
                <option value="New Mexico" {% if cart.attributes["state"] == "New Mexico" %} selected{% endif %}>New Mexico</option>
                <option value="New York" {% if cart.attributes["state"] == "New York" %} selected{% endif %}>New York</option>
                <option value="North Carolina" {% if cart.attributes["state"] == "North Carolina" %} selected{% endif %}>North Carolina</option>
                <option value="North Dakota" {% if cart.attributes["state"] == "North Dakota" %} selected{% endif %}>North Dakota</option>
                <option value="Ohio" {% if cart.attributes["state"] == "Ohio" %} selected{% endif %}>Ohio</option>
                <option value="Oklahoma" {% if cart.attributes["state"] == "Oklahoma" %} selected{% endif %}>Oklahoma</option>
                <option value="Oregon" {% if cart.attributes["state"] == "Oregon" %} selected{% endif %}>Oregon</option>
                <option value="Pennsylvania" {% if cart.attributes["state"] == "Pennsylvania" %} selected{% endif %}>Pennsylvania</option>
                <option value="Puerto Rico" {% if cart.attributes["state"] == "Puerto Rico" %} selected{% endif %}>Puerto Rico</option>
                <option value="Rhode Island" {% if cart.attributes["state"] == "Rhode Island" %} selected{% endif %}>Rhode Island</option>
                <option value="South Carolina" {% if cart.attributes["state"] == "South Carolina" %} selected{% endif %}>South Carolina</option>
                <option value="South Dakota" {% if cart.attributes["state"] == "South Dakota" %} selected{% endif %}>South Dakota</option>
                <option value="Tennessee" {% if cart.attributes["state"] == "Tennessee" %} selected{% endif %}>Tennessee</option>
                <option value="Texas" {% if cart.attributes["state"] == "Texas" %} selected{% endif %}>Texas</option>
                <option value="Utah" {% if cart.attributes["state"] == "Utah" %} selected{% endif %}>Utah</option>
                <option value="Vermont" {% if cart.attributes["state"] == "Vermont" %} selected{% endif %}>Vermont</option>
                <option value="Virginia" {% if cart.attributes["state"] == "Virginia" %} selected{% endif %}>Virginia</option>
                <option value="Washington" {% if cart.attributes["state"] == "Washington" %} selected{% endif %}>Washington</option>
                <option value="West Virginia" {% if cart.attributes["state"] == "West Virginia" %} selected{% endif %}>West Virginia</option>
                <option value="Wisconsin" {% if cart.attributes["state"] == "Wisconsin" %} selected{% endif %}>Wisconsin</option>
                <option value="Wyoming" {% if cart.attributes["state"] == "Wyoming" %} selected{% endif %}>Wyoming</option>
              </select>
              </p>

            <div id="PrisonDropdown">
            </div>
            <br>
            </div>
 <script>
jQuery(function(){
$("#PrisonDropdown").load('https://cdn.shopify.com/s/files/1/0060/7577/7135/t/2/assets/PrisonDropdown.html');
                  });
 </script>

</code>```

theme.liquid:

```<code>{% if template == 'cart' %}
<script>
  jQuery(window).load(function(){
       $('.states').on('change', function(){
          var selected = $(this).val();
          $('.select-list').addClass('select-hidden');
          $('[id="' + selected + '"]').removeClass('select-hidden');

          })
        });

   </script>

</code>```

答:
All the if statements from your HTML are not working and are loaded as-is because the liquid code is not rendered on requesting them this way, so just delete all of them.

The 3108 value is the first option from the last select box. As all your select boxes have the same name, no matter what do you display and select - the selected values from the last select box will always be sent on submitting the form. The quick solution for that would be moving the displayed select box to the bottom. You can do that by adding .insertAfter(".select-list:last") after removing the select-hidden class. So the whole line in your theme.liquid would look like the below:

```<code>$('[id="' + selected + '"]').removeClass('select-hidden').insertAfter(".select-list:last");
</code>```

Body:
I have two dynamic dropdowns on my cart page for collecting cart attributes - the first is to select your state, and the second dropdown is a list of facilities in that state. Everything looks great on the front end. The first dropdown for states works and saves the information perfectly. The second dropdown, with the facilities looks good on the frontend, but saves the incorrect value each time - the second dropdown always saves the same value - 3108.

I load these using three files - my secondary dropdowns are now loaded in one html file, as it is too large to load in the cart-template.liquid file.

cart-template.liquid:

              Please select the state and name of the prison facility you are ordering for.

                State
              <select required class="required states" id="state" name="attributes[state]">
                <option value="" disabled="" selected=""{% if cart.attributes["state"] == "Disabled" %} selected{% endif %}>Please Select a State</option>
                <option value="Alabama" {% if cart.attributes["state"] == "Alabama" %} selected{% endif %}>Alabama</option>
                <option value="Alaska" {% if cart.attributes["state"] == "Alaska" %} selected{% endif %}>Alaska</option>
                <option value="Arizona" {% if cart.attributes["state"] == "Arizona" %} selected{% endif %}>Arizona</option>
                <option value="Arkansas" {% if cart.attributes["state"] == "Arkansas" %} selected{% endif %}>Arkansas</option>
                <option value="California" {% if cart.attributes["state"] == "California" %} selected{% endif %}>California</option>
                <option value="Colorado" {% if cart.attributes["state"] == "Colorado" %} selected{% endif %}>Colorado</option>
                <option value="Connecticut" {% if cart.attributes["state"] == "Connecticut" %} selected{% endif %}>Connecticut</option>
                <option value="Delaware" {% if cart.attributes["state"] == "Delaware" %} selected{% endif %}>Delaware</option>
                <option value="District of Columbia" {% if cart.attributes["state"] == "District of Columbia" %} selected{% endif %}>District of Columbia</option>
                <option value="Florida" {% if cart.attributes["state"] == "Florida" %} selected{% endif %}>Florida</option>
                <option value="Georgia" {% if cart.attributes["state"] == "Georgia" %} selected{% endif %}>Georgia</option>
                <option value="Hawaii" {% if cart.attributes["state"] == "Hawaii" %} selected{% endif %}>Hawaii</option>
                <option value="Idaho" {% if cart.attributes["state"] == "Idaho" %} selected{% endif %}>Idaho</option>
                <option value="Illinois" {% if cart.attributes["state"] == "Illinois" %} selected{% endif %}>Illinois</option>
                <option value="Indiana" {% if cart.attributes["state"] == "Indiana" %} selected{% endif %}>Indiana</option>
                <option value="Iowa" {% if cart.attributes["state"] == "Iowa" %} selected{% endif %}>Iowa</option>
                <option value="Kansas" {% if cart.attributes["state"] == "Kansas" %} selected{% endif %}>Kansas</option>
                <option value="Kentucky" {% if cart.attributes["state"] == "Kentucky" %} selected{% endif %}>Kentucky</option>
                <option value="Louisiana" {% if cart.attributes["state"] == "Louisiana" %} selected{% endif %}>Louisiana</option>
                <option value="Maine" {% if cart.attributes["state"] == "Maine" %} selected{% endif %}>Maine</option>
                <option value="Maryland" {% if cart.attributes["state"] == "Maryland" %} selected{% endif %}>Maryland</option>
                <option value="Massachusetts" {% if cart.attributes["state"] == "Massachusetts" %} selected{% endif %}>Massachusetts</option>
                <option value="Michigan" {% if cart.attributes["state"] == "Michigan" %} selected{% endif %}>Michigan</option>
                <option value="Minnesota" {% if cart.attributes["state"] == "Minnesota" %} selected{% endif %}>Minnesota</option>
                <option value="Mississippi" {% if cart.attributes["state"] == "Mississippi" %} selected{% endif %}>Mississippi</option>
                <option value="Missouri" {% if cart.attributes["state"] == "Missouri" %} selected{% endif %}>Missouri</option>
                <option value="Montana" {% if cart.attributes["state"] == "Montana" %} selected{% endif %}>Montana</option>
                <option value="Nebraska" {% if cart.attributes["state"] == "Nebraska" %} selected{% endif %}>Nebraska</option>
                <option value="Nevada" {% if cart.attributes["state"] == "Nevada" %} selected{% endif %}>Nevada</option>
                <option value="New Hampshire" {% if cart.attributes["state"] == "New Hampshire" %} selected{% endif %}>New Hampshire</option>
                <option value="New Jersey" {% if cart.attributes["state"] == "New Jersey" %} selected{% endif %}>New Jersey</option>
                <option value="New Mexico" {% if cart.attributes["state"] == "New Mexico" %} selected{% endif %}>New Mexico</option>
                <option value="New York" {% if cart.attributes["state"] == "New York" %} selected{% endif %}>New York</option>
                <option value="North Carolina" {% if cart.attributes["state"] == "North Carolina" %} selected{% endif %}>North Carolina</option>
                <option value="North Dakota" {% if cart.attributes["state"] == "North Dakota" %} selected{% endif %}>North Dakota</option>
                <option value="Ohio" {% if cart.attributes["state"] == "Ohio" %} selected{% endif %}>Ohio</option>
                <option value="Oklahoma" {% if cart.attributes["state"] == "Oklahoma" %} selected{% endif %}>Oklahoma</option>
                <option value="Oregon" {% if cart.attributes["state"] == "Oregon" %} selected{% endif %}>Oregon</option>
                <option value="Pennsylvania" {% if cart.attributes["state"] == "Pennsylvania" %} selected{% endif %}>Pennsylvania</option>
                <option value="Puerto Rico" {% if cart.attributes["state"] == "Puerto Rico" %} selected{% endif %}>Puerto Rico</option>
                <option value="Rhode Island" {% if cart.attributes["state"] == "Rhode Island" %} selected{% endif %}>Rhode Island</option>
                <option value="South Carolina" {% if cart.attributes["state"] == "South Carolina" %} selected{% endif %}>South Carolina</option>
                <option value="South Dakota" {% if cart.attributes["state"] == "South Dakota" %} selected{% endif %}>South Dakota</option>
                <option value="Tennessee" {% if cart.attributes["state"] == "Tennessee" %} selected{% endif %}>Tennessee</option>
                <option value="Texas" {% if cart.attributes["state"] == "Texas" %} selected{% endif %}>Texas</option>
                <option value="Utah" {% if cart.attributes["state"] == "Utah" %} selected{% endif %}>Utah</option>
                <option value="Vermont" {% if cart.attributes["state"] == "Vermont" %} selected{% endif %}>Vermont</option>
                <option value="Virginia" {% if cart.attributes["state"] == "Virginia" %} selected{% endif %}>Virginia</option>
                <option value="Washington" {% if cart.attributes["state"] == "Washington" %} selected{% endif %}>Washington</option>
                <option value="West Virginia" {% if cart.attributes["state"] == "West Virginia" %} selected{% endif %}>West Virginia</option>
                <option value="Wisconsin" {% if cart.attributes["state"] == "Wisconsin" %} selected{% endif %}>Wisconsin</option>
                <option value="Wyoming" {% if cart.attributes["state"] == "Wyoming" %} selected{% endif %}>Wyoming</option>
              </select>

theme.liquid:

{% if template == 'cart' %}

Body:
All the if statements from your HTML are not working and are loaded as-is because the liquid code is not rendered on requesting them this way, so just delete all of them.

The 3108 value is the first option from the last select box. As all your select boxes have the same name, no matter what do you display and select - the selected values from the last select box will always be sent on submitting the form. The quick solution for that would be moving the displayed select box to the bottom. You can do that by adding .insertAfter(".select-list:last") after removing the select-hidden class. So the whole line in your theme.liquid would look like the below:

$('[id="' + selected + '"]').removeClass('select-hidden').insertAfter(".select-list:last");


来源: stackexchange

问:
How do I cut substrings in these strings in powershell?
everyone. I'm a rookie at Powershell and I don't know much about the values in a particular column.

```<code>JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1
</code>```

I filter the lines with a Select-String by jobid for example but I need the value of subclient column in particular.
As it is not a cmdlet I can't split by properties, so how do I do it with a regular expression?and which one?

答:
Quick solution... Using ConvertFrom-Csv

```<code>$text = @"
JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1
"@ -split '\n' | ? {$_ -notmatch '---|^\s+'}

$csv = $text | % {$_ -replace '\s+',','} | ConvertFrom-Csv
</code>```

Will results this:

```<code>JOBID STATUS    STORAGE   POLICY APPTYPE BACKUPSET SUBCLIENT        INSTANCE   CLIENT
----- ------    -------   ------ ------- --------- ---------        --------   ------
647   Completed SP_Dedupe Files  File    System    defaultBackupSet ClienteDDB <default>
641   Completed SP_Dedupe Files  File    System    defaultBackupSet DDBBackup  <default>

$csv[0].JOBID
647
</code>```

ContentLicense: CC BY-SA 4.0

Body:
everyone. I'm a rookie at Powershell and I don't know much about the values in a particular column.

JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1

I filter the lines with a Select-String by jobid for example but I need the value of subclient column in particular.
As it is not a cmdlet I can't split by properties, so how do I do it with a regular expression?and which one?

Body:
Quick solution... Using ConvertFrom-Csv

$text = @"
JOBID    STATUS       STORAGE POLICY        APPTYPE          BACKUPSET           SUBCLIENT                              INSTANCE                CLIENT

-----    ------       --------------        -------          ---------           ---------                              --------                ------

647      Completed    SP_Dedupe Files       File System      defaultBackupSet    ClienteDDB                             <default>               WIN-U0O9K2LMAF1

641      Completed    SP_Dedupe Files       File System      defaultBackupSet    DDBBackup                              <default>               WIN-U0O9K2LMAF1
"@ -split '\n' | ? {$_ -notmatch '---|^\s+'}

$csv = $text | % {$_ -replace '\s+',','} | ConvertFrom-Csv

Will results this:

JOBID STATUS    STORAGE   POLICY APPTYPE BACKUPSET SUBCLIENT        INSTANCE   CLIENT
----- ------    -------   ------ ------- --------- ---------        --------   ------
647   Completed SP_Dedupe Files  File    System    defaultBackupSet ClienteDDB <default>
641   Completed SP_Dedupe Files  File    System    defaultBackupSet DDBBackup  <default>

$csv[0].JOBID
647


问:
Vue-i18n translation in script part of component not updating when changing lang
I have a pretty simple landing page in Vue.js and Bootstrap vue and I managed to get i18n running pretty well on the whole page, however, on the subject part of the contact form I have some options to choose from (with a default value that says "Select one"), that I also want them to be translated.

```<code>import i18n from "@/i18n";

export default {
data() {
return {
  errors: [],
  form: {
    email: "",
    subject: null,
    message: "",
  },
  subject: [
    { text: i18n.t("contact.subjectoption"), value: null },
    this.$t("contact.subjectoption1"),
    "Business Inquiry",
    "Social Media",
    "Other",
  ],
  msg: "",
  show: true,
};}}
</code>```

However when I change languages, the whole landing page updates the language but the options do not!

Is there something I missed?

Thanks in advance!

答:
The answer from Hiws did the job but I'm leaving down below how the template looks like if anyone is after something similar:</p>

```<code><section class="contact">
  <b-container>
    <b-row class="my-md-5">
      <b-col
        id="contact-us"
        class="my-3 d-flex align-items-center justify-content-center"
        md="6"
      >
        <h1 class="mb-5 contact-title">{{ $t("contact.title") }}</h1>
      </b-col>
      <b-col class="contact-form" md="6">
        <b-form @submit="checkForm">
          <div class="form">{{ $t("contact.emailtitle") }}</div>
          <b-form-input
            id="email"
            v-model.trim="form.email"
            type="email"
            required
            placeholder="Email"
          ></b-form-input>
          <div class="form">{{ $t("contact.subjecttitle") }}</div>
          <b-form-select
            id="subject"
            v-model="form.subject"
            :options="subject"
            required
          ></b-form-select>

          <div class="form">{{ $t("contact.messagetitle") }}</div>
          <b-form-textarea
            id="message"
            v-model.trim="form.message"
            required
            placeholder="Message"
          ></b-form-textarea>
          <b-button
            class="form"
            style="margin-right: 10px;"
            type="submit"
            variant="success"
            >{{ $t("contact.submit") }}</b-button
          >
        </b-form>
      </b-col>
    </b-row>
  </b-container>
</section>
</code>```

Body:
I have a pretty simple landing page in Vue.js and Bootstrap vue and I managed to get i18n running pretty well on the whole page, however, on the subject part of the contact form I have some options to choose from (with a default value that says "Select one"), that I also want them to be translated.

import i18n from "@/i18n";

export default {
data() {
return {
  errors: [],
  form: {
    email: "",
    subject: null,
    message: "",
  },
  subject: [
    { text: i18n.t("contact.subjectoption"), value: null },
    this.$t("contact.subjectoption1"),
    "Business Inquiry",
    "Social Media",
    "Other",
  ],
  msg: "",
  show: true,
};}}

However when I change languages, the whole landing page updates the language but the options do not!

Is there something I missed?

Thanks in advance!

Body:
The answer from Hiws did the job but I'm leaving down below how the template looks like if anyone is after something similar:

<section class="contact">
  <b-container>
    <b-row class="my-md-5">
      <b-col
        id="contact-us"
        class="my-3 d-flex align-items-center justify-content-center"
        md="6"
      >
        <h1 class="mb-5 contact-title">{{ $t("contact.title") }}</h1>
      </b-col>
      <b-col class="contact-form" md="6">
        <b-form @submit="checkForm">
          <div class="form">{{ $t("contact.emailtitle") }}</div>
          <b-form-input
            id="email"
            v-model.trim="form.email"
            type="email"
            required
            placeholder="Email"
          ></b-form-input>
          <div class="form">{{ $t("contact.subjecttitle") }}</div>
          <b-form-select
            id="subject"
            v-model="form.subject"
            :options="subject"
            required
          ></b-form-select>

          <div class="form">{{ $t("contact.messagetitle") }}</div>
          <b-form-textarea
            id="message"
            v-model.trim="form.message"
            required
            placeholder="Message"
          ></b-form-textarea>
          <b-button
            class="form"
            style="margin-right: 10px;"
            type="submit"
            variant="success"
            >{{ $t("contact.submit") }}</b-button
          >
        </b-form>
      </b-col>
    </b-row>
  </b-container>
</section>


问:
Is it possible to add stroke to text in ffmpeg?
I would like to add black stroke to text in ffmpeg. Is it possible?</p>

```<code>-c:v libx264 -vf "hue=h=0, drawtext=fontfile=../bin/RobotoCondensed-Bold.ttf:text='Hello.':fontcolor=white: fontsize=158: x=0+(w-text_w)/2: y=50+(h-text_h-line_h)/2" -c:a copy -shortest -pix_fmt yuv420p ../bin/ENG_01.mov
</code>```

答:
You can change border-color and width of border by using drawtext and adding these parameters

```<code>bordercolor=black:
borderw=5:
</code>```

Your code will look

```<code>-c:v libx264 \
-vf "hue=h=0,\
  drawtext=fontfile=../bin/RobotoCondensed-Bold.ttf:\
   text='Hello.':\
   bordercolor=white:\
   borderw=5:\
   fontcolor=white:\
   fontsize=158:\
   x=0+(w-text_w)/2: y=50+(h-text_h-line_h)/2"\
 -c:a copy -shortest -pix_fmt yuv420p \
../bin/ENG_01.mov
</code>```

Body:
I would like to add black stroke to text in ffmpeg. Is it possible?

-c:v libx264 -vf "hue=h=0, drawtext=fontfile=../bin/RobotoCondensed-Bold.ttf:text='Hello.':fontcolor=white: fontsize=158: x=0+(w-text_w)/2: y=50+(h-text_h-line_h)/2" -c:a copy -shortest -pix_fmt yuv420p ../bin/ENG_01.mov

Body:
You can change border-color and width of border by using drawtext and adding these parameters

bordercolor=black:
borderw=5:

Your code will look

-c:v libx264 \
-vf "hue=h=0,\
  drawtext=fontfile=../bin/RobotoCondensed-Bold.ttf:\
   text='Hello.':\
   bordercolor=white:\
   borderw=5:\
   fontcolor=white:\
   fontsize=158:\
   x=0+(w-text_w)/2: y=50+(h-text_h-line_h)/2"\
 -c:a copy -shortest -pix_fmt yuv420p \
../bin/ENG_01.mov


问:
Unable to load MySQL database via entity framework in VS 2019
I know that there are a lot of questions in different communities. I have tried each and everything but still unable to load my database via the entity framework. The database I am using in MySQL and I am trying to load it using Entity Framework. But the window crashes from below window

I have installed all the latest versions as said here.

Below is my app.config

```<code> <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
  </provider></providers>
</code>```

PS: I am using the console application.

Any help would be highly appreciated

答:
From your reply to my comment, I understand that the Entity Data Model Wizard simply vanishes when you click Next.

What you are describing is a malfunction in Visual Studio. You should therefore repair Visual Studio. You can do this by running the Visual Studio installer and choosing the option to Repair, or failing that, uninstalling and reinstalling.

EDIT only do this if the standard resolution actions for the MySQL VS addin have not solved the problem. Visual Studio should handle addin failures robustly, displaying an informative message. However, per Bradley Grainger's comment below, it may fail to do so. In those cases a VS repair/reinstall will not help.

Body:
I know that there are a lot of questions in different communities. I have tried each and everything but still unable to load my database via the entity framework. The database I am using in MySQL and I am trying to load it using Entity Framework. But the window crashes from below window

I have installed all the latest versions as said here.

Below is my app.config

 <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.10.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d">
  </provider></providers>

PS: I am using the console application.

Any help would be highly appreciated


问:
step by step tutorial for using slim fitnesse in .net
anybody knows some step by step tutorial for using slim fitnesse in .net ?

for now I managed to run the slim fitnesse website on my localhost:3434

and I unziped the fitSharp plugin in c:/fitSharp

but I have no idea what's next

答:
in your case this will be useful:
http://fitsharp.github.com/Slim/GettingStarted.html

else you should consider:
http://schuchert.wikispaces.com/Acceptance+Testing.UsingSlimDotNetInFitNesse

ContentLicense: CC BY-SA 3.0


问:
What is the difference between C++/CLI and C#/VB with unsafe and extern?
.NET has C# and VB* as (relatively) high-level languages, both of which compile to the .NET CLI intermediate code (.NET's equivalent of Java's "bytecode"), and not to native machine code. There is also C++/CLI, which lets you write code for the .NET CLI intermediate code.

These can be familiar with each other the same way C#/VB projects can, with C++/CLI code able to use C#-defined elements (classes, methods, properties) with keywords like gcnew and notation ^, and C#/VB code. C++/CLI allows working with pointers, memory allocation, and getting and setting the actual bytes in memory (by pointers). However, these are things that can be done with C# (and VB?) with the unsafe keyword.

Is there a difference between the two ways? Are there things you can achieve with one but not the other? Is there a performance difference (consider both compile to intermediate .NET CLI code and not machine code)?

* when I say C#/VB, I only know the C# part so I may by wrong. I'm not familiar with VB.

Thanks in advance!

答:
The primary reason for C++/CLI is to have an easy way to interface to native c++ libraries, this is the most important difference.

In c++/cli there is a possibility to compile native code using the native VS C++ compiler. This can provide a speedup since it is possible to use lower level techniques, including SIMD, and since the compiler in general is better at optimization.Source.

If both compile to MSIL your performance will in both cases mostly depend on the JIT compiler. But there might be some minor difference I'm not aware of.


问:
How to change the default xampp php.ini directory
The php.ini file in xampp is located here: C:\Windows for php.ini

The phpinfo contains this information:

Configuration File (php.ini) Path C:\WINDOWS

Loaded Configuration File (none)

Scan this dir for additional .ini files   (none)

How can i change the directory?

答:
open this file
"\xampp\apache\conf\extra\httpd-xampp.conf"

find this block

    PHPINIDir "C:/xampp/php"

change the directory


问:
ICAL File Validation (ICAL .NET)
I use ICAL .NET to create a webcalendar link in my ASP .NET Core application. My service code is inspired from this post :

        [AllowAnonymous]
        [HttpGet("ical/{icalSecret:Guid}")]
        public IActionResult GetICalFeed(Guid icalSecret)
        {

            var calendar = this.eventService.GetUserCalendar(icalSecret);
            var serializer = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);
            var contentType = "text/calendar";
            var bytes = Encoding.UTF8.GetBytes(serializedCalendar);

            return File(bytes, contentType, "calendar.ics");
        }
```

<p>And the method that generates the calendar : </p>

<pre class="lang-cs prettyprint-override"><code>        public Calendar GetUserCalendar(Guid icalSecret)
        {
            var user = this._userRepository.GetByICalSecret(icalSecret);
            var events = this._eventRepository.GetUserFutureEvents(user.Id);

             var calendarEvents = events.Select(evt => new CalendarEvent()
             {
                 Start = new CalDateTime(evt.Start),
                 End = new CalDateTime(evt.End),
                 Attendees = evt.Participations.Select(p => new Attendee(){CommonName = p.User.Username, Value = new Uri($"mailto:{p.User.Email}")}).ToList(),
                 Description = evt.Description
             });

             var calendar = new Calendar();
             foreach (var calendarEvent in calendarEvents)
             {
                 calendar.Events.Add(calendarEvent);
             }

             return calendar;
        }
</code>```

And the returned ical fil seems fine to me :

```<code>BEGIN:VCALENDAR
PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN
VERSION:2.0
BEGIN:STRING
ATTENDEE;CN=test mail:mailto:test@test.fr
ATTENDEE;CN=test droits:mailto:test@test.fr
ATTENDEE;CN=jm:mailto:test@test.com
ATTENDEE;CN=test:mailto:test@test.fr
DESCRIPTION:string
DTEND:20200610T093036
DTSTAMP:20200602T093344Z
DTSTART:20200610T093036
SEQUENCE:0
UID:a8845fea-6d16-49df-aa5e-a8cf61e1575a
END:STRING
END:VCALENDAR
</code>```

But windows calendar app can't open it (says it's damaged) and it fails validation on this ICAL validator.

Do you have any clue of what I did wrong?

答: Ok turn out I used the wrong field to store the name of my event in ICAL.NET. One should use the field Summary and not the field Name.

Title: ICAL File Validation (ICAL .NET)

Body:
I use ICAL .NET to create a webcalendar link in my ASP .NET Core application. My service code is inspired from this post :

        [AllowAnonymous]
        [HttpGet("ical/{icalSecret:Guid}")]
        public IActionResult GetICalFeed(Guid icalSecret)
        {

            var calendar = this.eventService.GetUserCalendar(icalSecret);
            var serializer = new CalendarSerializer();
            var serializedCalendar = serializer.SerializeToString(calendar);
            var contentType = "text/calendar";
            var bytes = Encoding.UTF8.GetBytes(serializedCalendar);

            return File(bytes, contentType, "calendar.ics");
        }

And the method that generates the calendar :

        public Calendar GetUserCalendar(Guid icalSecret)
        {
            var user = this._userRepository.GetByICalSecret(icalSecret);
            var events = this._eventRepository.GetUserFutureEvents(user.Id);

             var calendarEvents = events.Select(evt => new CalendarEvent()
             {
                 Start = new CalDateTime(evt.Start),
                 End = new CalDateTime(evt.End),
                 Attendees = evt.Participations.Select(p => new Attendee(){CommonName = p.User.Username, Value = new Uri($"mailto:{p.User.Email}")}).ToList(),
                 Description = evt.Description
             });

             var calendar = new Calendar();
             foreach (var calendarEvent in calendarEvents)
             {
                 calendar.Events.Add(calendarEvent);
             }

             return calendar;
        }

And the returned ical fil seems fine to me :

BEGIN:VCALENDAR
PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN
VERSION:2.0
BEGIN:STRING
ATTENDEE;CN=test mail:mailto:test@test.fr
ATTENDEE;CN=test droits:mailto:test@test.fr
ATTENDEE;CN=jm:mailto:test@test.com
ATTENDEE;CN=test:mailto:test@test.fr
DESCRIPTION:string
DTEND:20200610T093036
DTSTAMP:20200602T093344Z
DTSTART:20200610T093036
SEQUENCE:0
UID:a8845fea-6d16-49df-aa5e-a8cf61e1575a
END:STRING
END:VCALENDAR

But windows calendar app can't open it (says it's damaged) and it fails validation on this ICAL validator.

Do you have any clue of what I did wrong?


问:
Lazy load Google map
I want to Lazy Load Google Maps to get a better pageload-speed for SEO. My javascript works, but it still tries to load the map multiple times. How can i get it to load once? I found other scripts but i want to use as less code as possible.

My script:

```<code>google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
            initialize();
        });
   }
});
</code>```

Console log:

```<code>js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
</code>```

Thanks in advance!
Peter

答:
This works, only fires once. Thanks Sprep && Musefan</p>

```<code>    var fired = false;
    $(window).scroll(function() {
       var hT = $('#google-map').offset().top,
           hH = $('#google-map').outerHeight(),
           wH = $(window).height(),
           wS = $(this).scrollTop();
           wB = hT+hH-wH;
        if (wS > wB  && fired === false ){
            console.log('This will happen only once');
            fired = true;
            $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
                initialize();
            });
       }
    });
</code>```

Title: Lazy load Google map

Body:
I want to Lazy Load Google Maps to get a better pageload-speed for SEO. My javascript works, but it still tries to load the map multiple times. How can i get it to load once? I found other scripts but i want to use as less code as possible.

My script:

google = false;
$(window).scroll(function() {
   var hT = $('#google-map').offset().top,
       hH = $('#google-map').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
   if (wS > (hT+hH-wH)){
        if (!google) $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
            initialize();
        });
   }
});

Console log:

js?key={key}&_=1591085205888:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205888:140
js?key={key}&_=1591085205890:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205890:140
js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.
dj @ js?key={key}&_=1591085205891:140 You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

Thanks in advance!
Peter

Body:
This works, only fires once. Thanks Sprep && Musefan

    var fired = false;
    $(window).scroll(function() {
       var hT = $('#google-map').offset().top,
           hH = $('#google-map').outerHeight(),
           wH = $(window).height(),
           wS = $(this).scrollTop();
           wB = hT+hH-wH;
        if (wS > wB  && fired === false ){
            console.log('This will happen only once');
            fired = true;
            $.getScript( 'https://maps.googleapis.com/maps/api/js?key={key}', function( google, textStatus, jqxhr ) {
                initialize();
            });
       }
    });


问:
RxJS: Run asynchronous code before next or error
I have the following code:

```<code>of(true)
  .pipe(
    take(1)
  )
  .subscribe(async (_) =>  {
    await this.close();
    await Promise.all(...);
  }, _ => {
    this.close();
    console.error(_);
  });
</code>```

I want to only write once this.close(), however I can't use finalize since it has to be run before Promise.all. Is there something I could use to run a code (and wait for it to resolve) before next or error ?

答:
Is there something I could use to run a code (and wait for it to resolve) before next or error

I think materialize() and dematerialize() can be useful here:

src$.pipe(
  // Suppress errors so that `delayWhen()` can run properly
  // by converting everything into `Notification` objects
  materialize(),

  // Wait until `close()` finishes
  delayWhen(() => this.close())

  // Convert from `Notification` to the initial state: `next` || `error` || `complete`
  // so that their handlers can be invoked accordingly
  dematerialize(),
)
```

Note that with this approach it is going to wait for a complete notification as well, which can be avoided with the help of filter().

Body:
I have the following code:

of(true)
  .pipe(
    take(1)
  )
  .subscribe(async (_) =>  {
    await this.close();
    await Promise.all(...);
  }, _ => {
    this.close();
    console.error(_);
  });

I want to only write once this.close(), however I can't use finalize since it has to be run before Promise.all. Is there something I could use to run a code (and wait for it to resolve) before next or error ?

Body:
Is there something I could use to run a code (and wait for it to resolve) before next or error

I think materialize() and dematerialize() can be useful here:

src$.pipe(
  // Suppress errors so that `delayWhen()` can run properly
  // by converting everything into `Notification` objects
  materialize(),

  // Wait until `close()` finishes
  delayWhen(() => this.close())

  // Convert from `Notification` to the initial state: `next` || `error` || `complete`
  // so that their handlers can be invoked accordingly
  dematerialize(),
)

Note that with this approach it is going to wait for a complete notification as well, which can be avoided with the help of filter().


问:
How to iterate through 2 columns and match one by one
Lets say i have 2 excel files each containing a column of names and dates

Excel 1:

```<code>Name
0      Bla bla bla June 04 2018
1      Puppy Dog June 01 2017
2      Donald Duck February 24 2017
3      Bruno Venus April 24 2019
</code>```

Excel 2:

```<code>                             Name
0        Pluto Feb 09 2019
1        Donald Glover Feb 22 2020
2        Dog Feb 22 2020
3        Bla Bla Feb 22 2020
</code>```

I want to match each cell from column 1 to each cell in column 2 and then locate the biggest similarity.

The following function will give a percentage value of how much two input match each other.

SequenceMatcher code example:

```<code>from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

x = "Adam Clausen a Feb 09 2019"
y = "Adam Clausen Feb 08 2019"
print(similar(x,y))
</code>```

Output:0.92

答:
If u know how to load colums as dataframe..this code should get your job done..</p>

```<code>from difflib import SequenceMatcher

col_1 = ['potato','tomato', 'apple']
col_2 = ['tomatoe','potatao','appel']

def similar(a,b):
    ratio = SequenceMatcher(None, a, b).ratio()
    matches = a, b
    return ratio, matches

for i in col_1:
    print(max(similar(i,j) for j in col_2))
</code>```

Body:
Lets say i have 2 excel files each containing a column of names and dates

Excel 1:

Name
0      Bla bla bla June 04 2018
1      Puppy Dog June 01 2017
2      Donald Duck February 24 2017
3      Bruno Venus April 24 2019

Excel 2:

                             Name
0        Pluto Feb 09 2019
1        Donald Glover Feb 22 2020
2        Dog Feb 22 2020
3        Bla Bla Feb 22 2020

I want to match each cell from column 1 to each cell in column 2 and then locate the biggest similarity.

The following function will give a percentage value of how much two input match each other.

SequenceMatcher code example:

from difflib import SequenceMatcher

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

x = "Adam Clausen a Feb 09 2019"
y = "Adam Clausen Feb 08 2019"
print(similar(x,y))

Output:0.92

Body:
If u know how to load colums as dataframe..this code should get your job done..

from difflib import SequenceMatcher

col_1 = ['potato','tomato', 'apple']
col_2 = ['tomatoe','potatao','appel']

def similar(a,b):
    ratio = SequenceMatcher(None, a, b).ratio()
    matches = a, b
    return ratio, matches

for i in col_1:
    print(max(similar(i,j) for j in col_2))


问:
Does using different hardware specs for different nodes in cassandra cause problems?
We started using Cassandra years ago with four nodes. All the nodes have same instance size, M5.xlarge which is vCPU:4 and Memory:16GB. By time we increased disk space for each node up to 300 GB each.

If we want to add a new node/nodes with different and higher hardware specs such as vCPU 16, memory 64GB (1 TB disk), does it cause problem across the nodes? It may sound silly but IOPS will be different, latency may be lower, even the data may be more up-to-date in higher spec node(maybe it chokes other nodes?). Since the traffic is distributed evenly the way new node handle the I/O will be different than other nodes.

Thank you.

答:
Yes, it will cause problems, especially if you're using consistency level that is higher than LOCAL_ONE or ONE... The latencies when reading or writing data will be different, and even if your new nodes will answer fast, they will need to answers from smaller nodes, etc.

If you're using AWS (or other cloud provider) - why not upgrade the nodes in-place? If you're using EBS, just remount them to bigger nodes, but keep the instance types the same for all nodes.


问:
how to build odoo-12.0 for windows as an executable software?
enter image description hereI want to use odoo-12.0 locally, but I don’t want to install the python environment, so I want to package odoo-12.0 into an exe executable file. When I use pyintaller to package it into an exe, and copy odoo, addons, myaddons, odoo.conf Go to the current directory of the executable file, and modify the addons_path path in the configuration file to the absolute path of odoo, addons, myaddons in the exe directory, compile all py files in the current directory of the exe into pyc files, and change the name to Under the corresponding directory, delete py. After clicking, there is a problem with the exe. After double-clicking the exe file, an error occurs and the versions cannot be found. What caused this?</p>

答: You should use pyinstaller --onefile, it generates one .exe file including everything.


问:
cakephp select list showing ids instead of text
i am using cakephp 1.3 to generate a form i am creating a select list using hasOne and belongsTo relation

```<code>my models: image, category
</code>```

category hasMany image

image belongsTo Category

category table has two columns id and category_name

i am doing

```<code>$this->set('categories',
           $this->Image->Category->find(
                                        'list',
                                         array( 'order' => 'category_name ASC' )
                                       )
          ); //to generate the select list
</code>```

so far so good, there is only one problem left, the select list generated shows the id of the category instead of the category_name as the option text, i know this is not cakePHP's fault but i need to know the solution

any help please.

P.S if i am unclear about the question please let me know

答:
You need to define the displayField property in your category model, so that CakePHP can properly determine which field to display as a label. This code in your category model will fix it for you:

```<code>var $displayField = 'category_name';
</code>```

Alternatively, rename the category_name field to 'name' or 'title' (I would do this, it's obvious that a 'name' field in a category table is going to be the name of the category).

Body:
i am using cakephp 1.3 to generate a form i am creating a select list using hasOne and belongsTo relation

my models: image, category

category hasMany image

image belongsTo Category

category table has two columns id and category_name

i am doing

$this->set('categories',
           $this->Image->Category->find(
                                        'list',
                                         array( 'order' => 'category_name ASC' )
                                       )
          ); //to generate the select list

so far so good, there is only one problem left, the select list generated shows the id of the category instead of the category_name as the option text, i know this is not cakePHP's fault but i need to know the solution

any help please.

P.S if i am unclear about the question please let me know

Body:
You need to define the displayField property in your category model, so that CakePHP can properly determine which field to display as a label. This code in your category model will fix it for you:

var $displayField = 'category_name';

Alternatively, rename the category_name field to 'name' or 'title' (I would do this, it's obvious that a 'name' field in a category table is going to be the name of the category).


问:
How to trim spaces dynamically?
I use input component from material library. User inputs to fileld several spaces + several symbols + several spaces. After that he click on submit button. In result, console displays only symbols (without begin/end spaces). Its OK, its right behavior.

But i need begin/end spaces disappeared after user press key up. Help me do it.

LIVE DEMO

```<code><md-input-container>
  <label>Title</label>
  <input ng-model="$ctrl.pass">
</md-input-container>
<button ng-click="$ctrl.change()">submit</button>

class HomeCtrl {
  constructor() {
    this.pass = null;
    this.change = function() {
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
    }
  }
}
</code>```

答:
Add ng-trim='false' to input element (default will be true) so that AngularJS will not automatically trim the input.
<input ng-model="$ctrl.pass" ng-trim="false">

Update this.pass in the change() function as follows:

```<code>this.pass = this.pass.replace(/\s+/g, ''); //to remove all whitespaces
this.pass = this.pass.trim(); //to remove leading and trailing whitespaces

this.change = function() {
      this.pass = this.pass.replace(/\s+/g, '');
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
}
</code>```

References:

Strip white spaces on input

https://docs.angularjs.org/api/ng/input/input%5Btext%5D

Title: How to trim spaces dynamically?

Body:
I use input component from material library. User inputs to fileld several spaces + several symbols + several spaces. After that he click on submit button. In result, console displays only symbols (without begin/end spaces). Its OK, its right behavior.

But i need begin/end spaces disappeared after user press key up. Help me do it.

LIVE DEMO

<md-input-container>
  Title
  <input ng-model="$ctrl.pass">
</md-input-container>
<button ng-click="$ctrl.change()">submit</button>

class HomeCtrl {
  constructor() {
    this.pass = null;
    this.change = function() {
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
    }
  }
}

Body:
Add ng-trim='false' to input element (default will be true) so that AngularJS will not automatically trim the input.
<input ng-model="$ctrl.pass" ng-trim="false">

Update this.pass in the change() function as follows:

this.pass = this.pass.replace(/\s+/g, ''); //to remove all whitespaces
this.pass = this.pass.trim(); //to remove leading and trailing whitespaces

this.change = function() {
      this.pass = this.pass.replace(/\s+/g, '');
      setTimeout(_ => {
        console.log(this.pass, 'length:', this.pass.length)
      });
}

References:

Strip white spaces on input

https://docs.angularjs.org/api/ng/input/input%5Btext%5D


问:
How to use imported libraries as a type property
I'd like to declare a type, and set one of its properties as an imported library.

The ultimate goal of this is to have the Dependencies of my platform defined in a single place.

Simplifying, I have something like this:

```<code>import * as crypto from 'crypto';

export type Dependencies = {
  ... (Some dependencies)...
  crypto: crypto;
  ... (Some more dependencies)...
}

function ({ crypto }: Dependencies, length: number) {
   return crypto
      .createHmac('sha256', Math.random() * 10 ** length + '')
      .digest('hex')
      .substring(0, length);
}

</code>```

But when defining the type I get Cannot use namespace 'crypto' as a type.ts(2709)

I've tried using interface instead of type, but ran into the same problem.

Bottom line, the question is: Is there any way I can define that X property (or method) of either an interface or a type, should be that of a library?

Thanks!

答:
Try :

```<code>type CryptoModule = typeof import("crypto");
</code>```

Dumb example:

/**
 * @param {CryptoModule} arg
 */
const foo = (arg) => 42;

foo("hi"); // Argument of type '"hi"' is not assignable to parameter of type 'typeof import("crypto")'.ts(2345)
foo(crypto); // fine
```

Body:
I'd like to declare a type, and set one of its properties as an imported library.

The ultimate goal of this is to have the Dependencies of my platform defined in a single place.

Simplifying, I have something like this:

import * as crypto from 'crypto';

export type Dependencies = {
  ... (Some dependencies)...
  crypto: crypto;
  ... (Some more dependencies)...
}

function ({ crypto }: Dependencies, length: number) {
   return crypto
      .createHmac('sha256', Math.random() * 10 ** length + '')
      .digest('hex')
      .substring(0, length);
}

But when defining the type I get Cannot use namespace 'crypto' as a type.ts(2709)

I've tried using interface instead of type, but ran into the same problem.

Bottom line, the question is: Is there any way I can define that X property (or method) of either an interface or a type, should be that of a library?

Thanks!

Body:
Try :

type CryptoModule = typeof import("crypto");

Dumb example:

/**
 * @param {CryptoModule} arg
 */
const foo = (arg) => 42;

foo("hi"); // Argument of type '"hi"' is not assignable to parameter of type 'typeof import("crypto")'.ts(2345)
foo(crypto); // fine


问:
Get consecutive days with momentjs
I have a string containing days of the week:

```<code>Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
</code>```

It can be also:

```<code>Monday, Tuesday
</code>```

Also:

```<code>Thursday, Friday, Saturday
</code>```

What I want to achieve is if more than 2 days are consecutive to "merge" them and display like:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday - will be Monday - Sunday;
Monday, Tuesday - will stay like that;
Thursday, Friday, Saturday - Thursday - Saturday.

I want to use only moment.js or javascript without other plugins (like range).
Thanks in advance!

答:
We can create a Day of the Week (dow) array with our list of days (and implicitly their indexes).

If a list of days are consecutive, we'll replace with Startday - Endday, though we won't bother if it's only two days.

I'm assuming that the week "wraps", e.g. Monday is considered to be consecutive to Sunday. If not, it's an easy tweak to make. We'd replace the function isModularConsecutive with isConsecutive.

function isModularConsecutive(a, modulus) {
   return !isNaN(a.reduce((prev, current, index) => (index === 0 || current === ((prev + 1) % modulus) ? current: NaN)));
}

function formatDowList(input) {
    const dow = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
    let inputArray = input.split(/\s*\,\s*/);
    let actualIndexes = inputArray.map(el => dow.findIndex(d => d === el));
    if (!isModularConsecutive(actualIndexes, 7) || actualIndexes.length <= 2) {
        return input;
    }
    return inputArray[0] + " - " + inputArray[inputArray.length-1];
}

/* Test the code */
const testInputs = ["Monday, Thursday, Friday", "Monday, Tuesday, Wednesday, Thursday, Friday", "Monday, Tuesday, Wednesday", "Sunday, Monday, Tuesday, Wednesday", "Monday, Wednesday", ];
testInputs.forEach(input => console.log("Input: '" + input + "'.", "Result: '"  + formatDowList(input) + "'"))```

Title: Get consecutive days with momentjs

Body:
I have a string containing days of the week:

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

It can be also:

Monday, Tuesday

Also:

Thursday, Friday, Saturday

What I want to achieve is if more than 2 days are consecutive to "merge" them and display like:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday - will be Monday - Sunday;
Monday, Tuesday - will stay like that;
Thursday, Friday, Saturday - Thursday - Saturday.

I want to use only moment.js or javascript without other plugins (like range).
Thanks in advance!


问:
Query firestore database for document id
I want to query a firestore database for document id. Currently I have the following code:

```<code>db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()
</code>```

I don't get a result. But when I query for a different field it works:

```<code>db.collection('books').where('genre', '==', 'biography').get()
</code>```

How is the name of the document id called?

答:
You can use the __name__ key word to use your document ID in a query.

Instead of this db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get() you can write

db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get().

In this case you should get an array of length 1 back.

The firebase docs mention this feature in the rules documentation. https://firebase.google.com/docs/reference/rules/rules.firestore.Resource

Body:
I want to query a firestore database for document id. Currently I have the following code:

db.collection('books').where('id', '==', 'fK3ddutEpD2qQqRMXNW5').get()

I don't get a result. But when I query for a different field it works:

db.collection('books').where('genre', '==', 'biography').get()

How is the name of the document id called?


问:
Set a corner radius on a spark list Flex 4 air mobile
I'm creating a spark list in my flex mobile application and i want to do like a list on the iphone with a corner radius.
Unfortunately there is no cornerRadius or simply radius in list styles.

I call a list in a view:

```<code>  <s:List id="language" width="100%" height="70" borderVisible="true"
                    change="navigator.pushView(LanguageView)" dataProvider="{languageCell}"
                    itemRenderer="skins.CustomCellStyle1"/>
</code>```

Then I call itemRenderer:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                width="100%" height="70">
    <s:HGroup width="100%" verticalCenter="0" paddingLeft="15" paddingRight="15">
        <s:Label text="{data.label}"/>
        <s:Spacer width="100%"/>
        <s:Label text="{data.content}"
                 textAlign="right"
                 color="0x046380" paddingRight="5"/>
        <s:BitmapImage id="icon"
                       source="{data.mark}"
                       verticalCenter="0"/>
    </s:HGroup>
</s:ItemRenderer>
</code>```

So how can I use corner radius on my cells?

答:
http://viconflex.blogspot.com/2008/05/sometimes-cornerradius-just-isnt-enough.html

Two tips for coders new to Flex... if you want to have rounded corners in mx.containers like VBox, HBox, Canvas, etc, set the borderStyle to solid and the borderThickness to 0, and then set your cornerRadius to whatever you want. If the borderStyle is left at none (default), the cornerRadius attribute seems broken and ineffective.

The second tip, if you want rounded corners at the top and bottom of your Panel, there's a property called roundedBottomCorners which defaults to false. When set to true, you will see rounding both top and bottom.

Body:
I'm creating a spark list in my flex mobile application and i want to do like a list on the iphone with a corner radius.
Unfortunately there is no cornerRadius or simply radius in list styles.

I call a list in a view:

  <s:List id="language" width="100%" height="70" borderVisible="true"
                    change="navigator.pushView(LanguageView)" dataProvider="{languageCell}"
                    itemRenderer="skins.CustomCellStyle1"/>

Then I call itemRenderer:

<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                xmlns:s="library://ns.adobe.com/flex/spark"
                width="100%" height="70">
    <s:HGroup width="100%" verticalCenter="0" paddingLeft="15" paddingRight="15">
        <s:Label text="{data.label}"/>
        <s:Spacer width="100%"/>
        <s:Label text="{data.content}"
                 textAlign="right"
                 color="0x046380" paddingRight="5"/>
        <s:BitmapImage id="icon"
                       source="{data.mark}"
                       verticalCenter="0"/>
    </s:HGroup>
</s:ItemRenderer>

So how can I use corner radius on my cells?


问:
Code returns "none" on codecademy and im not sure why
Instructions:

First, def a function called distance_from_zero, with one argument (choose any >argument name you like).

If the type of the argument is either int or float, the function should return >the absolute value of the function input.

Otherwise, the function should return "Nope"

I've done the first task and I thought that i completed the task, however

"Your function seems to fail on input True when it returned 'None' instead of 'Nope'"

Here is my code:

```<code>def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
    return abs(argument)
    print(argument)
else:
    print("Nope")
</code>```

From what ive seen in other modules codecademy tests this with my arguement being "1", such that the if statement goes through, will return the absolute value of (argument) and then i would pass the module. (i added print(argument) for testing purposes, the console outputs nothing.)

Am i mis understanding how returning works? Why is this not working?
I appreciate all responses! :)

EDIT: It prints "None", not "Nope" in the console. Forgot to mention this.

答:
```<code>def distance_from_zero(num):
    if type(num) == int or type(num) == float:
        return abs(num)
    else:
        return "Nope"
</code>```

Body:
Instructions:

First, def a function called distance_from_zero, with one argument (choose any >argument name you like).

If the type of the argument is either int or float, the function should return >the absolute value of the function input.

Otherwise, the function should return "Nope"

I've done the first task and I thought that i completed the task, however

"Your function seems to fail on input True when it returned 'None' instead of 'Nope'"

Here is my code:

def distance_from_zero(argument):
if type(argument) == int or type(argument) == float:
    return abs(argument)
    print(argument)
else:
    print("Nope")

From what ive seen in other modules codecademy tests this with my arguement being "1", such that the if statement goes through, will return the absolute value of (argument) and then i would pass the module. (i added print(argument) for testing purposes, the console outputs nothing.)

Am i mis understanding how returning works? Why is this not working?
I appreciate all responses! :)

EDIT: It prints "None", not "Nope" in the console. Forgot to mention this.


问:
How to reload Excel add-in for Desktop Version
We deployed Excel add-in project which was developed in Office Js in intranet. And manifest file uploaded in Office 365 admin center to reflect users. But it is working in Office online Excel version only. But in desktop version it is not getting refreshing and only showing old changes. Kindly help on this so that it can be upload with new changes to get reflect.</p>

答:
You can remove an add-in that you've previously sideloaded on Windows, Mac, or iOS by clearing the Office cache on your computer.

Additionally, if you make changes to your add-in's manifest (for example, update file names of icons or text of add-in commands), you should clear the Office cache and then re-sideload the add-in using updated manifest. Doing so will allow Office to render the add-in as it's described by the updated manifest.

To remove all sideloaded add-ins from Excel, Word, and PowerPoint, delete the contents of the folder:

```<code>%LOCALAPPDATA%\Microsoft\Office\16.0\Wef\
</code>```

To remove a sideloaded add-in from Outlook, use the steps outlined in Sideload Outlook add-ins for testing to find the add-in in the Custom add-ins section of the dialog box that lists your installed add-ins. Choose the ellipsis (...) for the add-in and then choose Remove to remove that specific add-in. If this add-in removal doesn't work, then delete the contents of the Wef folder as noted previously for Excel, Word, and PowerPoint.

Additionally, to clear the Office cache on Windows 10 when the add-in is running in Microsoft Edge, you can use the Microsoft Edge DevTools.

Read more about that in the Clear the Office cache article.

Body:
You can remove an add-in that you've previously sideloaded on Windows, Mac, or iOS by clearing the Office cache on your computer.

Additionally, if you make changes to your add-in's manifest (for example, update file names of icons or text of add-in commands), you should clear the Office cache and then re-sideload the add-in using updated manifest. Doing so will allow Office to render the add-in as it's described by the updated manifest.

To remove all sideloaded add-ins from Excel, Word, and PowerPoint, delete the contents of the folder:

%LOCALAPPDATA%\Microsoft\Office\16.0\Wef\

To remove a sideloaded add-in from Outlook, use the steps outlined in Sideload Outlook add-ins for testing to find the add-in in the Custom add-ins section of the dialog box that lists your installed add-ins. Choose the ellipsis (...) for the add-in and then choose Remove to remove that specific add-in. If this add-in removal doesn't work, then delete the contents of the Wef folder as noted previously for Excel, Word, and PowerPoint.

Additionally, to clear the Office cache on Windows 10 when the add-in is running in Microsoft Edge, you can use the Microsoft Edge DevTools.

Read more about that in the Clear the Office cache article.


问:
How to omit results with date subquery on Laravel Query Builder
I have a Laravel app that has a table of models and a table of dates they're booked out. Only models who have entered dates they're booked out will have dates in the dates table. The dates are stored day by day. So the schema looks like the following (simplified):

tbl_models

```<code> id   | name         | details         | gender
 1    | joe bloggs   | over 60         | male
 2    | jill bloggs  | pink nails      | female
 3    | a n other    | greying         | male
</code>```

tbl_ModelCalendar

```<code> id   | model_id  | date
 1    | 1         | 2020-06-05 00:00:00
 2    | 1         | 2020-06-06 00:00:00
 3    | 1         | 2020-06-07 00:00:00
 4    | 3         | 2020-09-15 00:00:00
</code>```

I want to be able to select models based on those that aren't booked out within a certain date range. So, we feed in a NotBookedOutFrom date object and a NotBookedOutTo date object and return any models that are available between those two dates. I think I need a subquery for this? I can't INNER JOIN the bookings table because it then omits any models that don't have any booked out dates (i.e. are free all the time - ideal!) and I can't LEFT JOIN because it will return a result based on another available date outside of the scope of dates we've omitted.

At the moment, the code block from my controller looks like this:

```<code>$model->select('tbl_models.*');

$from =  DateTime::createFromFormat('Y-m-d', Carbon::parse($NotBookedOutFrom)->format('Y-m-d'));
$to =  DateTime::createFromFormat('Y-m-d', Carbon::parse($NotBookedOutTo)->format('Y-m-d'));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($from, $interval, $to);

$model->leftJoin('tbl_ModelCalendar', 'tbl_ModelCalendar.model_id', '=', 'tbl_models.id');

$bookedDates = array();
      foreach ($period as $dt) {
          $thisDate = $dt->format("Y-m-d H:i:s");
          $bookedDates[] = $thisDate;

      }

$model->whereNotIn('tbl_ModelCalendar.date', [$bookedDates]);
</code>```

Anyway, needless to say, this doesn't work and is a mess. I'm definitely missing something quite simple here but I've run around in circles for hours.

EDIT:

On the suggestion of Akina, I've tried to translate his answer to Query Builder but it's still not excluding booked out models:

```<code>$model->leftJoin('tbl_ModelCalendar', 'tbl_models.id', '=', DB::raw("tbl_ModelCalendar.model_id AND tbl_ModelCalendar.date BETWEEN $from AND $to"));
$model->whereNull('tbl_ModelCalendar.model_id');
</code>```

答:
In pure SQL your query looks like

```<code>SELECT tbl_models.*
FROM tbl_models
LEFT JOIN tbl_ModelCalendar
    ON tbl_models.id = tbl_ModelCalendar.model_id
   AND tbl_ModelCalendar.`date` BETWEEN @NotBookedOutFrom AND @NotBookedOutTo
WHERE tbl_ModelCalendar.model_id IS NULL;
</code>```

fiddle

Body:
I have a Laravel app that has a table of models and a table of dates they're booked out. Only models who have entered dates they're booked out will have dates in the dates table. The dates are stored day by day. So the schema looks like the following (simplified):

tbl_models

 id   | name         | details         | gender
 1    | joe bloggs   | over 60         | male
 2    | jill bloggs  | pink nails      | female
 3    | a n other    | greying         | male

tbl_ModelCalendar

 id   | model_id  | date
 1    | 1         | 2020-06-05 00:00:00
 2    | 1         | 2020-06-06 00:00:00
 3    | 1         | 2020-06-07 00:00:00
 4    | 3         | 2020-09-15 00:00:00

I want to be able to select models based on those that aren't booked out within a certain date range. So, we feed in a NotBookedOutFrom date object and a NotBookedOutTo date object and return any models that are available between those two dates. I think I need a subquery for this? I can't INNER JOIN the bookings table because it then omits any models that don't have any booked out dates (i.e. are free all the time - ideal!) and I can't LEFT JOIN because it will return a result based on another available date outside of the scope of dates we've omitted.

At the moment, the code block from my controller looks like this:

$model->select('tbl_models.*');

$from =  DateTime::createFromFormat('Y-m-d', Carbon::parse($NotBookedOutFrom)->format('Y-m-d'));
$to =  DateTime::createFromFormat('Y-m-d', Carbon::parse($NotBookedOutTo)->format('Y-m-d'));
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($from, $interval, $to);

$model->leftJoin('tbl_ModelCalendar', 'tbl_ModelCalendar.model_id', '=', 'tbl_models.id');

$bookedDates = array();
      foreach ($period as $dt) {
          $thisDate = $dt->format("Y-m-d H:i:s");
          $bookedDates[] = $thisDate;

      }

$model->whereNotIn('tbl_ModelCalendar.date', [$bookedDates]);

Anyway, needless to say, this doesn't work and is a mess. I'm definitely missing something quite simple here but I've run around in circles for hours.

EDIT:

On the suggestion of Akina, I've tried to translate his answer to Query Builder but it's still not excluding booked out models:

$model->leftJoin('tbl_ModelCalendar', 'tbl_models.id', '=', DB::raw("tbl_ModelCalendar.model_id AND tbl_ModelCalendar.date BETWEEN $from AND $to"));
$model->whereNull('tbl_ModelCalendar.model_id');

Body:
In pure SQL your query looks like

SELECT tbl_models.*
FROM tbl_models
LEFT JOIN tbl_ModelCalendar
    ON tbl_models.id = tbl_ModelCalendar.model_id
   AND tbl_ModelCalendar.`date` BETWEEN @NotBookedOutFrom AND @NotBookedOutTo
WHERE tbl_ModelCalendar.model_id IS NULL;

fiddle


问:
Is it possible using cocos2d via javascript fully?
I am new to cocos2d.
Is it possible using cocos2d via javascript fully?
I prefer to use script language to control game elements.

Welcome any comment

答:
The only languages available to program with cocos2d on the iPhone are C++ and Objective-c as far as i'm aware. (I've been programming for the iPhone SDK for nearly 2 years with cocos2d and have never seen javascript mentioned.)

http://www.cocos2d-iphone.org


问:
Loop through dynamic template parameters in Azure devops YAML
I want to perform some actions (publish) on an array of string which are passed as parameter.
The thing is, this parameter is dynamic :

```<code># pipeline.yml

- job: MyJob
    pool:
      [...]
    steps:
      - pwsh: |
          $affected = ['app-one', 'app-two'] # Here I hardcoded the array but in my real code this is set dynamically
          Write-Host "##vso[task.setvariable variable=affected;isOutput=true]$affected"
        name: setAffected
        displayName: 'Settings affected'

- template: ./build.yml
  parameters:
    affected: $[ dependencies.Affected.outputs['setAffected.affected'] ] # Here I pass the array of string to the template
</code>```

```<code># build.yml

parameters:
  affected: ''

jobs:
  - job: Build
    condition: succeeded('Affected')
    dependsOn: Affected
    pool:
      [...]
    variables:
      affected: ${{ parameters.affected }}
    steps:
      - ${{each app in $(affected)}}:
          - pwsh: |
              Write-Host "${{app}}"
      - ${{each app in parameters.affected}}:
          - pwsh: |
              Write-Host "${{app}}"

</code>```

Neither of ${{each app in $(affected)}} or ${{each app in parameters.affected}} work...
How can I manage to execute some actions on each of my array item?

Thanks

答:
Within a template expression, you have access to the parameters
  context that contains the values of parameters passed in.
  Additionally, you have access to the variables context that contains
  all the variables specified in the YAML file plus the system
  variables. Importantly, it doesn't have runtime variables such
  as those stored on the pipeline or given when you start a run.
  Template expansion happens very early in the run, so those variables
  aren't available.

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops

Body:
I want to perform some actions (publish) on an array of string which are passed as parameter.
The thing is, this parameter is dynamic :

# pipeline.yml

- job: MyJob
    pool:
      [...]
    steps:
      - pwsh: |
          $affected = ['app-one', 'app-two'] # Here I hardcoded the array but in my real code this is set dynamically
          Write-Host "##vso[task.setvariable variable=affected;isOutput=true]$affected"
        name: setAffected
        displayName: 'Settings affected'

- template: ./build.yml
  parameters:
    affected: $[ dependencies.Affected.outputs['setAffected.affected'] ] # Here I pass the array of string to the template

# build.yml

parameters:
  affected: ''

jobs:
  - job: Build
    condition: succeeded('Affected')
    dependsOn: Affected
    pool:
      [...]
    variables:
      affected: ${{ parameters.affected }}
    steps:
      - ${{each app in $(affected)}}:
          - pwsh: |
              Write-Host "${{app}}"
      - ${{each app in parameters.affected}}:
          - pwsh: |
              Write-Host "${{app}}"

Neither of ${{each app in $(affected)}} or ${{each app in parameters.affected}} work...
How can I manage to execute some actions on each of my array item?

Thanks


问:
Alternative to creating views in SQL read only database
I have some longish queries that creates views to simplify the queries a lot but the underlying DB I'm reading from has been changed to read-only. The views, of course, are no longer created, but I am dreading the huge refactor and the way these select statements are going to look without it. Am I missing something obvious?</p>

答:
If you are on MySQL 8, you could get away with only a little refactoring by using CTEs, e.g. you can do something like

```<code>with tmp_a as (select id from table_a),
     tmp_b as (select id from tmp_a)
select * from tmp_a a join tmp_b b on a.id = b.id
</code>```

This would allow you to keep your basic code structure without much effort and as descriptive as your current code.

Before CTEs, you can just copy&paste the code of your views to wherever you use your views. MySQL actually does exactly the same when it runs your query, but if you use your views several times or heavily nested, it might not look as clean as CTEs. But the refactoring is still just limited to copy&paste.

To keep closer to your current situation with actual views, and maybe the least amount of refactoring, you could replace your views with temporary tables, which are allowed on read-only databases:

```<code>create view tmp_a as select id from table_a
</code>```

becomes

```<code>create temporary table tmp_a as select id from table_a
</code>```

This has the restriction though that you cannot use such a temporary table several times in a query (e.g. in a from/join), so you may have to check if this can happen, in which case you may have to create the temporary table several times (which may increase your memory requirements). Otherwise, you can use those almost like your views, with the exception that the temporary tables are only accessable in the session that created them, and will vanish with the session.

If you are on a readonly slave (and not a static database), you may also have to make sure that you are in a transaction if you use several base tables (e.g. not generate "view2" just from "view1"). In contrast to a single query based on views (which are merged into one big query), the temporary tables might otherwise represent different times.

Another alternative to get actual views, although this definitely has the smell of a workaround, could be to add a non-readonly dummy database on the server where you create the views and access the other database, e.g.

```<code>create view tmp_a as select id from ro_db.table_a
</code>```

You'll need to adjust your queries to refer to the correct database, and of course have to setup the database and permissions.

Body:
If you are on MySQL 8, you could get away with only a little refactoring by using CTEs, e.g. you can do something like

with tmp_a as (select id from table_a),
     tmp_b as (select id from tmp_a)
select * from tmp_a a join tmp_b b on a.id = b.id

This would allow you to keep your basic code structure without much effort and as descriptive as your current code.

Before CTEs, you can just copy&paste the code of your views to wherever you use your views. MySQL actually does exactly the same when it runs your query, but if you use your views several times or heavily nested, it might not look as clean as CTEs. But the refactoring is still just limited to copy&paste.

To keep closer to your current situation with actual views, and maybe the least amount of refactoring, you could replace your views with temporary tables, which are allowed on read-only databases:

create view tmp_a as select id from table_a

becomes

create temporary table tmp_a as select id from table_a

This has the restriction though that you cannot use such a temporary table several times in a query (e.g. in a from/join), so you may have to check if this can happen, in which case you may have to create the temporary table several times (which may increase your memory requirements). Otherwise, you can use those almost like your views, with the exception that the temporary tables are only accessable in the session that created them, and will vanish with the session.

If you are on a readonly slave (and not a static database), you may also have to make sure that you are in a transaction if you use several base tables (e.g. not generate "view2" just from "view1"). In contrast to a single query based on views (which are merged into one big query), the temporary tables might otherwise represent different times.

Another alternative to get actual views, although this definitely has the smell of a workaround, could be to add a non-readonly dummy database on the server where you create the views and access the other database, e.g.

create view tmp_a as select id from ro_db.table_a

You'll need to adjust your queries to refer to the correct database, and of course have to setup the database and permissions.