问:
Having trouble identifying matching characters in two strings
I am able to iterate through two given strings of the same length.

I am supposed to output a green emoji if the letters in guess_word are are also contained and in the correct position of the secret_word. If a letter in the guess_word is in the secret_word but it's in the wrong position, then I should have an output of a yellow emoji.

This is where my issue is. The yellow emoji is not showing up in my output, only the green and white boxes. I have a picture below of what it should look like in the output.

I have to stick to two different functions because this is what my homework is asking me to do.

```<code>def contains_char(any_length: str, single_character: str) -> bool:
    """Loop iterates through each character in string to find matching character."""
    assert len(single_character) == 1
    if single_character in any_length:
        return True
    else:
        return False

def emojified(guess_word: str, secret_word: str) -> str:
    """A way to match letters to its corresponding emoji color output. """
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\U00002B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    emoji_color: str = ""
    i: int = 0
    while i < len(secret_word):
        i += 1
        if guess_word[0] in secret_word[0]:
            emoji_color += GREEN_BOX
            i += 1
        else:
            emoji_color += WHITE_BOX
            i += 1
        if contains_char is True:
            emoji_color += YELLOW_BOX
        else:
            emoji_color += WHITE_BOX
    return emoji_color
</code>```

Output:

答:
In order to properly process the "same-position" matches without interfering with the "different-position" matched, you need to check for same-positions first and fallback on diffrent-position matches otherwise.

You can do this by replacing characters in a comprehension that you join into the final result.

For example:

```<code>def emojified(guess,secret):
    WHITE_BOX  = "\U00002B1C"
    GREEN_BOX  = "\U0001F7E9"
    YELLOW_BOX = "\U0001F7E8"

    return "".join( GREEN_BOX  if s==g            # same-position
               else YELLOW_BOX if g in secret     # different-position
               else WHITE_BOX                     # no match
                    for s,g in zip(secret,guess)) # character pairs
</code>```

Output:

```<code>print(emojified("hello","world"))   # ⬜⬜
print(emojified("elloh","hello"))   #
print(emojified("python","woohoo")) # ⬜⬜⬜⬜
print(emojified("python","python")) #
print(emojified("yikyak","tiktok")) # ⬜⬜⬜
</code>```

Body:
I am able to iterate through two given strings of the same length.

I am supposed to output a green emoji if the letters in guess_word are are also contained and in the correct position of the secret_word. If a letter in the guess_word is in the secret_word but it's in the wrong position, then I should have an output of a yellow emoji.

This is where my issue is. The yellow emoji is not showing up in my output, only the green and white boxes. I have a picture below of what it should look like in the output.

I have to stick to two different functions because this is what my homework is asking me to do.

def contains_char(any_length: str, single_character: str) -> bool:
    """Loop iterates through each character in string to find matching character."""
    assert len(single_character) == 1
    if single_character in any_length:
        return True
    else:
        return False

def emojified(guess_word: str, secret_word: str) -> str:
    """A way to match letters to its corresponding emoji color output. """
    assert len(guess_word) == len(secret_word)
    WHITE_BOX: str = "\U00002B1C"
    GREEN_BOX: str = "\U0001F7E9"
    YELLOW_BOX: str = "\U0001F7E8"
    emoji_color: str = ""
    i: int = 0
    while i < len(secret_word):
        i += 1
        if guess_word[0] in secret_word[0]:
            emoji_color += GREEN_BOX
            i += 1
        else:
            emoji_color += WHITE_BOX
            i += 1
        if contains_char is True:
            emoji_color += YELLOW_BOX
        else:
            emoji_color += WHITE_BOX
    return emoji_color

Output:

Body:
In order to properly process the "same-position" matches without interfering with the "different-position" matched, you need to check for same-positions first and fallback on diffrent-position matches otherwise.

You can do this by replacing characters in a comprehension that you join into the final result.

For example:

def emojified(guess,secret):
    WHITE_BOX  = "\U00002B1C"
    GREEN_BOX  = "\U0001F7E9"
    YELLOW_BOX = "\U0001F7E8"

    return "".join( GREEN_BOX  if s==g            # same-position
               else YELLOW_BOX if g in secret     # different-position
               else WHITE_BOX                     # no match
                    for s,g in zip(secret,guess)) # character pairs

Output:

print(emojified("hello","world"))   # ⬜⬜
print(emojified("elloh","hello"))   #
print(emojified("python","woohoo")) # ⬜⬜⬜⬜
print(emojified("python","python")) #
print(emojified("yikyak","tiktok")) # ⬜⬜⬜


来源: stackexchange

问:
How to turn HTML widget code into NEXTjs code to use in an app (CoinMarketCap Price Marquee Ticker)
I'm trying to embed this CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app and am having issues with this. I'll go through what I'm trying to do and walk through my process. Hopefully someone has maybe tried to do this and might have some suggestions.

Template Code:

Here is the code that is presented on the CoinMarketCap website, ideally for an HTML page: https://coinmarketcap.com/widget/price-marquee/

```
<p>This is an example of it working, but only in HTML:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <script
      type="text/javascript"
      src="https://files.coinmarketcap.com/static/widget/coinMarquee.js"
    ></script>
  </head>
  <body>
    <h1>
      Cryptocurrency Ticker Slider
    </h1>
    <h3>Powered by: CoinMarketCap</h3>
    <div
      id="coinmarketcap-widget-marquee"
      coins="1,1027,825"
      currency="USD"
      theme="light"
      transparent="false"
      show-symbol-logo="true"
    ></div>
  </body>
</html></code>```

❌ My Attempt #1:

I tried to create it as a separate div and import the script from  off of next/script. However, I don't see anything in the window on my app when I save and load the app. I even added some styling, but I'm not seeing that the script is executing.

import type { NextPage } from 'next'
import Script from 'next/script'

const About: NextPage = () => {
return (

  )
}

export default About
```
<h2>❌ Attempt #2:</h2>
<p>This is what I thought would work, but I get this error on "coins" with NEXTjs, where it says the below and same as above, the script doesn't load into the widget div space:
<code>(JSX attribute) coins: string Type '{ id: string; coins: string; currency: string; theme: string; transparent: string; "show-symbol-logo": string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'coins' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.</code></p>
<pre class="lang-js prettyprint-override"><code>import type { NextPage } from 'next'
import Script from 'next/script'

const About: NextPage = () => {
return (
<Script type="text/javascript" src="https://files.coinmarketcap.com/static/widget/coinMarquee.js"></Script>
<div id="coinmarketcap-widget-marquee" coins="1,1027,825" currency="USD" theme="light" transparent="false" show-symbol-logo="true"></div>
  )
}

export default About
</code>```

I would be super grateful for any help or guidance on how to add this widget from CoinMarketCap into my site!

Thanks so much!

答:
When using Typescript and next.js you can edit your index.d.ts to include the attributes that the div is using:

```<code>declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    coins?:string;
    currency?:string;
    theme?:string;
    transparent?:string;
    tshow-symbol-logo?:string;
  }
}
</code>```

As an alternative, if you are only using Javascript and React you can create the widget in the index.html and append it to a div when your React component mounts.

Codesandbox

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to embed this CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app and am having issues with this. I'll go through what I'm trying to do and walk through my process. Hopefully someone has maybe tried to do this and might have some suggestions.

Template Code:

Here is the code that is presented on the CoinMarketCap website, ideally for an HTML page: https://coinmarketcap.com/widget/price-marquee/

This is an example of it working, but only in HTML:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>

      Cryptocurrency Ticker Slider

Powered by: CoinMarketCap

❌ My Attempt #1:

I tried to create it as a separate div and import the script from  off of next/script. However, I don't see anything in the window on my app when I save and load the app. I even added some styling, but I'm not seeing that the script is executing.

import type { NextPage } from 'next'
import Script from 'next/script'

const About: NextPage = () => {
return (

  )
}

export default About

❌ Attempt #2:

This is what I thought would work, but I get this error on "coins" with NEXTjs, where it says the below and same as above, the script doesn't load into the widget div space:
(JSX attribute) coins: string Type '{ id: string; coins: string; currency: string; theme: string; transparent: string; "show-symbol-logo": string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'coins' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.

import type { NextPage } from 'next'
import Script from 'next/script'

const About: NextPage = () => {
return (

  )
}

export default About

I would be super grateful for any help or guidance on how to add this widget from CoinMarketCap into my site!

Thanks so much!

