问:
css/html- to create a circle with a hole in the bottom
enter image description here

I wanna make circle chart like this.
below is my code.

If I invert up and down in that code, i get the shape you want.
But what I really want is a graph with the yellow graph pointing further to the right. How do I adjust the spacing?
Please help me

```<code><svg width="4.5rem" height="4.5rem" viewBox="0 0 40 40">
  <circle class="pieSegment segment1" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#1a0d1c" stroke-dashoffset="11" stroke-dasharray="74" stroke-width="5"></circle>
  <circle class="pieSegment segment3" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#e9ad61" stroke-dashoffset="14" stroke-dasharray="25 75" stroke-width="5"></circle>
</svg>
</code>```

答:
Edit (missed the previous answer by @jeremy-denis also using pathLength)

Here is another approach also using pathLength value:

See also MDN Docs: pathLength

example horse shoe gauge

let progress = document.querySelector("#progress");
let svgGauges = document.querySelectorAll(".svgGauge");
let gauges = document.querySelectorAll(".gaugePercent");
let percentText = document.querySelector(".percentText");

progress.addEventListener("change", function(e) {
  let percent = e.target.value;
  if (svgGauges.length) {
    svgGauges.forEach(function(item, i) {
      let currentGauge = svgGauges[i];
      let gauge = currentGauge.querySelector(".gaugePercent");
      let dashGap = gauge.getAttribute("stroke-dasharray").split(" ")[1];
      // console.log(gauge);
      gauge.setAttribute("stroke-dasharray", percent + " " + dashGap);
      gauge.setAttribute("style", "animation-fill-mode: none");
      percentText.textContent = percent;
    });
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.gaugeWrap {
  display: inline-block;
  width: 10rem;
}

.layout {
  width: 50%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

.txt-cnt {
  text-align: center;
}

.circle {
  transition: 0.3s;
  stroke-width: 15;
}

.linecap-round .circle {
  stroke-linecap: round;
  shape-rendering: geometricPrecision;
}

.linecap-round .circle[stroke-dasharray^="0 "] {
  stroke-linecap: unset;
}</code>```

Progress (50 %) <input id="progress" style="width:100px" type="range" min="0" max="100" step="10" value="50" />

horse shoe gauge 270°

    <svg class="svgGauge linecap-round" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="scale(-1 1) rotate(-225) ">
      <circle class="circle gaugeBG" id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="133.333" fill="none" stroke="#000" stroke-dasharray="100 100" />
      <circle class="circle gaugePercent " id="gauge" cx="50%" cy="50%" r="45" pathLength="133.333" fill="none" stroke-dasharray="50 133.333" stroke="#e9ad61" />
    </svg>

Semi-circle gauge 180°

    <svg class="svgGauge linecap-round" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="scale(-1 1) rotate(-180)">
      <circle class="circle gaugeBG " id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="200" fill="none" stroke="#000" stroke-dasharray="100 200" />
      <circle class="circle gaugePercent" id="gauge" cx="50%" cy="50%" r="45" pathLength="200" fill="none" stroke-dasharray="50 200" stroke="#e9ad61" />
    </svg>

Full-circle gauge 360°

    <svg class="svgGauge" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="rotate(-90)">
      <circle class="circle gaugeBG" id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="100" fill="none" stroke="#000" stroke-dasharray="100 100" />
      <circle class="circle gaugePercent" id="gauge" cx="50%" cy="50%" r="45" pathLength="100" fill="none" stroke-linecap="butt" stroke-dasharray="50 100" stroke="#e9ad61" />
    </svg>

```

Your example has approximately a 270° range (3/4 of 360°).

By setting pathLengthto 133 (360/270*100) we change the computation of the dash lengths.

Since we don't use the complete circumference of the circle (see the full circle example with pathLength=100) we increase the pathlength to make this 3/4 segment to have a length of 100 units.

We can set the first stroke-dasharray value e.g. to 50 (display 50% progress).

The 2nd value 133 ensures the dash gap is large enough to fill the rest of the circle gauge.

To make the horse shoe gauge stand upright we need to calculate a rotation like this:

(360 + 270)/2 - 90 = -225

So we can rotate the parent svg by setting the transform attribute to

transform="scale(-1 1) rotate(-225)"

Gauge generator pen

Body:
enter image description here

I wanna make circle chart like this.
below is my code.

If I invert up and down in that code, i get the shape you want.
But what I really want is a graph with the yellow graph pointing further to the right. How do I adjust the spacing?
Please help me

<svg width="4.5rem" height="4.5rem" viewBox="0 0 40 40">
  <circle class="pieSegment segment1" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#1a0d1c" stroke-dashoffset="11" stroke-dasharray="74" stroke-width="5"></circle>
  <circle class="pieSegment segment3" cx="20" cy="20" r="15.915494309189533" fill="transparent" stroke="#e9ad61" stroke-dashoffset="14" stroke-dasharray="25 75" stroke-width="5"></circle>
</svg>

Body:
Edit (missed the previous answer by @jeremy-denis also using pathLength)

Here is another approach also using pathLength value:

See also MDN Docs: pathLength

example horse shoe gauge

let progress = document.querySelector("#progress");
let svgGauges = document.querySelectorAll(".svgGauge");
let gauges = document.querySelectorAll(".gaugePercent");
let percentText = document.querySelector(".percentText");

progress.addEventListener("change", function(e) {
  let percent = e.target.value;
  if (svgGauges.length) {
    svgGauges.forEach(function(item, i) {
      let currentGauge = svgGauges[i];
      let gauge = currentGauge.querySelector(".gaugePercent");
      let dashGap = gauge.getAttribute("stroke-dasharray").split(" ")[1];
      // console.log(gauge);
      gauge.setAttribute("stroke-dasharray", percent + " " + dashGap);
      gauge.setAttribute("style", "animation-fill-mode: none");
      percentText.textContent = percent;
    });
  }
});

.gaugeWrap {
  display: inline-block;
  width: 10rem;
}

.layout {
  width: 50%;
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

.txt-cnt {
  text-align: center;
}

.circle {
  transition: 0.3s;
  stroke-width: 15;
}

.linecap-round .circle {
  stroke-linecap: round;
  shape-rendering: geometricPrecision;
}

.linecap-round .circle[stroke-dasharray^="0 "] {
  stroke-linecap: unset;
}

<p class="txt-cnt">Progress (<span class="percentText">50</span>&thinsp;%) <input id="progress" style="width:100px" type="range" min="0" max="100" step="10" value="50" />
</p>
<div class="layout">

  <div class="gaugeWrap">
    <p>horse shoe gauge 270°</p>
    <svg class="svgGauge linecap-round" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="scale(-1 1) rotate(-225) ">
      <circle class="circle gaugeBG" id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="133.333" fill="none" stroke="#000" stroke-dasharray="100 100" />
      <circle class="circle gaugePercent " id="gauge" cx="50%" cy="50%" r="45" pathLength="133.333" fill="none" stroke-dasharray="50 133.333" stroke="#e9ad61" />
    </svg>
  </div>

  <div class="gaugeWrap">
    <p>Semi-circle gauge 180°</p>
    <svg class="svgGauge linecap-round" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="scale(-1 1) rotate(-180)">
      <circle class="circle gaugeBG " id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="200" fill="none" stroke="#000" stroke-dasharray="100 200" />
      <circle class="circle gaugePercent" id="gauge" cx="50%" cy="50%" r="45" pathLength="200" fill="none" stroke-dasharray="50 200" stroke="#e9ad61" />
    </svg>
  </div>

  <div class="gaugeWrap">
    <p>Full-circle gauge 360°</p>
    <svg class="svgGauge" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" transform="rotate(-90)">
      <circle class="circle gaugeBG" id="gaugeBG" cx="50%" cy="50%" r="45" pathLength="100" fill="none" stroke="#000" stroke-dasharray="100 100" />
      <circle class="circle gaugePercent" id="gauge" cx="50%" cy="50%" r="45" pathLength="100" fill="none" stroke-linecap="butt" stroke-dasharray="50 100" stroke="#e9ad61" />
    </svg>
  </div>

</div>

Your example has approximately a 270° range (3/4 of 360°).

By setting pathLengthto 133 (360/270*100) we change the computation of the dash lengths.

Since we don't use the complete circumference of the circle (see the full circle example with pathLength=100) we increase the pathlength to make this 3/4 segment to have a length of 100 units.

We can set the first stroke-dasharray value e.g. to 50 (display 50% progress).

The 2nd value 133 ensures the dash gap is large enough to fill the rest of the circle gauge.

To make the horse shoe gauge stand upright we need to calculate a rotation like this:

(360 + 270)/2 - 90 = -225

So we can rotate the parent svg by setting the transform attribute to

transform="scale(-1 1) rotate(-225)"

Gauge generator pen


来源: stackexchange

问:
Does anyone know the performance or pro/con of journey vs express?
Curious about using either framework for a REST API</p>

答:
Well journey hasn't been updated for over 170 days. I've never heard of it before.

Where as express is being actively worked on and it has a great community.

Journey also seems to be for 0.2 so it might not work with 0.4.

I would choose express because it's properly documented and has great support.

You may also want to look at express-resources.

ContentLicense: CC BY-SA 3.0


问:
TypeError: Cannot read properties of undefined (reading 'path')
I'm attempting to generate NFTs using this code but keep getting cannot read properties of undefined reading path, if anyone knows of a fix please write back. I am very new to this whole process and do not know what i should be looking at, i've been following the steps exactly as stated in the youtube video i was watching and this problem was not happening with the person in the video.</p>
```<code>const path = require("path");
const isLocal = typeof process.pkg === "undefined";
const basePath = isLocal ? process.cwd() : path.dirname(process.execPath);
const { MODE } = require(path.join(basePath, "constants/blend_mode.js"));
const { NETWORK } = require(path.join(basePath, "constants/network.js"));

const network = NETWORK.sol;

// General metadata for Ethereum
const namePrefix = "CHUMPSNFT";
const description = "2,222 Chumps storming Solana Beaches";
const baseUri = "ipfs://NewUriToReplace";

const solanaMetadata = {
  symbol: "CHUMP",
  seller_fee_basis_points: 700, // Define how much % you want from secondary market sales 1000 = 10%
  external_url: "https://www.loosebucks.net",
  creators: [
    {
      address: "HXzaa6foNqG3w7XaVykaH6jWAFpNkCfJeDyhXsih2U93",
      share: 100,
    },
  ],
};

// If you have selected Solana then the collection starts from 0 automatically
const layerConfigurations = [
  {
    growEditionSizeTo: 163,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 326,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 489,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Accessories" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 652,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 815,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 978,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Top1" },
      { name: "Accessories1" },
      { name: "Face1" },
      { name: "Head1" },
      { name: "Eyes1" },
    ],
  },
  {
    growEditionSizeTo: 1141,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1304,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1467,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1630,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Face" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1793,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1956,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 2119,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Accessories1" },
      { name: "Eyes1" },
    ],
  },
  {
    growEditionSizeTo: 2282,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Top1" },
      { name: "Accessories1" },
      { name: "Face1" },
      { name: "Eyes1" },
    ],
  },
];

const shuffleLayerConfigurations = false;

const debugLogs = false;

const format = {
  width: 512,
  height: 512,
};

const text = {
  only: false,
  color: "#ffffff",
  size: 20,
  xGap: 40,
  yGap: 40,
  align: "left",
  baseline: "top",
  weight: "regular",
  family: "Courier",
  spacer: " => ",
};

const pixelFormat = {
  ratio: 2 / 128,
};

const background = {
  generate: true,
  brightness: "80%",
  static: false,
  default: "#000000",
};

const extraMetadata = {};

const rarityDelimiter = "#";

const uniqueDnaTorrance = 10000;

const preview = {
  thumbPerRow: 5,
  thumbWidth: 50,
  imageRatio: format.width / format.height,
  imageName: "preview.png",
};

module.exports = {
  format,
  baseUri,
  description,
  background,
  uniqueDnaTorrance,
  layerConfigurations,
  rarityDelimiter,
  preview,
  shuffleLayerConfigurations,
  debugLogs,
  extraMetadata,
  pixelFormat,
  text,
  namePrefix,
  network,
  solanaMetadata,
}; ```
</code>```

答:
Make sure the naming of your assets in layers is correct(only use underscores, a to z and hashtag).
Also no folder should be empty

Best of luck

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to generate NFTs using this code but keep getting cannot read properties of undefined reading path, if anyone knows of a fix please write back. I am very new to this whole process and do not know what i should be looking at, i've been following the steps exactly as stated in the youtube video i was watching and this problem was not happening with the person in the video.

const path = require("path");
const isLocal = typeof process.pkg === "undefined";
const basePath = isLocal ? process.cwd() : path.dirname(process.execPath);
const { MODE } = require(path.join(basePath, "constants/blend_mode.js"));
const { NETWORK } = require(path.join(basePath, "constants/network.js"));

const network = NETWORK.sol;

// General metadata for Ethereum
const namePrefix = "CHUMPSNFT";
const description = "2,222 Chumps storming Solana Beaches";
const baseUri = "ipfs://NewUriToReplace";

const solanaMetadata = {
  symbol: "CHUMP",
  seller_fee_basis_points: 700, // Define how much % you want from secondary market sales 1000 = 10%
  external_url: "https://www.loosebucks.net",
  creators: [
    {
      address: "HXzaa6foNqG3w7XaVykaH6jWAFpNkCfJeDyhXsih2U93",
      share: 100,
    },
  ],
};

// If you have selected Solana then the collection starts from 0 automatically
const layerConfigurations = [
  {
    growEditionSizeTo: 163,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 326,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 489,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Accessories" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 652,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 815,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 978,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Top1" },
      { name: "Accessories1" },
      { name: "Face1" },
      { name: "Head1" },
      { name: "Eyes1" },
    ],
  },
  {
    growEditionSizeTo: 1141,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1304,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Face" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1467,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1630,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Face" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1793,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Top" },
      { name: "Head" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 1956,
    layersOrder: [
      { name: "Background" },
      { name: "Body Color" },
      { name: "Accessories" },
      { name: "Eyes" },
    ],
  },
  {
    growEditionSizeTo: 2119,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Accessories1" },
      { name: "Eyes1" },
    ],
  },
  {
    growEditionSizeTo: 2282,
    layersOrder: [
      { name: "Background1" },
      { name: "Body Color1" },
      { name: "Top1" },
      { name: "Accessories1" },
      { name: "Face1" },
      { name: "Eyes1" },
    ],
  },
];

const shuffleLayerConfigurations = false;

const debugLogs = false;

const format = {
  width: 512,
  height: 512,
};

const text = {
  only: false,
  color: "#ffffff",
  size: 20,
  xGap: 40,
  yGap: 40,
  align: "left",
  baseline: "top",
  weight: "regular",
  family: "Courier",
  spacer: " => ",
};

const pixelFormat = {
  ratio: 2 / 128,
};

const background = {
  generate: true,
  brightness: "80%",
  static: false,
  default: "#000000",
};

const extraMetadata = {};

const rarityDelimiter = "#";

const uniqueDnaTorrance = 10000;

const preview = {
  thumbPerRow: 5,
  thumbWidth: 50,
  imageRatio: format.width / format.height,
  imageName: "preview.png",
};

module.exports = {
  format,
  baseUri,
  description,
  background,
  uniqueDnaTorrance,
  layerConfigurations,
  rarityDelimiter,
  preview,
  shuffleLayerConfigurations,
  debugLogs,
  extraMetadata,
  pixelFormat,
  text,
  namePrefix,
  network,
  solanaMetadata,
}; ```


问:
Is there any way to handle java Script based Pop up in selenium (Java) without using alert.dismiss method?
Image attached I have used Alert.dismiss(); but it is not working. I want to click on cancel button. Is there any other way to handle. I have tried considering this pop up as window.

Please find image in attachment.

答:
Try to click on the cancel button:

```<code>WebElement cancelBtn = driver.findElementByXpath("//button[contains(text(),'cancel')]");
cancelBtn.click();
</code>```

If this doesn't work, see if the pop-up is inside an Iframe. If so switch to the Iframe and then look for the cancel button.

```<code>driver.switchToIframe(0);
// or
driver.switchToIfrmae("IDOfTheIframe");
</code>```

Body:
Try to click on the cancel button:

WebElement cancelBtn = driver.findElementByXpath("//button[contains(text(),'cancel')]");
cancelBtn.click();

If this doesn't work, see if the pop-up is inside an Iframe. If so switch to the Iframe and then look for the cancel button.

driver.switchToIframe(0);
// or
driver.switchToIfrmae("IDOfTheIframe");


问:
zoom and change color Ui when Scrolling
I have ScrollRect with number inside (is working fine) I want  when if any number position is in image with blue color than number change color (red) and also increase font size i don't know how to achieve that please help

答:
There are probably multiple ways of how to achieve this.

I would probably go with something like this:

First on your Image have a dedicated component - this is just for finding it easier and have some pre-cached references:

[RequireComponent(typeof(RectTransform))]
public class TargetImage : MonoBehaviour
{
    [SerializeField]
    private RectTransform _rectTransform;

    public RectTransform RectTransform => _rectTransform;

    private void Awake()
    {
        if (!_rectTransform) _rectTransform = GetComponent<RectTransform>();
    }
}
```
<p>and then on every text you can have another component which controls what you want to achieve:</p>
<pre class="lang-cs prettyprint-override"><code>[RequireComponent(typeof(TMP_Text))]
// or if using Text
//[RequireComponent(typeof(Text))]
public class Example : NetworkBehaviour
{
    [SerializeField]
    private TMP_Text _text;
    // or if using Text
    //private Text _text;

    [SerializeField]
    private TargetImage _targetage;

    [SerializeField]
    private float _hitFontSize = 40;
    // or if using Text
    //private int _hitFontSize = 40;

    [SerializeField]
    private Color _hitFontColor = Color.red;

    private float _normalFontSize;
    // or if using Text
    //private int _normalFontSize;

    private Color _normalFontColor;

    private void Awake()
    {
        if (!_text) _text = GetComponent<TMP_Text>();
        if (!_targetage) _targetage = FindObjectOfType<TargetImage>();

        _normalFontColor = _text.color;
        _normalFontSize = _text.fontSize;
    }

    private void LateUpdate()
    {
        var isInsideTargetImage = _targetage && _targetage.RectTransform.FullyContains(_text.rectTransform);

        _text.color = isInsideTargetImage ? _hitFontColor : _normalFontColor;
        _text.fontSize = isInsideTargetImage ? _hitFontSize : _normalFontSize;
    }
}
</code>```

where FullyContains is a little extension method I came up with a while ago

public static class RectTransformExtensions
{
    ///
    /// Returns a Rect in WorldSpace dimensions using <see cref="RectTransform.GetWorldCorners"/>
    ///
    public static Rect GetWorldRect(this RectTransform rectTransform)
    {
        // This returns the world space positions of the corners in the order
        // [0] bottom left,
        // [1] top left
        // [2] top right
        // [3] bottom right
        var corners = new Vector3[4];
        rectTransform.GetWorldCorners(corners);

        Vector2 min = corners[0];
        Vector2 max = corners[2];
        Vector2 size = max - min;

        return new Rect(min, size);
    }

    ///
    /// Checks if a <see cref="RectTransform"/> fully encloses another one
    ///
    public static bool FullyContains (this RectTransform rectTransform, RectTransform other)
    {
        var rect = rectTransform.GetWorldRect();
        var otherRect = other.GetWorldRect();

        // Now that we have the world space rects simply check
        // if the other rect lies completely between min and max of this rect
        return rect.xMin <= otherRect.xMin
            && rect.yMin <= otherRect.yMin
            && rect.xMax >= otherRect.xMax
            && rect.yMax >= otherRect.yMax;
    }
}
```

Then the following would happen when you scroll now

Title: zoom and change color Ui when Scrolling

Body:
There are probably multiple ways of how to achieve this.

I would probably go with something like this:

First on your Image have a dedicated component - this is just for finding it easier and have some pre-cached references:

[RequireComponent(typeof(RectTransform))]
public class TargetImage : MonoBehaviour
{
    [SerializeField]
    private RectTransform _rectTransform;

    public RectTransform RectTransform => _rectTransform;

    private void Awake()
    {
        if (!_rectTransform) _rectTransform = GetComponent<RectTransform>();
    }
}

and then on every text you can have another component which controls what you want to achieve:

[RequireComponent(typeof(TMP_Text))]
// or if using Text
//[RequireComponent(typeof(Text))]
public class Example : NetworkBehaviour
{
    [SerializeField]
    private TMP_Text _text;
    // or if using Text
    //private Text _text;

    [SerializeField]
    private TargetImage _targetage;

    [SerializeField]
    private float _hitFontSize = 40;
    // or if using Text
    //private int _hitFontSize = 40;

    [SerializeField]
    private Color _hitFontColor = Color.red;

    private float _normalFontSize;
    // or if using Text
    //private int _normalFontSize;

    private Color _normalFontColor;

    private void Awake()
    {
        if (!_text) _text = GetComponent<TMP_Text>();
        if (!_targetage) _targetage = FindObjectOfType<TargetImage>();

        _normalFontColor = _text.color;
        _normalFontSize = _text.fontSize;
    }

    private void LateUpdate()
    {
        var isInsideTargetImage = _targetage && _targetage.RectTransform.FullyContains(_text.rectTransform);

        _text.color = isInsideTargetImage ? _hitFontColor : _normalFontColor;
        _text.fontSize = isInsideTargetImage ? _hitFontSize : _normalFontSize;
    }
}

where FullyContains is a little extension method I came up with a while ago

public static class RectTransformExtensions
{
    ///<summary>
    /// Returns a Rect in WorldSpace dimensions using <see cref="RectTransform.GetWorldCorners"/>
    ///</summary>
    public static Rect GetWorldRect(this RectTransform rectTransform)
    {
        // This returns the world space positions of the corners in the order
        // [0] bottom left,
        // [1] top left
        // [2] top right
        // [3] bottom right
        var corners = new Vector3[4];
        rectTransform.GetWorldCorners(corners);

        Vector2 min = corners[0];
        Vector2 max = corners[2];
        Vector2 size = max - min;

        return new Rect(min, size);
    }

    ///<summary>
    /// Checks if a <see cref="RectTransform"/> fully encloses another one
    ///</summary>
    public static bool FullyContains (this RectTransform rectTransform, RectTransform other)
    {
        var rect = rectTransform.GetWorldRect();
        var otherRect = other.GetWorldRect();

        // Now that we have the world space rects simply check
        // if the other rect lies completely between min and max of this rect
        return rect.xMin <= otherRect.xMin
            && rect.yMin <= otherRect.yMin
            && rect.xMax >= otherRect.xMax
            && rect.yMax >= otherRect.yMax;
    }
}

Then the following would happen when you scroll now


问:
How to style 'disabled' class in TextField in Material UI 5 using global CreateTheme?
I want to style differently TextFiled component , variant outlined once disabled={true}.
The way it was catched in material ui v.4 don't work in material ui v.5. I cannot also google the solution how to customize disabled version.
Below You can see how it was styled in material ui4 and it worked, not it does not.

```<code>export const MainTheme: Theme = createTheme({
  components: {
    MuiInputLabel: {
        styleOverrides: {
            root: {
                fontSize: '13px',
                '&$focused': {
                    borderColor: '#000',
                },
                '&$disabled': {
                    color: '#724a4a',
                },
            },
        },
    },

    MuiInputBase: {
        styleOverrides: {
            root: {
                '&$disabled': {
                    '& fieldset.MuiOutlinedInput-notchedOutline': {
                        borderColor: 'transparent',
                        background: 'rgb(0 0 0 / 4%)',
                    },
                },
            },

            input: {
                height: 'unset',
                color: '#000000',
            },
        },
    },
  },
</code>```

)}

答:
You can do it like this SandBox

```<code>const finalTheme = createTheme({
  components: {
    MuiTextField: {
      variants: [ // variants will help you define the props given by Mui and the styles you want to apply for it
        {
          props: { variant: 'outlined', disabled: true },
          style: {
            backgroundColor: 'green',
            color: 'red',
            fontSize: '5rem'
          }
        }
      ]
    }
  }
})

<ThemeProvider theme={finalTheme}>
  <TextField
    disabled
    id="outlined-basic"
    label="Outlined"
    variant="outlined"
  />
</ThemeProvider>
</code>```

Reference : https://mui.com/customization/theme-components/#global-style-overrides

Body:
I want to style differently TextFiled component , variant outlined once disabled={true}.
The way it was catched in material ui v.4 don't work in material ui v.5. I cannot also google the solution how to customize disabled version.
Below You can see how it was styled in material ui4 and it worked, not it does not.

export const MainTheme: Theme = createTheme({
  components: {
    MuiInputLabel: {
        styleOverrides: {
            root: {
                fontSize: '13px',
                '&$focused': {
                    borderColor: '#000',
                },
                '&$disabled': {
                    color: '#724a4a',
                },
            },
        },
    },

    MuiInputBase: {
        styleOverrides: {
            root: {
                '&$disabled': {
                    '& fieldset.MuiOutlinedInput-notchedOutline': {
                        borderColor: 'transparent',
                        background: 'rgb(0 0 0 / 4%)',
                    },
                },
            },

            input: {
                height: 'unset',
                color: '#000000',
            },
        },
    },
  },

)}

Body:
You can do it like this SandBox

const finalTheme = createTheme({
  components: {
    MuiTextField: {
      variants: [ // variants will help you define the props given by Mui and the styles you want to apply for it
        {
          props: { variant: 'outlined', disabled: true },
          style: {
            backgroundColor: 'green',
            color: 'red',
            fontSize: '5rem'
          }
        }
      ]
    }
  }
})

<ThemeProvider theme={finalTheme}>
  <TextField
    disabled
    id="outlined-basic"
    label="Outlined"
    variant="outlined"
  />
</ThemeProvider>

Reference : https://mui.com/customization/theme-components/#global-style-overrides


问:
Flutter TextFormField Validator show error suffixIcon on text empty or null
I am having a flutter TextFormField and i am already showing an error and outlined border color change to red when text is empty or null. What i want is to also show a suffixIcon when TextFormField is empty

below is my code

```<code>
class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final loginFormKey = GlobalKey<FormState>();

  TextEditingController userNameController = TextEditingController();

  FocusNode userNameFocusNode = FocusNode();

  bool userNameHasFocus = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    userNameController.dispose();
    userNameFocusNode.dispose();

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
          child: Center(
              child: Form(
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  key: loginFormKey,
                  child: Column(
                    children: [
                      Container(
                          padding: const EdgeInsets.all(1),
                          margin: const EdgeInsets.only(top: 5, bottom: 5),
                          child: const Text(
                            "Welcome to my app",
                            textAlign: TextAlign.center,
                          )),
                      Container(
                          margin: const EdgeInsets.only(
                              top: 1, bottom: 2, right: 1, left: 10),
                          child: TextFormField(
                            focusNode: userNameFocusNode,
                            controller: userNameController,
                            decoration: InputDecoration(
                              labelText: "Please Enter Username",
                              border: OutlineInputBorder(),
                            ),
                            validator: (phoneNo) {
                              if (phoneNo!.isEmpty) {
                                userNameFocusNode.requestFocus();
                                userNameHasFocus = true;
                                return "You must enter username";
                              } else {
                                userNameHasFocus = false;
                                return null;
                              }
                            },
                          )),
                      Container(
                          margin: const EdgeInsets.only(
                              top: 2, bottom: 1, right: 10, left: 10),
                          child: ElevatedButton(
                              onPressed: () {

                                if (loginFormKey.currentState!.validate()) {

                                  print(proceed)

                                }

                              },
                              child: Text("Login"),
                              style: ElevatedButton.styleFrom(
                                shape: StadiumBorder(),
                              )))
                    ],
                  )))),
    );
  }
}

</code>```

The part that i am interested is below in validator

```<code>
validator: (phoneNo) {
                              if (phoneNo!.isEmpty) {
                                userNameFocusNode.requestFocus();
                                userNameHasFocus = true;
                                return "You must enter username";
                              } else {
                                userNameHasFocus = false;
                                return null;
                              }
                            },

</code>```

Where if phoneNo!.isEmpty i should show something like this below

```<code>
 suffixIcon: Icon(Icons.error_outline_rounded, color: Colors.red)

</code>```

答:
You can use a bool to show the suffixIcon.

  bool showSuffix = false;

  @override
  void initState() {
    super.initState();
    userNameController.addListener(() {
      if (userNameController.text.isEmpty) {
        showSuffix = true;
      } else {
        showSuffix = false;
      }
      setState(() {});
    });
  }

 ///.........

 /// aslo can be used [Visibility] widget
 suffixIcon: showSuffix
    ? const Icon(Icons.error_outline_rounded,
        color: Colors.red)
    : null,
```

Body:
I am having a flutter TextFormField and i am already showing an error and outlined border color change to red when text is empty or null. What i want is to also show a suffixIcon when TextFormField is empty

below is my code

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final loginFormKey = GlobalKey<FormState>();

  TextEditingController userNameController = TextEditingController();

  FocusNode userNameFocusNode = FocusNode();

  bool userNameHasFocus = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    userNameController.dispose();
    userNameFocusNode.dispose();

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
          child: Center(
              child: Form(
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  key: loginFormKey,
                  child: Column(
                    children: [
                      Container(
                          padding: const EdgeInsets.all(1),
                          margin: const EdgeInsets.only(top: 5, bottom: 5),
                          child: const Text(
                            "Welcome to my app",
                            textAlign: TextAlign.center,
                          )),
                      Container(
                          margin: const EdgeInsets.only(
                              top: 1, bottom: 2, right: 1, left: 10),
                          child: TextFormField(
                            focusNode: userNameFocusNode,
                            controller: userNameController,
                            decoration: InputDecoration(
                              labelText: "Please Enter Username",
                              border: OutlineInputBorder(),
                            ),
                            validator: (phoneNo) {
                              if (phoneNo!.isEmpty) {
                                userNameFocusNode.requestFocus();
                                userNameHasFocus = true;
                                return "You must enter username";
                              } else {
                                userNameHasFocus = false;
                                return null;
                              }
                            },
                          )),
                      Container(
                          margin: const EdgeInsets.only(
                              top: 2, bottom: 1, right: 10, left: 10),
                          child: ElevatedButton(
                              onPressed: () {

                                if (loginFormKey.currentState!.validate()) {

                                  print(proceed)

                                }

                              },
                              child: Text("Login"),
                              style: ElevatedButton.styleFrom(
                                shape: StadiumBorder(),
                              )))
                    ],
                  )))),
    );
  }
}