Body:
When using Typescript and next.js you can edit your index.d.ts to include the attributes that the div is using:

declare module 'react' {
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    coins?:string;
    currency?:string;
    theme?:string;
    transparent?:string;
    tshow-symbol-logo?:string;
  }
}

As an alternative, if you are only using Javascript and React you can create the widget in the index.html and append it to a div when your React component mounts.

Codesandbox


问:
Ho do I add common css for stenciljs web-components
I am creating bunch of web-components, not sure how do I create common css for stenciljs web-components.
Based on documentation I can add globalStyle: 'src/global/app.css',
But it seems i can only share css variables. e.g.

```<code>:root {
   --font_color: #484848;
   --bg_color--light: #f9f9f9;
}
</code>```

if I want to have common base css for buttons e.g.

```<code>button {
  border-radius: 5px;
  padding: 2px 10px;
}
</code>```

Which i want to share across all the components | Not sure how to achieve that.
Thanks in advance for suggestions.

答:
The Stencil docs are a bit unclear on this issue. It took me a while to realize the globalStyle config doesn't actually do anything to apply global styles to components with shadow DOM.

If you wish to use the globalStyle globally across all components, you can try the following:

Link the globalStyle inside your index.html

Also link the globalStyle inside each of your components

The components may seem strange with a style link, but it actually works.

```<code>render() {
  return (
    <Host>
      <link rel="stylesheet" href="/build/my-app.css" />
      RENDER THIS COMPONENT WITH GLOBAL STYLES
    </Host>
  );
}
</code>```

Body:
I am creating bunch of web-components, not sure how do I create common css for stenciljs web-components.
Based on documentation I can add globalStyle: 'src/global/app.css',
But it seems i can only share css variables. e.g.

:root {
   --font_color: #484848;
   --bg_color--light: #f9f9f9;
}

if I want to have common base css for buttons e.g.

button {
  border-radius: 5px;
  padding: 2px 10px;
}

Which i want to share across all the components | Not sure how to achieve that.
Thanks in advance for suggestions.

Body:
The Stencil docs are a bit unclear on this issue. It took me a while to realize the globalStyle config doesn't actually do anything to apply global styles to components with shadow DOM.

If you wish to use the globalStyle globally across all components, you can try the following:

Link the globalStyle inside your index.html

Also link the globalStyle inside each of your components

The components may seem strange with a style link, but it actually works.

render() {
  return (
    <Host>
      <link rel="stylesheet" href="/build/my-app.css" />
      RENDER THIS COMPONENT WITH GLOBAL STYLES
    </Host>
  );
}


问:
Difference between [[NSDate date] retain] and [[NSDate alloc] init]
As both of the following serves the same purpose,

```<code>today = [[NSDate date] retain];
</code>```

and

```<code>today = [[NSDate alloc] init];
</code>```

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.

答: There is effectively no difference between the two. In the first example, you're just retaining an autoreleased instance created by the convenience method, which would have done something like return [[[NSDate alloc] init] autorelease].

ContentLicense: CC BY-SA 3.0

Body:
As both of the following serves the same purpose,

today = [[NSDate date] retain];

and

today = [[NSDate alloc] init];

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.


问:
Is this query possible in MongoDB?
Imagine a data set like this:

db.test.insertMany([
  { '_id':1, 'name':'aa1', 'price':10, 'quantity': 2, 'category': ['coffe'] },
  { '_id':2, 'name':'aa2', 'price':20, 'quantity': 1, 'category': ['coffe', 'snack'] },
  { '_id':3, 'name':'aa3', 'price':5,  'quantity':10, 'category': ['snack', 'coffe'] },
  { '_id':4, 'name':'aa4', 'price':5,  'quantity':20, 'category': ['coffe', 'cake'] },
  { '_id':5, 'name':'aa5', 'price':10, 'quantity':10, 'category': ['animal', 'dog'] },
  { '_id':6, 'name':'aa6', 'price':5,  'quantity': 5, 'category': ['dog', 'animal'] },
  { '_id':7, 'name':'aa7', 'price':5,  'quantity':10, 'category': ['animal', 'cat'] },
  { '_id':8, 'name':'aa8', 'price':10, 'quantity': 5, 'category': ['cat', 'animal'] },
]);
```
<p>I'm trying to make a query with this result (or something like it):</p>
<pre class="lang-js prettyprint-override"><code>[
  { ['animal', 'dog'],  125 },
  { ['animal', 'cat'],  100 },
  { ['coffe', 'cake'],  100 },
  { ['coffe', 'snack'],  70 },
  { ['coffe'],           20 }
]
</code>```

Meaning that it is:

Grouped by category.

The category is treated as a set (i.e. order is not important).

The result is sorted by price*quantity per unique category 'set'.

I've tried everything I know (which is very limited) and googled for days without getting anywhere.
Is this even possible in an aggregate query or do I have find a different way?

答:
```<code>db.collection.aggregate([
  {
    "$match": {}
  },
  {
    "$group": {
      "_id": {
        $function: {
          body: "function(arr) { return arr.sort((a,b) => a.localeCompare(b))}",
          args: [ "$category" ],
          lang: "js"
        }
      },
      "sum": {
        "$sum": { "$multiply": [ "$price", "$quantity" ] }
      }
    }
  },
  {
    "$sort": { sum: -1 }
  }
])
</code>```

mongoplayground

In mongodb 5.2 version you can use $sortArray instead of function sort that I used.

Title: Is this query possible in MongoDB?

Body:
Imagine a data set like this:

db.test.insertMany([
  { '_id':1, 'name':'aa1', 'price':10, 'quantity': 2, 'category': ['coffe'] },
  { '_id':2, 'name':'aa2', 'price':20, 'quantity': 1, 'category': ['coffe', 'snack'] },
  { '_id':3, 'name':'aa3', 'price':5,  'quantity':10, 'category': ['snack', 'coffe'] },
  { '_id':4, 'name':'aa4', 'price':5,  'quantity':20, 'category': ['coffe', 'cake'] },
  { '_id':5, 'name':'aa5', 'price':10, 'quantity':10, 'category': ['animal', 'dog'] },
  { '_id':6, 'name':'aa6', 'price':5,  'quantity': 5, 'category': ['dog', 'animal'] },
  { '_id':7, 'name':'aa7', 'price':5,  'quantity':10, 'category': ['animal', 'cat'] },
  { '_id':8, 'name':'aa8', 'price':10, 'quantity': 5, 'category': ['cat', 'animal'] },
]);

I'm trying to make a query with this result (or something like it):

[
  { ['animal', 'dog'],  125 },
  { ['animal', 'cat'],  100 },
  { ['coffe', 'cake'],  100 },
  { ['coffe', 'snack'],  70 },
  { ['coffe'],           20 }
]

Meaning that it is:

Grouped by category.

The category is treated as a set (i.e. order is not important).

The result is sorted by price*quantity per unique category 'set'.

I've tried everything I know (which is very limited) and googled for days without getting anywhere.
Is this even possible in an aggregate query or do I have find a different way?

Body:
db.collection.aggregate([
  {
    "$match": {}
  },
  {
    "$group": {
      "_id": {
        $function: {
          body: "function(arr) { return arr.sort((a,b) => a.localeCompare(b))}",
          args: [ "$category" ],
          lang: "js"
        }
      },
      "sum": {
        "$sum": { "$multiply": [ "$price", "$quantity" ] }
      }
    }
  },
  {
    "$sort": { sum: -1 }
  }
])

mongoplayground

In mongodb 5.2 version you can use $sortArray instead of function sort that I used.


问:
How to Measure Similarity or Difference of Meaning Between Words?
Say you have two random words ('yellow' and 'ambient' or 'goose' and 'kettle'). What tech could be used to rate how similar or different they are in meaning as informed by popular usage? For example, from 0 to 1 where antonyms are 0 and synonyms are 1, 'yellow' and 'ambient' might be 0.65 similar.

Note: I'm not talking about how close the two strings are to each other, but rather an approximation of how similar their meanings are.

答:
I do not really understand what you exactly mean with similarity especially if you want to talk about meaning. You would need a dataset to denote meaning unto words. A popular example of this would be sentiment analysis. If you got a lot of textual data, say tweets from twitter, you might want to know if the data is mostly positive or negative. To do this you would find a dataset of similar nature who has labelled the data already into categories. Then you can use this data to classify the texts into categories (e.g with a Naive Bayes classifier). In this way you can denote meaning on texts computationally.