The part that i am interested is below in validator

validator: (phoneNo) {
                              if (phoneNo!.isEmpty) {
                                userNameFocusNode.requestFocus();
                                userNameHasFocus = true;
                                return "You must enter username";
                              } else {
                                userNameHasFocus = false;
                                return null;
                              }
                            },

Where if phoneNo!.isEmpty i should show something like this below

 suffixIcon: Icon(Icons.error_outline_rounded, color: Colors.red)


问:
Django app on Google App Engine Standard slows down after 15 requests
I deployed a Django app on Google App Engine Standard with a F4 machine. The API is doing some machine learning and the processing has a duration of around 4s in local (between 3.5 and 4s). For my use case, it would be ok to have also 4-5s delays with the deployed app. However, when I test the deployed app doing the same request multiple times, I saw that the first requests take 3-4 seconds, but after 10-15 iterations, they take around 8s.

Here is the code I used to test my app:

```<code>session = requests.Session()

all_times = []
for i in range(50):
    try:
        t0 = time.time()
        resp = session.post(url_api, headers=headers, json=data)
        t1 = time.time()
        print(t1 - t0)
        all_times.append(t1 - t0)
    except Exception as e:
        print("Err", e)

</code>```

The results of the request durations are as follows:

I wonder why there is this gap after 15 requests and why some points are way above the average 7-8s (e.g. 10s).