This would allow general evaluations but also evaluations on an input to input basis on how well they scored across different categories of meaning.

I'm not sure if that's what you're looking for in an answer though.


问:
How to handle an interval play pause stop in javascript or nodejs?
I have a main file that acts like an API to manage the playing, resuming or a video.

main.js

const { mainModule } = require('process');
const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js');

function init(payload) {
    if(payload.type === 'play') {
        handlePlayVideo(payload.data)
    } else if(payload.type === 'pause') {
        handlePauseVideo(payload.data);
    } else if(payload.type === 'stop') {
        handleStopVideo(payload.data);
    }
}

function handlePlayVideo(data) {
    startVideo(data).then(() => {
        console.log('Video state: play');
    });
}

function handlePauseVideo(data) {
    pauseVideo().then(() => {
        console.log('Video state: pause');
    });
}

function handleStopVideo(data) {
    stopVideo().then(() => {
        console.log('Video state: stop');
    });
}```
</div>
</div>
</p>
<p>I want to be able to use the data every second when the state(<code>payload.type</code>) is 'play'. That would start my interval, but I'm stuck on how to be able to pause it (then continue later from the same second), or stop it.</p>
<p>This is what I've tried:
<code>video.js</code></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>module.exports = (function () {
    let currentSecond = 0;
    let videoIsPaused = false;
    let videoIsStopped = false;

    function startVideo(data) {
        const videoTicker = setInterval(() => {

            if(videoIsPaused || videoIsStopped) {
                console.log('video is paused or stopped');
                clearInterval(videoTicker);
                if(videoIsStopped) currentSecond = 0;
            }

            parseVideo(data.someData, currentSecond);
            if(currentSecond === 100) clearInterval(scenarioTicker);
            currentSecond++;
        }, 1000);
    }

    function pauseVideo() {
        videoIsPaused = true;
    }

    function videoIsStopped() {
        videoIsStopped = true;
    }

    function parseVideo(data) {
        // do something (stream) the data every second, except when the video is paused, or stopped
    }
})();</code>```

With this code, the startVideo method starts executing every second, but I cannot pause it.

Update:
The starting of the video has been started(tested) using cli (ex. node main.js), which started the execution of start video for let's say one minute. In the same time, I'm opening a second cmd window, where I try to call the pauseVideo of the first window. So I think that my issue is because of the separate window environments which acts like a different scope, and I assume that my calls cannot interact with each other in this way. Is there a better way of doing/testing this?

答:
In your if statement for the paused/stopped condition, you're not stopping the execution of the rest of the function. Therefore, the parts below it, like increasing currentSecond will still be hit. Perhaps an early return is what you need:

```<code>if(videoIsPaused || videoIsStopped) {
  console.log('video is paused or stopped');
  clearInterval(videoTicker);
  if(videoIsStopped) currentSecond = 0;
  return;
}
</code>```

Body:
I have a main file that acts like an API to manage the playing, resuming or a video.

main.js

const { mainModule } = require('process');
const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js');

function init(payload) {
    if(payload.type === 'play') {
        handlePlayVideo(payload.data)
    } else if(payload.type === 'pause') {
        handlePauseVideo(payload.data);
    } else if(payload.type === 'stop') {
        handleStopVideo(payload.data);
    }
}

function handlePlayVideo(data) {
    startVideo(data).then(() => {
        console.log('Video state: play');
    });
}

function handlePauseVideo(data) {
    pauseVideo().then(() => {
        console.log('Video state: pause');
    });
}

function handleStopVideo(data) {
    stopVideo().then(() => {
        console.log('Video state: stop');
    });
}

I want to be able to use the data every second when the state(payload.type) is 'play'. That would start my interval, but I'm stuck on how to be able to pause it (then continue later from the same second), or stop it.

This is what I've tried:
video.js

module.exports = (function () {
    let currentSecond = 0;
    let videoIsPaused = false;
    let videoIsStopped = false;

    function startVideo(data) {
        const videoTicker = setInterval(() => {

            if(videoIsPaused || videoIsStopped) {
                console.log('video is paused or stopped');
                clearInterval(videoTicker);
                if(videoIsStopped) currentSecond = 0;
            }

            parseVideo(data.someData, currentSecond);
            if(currentSecond === 100) clearInterval(scenarioTicker);
            currentSecond++;
        }, 1000);
    }

    function pauseVideo() {
        videoIsPaused = true;
    }

    function videoIsStopped() {
        videoIsStopped = true;
    }

    function parseVideo(data) {
        // do something (stream) the data every second, except when the video is paused, or stopped
    }
})();

With this code, the startVideo method starts executing every second, but I cannot pause it.

Update:
The starting of the video has been started(tested) using cli (ex. node main.js), which started the execution of start video for let's say one minute. In the same time, I'm opening a second cmd window, where I try to call the pauseVideo of the first window. So I think that my issue is because of the separate window environments which acts like a different scope, and I assume that my calls cannot interact with each other in this way. Is there a better way of doing/testing this?

Body:
In your if statement for the paused/stopped condition, you're not stopping the execution of the rest of the function. Therefore, the parts below it, like increasing currentSecond will still be hit. Perhaps an early return is what you need:

if(videoIsPaused || videoIsStopped) {
  console.log('video is paused or stopped');
  clearInterval(videoTicker);
  if(videoIsStopped) currentSecond = 0;
  return;
}


问:
Retrieving data from another column based on entries in another column within same table
I have this table.

```<code>+----+-----------+--------+----------+
| sku|  strength |  color | option_1 |
+----+-----------+--------+----------+
|  1 | 40 lb     | (NULL) | strength |
|  2 | 50 lb     | black  | color    |
|  3 | (NULL)    | black  | color    |
|  4 | (NULL)    | red    | color    |
+----+-----------+--------+----------+
</code>```

I want this table:

```<code>+----+-----------+--------+----------+----------------+
|sku | strength  | color  | option_1 | option_value_1 |
+----+-----------+--------+----------+----------------+
|  1 | 40 lb     | (NULL) | strength | 40 lb          |
|  2 | 50 lb     | black  | color    | black          |
|  3 | (NULL)    | black  | color    | black          |
|  4 | (NULL)    | red    | color    | red            |
+----+-----------+--------+----------+----------------+
</code>```

I'm new to mysql. I'm trying to do this index-match or vlookup like query where option_1 determines which column to retrieve data from and send to option_value_1. I wasn't sure if I should do an inner join or a case clause since I have a much larger table with a lot more options than just color and strength.

答:
I don't think you need a JOIN here. However, since you said there a lot more columns then it's going to be a long CASE expression to write. Also, if there's new column added then you need to remember to update the query from time to time. One way you can prevent that is using Prepare statement :

Setting variables as NULL just in case

```<code>SET @sql := NULL;
SET @columns := NULL;
</code>```

Constructing the CASE expression and assign to @columns variable:

```<code>SELECT GROUP_CONCAT(DISTINCT
        CONCAT('WHEN "',option_1,'" THEN ',option_1) SEPARATOR ' ')
         INTO @columns
FROM mytable;
</code>```

Constructing the final query by  appending the previously constructed @columns variable into the @sql variable:

```<code>SELECT CONCAT('SELECT *, CASE option_1 ',@columns,' END AS option_value_1 FROM mytable;')
        INTO @sql;
</code>```

Prepare, execute and deallocate the final generated query in @sql:

```<code>PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

To check the variables you can run:

```<code>SELECT @columns;
SELECT @sql;
</code>```

This will be good for you to test the query especially when the execution returned error; so that you can pin-point where the problem is and fix.

Note:

It's not necessary to have two variables in constructing the final query. I mean, you can just do a straight query construction to @sql by combining the @columns generating query with the @sql generating query. I personally separate them to make it easier to understand the components.

Demo fiddle

Body:
I have this table.

+----+-----------+--------+----------+
| sku|  strength |  color | option_1 |
+----+-----------+--------+----------+
|  1 | 40 lb     | (NULL) | strength |
|  2 | 50 lb     | black  | color    |
|  3 | (NULL)    | black  | color    |
|  4 | (NULL)    | red    | color    |
+----+-----------+--------+----------+

I want this table:

+----+-----------+--------+----------+----------------+
|sku | strength  | color  | option_1 | option_value_1 |
+----+-----------+--------+----------+----------------+
|  1 | 40 lb     | (NULL) | strength | 40 lb          |
|  2 | 50 lb     | black  | color    | black          |
|  3 | (NULL)    | black  | color    | black          |
|  4 | (NULL)    | red    | color    | red            |
+----+-----------+--------+----------+----------------+

I'm new to mysql. I'm trying to do this index-match or vlookup like query where option_1 determines which column to retrieve data from and send to option_value_1. I wasn't sure if I should do an inner join or a case clause since I have a much larger table with a lot more options than just color and strength.

Body:
I don't think you need a JOIN here. However, since you said there a lot more columns then it's going to be a long CASE expression to write. Also, if there's new column added then you need to remember to update the query from time to time. One way you can prevent that is using Prepare statement :

Setting variables as NULL just in case

SET @sql := NULL;
SET @columns := NULL;

Constructing the CASE expression and assign to @columns variable:

SELECT GROUP_CONCAT(DISTINCT
        CONCAT('WHEN "',option_1,'" THEN ',option_1) SEPARATOR ' ')
         INTO @columns
FROM mytable;

Constructing the final query by  appending the previously constructed @columns variable into the @sql variable:

SELECT CONCAT('SELECT *, CASE option_1 ',@columns,' END AS option_value_1 FROM mytable;')
        INTO @sql;

Prepare, execute and deallocate the final generated query in @sql:

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

To check the variables you can run:

SELECT @columns;
SELECT @sql;

This will be good for you to test the query especially when the execution returned error; so that you can pin-point where the problem is and fix.

Note:

It's not necessary to have two variables in constructing the final query. I mean, you can just do a straight query construction to @sql by combining the @columns generating query with the @sql generating query. I personally separate them to make it easier to understand the components.

Demo fiddle


问:
updating the database with single migration?
I have a table that has "projects" that have this field workspace which takes an array of strings. So I have converted this to store a single character

```<code> create table("projects") do
  add(:name, :string, null: false)
  add(:title, :string, null: false)
  add(:workspaces, {:array, :string})

  timestamps()
end
</code>```

I have written this migration to store a single string

```<code>alter table(:projects) do
      modify(:workspace, :string)
</code>```

I want to run this migration but also I want to update all the data which is stored in the database. I need to update all the workspace data to store a single string.

Suppose if workspace has this value {value1, value2}. It will look for value1 and if that is found it will store the value1 otherwise it will store value2

This is how {value1, value2} it is stored in the database table. So when we load it in elixir it looks something like this ["value1", "value2"]

What can I do here?

答:
If I understood correctly, you want to change the workspaces array column to a workspace string column that contains the first element of the array. If that is the case you can do something like this in a migration:

```<code># Add the `workspace` column:
alter table(:projects) do
  add(:workspace, :string)
end

# Set the value of the new column:
execute("""
  UPDATE projects SET workspace = CASE
    WHEN 'value1' = ANY(workspaces) THEN 'value1'
    WHEN 'value2' = ANY(workspaces) THEN 'value2'
    ELSE 'default_value'
    END
  """)

# Remove the old column
alter table(:projects) do
  remove(:workspaces)
end
</code>```

Body:
I have a table that has "projects" that have this field workspace which takes an array of strings. So I have converted this to store a single character

 create table("projects") do
  add(:name, :string, null: false)
  add(:title, :string, null: false)
  add(:workspaces, {:array, :string})

  timestamps()
end

I have written this migration to store a single string

alter table(:projects) do
      modify(:workspace, :string)

I want to run this migration but also I want to update all the data which is stored in the database. I need to update all the workspace data to store a single string.

Suppose if workspace has this value {value1, value2}. It will look for value1 and if that is found it will store the value1 otherwise it will store value2

This is how {value1, value2} it is stored in the database table. So when we load it in elixir it looks something like this ["value1", "value2"]

What can I do here?

Body:
If I understood correctly, you want to change the workspaces array column to a workspace string column that contains the first element of the array. If that is the case you can do something like this in a migration:

# Add the `workspace` column:
alter table(:projects) do
  add(:workspace, :string)
end

# Set the value of the new column:
execute("""
  UPDATE projects SET workspace = CASE
    WHEN 'value1' = ANY(workspaces) THEN 'value1'
    WHEN 'value2' = ANY(workspaces) THEN 'value2'
    ELSE 'default_value'
    END
  """)

# Remove the old column
alter table(:projects) do
  remove(:workspaces)
end


问:
How to fit UMAP object with an embedding_ property of shape (200,2)
I'm trying to take the first 200 rows of my dataframe and pass it through a UMAP fit method but I'm not able to get it to shape the way I want at (200,2). Should I add an embedding parameter?

This is the code I have so far:

```<code>def example():
    feature_names = ['beer_name','review_appearance', 'review_aroma', 'review_palate', 'review_taste', 'review_overall']
    new_df = df[feature_names]
    final_df = new_df.groupby(['beer_name']).mean()
    scaler = StandardScaler()
    scaler.fit(final_df)
    results = scaler.transform(final_df)

    X_normalized_200 = results[0:200,:]
    umap_obj = umap.UMAP(set_op_mix_ratio=0.15, random_state = 0).fit(final_df)
    output=umap_obj

    return output
</code>```

Snapshot of my dataframe:

答:
You need to use the transform method after fitting UMAP in order to get the coordinates of each point in the embedding.

def example():
    feature_names = [
        "beer_name",
        "review_appearance",
        "review_aroma",
        "review_pallete",
        "review_taste",
        "review_overall",
    ]
    new_df = df[feature_names]
    final_df = new_df.groupby(["beer_name"]).mean()
    scaler = StandardScaler()
    scaler.fit(final_df)
    results = scaler.transform(final_df)

    X_normalized_200 = results[0:200, :]
    umap_obj = umap.UMAP(set_op_mix_ratio=0.15, random_state=0).fit(final_df)
    output = umap_obj.transform(X_normalized_200)  # missing this line

    return output
```

Body:
I'm trying to take the first 200 rows of my dataframe and pass it through a UMAP fit method but I'm not able to get it to shape the way I want at (200,2). Should I add an embedding parameter?

This is the code I have so far:

def example():
    feature_names = ['beer_name','review_appearance', 'review_aroma', 'review_palate', 'review_taste', 'review_overall']
    new_df = df[feature_names]
    final_df = new_df.groupby(['beer_name']).mean()
    scaler = StandardScaler()
    scaler.fit(final_df)
    results = scaler.transform(final_df)

    X_normalized_200 = results[0:200,:]
    umap_obj = umap.UMAP(set_op_mix_ratio=0.15, random_state = 0).fit(final_df)
    output=umap_obj

    return output

Snapshot of my dataframe:


问:
Can a localhost directly lead to an html file?
total newbie to HTML here. I set up my localhost with an html file but i have to acess it with localhost:8080/filename.html. is there a way to access it directly with localhost:8080?</p>

答:
Depending on your operating envionment you should be able to accomplish this with an htaccess file. In your root directory create a file named .htaccess

Add this code:

```<code>RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
DirectoryIndex filename.html
</code>```

Body:
Depending on your operating envionment you should be able to accomplish this with an htaccess file. In your root directory create a file named .htaccess

Add this code:

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
DirectoryIndex filename.html


问:
Bound cell formula to a sorted table
I have a table at A1:C5 and also formula at H50 =C1+C2 and H51 =C3+C4+C5

How can I sort the table by column B without messing up H50 and H51? (I want that the formulas will be 'bound' to the cells even if the row position is changing)

Thanks.

答: Since you only have a few cells in the formulas, you can assign each cell in range C1 to C5 individual range names, then use these names in the formulas in H50 and H51. By addressing the cells with their name, the result will not change when the named cell changes position.</p>

Title: Bound cell formula to a sorted table


问:
Use a function declared in `mod.rs` in the same directory
I have a directory that looks like this:

```<code>tests /
|_mod.rs
|_common.rs
</code>```

Inside mod.rs I have a number of functions like e.g. hash that I am trying to use inside common.rs.

I tried doing this by having use self::mod::hash but it does not seem to work. How can I include and use the functions inside mod.rs in other files of the same directory?

Note: I have changed the structure currently, having all the functions I need to use inside an utils module and using that instead. I am just curious as to why it was not working.

答:
The name “mod” is purely a name for the file, and not at all a module name (just like lib.rs does not define a module named lib), so a path containing ::mod:: is never meaningful. Rather, the file src/tests/mod.rs provides the contents of a module named tests (or crate::tests).

So, assuming that src/tests/mod.rs contains mod common; as is normal, the way src/tests/common.rs refers to a function hash defined inside src/tests/mod.rs is as super::hash or crate::tests::hash.