I get the same pattern looking at the latency in the Google Cloud Console:

What I tried

I tried to change the autoscaling parameters, thinking that it could be because of the creation of instances. But I got the same pattern when I restrict the number of instance to 1 with this in app.yaml:

```<code>automatic_scaling:
  max_instances: 1
</code>```

I also tried to:

Use session in requests to avoid creating a new session at each iteration.

Do my requests using curl, which leads to the same results.

My goal is to minimize the variability and keep the request durations below 5s.

Update

Here is an example of the trace list from Cloud Trace, which shows the same pattern:

I compared traces associated with a large latency and traces with a lower latency, but didn't find any important difference.

Update 2

Thanks to the answer of Priyashree, setting the min_idle_instances to 1 to avoid machine restart solved the problem:

答:
When comparing Google Cloud Platform performance with the local one you should keep in mind that deploying on GCP needs more time to import all the necessary libraries and set up the Django framework.

In general it doesn't make much sense to compare the performance on your local machine with the performance on GCE, as local machines are likely running a different OS. But yes, I agree the difference in latency between the requests served by GAE after 10-15 requests is not acceptable and quite strange.

Check the following :

If the instance has exceeded the maximum memory for its configured
instance_class which is F4 in your case which may cause shut down of
your instance and App Engine creating a new one in its place as this
could be due to not having any available instances since that's about
the time it takes for an instance to be deployed and you have set
max_instances to 1.