Body:
I have a directory that looks like this:

tests /
|_mod.rs
|_common.rs

Inside mod.rs I have a number of functions like e.g. hash that I am trying to use inside common.rs.

I tried doing this by having use self::mod::hash but it does not seem to work. How can I include and use the functions inside mod.rs in other files of the same directory?

Note: I have changed the structure currently, having all the functions I need to use inside an utils module and using that instead. I am just curious as to why it was not working.


问:
Checking if an integer contains a certain digit in a for loop
I am trying to solve this problem:

Write a code which computes the sum = 1/1 + ... 1/6 + 1/8 + ... +1/16 +... from 1 to 10000, skipping over the integers that contain the number 7.

Here is my code so far, I am stuck on trying to skip over the integers that contain the digit 7.

```<code>def int():
 sum=0
 for i in range(10000):
    if # integer contains digit==7:
        continue
    sum += 1/i
 return sum
</code>```

答:
```<code>def int():

    sum=0
    for i in range(1,10000): # make sure range is from 1 to whatever. Otherwise, you'll a ZeroDivisionError
        if '7' in str(i): #convert i to string
            continue
        sum += 1/i
    return sum
print(int())
</code>```

Body:
I am trying to solve this problem:

Write a code which computes the sum = 1/1 + ... 1/6 + 1/8 + ... +1/16 +... from 1 to 10000, skipping over the integers that contain the number 7.

Here is my code so far, I am stuck on trying to skip over the integers that contain the digit 7.

def int():
 sum=0
 for i in range(10000):
    if # integer contains digit==7:
        continue
    sum += 1/i
 return sum


问:
Is it possible to filter the correct values in the geom_histogram function for my shiny app?
The values that I want to plot and the values for the sideBarpanel are in the same column. I prefer to work with a long table instead of wide table.

Is it possible to filter the correct values in the geom_histogram function?

```<code>library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(readxl)
library(dplyr)

Survey <- read_excel("~/EIGSI/Project/Work files for R studio/04_Participant.xlsx")
Question <- read_excel("~/EIGSI/Project/Work files for R studio/02_Question.xlsx")

Data <- Survey

Data <- Data %>%
  gather(key = "Question",
         value = "Answer",
         -Id)

Data <- Data %>%
  right_join(Question, by=c("Question" = "question_ID"))

names(Data)

Data <- Data %>%
  relocate(question_group_ID, .after = Id)

Data <- Data %>%
  relocate(question_group_text, .after = question_group_ID)

Data <- Data %>%
  relocate(question_text, .after = Question)

#APP STARTS HERE

# ui.R ----
ui <- fluidPage(
  titlePanel("Departure times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 selectInput("Answer", "Select mode", choices = c("On foot"="On foot",
                                                                "Bicycle" = "Bicycle",
                                                                "Bicycle (Yélo)"="Bicycle (Yélo)",
                                                                "Motorcycle/scooter"="Motorcycle/scooter",
                                                                "Scooter (trotinette)"="Scooter (trotinette)",
                                                                "Bus"="Bus",
                                                                "Train" = "Train",
                                                                "Car" = "Car",
                                                                "Carpool"="Carpool",
                                                                "Car (Yélo)"= "Car (Yélo)"),
                                                                 selected = "Car"),
                 br(),

    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  Data %>%
    filter(question_group_ID == "QG3") %>%
    ggplot(aes(x=Answer))+
    geom_histogram(stat = "count", data = Data[Data$Answer== input$Answer,])

}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

This is my table Data shown with the head function:

```<code> Id Question Answer
  <dbl> <chr>    <chr>
1    54 Q1       No
2   132 Q1       No
3   498 Q1       No
4   600 Q1       No
5   620 Q1       No
6   951 Q1       No
</code>```

答:
Yes, you can.  You need to render the plot in an output object as shown below.</p>
```<code>df <- mtcars

ui <- fluidPage(
  titlePanel("Departure times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 selectInput("Answer", "Select mode", choices = unique(df$cyl)),
                 br()
    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  output$myhist <- renderPlot({
    df %>% dplyr::filter(vs==1) %>%
      ggplot(aes(x=carb)) +
      geom_histogram(stat = "count", data = df[df$cyl == input$Answer,])
  })

}

# Run the app ----
shinyApp(ui = ui, server = server)
</code>```

Body:
The values that I want to plot and the values for the sideBarpanel are in the same column. I prefer to work with a long table instead of wide table.

Is it possible to filter the correct values in the geom_histogram function?

library(shiny)
library(ggplot2)
library(dplyr)
library(tidyverse)
library(readxl)
library(dplyr)

Survey <- read_excel("~/EIGSI/Project/Work files for R studio/04_Participant.xlsx")
Question <- read_excel("~/EIGSI/Project/Work files for R studio/02_Question.xlsx")

Data <- Survey

Data <- Data %>%
  gather(key = "Question",
         value = "Answer",
         -Id)

Data <- Data %>%
  right_join(Question, by=c("Question" = "question_ID"))

names(Data)

Data <- Data %>%
  relocate(question_group_ID, .after = Id)

Data <- Data %>%
  relocate(question_group_text, .after = question_group_ID)

Data <- Data %>%
  relocate(question_text, .after = Question)

#APP STARTS HERE

# ui.R ----
ui <- fluidPage(
  titlePanel("Departure times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 selectInput("Answer", "Select mode", choices = c("On foot"="On foot",
                                                                "Bicycle" = "Bicycle",
                                                                "Bicycle (Yélo)"="Bicycle (Yélo)",
                                                                "Motorcycle/scooter"="Motorcycle/scooter",
                                                                "Scooter (trotinette)"="Scooter (trotinette)",
                                                                "Bus"="Bus",
                                                                "Train" = "Train",
                                                                "Car" = "Car",
                                                                "Carpool"="Carpool",
                                                                "Car (Yélo)"= "Car (Yélo)"),
                                                                 selected = "Car"),
                 br(),

    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  Data %>%
    filter(question_group_ID == "QG3") %>%
    ggplot(aes(x=Answer))+
    geom_histogram(stat = "count", data = Data[Data$Answer== input$Answer,])

}

# Run the app ----
shinyApp(ui = ui, server = server)

This is my table Data shown with the head function:

 Id Question Answer
  <dbl> <chr>    <chr>
1    54 Q1       No
2   132 Q1       No
3   498 Q1       No
4   600 Q1       No
5   620 Q1       No
6   951 Q1       No

Body:
Yes, you can.  You need to render the plot in an output object as shown below.

df <- mtcars

ui <- fluidPage(
  titlePanel("Departure times"),  # Add a title panel
  sidebarLayout(
    position = "right",

    sidebarPanel(h3("Inputs for histogram"),
                 selectInput("Answer", "Select mode", choices = unique(df$cyl)),
                 br()
    ),

    # Inside the sidebarLayout, add a sidebarPanel
    mainPanel(
      plotOutput("myhist")

    )
  )
)

# server.R ----
server <- function(input, output) {

  output$myhist <- renderPlot({
    df %>% dplyr::filter(vs==1) %>%
      ggplot(aes(x=carb)) +
      geom_histogram(stat = "count", data = df[df$cyl == input$Answer,])
  })

}

# Run the app ----
shinyApp(ui = ui, server = server)


问:
Is there a way to return one specific table from a webpage that has multiple tables in Python?
I'm having trouble returning one particular table (the one titled 'BRN Substantial Shareholders') from this webpage - https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd

I'm able to return all the tables using the below code.

```<code>html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
all_tables = soup.find_all('table')
</code>```

I've tried two different methods to try and scrape using bs but I can't seem to find a way - am I doing something wrong? Both of these output an empty list.

Method 1

```<code># Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

sub_headers = []
sub_holdings = []

for found_table in soup.find_all('table', class_=f'{ticker_code} + "Substantial Shareholders"'):
    sub_headers = found_table.find_all('th').append(sub_headers)
    sub_holdings = found_table.find_all('td').append(sub_holdings)

print(sub_headers)
print(sub_holdings)
</code>```

Method 2

```<code># Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

all_headers = soup.find_all("th", class_=f"{ticker_code} Substantial Shareholders")
all_holdings = soup.find_all("tr", class_=f"{ticker_code} Substantial Shareholders")

sub_headers = []
sub_holdings = []

for header in all_headers:
    sub_headers.append(header.text)

for holding in all_holdings:
    holding.append(sub_holdings.text)

print(sub_headers)
print(sub_holdings)
</code>```

答:
To only scrape the table with the words "BRN Substantial Shareholders", you can use a CSS selector to locate that table with:

```<code>table = soup.select_one("div:nth-of-type(11) table")
</code>```

Body:
I'm having trouble returning one particular table (the one titled 'BRN Substantial Shareholders') from this webpage - https://www.intelligentinvestor.com.au/shares/asx-brn/brainchip-holdings-ltd

I'm able to return all the tables using the below code.

html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')
all_tables = soup.find_all('table')

I've tried two different methods to try and scrape using bs but I can't seem to find a way - am I doing something wrong? Both of these output an empty list.

Method 1

# Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

sub_headers = []
sub_holdings = []

for found_table in soup.find_all('table', class_=f'{ticker_code} + "Substantial Shareholders"'):
    sub_headers = found_table.find_all('th').append(sub_headers)
    sub_holdings = found_table.find_all('td').append(sub_holdings)

print(sub_headers)
print(sub_holdings)

Method 2

# Scrape the substantial holder list
html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

all_headers = soup.find_all("th", class_=f"{ticker_code} Substantial Shareholders")
all_holdings = soup.find_all("tr", class_=f"{ticker_code} Substantial Shareholders")

sub_headers = []
sub_holdings = []

for header in all_headers:
    sub_headers.append(header.text)

for holding in all_holdings:
    holding.append(sub_holdings.text)

print(sub_headers)
print(sub_holdings)

Body:
To only scrape the table with the words "BRN Substantial Shareholders", you can use a CSS selector to locate that table with:

table = soup.select_one("div:nth-of-type(11) table")


问:
dos batch iterate through a delimited string
I have a delimited list of IPs I'd like to process individually.  The list length is unknown ahead of time.  How do I split and process each item in the list?

```<code>@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

FOR /f "tokens=* delims=," %%a IN ("%servers%") DO call :sub %%a

:sub
    echo In subroutine
    echo %1
exit /b
</code>```

Outputs:

```<code>In subroutine
127.0.0.1
In subroutine
ECHO is off.
</code>```

Update:
Using Franci's answer as reference, here's the solution:

```<code>@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

call :parse "%servers%"
goto :end

:parse
setlocal
set list=%1
set list=%list:"=%
FOR /f "tokens=1* delims=," %%a IN ("%list%") DO (
  if not "%%a" == "" call :sub %%a
  if not "%%b" == "" call :parse "%%b"
)
endlocal
exit /b

:sub
setlocal
echo In subroutine
echo %1
endlocal
exit /b

:end
</code>```

Outputs:

```<code>In subroutine
127.0.0.1
In subroutine
192.168.0.1
In subroutine
10.100.0.1
</code>```

答:
This is a generalisation of Franci's solution, so that you can perform any job on each item in your list, without having copies of the list iteration code.

```
:list_iter
    rem Usage: call :list_iter :do_sub_for_each_item "CSV of items"
    set foo=%1
    set list=%~2
    for /f "tokens=1* delims=," %%i in ("%list%") do (
        call %foo% %%i
        if not "%%j" == "" ( call :list_iter %foo% "%%j" )
    )
    exit /b
```

Eg, you can call it by:

```
call :list_iter :my_foo "one,two,three"
call :list_iter :my_bar "sun,poo,wee"
```

ContentLicense: CC BY-SA 2.5

Body:
I have a delimited list of IPs I'd like to process individually.  The list length is unknown ahead of time.  How do I split and process each item in the list?

@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

FOR /f "tokens=* delims=," %%a IN ("%servers%") DO call :sub %%a

:sub
    echo In subroutine
    echo %1
exit /b

Outputs:

In subroutine
127.0.0.1
In subroutine
ECHO is off.

Update:
Using Franci's answer as reference, here's the solution:

@echo off
set servers=127.0.0.1,192.168.0.1,10.100.0.1

call :parse "%servers%"
goto :end

:parse
setlocal
set list=%1
set list=%list:"=%
FOR /f "tokens=1* delims=," %%a IN ("%list%") DO (
  if not "%%a" == "" call :sub %%a
  if not "%%b" == "" call :parse "%%b"
)
endlocal
exit /b

:sub
setlocal
echo In subroutine
echo %1
endlocal
exit /b

:end

Outputs:

In subroutine
127.0.0.1
In subroutine
192.168.0.1
In subroutine
10.100.0.1

Body:
This is a generalisation of Franci's solution, so that you can perform any job on each item in your list, without having copies of the list iteration code.

:list_iter
    rem Usage: call :list_iter :do_sub_for_each_item "CSV of items"
    set foo=%1
    set list=%~2
    for /f "tokens=1* delims=," %%i in ("%list%") do (
        call %foo% %%i
        if not "%%j" == "" ( call :list_iter %foo% "%%j" )
    )
    exit /b

Eg, you can call it by:

call :list_iter :my_foo "one,two,three"
call :list_iter :my_bar "sun,poo,wee"


问:
datediff and Excel not matching
Any ideas why R is adding 2 days to an Excel date?

Details:
I am importing an Excel file with openxlx using the code:

```<code>wb.temp <- loadWorkbook(filename)
data.import <- read.xlsx (wb.temp, sheet = 1, startRow = 3, colNames = TRUE, na.strings = "NA", detectDates = FALSE)
</code>```

(detectDates = TRUE gives an error although all dates in the XLSX look ok)

The xlsx files had some values for the field Event_Date of "2022-02-07"

R imported these dates as 44599

However, when I ran the following r-code to convert these dates to yyyy-mm-dd:

```<code>data.import$Event_Date <- as.Date(import.temp$Event_Date, origin = '1900-01-01')
</code>```

data.import$Event_Date took the value of "2022-02-09" when inputting  44599

As a check:

difftime("2022-02-07","1900-01-01") yields 44597

So, why R is adding 2 days to an Excel date during the data import?

thanks

bob

答:
Thanks much; I found another solution.

Instead of using the R as.date, the xlsx::convertToDate solves it using:

```<code>data.temp$Event_Date <- openxlsx::convertToDate(data.temp$Event_Date, origin = '1900-01-01')
</code>```

https://rdrr.io/cran/openxlsx/man/convertToDate.html

Title: datediff and Excel not matching

Body:
Any ideas why R is adding 2 days to an Excel date?

Details:
I am importing an Excel file with openxlx using the code:

wb.temp <- loadWorkbook(filename)
data.import <- read.xlsx (wb.temp, sheet = 1, startRow = 3, colNames = TRUE, na.strings = "NA", detectDates = FALSE)

(detectDates = TRUE gives an error although all dates in the XLSX look ok)

The xlsx files had some values for the field Event_Date of "2022-02-07"

R imported these dates as 44599

However, when I ran the following r-code to convert these dates to yyyy-mm-dd:

data.import$Event_Date <- as.Date(import.temp$Event_Date, origin = '1900-01-01')

data.import$Event_Date took the value of "2022-02-09" when inputting  44599

As a check:

difftime("2022-02-07","1900-01-01") yields 44597

So, why R is adding 2 days to an Excel date during the data import?

thanks

bob

Body:
Thanks much; I found another solution.

Instead of using the R as.date, the xlsx::convertToDate solves it using:

data.temp$Event_Date <- openxlsx::convertToDate(data.temp$Event_Date, origin = '1900-01-01')

https://rdrr.io/cran/openxlsx/man/convertToDate.html


问:
Google Sheets query pivot multiple values
I am trying to use a Query to replicate the behaviour pictured below. I have a pivot table with two values (as rows) displaying a job name and it's status. This works fine with the built-in pivot table.

Sample Data:

Resulting pivot table:

I've then tried to recreate this using the following Query formula:

=QUERY(A1:D6, " select C, max(A), max(D) GROUP BY C PIVOT B Order by C  ")

This gives me the result below. This is as close as I've managed to get to replicating the original pivot table.

Edit

The main part of this question has been solved below but I'm wondering how to extend this out if I had more columns of data that I then wanted to display in the same way. Below I have added an additional column 'Other'.

New data:

New desired result:


问:
Max width is not working on a input wrapped Inside a Div?
Hi I created a Search Bar and wrapped it inside a div and have given it the max-width of 500px (100% with to the search Input) but don't know why max width is not working and I search the Stack Overflow and found a link Why would max-width not work on this? and tried this but it didn't worked for me

So can anyone please tell me why its not working and how to make it work :)

Any kind of help is highly Appreciated

*{
  margin: 0;
  padding: 0;
  box-sizing:border-box;
}
body{
  font-family:arial;
}
header{
  width: 100%;
  padding:20px 20px;
}
nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}
.menu-container{
  display:flex;
  justify-content:space-between;
  align-items:center;
  position:relative;
}
.search-input-container{
  width:100%;
  max-width:500px;
}
input[type="search"]{
  border-radius:500px;
  padding:5px 10px;
  width:100%;
}

ul li{
  list-style:none;
}
ul{
  margin:10px;
}
button{
  outline:none;
  border:none;
  padding:8px 15px;
}

a{
  text-decoration:none;
}
.submenu-items{
  position:absolute;
  top:100%;
  border:2px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <header>
    <nav>

      <!--  Logo Wrapper -->
      <div class="logo">
        <img src="" alt="Test Logo">
      </div>

      <!--  Search Wrapper || Issue Area-->
      <div class="search-container">

        <form action="get">

          <div class="search-input-container">

            <input type="search" class="search">

          </div>

        </form>

      </div>
      <!--  Search Wrapper Ends ↑ -->

      <div class="menu-container">
        <ul>

          <li>
            Help

          </li>

        </ul>
        <ul>
          <li>
            Campagians
          </li>
        </ul>
      </div>

      <div class="buttons-container">
        <button class="Login-btn">Log in</button>

        <button class="signup-btn">Sign up</button>

      </div>

    </nav>
  </header>
</body>

</html></code>```

答:
Instead of max-width, try using width: clamp() (MDN)

I think in your case it would be something like:

.search-input-container {
  width: clamp(150px, 400px, 500px);
}
```

Here 150px is the minimal size,
400px - is the ideal size, that the element wants to be,
and 500px - is the maximum possible size. so it can't grow bigger then that.

That way the input will try to be 400px, but if there is no space - it will shrink down up to 150px.

Body:
Hi I created a Search Bar and wrapped it inside a div and have given it the max-width of 500px (100% with to the search Input) but don't know why max width is not working and I search the Stack Overflow and found a link Why would max-width not work on this? and tried this but it didn't worked for me

So can anyone please tell me why its not working and how to make it work :)

Any kind of help is highly Appreciated

*{
  margin: 0;
  padding: 0;
  box-sizing:border-box;
}
body{
  font-family:arial;
}
header{
  width: 100%;
  padding:20px 20px;
}
nav{
  display:flex;
  justify-content:space-between;
  align-items:center;
}
.menu-container{
  display:flex;
  justify-content:space-between;
  align-items:center;
  position:relative;
}
.search-input-container{
  width:100%;
  max-width:500px;
}
input[type="search"]{
  border-radius:500px;
  padding:5px 10px;
  width:100%;
}

ul li{
  list-style:none;
}
ul{
  margin:10px;
}
button{
  outline:none;
  border:none;
  padding:8px 15px;
}

a{
  text-decoration:none;
}
.submenu-items{
  position:absolute;
  top:100%;
  border:2px solid red;
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

        <form action="get">

            <input type="search" class="search">

        </form>

            Help

            Campagians

        <button class="Login-btn">Log in</button>

        <button class="signup-btn">Sign up</button>

Body:
Instead of max-width, try using width: clamp() (MDN)

I think in your case it would be something like:

.search-input-container {
  width: clamp(150px, 400px, 500px);
}

Here 150px is the minimal size,
400px - is the ideal size, that the element wants to be,
and 500px - is the maximum possible size. so it can't grow bigger then that.

That way the input will try to be 400px, but if there is no space - it will shrink down up to 150px.


问:
Function is Extremely slow with 700K Rows Data
Using below function which performs well on short data but whenever i move on large data set it takes long time to processing and sometime stuck.

I would appreciate if there could be another faster way to perfrom this.

```<code>Sub minustozeo()
Dim c As Range
For Each c In Selection.SpecialCells(xlCellTypeVisible)
 If c.Value < 0 Then
 c.Value = 0
 End If
Next
End Sub
</code>```

答:
Here's a faster method using the array approach:

Sub Tester()

    Dim ws As Worksheet, c As Range, t, rngVis As Range, rngVals As Range
    Dim arr, r As Long

    Set ws = ActiveSheet
    Set rngVals = ws.Range("A2:A500000") 'range to operate on

    'create some dummy data with about 70% < 0
    If ws.FilterMode Then ws.ShowAllData
    With rngVals
        .Formula = "=RAND()-0.7"
        .Value = .Value
    End With

    rngVals.Copy rngVals.Offset(, 2) 'for verification only...

    'autofilter
    rngVals.AutoFilter Field:=1, Criteria1:="<0", Operator:=xlAnd

    On Error Resume Next
    Set rngVis = rngVals.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    If rngVis Is Nothing Then Exit Sub 'no cells found

    Debug.Print rngVis.Cells.Count 'approx 350k

    t = Timer
    arr = rngVals.Value 'read the data
    For Each c In rngVis.Cells
        If c.Value < 0 Then arr(c.Row - 1, 1) = 0 ' -1 because first array value is from row #2
    Next c
    rngVals.Value = arr     'write the altered data back
    Debug.Print Timer - t   ' ~1 sec

    ws.ShowAllData

End Sub
```

Body:
Using below function which performs well on short data but whenever i move on large data set it takes long time to processing and sometime stuck.

I would appreciate if there could be another faster way to perfrom this.

Sub minustozeo()
Dim c As Range
For Each c In Selection.SpecialCells(xlCellTypeVisible)
 If c.Value < 0 Then
 c.Value = 0
 End If
Next
End Sub


问:
How to define and populate a data transfer object from sql in EF5 core?
I am used to DBSet mapping to a blog table in the database
But looking at the .FromSqlRaw docs it seems it need not.
For example

```<code>var blogs = context.Blogs
    .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogs")
    .ToList();
</code>```

Suppose I don't actually want a blogs table in the database.
Do I still create a DbSet for one so that I can define my data transfer object?

I have been using an alternative method that makes use of DbDataReader with a mapping

```<code>Func<DbDataReader, T> map
</code>```

But the catch is that I then need to refer to the ordinal of the properties
For example

```<code>var results = MyDataHelpers.RawSqlQuery( sql, x => new Dto
{
     Id = x.GetInt16(0),
     Name = x.GetString(1)
}  ).
</code>```

I don't want to do this ( or use reflection or automapper as a work around) so this question is not a duplicate of Raw Sql without DbSet

I don't mind DbSet per se but how do I do that when there is no table?

[Update]

I tried the following test

```<code>    [TestMethod]
    public void T040_DbSetForDto()
    {
        var db = DataHelpers.MakeDbContext();
        var temps = db.DtoInts.FromSqlRaw("select top 1 Id from mytable").ToList();
        Assert.IsTrue(temps.Any());
    }
</code>```

with the DBContext containing

```<code> public DbSet<DtoTempInt> DtoTempInts { get; set; }
</code>```

and

```<code>public class DtoTempInt
{
    [NotMapped]
    public int Id { get; set; }
}
</code>```

and OnModelCreating containing

```<code>modelBuilder.Entity<DtoTempInt>().HasNoKey();

</code>```

However the test fails with

```<code> Message:
Test method TestProject1.UnitTest1.T040_DbSetForDto threw exception:
System.InvalidOperationException: Sequence contains no elements

  Stack Trace:
ThrowHelper.ThrowNoElementsException()
Enumerable.Max(IEnumerable`1 source)
ShaperProcessingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
BinaryExpression.Accept(ExpressionVisitor visitor)
ExpressionVisitor.Visit(Expression node)
ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
ExpressionVisitor.VisitBlock(BlockExpression node)
BlockExpression.Accept(ExpressionVisitor visitor)
ExpressionVisitor.Visit(Expression node)
ShaperProcessingExpressionVisitor.VisitExtension(Expression extensionExpression)
<8 more frames...>
Database.CompileQuery[TResult](Expression query, Boolean async)
QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
<>c__DisplayClass9_0`1.<Execute>b__0()
CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
QueryCompiler.Execute[TResult](Expression query)
EntityQueryProvider.Execute[TResult](Expression expression)
EntityQueryable`1.GetEnumerator()
List`1.ctor(IEnumerable`1 collection)
Enumerable.ToList[TSource](IEnumerable`1 source)
</code>```

I am using net5.0 and

```<code>   <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.13" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.13" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.13" />
</code>```

答:
The following works

```<code>[TestClass]
public class UnitTest1
{
        [TestMethod]
        public void T040_DbSetForDto()
        {
            var db = DataHelpers.MakeDbContext();
            var temps = db.DtoInts.FromSqlRaw("select top 1 Id from mytable").ToList();

            Assert.IsTrue(temps.Any());
            var temp = temps.FirstOrDefault();
            Trace.WriteLine($"First id is {temp.Id}");
        }
}
</code>```

My error message  may have been that I had put a [NotMapped] tag on the Id property.
It was also important to have

```<code>modelBuilder.Entity<DtoTempInt>().HasNoKey();
</code>```

in OnModelCreating

I was also thinking that DbSet should only be used for actual data tables, but this is not true.

Body:
I am used to DBSet mapping to a blog table in the database
But looking at the .FromSqlRaw docs it seems it need not.
For example

var blogs = context.Blogs
    .FromSqlRaw("EXECUTE dbo.GetMostPopularBlogs")
    .ToList();

Suppose I don't actually want a blogs table in the database.
Do I still create a DbSet for one so that I can define my data transfer object?

I have been using an alternative method that makes use of DbDataReader with a mapping

Func<DbDataReader, T> map

But the catch is that I then need to refer to the ordinal of the properties
For example

var results = MyDataHelpers.RawSqlQuery( sql, x => new Dto
{
     Id = x.GetInt16(0),
     Name = x.GetString(1)
}  ).

I don't want to do this ( or use reflection or automapper as a work around) so this question is not a duplicate of Raw Sql without DbSet

I don't mind DbSet per se but how do I do that when there is no table?

[Update]

I tried the following test

    [TestMethod]
    public void T040_DbSetForDto()
    {
        var db = DataHelpers.MakeDbContext();
        var temps = db.DtoInts.FromSqlRaw("select top 1 Id from mytable").ToList();
        Assert.IsTrue(temps.Any());
    }

with the DBContext containing

 public DbSet<DtoTempInt> DtoTempInts { get; set; }

and

public class DtoTempInt
{
    [NotMapped]
    public int Id { get; set; }
}

and OnModelCreating containing

modelBuilder.Entity<DtoTempInt>().HasNoKey();

However the test fails with

 Message:
Test method TestProject1.UnitTest1.T040_DbSetForDto threw exception:
System.InvalidOperationException: Sequence contains no elements

  Stack Trace:
ThrowHelper.ThrowNoElementsException()
Enumerable.Max(IEnumerable`1 source)
ShaperProcessingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
BinaryExpression.Accept(ExpressionVisitor visitor)
ExpressionVisitor.Visit(Expression node)
ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
ExpressionVisitor.VisitBlock(BlockExpression node)
BlockExpression.Accept(ExpressionVisitor visitor)
ExpressionVisitor.Visit(Expression node)
ShaperProcessingExpressionVisitor.VisitExtension(Expression extensionExpression)
<8 more frames...>
Database.CompileQuery[TResult](Expression query, Boolean async)
QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
<>c__DisplayClass9_0`1.<Execute>b__0()
CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
QueryCompiler.Execute[TResult](Expression query)
EntityQueryProvider.Execute[TResult](Expression expression)
EntityQueryable`1.GetEnumerator()
List`1.ctor(IEnumerable`1 collection)
Enumerable.ToList[TSource](IEnumerable`1 source)

I am using net5.0 and

   <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.13" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.13" />
   <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.13" />

Body:
The following works

[TestClass]
public class UnitTest1
{
        [TestMethod]
        public void T040_DbSetForDto()
        {
            var db = DataHelpers.MakeDbContext();
            var temps = db.DtoInts.FromSqlRaw("select top 1 Id from mytable").ToList();

            Assert.IsTrue(temps.Any());
            var temp = temps.FirstOrDefault();
            Trace.WriteLine($"First id is {temp.Id}");
        }
}

My error message  may have been that I had put a [NotMapped] tag on the Id property.
It was also important to have

modelBuilder.Entity<DtoTempInt>().HasNoKey();

in OnModelCreating

I was also thinking that DbSet should only be used for actual data tables, but this is not true.


问:
Between in createdCriteria not works
I have a very strange problem. I create 3 entities with the following data:

```<code>CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)
</code>```

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )
</code>```

I've tried this alternative and it doesn't work either:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )
</code>```

The incredible thing is that if I replace the between with the eq:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )
</code>```

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

```<code>    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
</code>```

答:
try this:

```<code>        Ccb.createCriteria().list {
            between("id", 1l, 5l)
            projections {
                property('id')
            }
        }