If you have set any target_cpu_utilization. It specifies the CPU
usage threshold at which new instances will be started to handle
traffic when old instances reach the target CPU usage.

The interval at which you are sending requests matters as you
mentioned in your comments, “you are making the requests one by one”.
When request volumes decrease, App Engine reduces the number of
instances. When an application is not being used at all, App Engine
turns off its associated dynamic instances, but readily reloads them
as soon as they are needed. Reloading instances can result in
additional latency for users. To make sure, you are not reloading
instances, specify a minimum number of idle instances. Setting an
appropriate number of idle instances for your application based on
request volume allows your application to serve every request with
little latency, unless you are experiencing abnormally high request
volume.

Also, as per documentation if instance_class is set to F2 or higher, you can optimize your instances by setting max_concurrent_requests to a value higher than the default value of 10. To determine the optimal value, gradually increase it and monitor the performance of your application.

Go through PageSpeed Insights, which analyzes the content of a web page, then generates suggestions to make that page faster and could be handy. I would also suggest you to contact Google Support for a 1:1 interaction as this case/issue is environment specific.

Body:
I deployed a Django app on Google App Engine Standard with a F4 machine. The API is doing some machine learning and the processing has a duration of around 4s in local (between 3.5 and 4s). For my use case, it would be ok to have also 4-5s delays with the deployed app. However, when I test the deployed app doing the same request multiple times, I saw that the first requests take 3-4 seconds, but after 10-15 iterations, they take around 8s.

Here is the code I used to test my app:

session = requests.Session()

all_times = []
for i in range(50):
    try:
        t0 = time.time()
        resp = session.post(url_api, headers=headers, json=data)
        t1 = time.time()
        print(t1 - t0)
        all_times.append(t1 - t0)
    except Exception as e:
        print("Err", e)

The results of the request durations are as follows:

I wonder why there is this gap after 15 requests and why some points are way above the average 7-8s (e.g. 10s).

I get the same pattern looking at the latency in the Google Cloud Console:

What I tried

I tried to change the autoscaling parameters, thinking that it could be because of the creation of instances. But I got the same pattern when I restrict the number of instance to 1 with this in app.yaml:

automatic_scaling:
  max_instances: 1

I also tried to:

Use session in requests to avoid creating a new session at each iteration.

Do my requests using curl, which leads to the same results.

My goal is to minimize the variability and keep the request durations below 5s.

Update

Here is an example of the trace list from Cloud Trace, which shows the same pattern:

I compared traces associated with a large latency and traces with a lower latency, but didn't find any important difference.

Update 2

Thanks to the answer of Priyashree, setting the min_idle_instances to 1 to avoid machine restart solved the problem:


答:
You need to show the icon or hide it according to a condition if the TextFormField is validated or not.

Remove autovalidateMode: AutovalidateMode.onUserInteraction and add onChanged method instead like this:

```<code>import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final loginFormKey = GlobalKey<FormState>();

  TextEditingController userNameController = TextEditingController();

  FocusNode userNameFocusNode = FocusNode();

  bool userNameHasFocus = false;
  bool validated = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    userNameController.dispose();
    userNameFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Center(
          child: Form(
            key: loginFormKey,
            child: Column(
              children: [
                Container(
                    padding: const EdgeInsets.all(1),
                    margin: const EdgeInsets.only(top: 5, bottom: 5),
                    child: const Text(
                      "Welcome to my app",
                      textAlign: TextAlign.center,
                    )),
                Container(
                    margin: const EdgeInsets.only(top: 1, bottom: 2, right: 1, left: 10),
                    child: TextFormField(
                      focusNode: userNameFocusNode,
                      controller: userNameController,
                      decoration: InputDecoration(
                          labelText: "Please Enter Username",
                          border: const OutlineInputBorder(),
                          suffixIcon: !validated ? const Icon(Icons.error_outline_rounded, color: Colors.red) : const SizedBox()),
                      validator: (phoneNo) {
                        if (phoneNo!.isEmpty) {
                          userNameFocusNode.requestFocus();
                          userNameHasFocus = true;
                          return "You must enter username";
                        } else {
                          userNameHasFocus = false;
                          return null;
                        }
                      },
                      onChanged: (value) {
                        if (value.isNotEmpty) {
                          setState(() {
                            validated = true;
                            loginFormKey.currentState!.validate();
                          });
                        }
                      },
                    )),
                Container(
                  margin: const EdgeInsets.only(top: 2, bottom: 1, right: 10, left: 10),
                  child: ElevatedButton(
                    onPressed: () {
                      if (loginFormKey.currentState!.validate()) {
                        setState(() {
                          validated = loginFormKey.currentState!.validate();
                        });
                      } else {
                        setState(() {
                          validated = loginFormKey.currentState!.validate();
                        });
                      }
                    },
                    child: const Text("Login"),
                    style: ElevatedButton.styleFrom(
                      shape: const StadiumBorder(),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

Happy coding!!

Title: Flutter TextFormField Validator show error suffixIcon on text empty or null

Body:
You need to show the icon or hide it according to a condition if the TextFormField is validated or not.

Remove autovalidateMode: AutovalidateMode.onUserInteraction and add onChanged method instead like this:

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final loginFormKey = GlobalKey<FormState>();

  TextEditingController userNameController = TextEditingController();

  FocusNode userNameFocusNode = FocusNode();

  bool userNameHasFocus = false;
  bool validated = true;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    userNameController.dispose();
    userNameFocusNode.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Center(
          child: Form(
            key: loginFormKey,
            child: Column(
              children: [
                Container(
                    padding: const EdgeInsets.all(1),
                    margin: const EdgeInsets.only(top: 5, bottom: 5),
                    child: const Text(
                      "Welcome to my app",
                      textAlign: TextAlign.center,
                    )),
                Container(
                    margin: const EdgeInsets.only(top: 1, bottom: 2, right: 1, left: 10),
                    child: TextFormField(
                      focusNode: userNameFocusNode,
                      controller: userNameController,
                      decoration: InputDecoration(
                          labelText: "Please Enter Username",
                          border: const OutlineInputBorder(),
                          suffixIcon: !validated ? const Icon(Icons.error_outline_rounded, color: Colors.red) : const SizedBox()),
                      validator: (phoneNo) {
                        if (phoneNo!.isEmpty) {
                          userNameFocusNode.requestFocus();
                          userNameHasFocus = true;
                          return "You must enter username";
                        } else {
                          userNameHasFocus = false;
                          return null;
                        }
                      },
                      onChanged: (value) {
                        if (value.isNotEmpty) {
                          setState(() {
                            validated = true;
                            loginFormKey.currentState!.validate();
                          });
                        }
                      },
                    )),
                Container(
                  margin: const EdgeInsets.only(top: 2, bottom: 1, right: 10, left: 10),
                  child: ElevatedButton(
                    onPressed: () {
                      if (loginFormKey.currentState!.validate()) {
                        setState(() {
                          validated = loginFormKey.currentState!.validate();
                        });
                      } else {
                        setState(() {
                          validated = loginFormKey.currentState!.validate();
                        });
                      }
                    },
                    child: const Text("Login"),
                    style: ElevatedButton.styleFrom(
                      shape: const StadiumBorder(),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Happy coding!!


问:
How to integrate offline Unity simulation with Canvas LMS
Im thinking xAPI would be the way to go here (though need to research more).
Seems like LTI not the way, as this is more like an exercise than a separate app?
Seems SCORM would require the simulation to be HTML and embedded in the LMS?

We are using Canvas LMS.
Thanks!

答:
This is a largely subjective question so may not be the best fit here, but I can write some words.

Agree SCORM is probably not the best fit, there is likely a way to shoehorn it in somehow but it isn't going to be a great use of that particular delivery method.

I would not necessarily dismiss LTI as an option here, but not dismissing it really engenders more questions. It is less about the type of activity in this case, than what you hope to get back in terms of data. LTI is perfectly well suited for the launch use case for different types of experiences, but generally provides nothing in regards to how to record data back to the launching system in any particularly interoperable way. So, if you are most concerned about the launch moment and not about data capture then LTI is still on the table.

If you need launch and data capture then I think xAPI is probably a reasonable approach, and Canvas likely supports packages based on a tincan.xml file and this gives you both a launch mechanism and the data capture possibility provided by leveraging an LRS through xAPI. Note that these types of packages are based on a set of guidelines that are no longer maintained, were never peer reviewed, and are known to not be great.

The best option would be to use cmi5 because it provides for a defined launch methodology, records data via xAPI, has a defined information model, is on a standards path, has been peer reviewed, is actively maintained, and is starting to have better tooling around it than the Tin Can guidelines. But adoption is still pretty limited, you would have to contact Canvas support to know whether they support it or when they plan to.


问:
How to get all of the array values out of a dictionary of arrays as a list?
I have a dictionary of arrays of the following format:

```<code>letters = {1: ['h'], 2: ['e'], 3: ['l', 'l'], 4: ['o']}
</code>```

I'd like to know how I can get all of the values out of the arrays within the letters dict, bearing in mind that there may be single or multiple values within each one and the array values may be duplicates. So for the above example, I'd want the following output:

```<code>letter_values = ['h', 'e', 'l', 'l', 'o']
</code>```

although the output needn't necessarily be in order.

I know how to get the values out of a dictionary using dict.values(), but not when there is an additional layer of abstraction like this.

答:
While writing this question (as is often the case), I figured out the answer.

You just need to use the dict.values() functionality to obtain a list of lists, and then concatenate those lists (for which there is a convenient shorthand), like so:

```<code>letter_values = [item for sublist in list(letters.values()) for item in sublist]
</code>```

Where item and sublist are just throwaway variables.

Easy!

(A reminder)

Body:
I have a dictionary of arrays of the following format:

letters = {1: ['h'], 2: ['e'], 3: ['l', 'l'], 4: ['o']}

I'd like to know how I can get all of the values out of the arrays within the letters dict, bearing in mind that there may be single or multiple values within each one and the array values may be duplicates. So for the above example, I'd want the following output:

letter_values = ['h', 'e', 'l', 'l', 'o']

although the output needn't necessarily be in order.

I know how to get the values out of a dictionary using dict.values(), but not when there is an additional layer of abstraction like this.

Body:
While writing this question (as is often the case), I figured out the answer.

You just need to use the dict.values() functionality to obtain a list of lists, and then concatenate those lists (for which there is a convenient shorthand), like so:

letter_values = [item for sublist in list(letters.values()) for item in sublist]

Where item and sublist are just throwaway variables.

Easy!

(A reminder)


问:
getTitle() in News.class.php in Symfony
i have table News:

```<code>id   | title  | body
1    | title1 | body1
2    | title2 | body2
</code>```

etc.

I have

News.class.php
and
NewsTable.class.php

i would like edit method getTitle().
In News.class.php i add:

```<code>public function getTitle()
{
    return $this->title . "aa"; //line 35
}
</code>```

but i have error:

Notice: Undefined property: News::$title in localhost/new/lib/model/doctrine/News.class.php on line 35

i if change for:

```<code>public function getTitle()
{
    return $this->getTitle() . "aa"; //line 35
}
</code>```

then site not show.

if change:

```<code>public function getTitle()
{
    return $this->body . "aa"; //line 35
}
</code>```

this work OK!
How can i fix?

答:
Use $this->get('title'). That gets the title from the Doctrine model class. :)

```<code>public function getTitle() {
  return $this->get('title').'aa';
}
</code>```

Title: getTitle() in News.class.php in Symfony

Body:
i have table News:

id   | title  | body
1    | title1 | body1
2    | title2 | body2

etc.

I have

News.class.php
and
NewsTable.class.php

i would like edit method getTitle().
In News.class.php i add:

public function getTitle()
{
    return $this->title . "aa"; //line 35
}

but i have error:

Notice: Undefined property: News::$title in localhost/new/lib/model/doctrine/News.class.php on line 35

i if change for:

public function getTitle()
{
    return $this->getTitle() . "aa"; //line 35
}

then site not show.

if change:

public function getTitle()
{
    return $this->body . "aa"; //line 35
}

this work OK!
How can i fix?

Body:
Use $this->get('title'). That gets the title from the Doctrine model class. :)

public function getTitle() {
  return $this->get('title').'aa';
}


问:
Opcache Preloading with Symfony 5.4 / PHP8 / Platform.sh
I am attempting to set up Opcache Preloading on Symfony 5.4 running on PHP8 at Platform.sh, and running into a fatal error.

Configuration

Necessary pieces included:

```<code>// platform.app.yaml
...
variables
  php
    'opcache.preload': 'var/cache/prod/App_KernelProdContainer.php'
...

hooks:
  build: |
    ...
    composer dump-autoload --no-dev --classmap-authoritative
  deploy: |
    ...
    sv restart app
...

</code>```

I can verify that the App_KernelProdContainer.php file is being created at the correct location defined in the config above:

```<code><?php

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.

if (\class_exists(\ContainerF9HiXre\App_KernelProdContainer::class, false)) {
    // no-op
} elseif (!include __DIR__.'/ContainerF9HiXre/App_KernelProdContainer.php') {
    touch(__DIR__.'/ContainerF9HiXre.legacy');

    return;
}

if (!\class_exists(App_KernelProdContainer::class, false)) {
    \class_alias(\ContainerF9HiXre\App_KernelProdContainer::class, App_KernelProdContainer::class, false);
}

return new \ContainerF9HiXre\App_KernelProdContainer([
    'container.build_hash' => 'F9HiXre',
    'container.build_id' => '98091d49',
    'container.build_time' => 1644501054,
], __DIR__.\DIRECTORY_SEPARATOR.'ContainerF9HiXre');
</code>```

The included file ContainerF9HiXre/App_KernelProdContainer.php throws errors on the use statements like this:

```<code>Fatal error:  Uncaught Error: Class "Symfony\Component\DependencyInjection\Container" not found in /app/var/cache/prod/ContainerF9HiXre/App_KernelProdContainer.php:17
Stack trace:
#0 /app/var/cache/prod/App_KernelProdContainer.php(7): include()
#1 {main}
  thrown in /app/var/cache/prod/ContainerF9HiXre/App_KernelProdContainer.php on line 17
</code>```

Use statements in the included file appear as such:

```<code>namespace ContainerF9HiXre;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
</code>```

答:
You seem to be using the wrong file for preloading.

The generated file is named something like srcApp_KernelProdContainer.preload.php. But in any case, you probably should't be adding this file directly to opcache.preload, but the Symfony generated config/preload.php.

Since on platform.sh the path is resolved relative to the project root, you can use a relative path like this:

```<code>opcache.preload=config/preload.php
</code>```

If you do not have this file (e.g. incomplete recipes), you could simply re-generate it by running composer recipes:update symfony/framework-bundle, as explained here.

Or, ir you are not using Symfony Flex and want to do it manually, you can simply copy the file from the appropriate recipe, like this one.

It's a very simple script in any case:

```<code><?php

if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
    require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}
</code>```

Body:
I am attempting to set up Opcache Preloading on Symfony 5.4 running on PHP8 at Platform.sh, and running into a fatal error.

Configuration

Necessary pieces included:

// platform.app.yaml
...
variables
  php
    'opcache.preload': 'var/cache/prod/App_KernelProdContainer.php'
...

hooks:
  build: |
    ...
    composer dump-autoload --no-dev --classmap-authoritative
  deploy: |
    ...
    sv restart app
...

I can verify that the App_KernelProdContainer.php file is being created at the correct location defined in the config above:

<?php

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.

if (\class_exists(\ContainerF9HiXre\App_KernelProdContainer::class, false)) {
    // no-op
} elseif (!include __DIR__.'/ContainerF9HiXre/App_KernelProdContainer.php') {
    touch(__DIR__.'/ContainerF9HiXre.legacy');

    return;
}

if (!\class_exists(App_KernelProdContainer::class, false)) {
    \class_alias(\ContainerF9HiXre\App_KernelProdContainer::class, App_KernelProdContainer::class, false);
}

return new \ContainerF9HiXre\App_KernelProdContainer([
    'container.build_hash' => 'F9HiXre',
    'container.build_id' => '98091d49',
    'container.build_time' => 1644501054,
], __DIR__.\DIRECTORY_SEPARATOR.'ContainerF9HiXre');

The included file ContainerF9HiXre/App_KernelProdContainer.php throws errors on the use statements like this:

Fatal error:  Uncaught Error: Class "Symfony\Component\DependencyInjection\Container" not found in /app/var/cache/prod/ContainerF9HiXre/App_KernelProdContainer.php:17
Stack trace:
#0 /app/var/cache/prod/App_KernelProdContainer.php(7): include()
#1 {main}
  thrown in /app/var/cache/prod/ContainerF9HiXre/App_KernelProdContainer.php on line 17

Use statements in the included file appear as such:

namespace ContainerF9HiXre;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

Body:
You seem to be using the wrong file for preloading.

The generated file is named something like srcApp_KernelProdContainer.preload.php. But in any case, you probably should't be adding this file directly to opcache.preload, but the Symfony generated config/preload.php.

Since on platform.sh the path is resolved relative to the project root, you can use a relative path like this:

opcache.preload=config/preload.php

If you do not have this file (e.g. incomplete recipes), you could simply re-generate it by running composer recipes:update symfony/framework-bundle, as explained here.

Or, ir you are not using Symfony Flex and want to do it manually, you can simply copy the file from the appropriate recipe, like this one.

It's a very simple script in any case:

<?php

if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
    require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}


问:
MongoDB keysExamined:return Ratio
In MongoDB, we use aggregate and $group if we want to get count of some action. Suppose, we  have to get total number of deposits users have done in last 2 months then we use $group and then $sum to get count. Now in MongoDB Atlas profiler, it shows that as a very time taking and intensive operation. Because it scans keys of 2 months' data and return only 1 document(count). So is this a good way to get count or not?</p>

答:
If your query is "get total number of deposits for a set of users between two dates where that set can be all users" and deposits is a collection with a field user or similar then you do not need $group.  Simply count() the filtered set:

```<code>db.deposits.find({$and:[
    {"user":{$in: [ list ]}},
    {"depositDate":{$gte: startDate}},
    {"depositDate":{$lt: endDate}}
]}).count();