</code>```

or:

```<code>        Ccb.createCriteria().list {
            and{
                between("id", 1l, 5l)
            }
            projections {
                property('id')
            }
        }
</code>```

Title: Between in createdCriteria not works

Body:
I have a very strange problem. I create 3 entities with the following data:

CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )

I've tried this alternative and it doesn't work either:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )

The incredible thing is that if I replace the between with the eq:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }

Body:
try this:

        Ccb.createCriteria().list {
            between("id", 1l, 5l)
            projections {
                property('id')
            }
        }

or:

        Ccb.createCriteria().list {
            and{
                between("id", 1l, 5l)
            }
            projections {
                property('id')
            }
        }


问:
Is there a way to create a list that auto populates with the the required articles?
I am a UI/UX designer and I have taken on a new project to overhaul our Zendesk. I have no experience but I am learning on the fly, I have already built a custom sidebar navigation and now my problem is this:

Is there a way to have the sidebar auto populate with the categories and articles from our knowledge base? I assume there is a way to do this, otherwise that would mean every time I upload a new document to our knowledge base I will also have to go back into the code and add the href with the link and title to the sidebar nav html and I'm certain that's not the way this works. I'm happy to do the research but I don't know what to search for, I've tried researching auto populating lists etc. but nothing matches my need. I can manually input every article into the side bar and it functions beautifully, I just figured there was an actual way to automate this once the code is input.

Thank you in advance,

-Newbie

答:
As, I said in my comment, if you have a db in the backend with your info, you should use Ajax.

Ajax allows JavaScript to send requests to the backend. When this request is sent, the backend should reply with data in some form, such as JSON, and then your client side JavaScript will need to populate the sidebar using the data.

If you give some more info about your backend and html, I can give an example!


答:
if you want to check a digit in number use this

if "7" in str(i)
```