or with the aggregation pipeline:

db.deposits.aggregate([
    {$match: {$and:[
        {"user":{$in: [ list ]}},
        {"depositDate":{$gte: startDate}},
        {"depositDate":{$lt: endDate}}
    ]}},
    {$count: "n"}
]});

</code>```

Note you should be using a real datetime type for 'depositDate' -- not a string, not even ISO 8601 -- to facilitate more sophisticated queries involving dates.

Title: MongoDB keysExamined:return Ratio

Body:
If your query is "get total number of deposits for a set of users between two dates where that set can be all users" and deposits is a collection with a field user or similar then you do not need $group.  Simply count() the filtered set:

db.deposits.find({$and:[
    {"user":{$in: [ list ]}},
    {"depositDate":{$gte: startDate}},
    {"depositDate":{$lt: endDate}}
]}).count();

or with the aggregation pipeline:

db.deposits.aggregate([
    {$match: {$and:[
        {"user":{$in: [ list ]}},
        {"depositDate":{$gte: startDate}},
        {"depositDate":{$lt: endDate}}
    ]}},
    {$count: "n"}
]});

Note you should be using a real datetime type for 'depositDate' -- not a string, not even ISO 8601 -- to facilitate more sophisticated queries involving dates.


问:
Gradle threw an error while downloading artifacts from the network .. Exception: Gradle task assembleDebug failed with exit code 1
I just started with app development with flutter, but am not even able to run the test app. This is what come on console :

```<code>Launching lib/main.dart on AOSP on IA Emulator in debug mode... Running Gradle task 'assembleDebug'... Exception in thread "main" java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.(ZipFile.java:225) at java.util.zip.ZipFile.(ZipFile.java:155) at java.util.zip.ZipFile.(ZipFile.java:169) at org.gradle.wrapper.Install.unzip(Install.java:214) at org.gradle.wrapper.Install.access$600(Install.java:27) at org.gradle.wrapper.Install$1.call(Install.java:74) at org.gradle.wrapper.Install$1.call(Install.java:48) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) at org.gradle.wrapper.Install.createDist(Install.java:48) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) [!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
</code>```

I have active Internet connection. I also downloaded the gradle 6.4.1 and extracted it in android-studio >> plugins, This what is been shown on gradle-wrapper.properties :

```<code>distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https://services.gradle.org/distributions/gradle-5.6.2-all.zip*
</code>```

I use Ubuntu 18.04.

答:
[!] Gradle threw an error while downloading artifacts from the network.Retrying to download...
Exception: Gradle task assembleDebug failed with exit code 1

in my flutter project ------->

I solved it by removing  ->  firebase_storage: ^0.3.0   this from pubspec.ymal

Body:
I just started with app development with flutter, but am not even able to run the test app. This is what come on console :

Launching lib/main.dart on AOSP on IA Emulator in debug mode... Running Gradle task 'assembleDebug'... Exception in thread "main" java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.(ZipFile.java:225) at java.util.zip.ZipFile.(ZipFile.java:155) at java.util.zip.ZipFile.(ZipFile.java:169) at org.gradle.wrapper.Install.unzip(Install.java:214) at org.gradle.wrapper.Install.access$600(Install.java:27) at org.gradle.wrapper.Install$1.call(Install.java:74) at org.gradle.wrapper.Install$1.call(Install.java:48) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65) at org.gradle.wrapper.Install.createDist(Install.java:48) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) [!] Gradle threw an error while downloading artifacts from the network. Retrying to download...

I have active Internet connection. I also downloaded the gradle 6.4.1 and extracted it in android-studio >> plugins, This what is been shown on gradle-wrapper.properties :

distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https://services.gradle.org/distributions/gradle-5.6.2-all.zip*

I use Ubuntu 18.04.


问:
How to define array range of array of numbers in TypeScript
In Next.js I create a function component and use useState hook to declare variable for store array of digits like this

const [digits, setDigits] = useState<number[]>();
```

But I also want to define the range of array generic, something like Array(3) (but not [number, number, number] because that is too long)

How to solve this?

答:
You can do something like this:

```<code>const data = new Array<number>(100)
</code>```

An array length of 100 where the elements have a type of number. Array comes with with a fill function to initialize your array if needed, for example

```<code>const array = new Array<number>(100).fill(9)
</code>```

An array of length 100 where all indexes will be number 9.

Body:
In Next.js I create a function component and use useState hook to declare variable for store array of digits like this

const [digits, setDigits] = useState<number[]>();

But I also want to define the range of array generic, something like Array(3) (but not [number, number, number] because that is too long)

How to solve this?

Body:
You can do something like this:

const data = new Array<number>(100)

An array length of 100 where the elements have a type of number. Array comes with with a fill function to initialize your array if needed, for example

const array = new Array<number>(100).fill(9)

An array of length 100 where all indexes will be number 9.


问:
microsoft teams get conversation link
I am using Microsoft team integration using nodejs. In the Teams client you can easily copy a link to the conversation and this can be used to navigate to the specific conversation any time.

see the screenshot for the reference: https://www.dropbox.com/s/fog3ojddcb6mdis/screen%20shot%202021-02-10%20at%202.44.31%20pm.png?dl=0

Is there a way to get this link in the botframework when the conversation is created? I have seen there are deep link apis for group chat etc. which requires the list of users to be provided.

but I am interested in obtaining the conversation link that appears on client.

This one is not useful https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links

The activity object I get in nodejs on starting a conversation is:

```<code>{
  "localTimestamp": "2021-02-13T05:42:25.313Z",
  "timestamp": "2021-02-13T05:42:25.313Z",
  "type": "message",
  "locale": "en-US",
  "from": {
    "name": "Stacy",
    "id": "29:1a-Xb7uPrMwF2XqjMEHCC7ytV2xb2VUCqTA-n_s-k5ZyMCTKIL-ku2XkgbE167D_5ZbmVaqQxJGIQ13vypSqu-A",
    "aadObjectId": "718ab805-850c-43ec-8d4e-4af0c543df75"
  },
  "serviceUrl": "https://smba.trafficmanager.net/amer/",
  "conversation": {
    "isGroup": true,
    "conversationType": "channel",
    "id": "19:a0a0088174a644cb91406f4d8f79d888@thread.tacv2;messageid=1613194945273",
    "tenantId": "04e934f3-0866-4a6d-b07c-a4737e8f9865"
  },
  "localTimezone": "America/Los_Angeles",
  "recipient": {
    "name": "MyBot",
    "id": "28:a835cf1d-83a8-5ae9-845a-23a68a1df442"
  },
  "id": "1613194445273",
  "channelData": {
    "channel": {
      "id": "19:a0a0088174a644cb91459f4d8f79d888@thread.tacv2"
    },
    "tenant": {
      "id": "04e930f3-0866-4a6d-c07c-a4737e8f9865"
    },
    "team": {
      "id": "19:774d4103fe51420db1437130378b196e@thread.tacv2"
    },
    "teamsChannelId": "19:a0a0088174a644cb91409f5d8f79d888@thread.tacv2",
    "teamsTeamId": "19:774d4103fe51420db1437190478b196e@thread.tacv2"
  },
  "attachments": [
    {
      "contentType": "text/html",
      "content": "<div><div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">MyBot</span> opty </div>\n</div>"
    }
  ],
  "textFormat": "plain",
  "channelId": "msteams",
  "entities": [
    {
      "text": "<at>MyBot</at>",
      "mentioned": {
        "id": "28:a835cf1d-83a8-4ae9-845a-23a68a1df432",
        "name": "MyBot"
      },
      "type": "mention"
    },
    {
      "country": "US",
      "platform": "Mac",
      "timezone": "America/Los_Angeles",
      "locale": "en-US",
      "type": "clientInfo"
    }
  ],
  "text": "opty"
}

</code>```

答:
For anyone wondering how to do deep linking to an existing group chat, you'd need to have the chatId.
The URL is as follows:</p>
```<code>https://teams.microsoft.com/l/chat/{chatId}/0?tenantId={tenantId}
</code>```

Title: microsoft teams get conversation link

Body:
I am using Microsoft team integration using nodejs. In the Teams client you can easily copy a link to the conversation and this can be used to navigate to the specific conversation any time.

see the screenshot for the reference: https://www.dropbox.com/s/fog3ojddcb6mdis/screen%20shot%202021-02-10%20at%202.44.31%20pm.png?dl=0

Is there a way to get this link in the botframework when the conversation is created? I have seen there are deep link apis for group chat etc. which requires the list of users to be provided.

but I am interested in obtaining the conversation link that appears on client.

This one is not useful https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links

The activity object I get in nodejs on starting a conversation is:

{
  "localTimestamp": "2021-02-13T05:42:25.313Z",
  "timestamp": "2021-02-13T05:42:25.313Z",
  "type": "message",
  "locale": "en-US",
  "from": {
    "name": "Stacy",
    "id": "29:1a-Xb7uPrMwF2XqjMEHCC7ytV2xb2VUCqTA-n_s-k5ZyMCTKIL-ku2XkgbE167D_5ZbmVaqQxJGIQ13vypSqu-A",
    "aadObjectId": "718ab805-850c-43ec-8d4e-4af0c543df75"
  },
  "serviceUrl": "https://smba.trafficmanager.net/amer/",
  "conversation": {
    "isGroup": true,
    "conversationType": "channel",
    "id": "19:a0a0088174a644cb91406f4d8f79d888@thread.tacv2;messageid=1613194945273",
    "tenantId": "04e934f3-0866-4a6d-b07c-a4737e8f9865"
  },
  "localTimezone": "America/Los_Angeles",
  "recipient": {
    "name": "MyBot",
    "id": "28:a835cf1d-83a8-5ae9-845a-23a68a1df442"
  },
  "id": "1613194445273",
  "channelData": {
    "channel": {
      "id": "19:a0a0088174a644cb91459f4d8f79d888@thread.tacv2"
    },
    "tenant": {
      "id": "04e930f3-0866-4a6d-c07c-a4737e8f9865"
    },
    "team": {
      "id": "19:774d4103fe51420db1437130378b196e@thread.tacv2"
    },
    "teamsChannelId": "19:a0a0088174a644cb91409f5d8f79d888@thread.tacv2",
    "teamsTeamId": "19:774d4103fe51420db1437190478b196e@thread.tacv2"
  },
  "attachments": [
    {
      "contentType": "text/html",
      "content": "

MyBot opty
\n
"
    }
  ],
  "textFormat": "plain",
  "channelId": "msteams",
  "entities": [
    {
      "text": "<at>MyBot</at>",
      "mentioned": {
        "id": "28:a835cf1d-83a8-4ae9-845a-23a68a1df432",
        "name": "MyBot"
      },
      "type": "mention"
    },
    {
      "country": "US",
      "platform": "Mac",
      "timezone": "America/Los_Angeles",
      "locale": "en-US",
      "type": "clientInfo"
    }
  ],
  "text": "opty"
}

Body:
For anyone wondering how to do deep linking to an existing group chat, you'd need to have the chatId.
The URL is as follows:

https://teams.microsoft.com/l/chat/{chatId}/0?tenantId={tenantId}


问:
API gateway SQS response ends with UnknownOperationException
I have an API Gateway which routes requests to SQS, API Gateway has a the needed permission to send messages to SQS (Created IAM role), when I send test data, I'll get the response below with UnknownOperationException.

SQS is also empty with no messages available.

```<code>Tue Nov 09 13:46:11 UTC 2021 : Sending request to https://sqs.ca-central-1.amazonaws.com/XXXXXXXX/XXXX
Tue Nov 09 13:46:11 UTC 2021 : Received response. Status: 404, Integration latency: 2 ms
Tue Nov 09 13:46:11 UTC 2021 : Endpoint response headers: {x-amzn-RequestId=e63b5577-9866-569d-85d8-0f73e5851cf0, Date=Tue, 09 Nov 2021 13:46:11 GMT, X-Amzn-Trace-Id=Root=1-618a7ba3-dd93ee11df45d437f9c98705, Content-Type=null, Content-Length=29}
Tue Nov 09 13:46:11 UTC 2021 : Endpoint response body before transformations: <UnknownOperationException/>

Tue Nov 09 13:46:11 UTC 2021 : Method response body after transformations: <UnknownOperationException/>
</code>```

Any ideas?

答:
To fix that issue you have to add the Content-Type:'application/x-www-form-urlencoded' header to the integration request:
integration request headers</p>

Body:
I have an API Gateway which routes requests to SQS, API Gateway has a the needed permission to send messages to SQS (Created IAM role), when I send test data, I'll get the response below with UnknownOperationException.

SQS is also empty with no messages available.

Tue Nov 09 13:46:11 UTC 2021 : Sending request to https://sqs.ca-central-1.amazonaws.com/XXXXXXXX/XXXX
Tue Nov 09 13:46:11 UTC 2021 : Received response. Status: 404, Integration latency: 2 ms
Tue Nov 09 13:46:11 UTC 2021 : Endpoint response headers: {x-amzn-RequestId=e63b5577-9866-569d-85d8-0f73e5851cf0, Date=Tue, 09 Nov 2021 13:46:11 GMT, X-Amzn-Trace-Id=Root=1-618a7ba3-dd93ee11df45d437f9c98705, Content-Type=null, Content-Length=29}
Tue Nov 09 13:46:11 UTC 2021 : Endpoint response body before transformations: <UnknownOperationException/>

Tue Nov 09 13:46:11 UTC 2021 : Method response body after transformations: <UnknownOperationException/>

Any ideas?


问:
What is the difference between `minikube cache list` and `minikube image list`
These two commands appear to list the images which are available in minikube. Obviously one refers to images that are 'in cache' and the other does not however it is not clear where the images being listed by minikube image list reside if not in the cache, or how images could be in the list returned by minikube image list but not be returned by minikube cache list.

答:
The differences between them are that image list shows all images in cluster and cache list shows images which you added manually. You can read more about Offline usage and about Pushing images

minikube start  caches all required Kubernetes images by default. This default may be changed by setting  --cache-images=false. These images are not displayed by the  minikube cache  command.

To add Docker image to Minikube you can use:

```<code>minikube image load <name-of-docker-image>
</code>```

Here is an example:

```<code>user@minikube:~/myproject$ minikube cache list
user@minikube:~/myproject$ minikube image load helloapp:v1
user@minikube:~/myproject$ minikube cache list
helloapp:v1
user@minikube:~/myproject$
</code>```

Body:
The differences between them are that image list shows all images in cluster and cache list shows images which you added manually. You can read more about Offline usage and about Pushing images

minikube start  caches all required Kubernetes images by default. This default may be changed by setting  --cache-images=false. These images are not displayed by the  minikube cache  command.

To add Docker image to Minikube you can use:

minikube image load <name-of-docker-image>

Here is an example:

user@minikube:~/myproject$ minikube cache list
user@minikube:~/myproject$ minikube image load helloapp:v1
user@minikube:~/myproject$ minikube cache list
helloapp:v1
user@minikube:~/myproject$


问:
Flutter - I am looking for a way to do a pulse animation
i am trying to achieved some thing like this in flutter <img src="https://i.stack.imgur.com/olcrj.gif" alt="enter image description here"> </p>

答:
For those looking to create an animation which is not circular, but rectangular with possible rounded borders, you can replace the SpritePainter from the top answer with:</p>
```<code>class SpritePainter extends CustomPainter {
  final Animation<double> _animation;

  SpritePainter(this._animation) : super(repaint: _animation);

  void roundedRect(Canvas canvas, Rect rect, double animValue, int waveAmount) {
    double opacity = (1.0 - (animValue / waveAmount)).clamp(0.0, 1.0);
    Color color = new Color.fromRGBO(0, 117, 194, opacity);

    final pixelMiltiplier = 20;
    final newWidth = rect.width + animValue*pixelMiltiplier;
    final newHeight = rect.height + animValue*pixelMiltiplier;
    final widthIncrease = newWidth/rect.width;
    final heightIncrease = newHeight/rect.height;
    final widthOffset = (widthIncrease - 1) / 2;
    final heightOffet = (heightIncrease - 1) / 2;

    final Paint paint = new Paint()..color = color;
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromLTWH(-rect.width * widthOffset, -rect.height * heightOffet,
                rect.width * widthIncrease, rect.height * heightIncrease),
            Radius.circular(15.0)),
        paint);
  }

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = new Rect.fromLTRB(0.0, 0.0, size.width, size.height);
    final waveAmount = 1;

    if (!_animation.isDismissed) {
      for (int wave = waveAmount-1; wave >= 0; wave--) {
        roundedRect(canvas, rect, wave + _animation.value, waveAmount);
      }
    }
  }

  @override
  bool shouldRepaint(SpritePainter oldDelegate) {
    return true;
  }
}
</code>```

Body:
For those looking to create an animation which is not circular, but rectangular with possible rounded borders, you can replace the SpritePainter from the top answer with:

class SpritePainter extends CustomPainter {
  final Animation<double> _animation;

  SpritePainter(this._animation) : super(repaint: _animation);

  void roundedRect(Canvas canvas, Rect rect, double animValue, int waveAmount) {
    double opacity = (1.0 - (animValue / waveAmount)).clamp(0.0, 1.0);
    Color color = new Color.fromRGBO(0, 117, 194, opacity);

    final pixelMiltiplier = 20;
    final newWidth = rect.width + animValue*pixelMiltiplier;
    final newHeight = rect.height + animValue*pixelMiltiplier;
    final widthIncrease = newWidth/rect.width;
    final heightIncrease = newHeight/rect.height;
    final widthOffset = (widthIncrease - 1) / 2;
    final heightOffet = (heightIncrease - 1) / 2;

    final Paint paint = new Paint()..color = color;
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromLTWH(-rect.width * widthOffset, -rect.height * heightOffet,
                rect.width * widthIncrease, rect.height * heightIncrease),
            Radius.circular(15.0)),
        paint);
  }

  @override
  void paint(Canvas canvas, Size size) {
    Rect rect = new Rect.fromLTRB(0.0, 0.0, size.width, size.height);
    final waveAmount = 1;

    if (!_animation.isDismissed) {
      for (int wave = waveAmount-1; wave >= 0; wave--) {
        roundedRect(canvas, rect, wave + _animation.value, waveAmount);
      }
    }
  }

  @override
  bool shouldRepaint(SpritePainter oldDelegate) {
    return true;
  }
}


问:
Optimization integer programming with covariance matrix
I am trying to do a optimization problem which requires the calculation of a new covariance matrix affected by the variable within the implementation.

I am able to do so with scipy optimization Minimize using numpy.cov within my objective function. However, as I need to have integer constraints, I am not able to think of a solution which tackles my issue with cvxpy, gekko since most of the optimization problem online have a fixed covariance matrix.

Below is my code for scipy:

room_revpar = np.array(df.iloc[:,1:10])
nla = np.array([753.2,1077.6, 1278.6,1463.9,1657.0,1990.6,2404.9,2754.6,3464.72])
min_nla = 270517.16
max_nla = 271270.359995

def objective(x, room_revpar,nla,sign = -1.0):
    room_revenue = room_revpar * x
    avg_revenue = np.mean(room_revenue, axis = 0)

    total_revenue = sum(avg_revenue)

    cov_matrix = np.cov(room_revenue.T)

    total_nla = np.matmul(x.T, nla)
    weights = x * nla / total_nla

    portfolio_sd = np.sqrt(np.matmul(np.matmul(weights.T, cov_matrix), weights))

    adj_risk = total_revenue / portfolio_sd
    return sign * adj_risk

def constraint1(x, nla, min_nla):
    total_nla = np.matmul(x.T, nla)
    return total_nla - min_nla