Title: Checking if an integer contains a certain digit in a for loop


问:
Altair: How to color when there are more categories than colors available
Here is the code taken from the Altair documentation on color schemes.

```<code>alt.Chart(iris).mark_point().encode(
    x='petalWidth',
    y='petalLength',
    color=alt.Color('species', scale=alt.Scale(scheme='dark2'))
)
</code>```

Here, to color based on species, they used the dark2 color scheme. There are 8 colors in the dark2 vega scheme. I have noticed that when there more categories than colors available, it appears that the colors are recycled again, which means some categories have the same color. In this example, suppose species had more than 8 categories. This means two species will be colored in the same way.

Is there anyway to within Altair to automatically 'extend' the dark2 color scheme to support more categories? I was thinking something along the lines of interpolation or mixing colors in the scheme.

As a side note, I'm aware that there are other color schemes with more colors available, but I would like to have a solution which I mentioned above with dark2.

答:
It is not possible to extend a color scheme automatically via Altair/VegaLite. You would need to manually define the colors you would want to use, or switch to another color scheme, as you mentioned.

Note that when you are using this many categorical colors, it can become quite difficult for the reader to parse the information in the plot and it is usually better to break down the plot into multiple plots via faceting, or use labels/hovering to encode some of the information instead of relying solely on color. There are some good pointers on this topic in this book chapter.

Body:
Here is the code taken from the Altair documentation on color schemes.

alt.Chart(iris).mark_point().encode(
    x='petalWidth',
    y='petalLength',
    color=alt.Color('species', scale=alt.Scale(scheme='dark2'))
)

Here, to color based on species, they used the dark2 color scheme. There are 8 colors in the dark2 vega scheme. I have noticed that when there more categories than colors available, it appears that the colors are recycled again, which means some categories have the same color. In this example, suppose species had more than 8 categories. This means two species will be colored in the same way.

Is there anyway to within Altair to automatically 'extend' the dark2 color scheme to support more categories? I was thinking something along the lines of interpolation or mixing colors in the scheme.

As a side note, I'm aware that there are other color schemes with more colors available, but I would like to have a solution which I mentioned above with dark2.