def constraint2(x, nla, max_nla):
    total_nla = np.matmul(x.T, nla)
    return max_nla - total_nla

con1 = {'type': 'ineq', 'fun': constraint1, 'args': (nla, min_nla)}
con2 = {'type': 'ineq', 'fun': constraint2, 'args': (nla, max_nla)}

from scipy.optimize import minimize
x = np.ones(9)
sol = minimize(objective,x0 = x, args = (room_revpar, nla), constraints = (con1,con2), options = {'maxiter': 100000})

```

Would appreciate if anybody has a solution! Thank you.

答:
The covariance of xi and yi is calculated explicitly with np.cov().

import numpy as np
xi = [2.1,2.5,3.6,4.0]
yi = [8,10,12,14]
print(np.cov(xi,yi))
```
<p>The function <code>np.cov(xi,yi)</code> returns a 2x2 symmetric matrix</p>
<pre class="lang-py prettyprint-override"><code>[[cov[xi,xi],cov[xi,yi]],
 [cov[xi,yi],cov[yi,yi]]]
</code>```

[[0.80333333 2.26666667]
 [2.26666667 6.66666667]]
```
<p>Gekko needs a symbolic form of the covariance formula for the gradient-based optimizer. Below is a function <code>cov()</code> that creates the symbolic covariance calculation with Gekko variables.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
from gekko import GEKKO

def cov(m,x,y,ddof=1):
    ''' Calculate the covariance matrix of x, y
    Inputs:
      m: Gekko model
      x: x vector of equal length to y
      y: y vector of equal length to x
      [ddof=1]: delta degrees of freedom
    Returns:
      c: covariance as a Gekko variable
    '''
    nx = len(x); ny = len(y)  # length of x, y
    if nx!=ny:
        print('Error: mismatch of x and y')
    xm = m.sum(x)/nx  # mean of x
    ym = m.sum(y)/ny  # mean of y
    c = m.Var()       # covariance
    m.Equation(c==(m.sum([(x[i]-xm)*(y[i]-ym) \
                     for i in range(nx)]))/(nx-ddof))
    return c

m = GEKKO()

n = 4
x = m.Array(m.Param,n)
y = m.Array(m.Param,n)
xi = [2.1,2.5,3.6,4.0]
yi = [8,10,12,14]
for i in range(n):
    x[i].value = xi[i]
    y[i].value = yi[i]

c0 = cov(m,x,y,ddof=0)
c1 = cov(m,x,y)

m.solve(disp=False)

print('Covariance (Numpy) population cov: ', np.cov(xi,yi,ddof=0)[0,1])
print('Covariance (Numpy) sample cov: ', np.cov(xi,yi)[0,1])
print('Covariance (Gekko) population cov: ', c0.value[0])
print('Covariance (Gekko) sample cov: ', c1.value[0])
</code>```

Gekko and Numpy produce the same results for the fixed xi and yi values:

```<code>Covariance (Numpy) population cov:  1.7
Covariance (Numpy) sample cov:  2.2666666666666666
Covariance (Gekko) population cov:  1.7
Covariance (Gekko) sample cov:  2.2666666667
</code>```

Now that the cov() function is verified, you can switch x and y to be calculated integer values such as:

x = m.Array(m.Var,n,lb=0,ub=10,integer=True)
y = m.Array(m.Var,n,lb=0,ub=5,integer=True)
```

To obtain an integer solution, switch to m.options.SOLVER=1 (APOPT) solver before the m.solve() command.

Body:
I am trying to do a optimization problem which requires the calculation of a new covariance matrix affected by the variable within the implementation.

I am able to do so with scipy optimization Minimize using numpy.cov within my objective function. However, as I need to have integer constraints, I am not able to think of a solution which tackles my issue with cvxpy, gekko since most of the optimization problem online have a fixed covariance matrix.

Below is my code for scipy:

room_revpar = np.array(df.iloc[:,1:10])
nla = np.array([753.2,1077.6, 1278.6,1463.9,1657.0,1990.6,2404.9,2754.6,3464.72])
min_nla = 270517.16
max_nla = 271270.359995

def objective(x, room_revpar,nla,sign = -1.0):
    room_revenue = room_revpar * x
    avg_revenue = np.mean(room_revenue, axis = 0)

    total_revenue = sum(avg_revenue)

    cov_matrix = np.cov(room_revenue.T)

    total_nla = np.matmul(x.T, nla)
    weights = x * nla / total_nla

    portfolio_sd = np.sqrt(np.matmul(np.matmul(weights.T, cov_matrix), weights))

    adj_risk = total_revenue / portfolio_sd
    return sign * adj_risk

def constraint1(x, nla, min_nla):
    total_nla = np.matmul(x.T, nla)
    return total_nla - min_nla

def constraint2(x, nla, max_nla):
    total_nla = np.matmul(x.T, nla)
    return max_nla - total_nla

con1 = {'type': 'ineq', 'fun': constraint1, 'args': (nla, min_nla)}
con2 = {'type': 'ineq', 'fun': constraint2, 'args': (nla, max_nla)}

from scipy.optimize import minimize
x = np.ones(9)
sol = minimize(objective,x0 = x, args = (room_revpar, nla), constraints = (con1,con2), options = {'maxiter': 100000})

Would appreciate if anybody has a solution! Thank you.

Body:
The covariance of xi and yi is calculated explicitly with np.cov().

import numpy as np
xi = [2.1,2.5,3.6,4.0]
yi = [8,10,12,14]
print(np.cov(xi,yi))

The function np.cov(xi,yi) returns a 2x2 symmetric matrix

[[cov[xi,xi],cov[xi,yi]],
 [cov[xi,yi],cov[yi,yi]]]

[[0.80333333 2.26666667]
 [2.26666667 6.66666667]]

Gekko needs a symbolic form of the covariance formula for the gradient-based optimizer. Below is a function cov() that creates the symbolic covariance calculation with Gekko variables.

import numpy as np
from gekko import GEKKO

def cov(m,x,y,ddof=1):
    ''' Calculate the covariance matrix of x, y
    Inputs:
      m: Gekko model
      x: x vector of equal length to y
      y: y vector of equal length to x
      [ddof=1]: delta degrees of freedom
    Returns:
      c: covariance as a Gekko variable
    '''
    nx = len(x); ny = len(y)  # length of x, y
    if nx!=ny:
        print('Error: mismatch of x and y')
    xm = m.sum(x)/nx  # mean of x
    ym = m.sum(y)/ny  # mean of y
    c = m.Var()       # covariance
    m.Equation(c==(m.sum([(x[i]-xm)*(y[i]-ym) \
                     for i in range(nx)]))/(nx-ddof))
    return c

m = GEKKO()

n = 4
x = m.Array(m.Param,n)
y = m.Array(m.Param,n)
xi = [2.1,2.5,3.6,4.0]
yi = [8,10,12,14]
for i in range(n):
    x[i].value = xi[i]
    y[i].value = yi[i]

c0 = cov(m,x,y,ddof=0)
c1 = cov(m,x,y)

m.solve(disp=False)

print('Covariance (Numpy) population cov: ', np.cov(xi,yi,ddof=0)[0,1])
print('Covariance (Numpy) sample cov: ', np.cov(xi,yi)[0,1])
print('Covariance (Gekko) population cov: ', c0.value[0])
print('Covariance (Gekko) sample cov: ', c1.value[0])

Gekko and Numpy produce the same results for the fixed xi and yi values:

Covariance (Numpy) population cov:  1.7
Covariance (Numpy) sample cov:  2.2666666666666666
Covariance (Gekko) population cov:  1.7
Covariance (Gekko) sample cov:  2.2666666667

Now that the cov() function is verified, you can switch x and y to be calculated integer values such as:

x = m.Array(m.Var,n,lb=0,ub=10,integer=True)
y = m.Array(m.Var,n,lb=0,ub=5,integer=True)

To obtain an integer solution, switch to m.options.SOLVER=1 (APOPT) solver before the m.solve() command.


问:
Splitting out product details in cell
I have a sheet full of product details that have been scraped from a website. All the dimensions are grouped in one cell by product. The same goes for product details. Some contain more dimension and product details than others.

Is there a way to split all these out into unique columns?

Thanks!

答:
Any cell that contains multiple lines of text can be split into an array of text.  For example G112 contains 7 lines.

```<code>function test() {
  try {
    var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
    var value = sh.getRange("G112").getValue();
    console.log(value.split('\n'));
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

Would produce an array ['Size Small','Item Width 1,400mm',...]?

Since each cell has a different number of lines you'll have to pack some rows to make a symmetrical 2 dimensional array and then put if back somewhere.

Title: Splitting out product details in cell

Body:
Any cell that contains multiple lines of text can be split into an array of text.  For example G112 contains 7 lines.

function test() {
  try {
    var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
    var value = sh.getRange("G112").getValue();
    console.log(value.split('\n'));
  }
  catch(err) {
    console.log(err);
  }
}

Would produce an array ['Size Small','Item Width 1,400mm',...]?

Since each cell has a different number of lines you'll have to pack some rows to make a symmetrical 2 dimensional array and then put if back somewhere.