问:
How Can I Pass My SQL Data to Chart.js Line Chart?
I'm trying to run a PostgreSQL query in my Flask app using psycopg2, and then pass the results to a Chart.js line chart. The SQL query appears to be running fine, the Chart.js bit not so much...

My flask app:

```<code>@app.route('/')
def index():
    conn = get_db_connection()
    cur = conn.cursor()
    #Execute a query
    cur.execute("SELECT price_date AS x, price AS y FROM economics.prices ORDER BY price_date ASC")
    result = cur.fetchall()
    cur.close()
    conn.close()
    return render_template('index.html', result = result)
</code>```

That returns the following:

```<code>[(datetime.date(2016, 8, 4), Decimal('0.25')), (datetime.date(2017, 11, 2), Decimal('0.5')), (datetime.date(2018, 8, 2), Decimal('0.75')), (datetime.date(2020, 3, 11), Decimal('0.25')), (datetime.date(2020, 3, 19), Decimal('0.1')), (datetime.date(2021, 12, 16), Decimal('0.25')), (datetime.date(2022, 2, 3), Decimal('0.5')), (datetime.date(2022, 3, 17), Decimal('0.75')), (datetime.date(2022, 5, 5), Decimal('1')), (datetime.date(2022, 6, 16), Decimal('1.25')), (datetime.date(2022, 8, 4), Decimal('1.75'))]
</code>```

My chart (which renders a chart, but without any points plotted on it):

```<code><canvas id="myChart"></canvas>

  <script>

    var xydata = {{ result|tojson }}

    new Chart("myChart", {
      type: "line",
      data: {
        datasets: [{
          fill: false,
          lineTension: 0,
          backgroundColor: "rgba(0,0,255,1.0)",
          borderColor: "rgba(0,0,255,0.1)",
          data: xydata
        }]
      },
      options: {
        scales: {
          x: {
            type: 'time',
            time: {
                    unit: 'quarter',
                    displayFormats: {
                        month: 'DD-MM-YYYY'
                    }
                }
          },
          y: {
            beginAtZero: true
          }
        }
      }
    });

  </script>
</code>```

The chart works if I specify the values manually as below, but I can't work out how to pass the data properly despite some furious Googling. Help please!

```<code>  <canvas id="myChart"></canvas>

  <script>

    new Chart("myChart", {
      type: "line",
      data: {
        datasets: [{
          fill: false,
          lineTension: 0,
          backgroundColor: "rgba(0,0,255,1.0)",
          borderColor: "rgba(0,0,255,0.1)",
          data: [{'x': '2016-08-04', 'y': 0.25}, {'x': '2017-11-02', 'y': 0.5}, {'x': '2018-08-02', 'y': 0.75}, {'x': '2020-03-11', 'y': 0.25}, {'x': '2020-03-19', 'y': 0.1}, {'x': '2021-12-16', 'y': 0.25}, {'x': '2022-02-03', 'y': 0.5}, {'x': '2022-03-17', 'y': 0.75}, {'x': '2022-05-05', 'y': 1}, {'x': '2022-06-16', 'y': 1.25}, {'x': '2022-08-04', 'y': 1.75}]
        }]
      },
      options: {
        scales: {
          x: {
            type: 'time',
            time: {
                    unit: 'day',
                    displayFormats: {
                        month: 'DD-MM-YYYY'
                    }
                }
          },
          y: {
            beginAtZero: true
          }
        }
      }
    });

  </script>

</code>```

EDIT: I forgot to mention, I did try this query:

```<code>    cur.execute("SELECT json_agg(src) FROM (SELECT price_date AS x, price AS y FROM economics.prices ORDER BY price_date ASC) src")
</code>```

which made the data look how I thought it needed to be to pass to the chart:

```<code>[([{'x': '2016-08-04', 'y': 0.25}, {'x': '2017-11-02', 'y': 0.5}, {'x': '2018-08-02', 'y': 0.75}, {'x': '2020-03-11', 'y': 0.25}, {'x': '2020-03-19', 'y': 0.1}, {'x': '2021-12-16', 'y': 0.25}, {'x': '2022-02-03', 'y': 0.5}, {'x': '2022-03-17', 'y': 0.75}, {'x': '2022-05-05', 'y': 1}, {'x': '2022-06-16', 'y': 1.25}, {'x': '2022-08-04', 'y': 1.75}],)]
</code>```

but I still couldn't get it to work, and from what I read converting to JSON in the template using |tojson is the better way to handle it anyway.

Body:
I'm trying to run a PostgreSQL query in my Flask app using psycopg2, and then pass the results to a Chart.js line chart. The SQL query appears to be running fine, the Chart.js bit not so much...

My flask app:

@app.route('/')
def index():
    conn = get_db_connection()
    cur = conn.cursor()
    #Execute a query
    cur.execute("SELECT price_date AS x, price AS y FROM economics.prices ORDER BY price_date ASC")
    result = cur.fetchall()
    cur.close()
    conn.close()
    return render_template('index.html', result = result)

That returns the following:

[(datetime.date(2016, 8, 4), Decimal('0.25')), (datetime.date(2017, 11, 2), Decimal('0.5')), (datetime.date(2018, 8, 2), Decimal('0.75')), (datetime.date(2020, 3, 11), Decimal('0.25')), (datetime.date(2020, 3, 19), Decimal('0.1')), (datetime.date(2021, 12, 16), Decimal('0.25')), (datetime.date(2022, 2, 3), Decimal('0.5')), (datetime.date(2022, 3, 17), Decimal('0.75')), (datetime.date(2022, 5, 5), Decimal('1')), (datetime.date(2022, 6, 16), Decimal('1.25')), (datetime.date(2022, 8, 4), Decimal('1.75'))]

My chart (which renders a chart, but without any points plotted on it):

<canvas id="myChart"></canvas>

The chart works if I specify the values manually as below, but I can't work out how to pass the data properly despite some furious Googling. Help please!

  <canvas id="myChart"></canvas>

EDIT: I forgot to mention, I did try this query:

    cur.execute("SELECT json_agg(src) FROM (SELECT price_date AS x, price AS y FROM economics.prices ORDER BY price_date ASC) src")

which made the data look how I thought it needed to be to pass to the chart:

[([{'x': '2016-08-04', 'y': 0.25}, {'x': '2017-11-02', 'y': 0.5}, {'x': '2018-08-02', 'y': 0.75}, {'x': '2020-03-11', 'y': 0.25}, {'x': '2020-03-19', 'y': 0.1}, {'x': '2021-12-16', 'y': 0.25}, {'x': '2022-02-03', 'y': 0.5}, {'x': '2022-03-17', 'y': 0.75}, {'x': '2022-05-05', 'y': 1}, {'x': '2022-06-16', 'y': 1.25}, {'x': '2022-08-04', 'y': 1.75}],)]

but I still couldn't get it to work, and from what I read converting to JSON in the template using |tojson is the better way to handle it anyway.


来源: stackexchange

问:
Android kotlin spinner adapter with items
I am writing code and need to achieve design from image provided. I am using android spinner like this:

```<code> private fun setSpinnerAdapter() {
        binding?.sortSpinner?.adapter =
            ArrayAdapter(context, R.layout.simple_spinner_dropdown_item, getSpinnerItems())
                .apply {
                    setDropDownViewResource(R.layout.simple_spinner_selected_item)
                }
    }

    private fun getSpinnerItems(): MutableList<String> {
        val spinnerItems = TKeys.SORT_SPINNER.translated
        val spinnerItemsArray: MutableList<String> = spinnerItems.split(",") as MutableList<String>
        for (i in spinnerItemsArray.indices)
            spinnerItemsArray[i] = spinnerItemsArray[i].trim()
        return spinnerItemsArray
    }

 private fun setSpinnerSelectionListener() {
        binding?.sortSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                val sortOption =
                    getSortOptionEnum(binding?.sortSpinner?.adapter?.getItem(position).toString())
                manipulateGameList(GameManipulation(sortOption))
            }
        }
    }
</code>```

First problem here is that my onItemSelected function is called 2 times whenever user picks sort option. And what is funny that at first it is called with correct value and on second call, it gets called with wrong one. So the wrong one overrides correct one which makes my sorting wrong.

Second question you can see from image. So designers decide to add SORT text on spinner. After click, we open white window with sort options. But sort options are only 3 (A - Z, MOST PLAYED, POPULAR) available in list and SORT is just text on spinner user needs to see. I didn't find way to give spinner text without using it in adapter. How to achieve this design from picture with white window with nice margins and default text on spinner.
Thanks in advance

ContentLicense: CC BY-SA 4.0

Body:
I am writing code and need to achieve design from image provided. I am using android spinner like this:

 private fun setSpinnerAdapter() {
        binding?.sortSpinner?.adapter =
            ArrayAdapter(context, R.layout.simple_spinner_dropdown_item, getSpinnerItems())
                .apply {
                    setDropDownViewResource(R.layout.simple_spinner_selected_item)
                }
    }

    private fun getSpinnerItems(): MutableList<String> {
        val spinnerItems = TKeys.SORT_SPINNER.translated
        val spinnerItemsArray: MutableList<String> = spinnerItems.split(",") as MutableList<String>
        for (i in spinnerItemsArray.indices)
            spinnerItemsArray[i] = spinnerItemsArray[i].trim()
        return spinnerItemsArray
    }

 private fun setSpinnerSelectionListener() {
        binding?.sortSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                val sortOption =
                    getSortOptionEnum(binding?.sortSpinner?.adapter?.getItem(position).toString())
                manipulateGameList(GameManipulation(sortOption))
            }
        }
    }

First problem here is that my onItemSelected function is called 2 times whenever user picks sort option. And what is funny that at first it is called with correct value and on second call, it gets called with wrong one. So the wrong one overrides correct one which makes my sorting wrong.

Second question you can see from image. So designers decide to add SORT text on spinner. After click, we open white window with sort options. But sort options are only 3 (A - Z, MOST PLAYED, POPULAR) available in list and SORT is just text on spinner user needs to see. I didn't find way to give spinner text without using it in adapter. How to achieve this design from picture with white window with nice margins and default text on spinner.
Thanks in advance


问:
Npgsql EF Core (.NET 6) is extremely slow (EF Core + Postgres, Database-First)
There is a problem with queries to existing Postgres database using Npgsql EF Core (.NET 6). Even simple EF queries are extremely slow (from 25  sec to several minutes for big expressions). At the same time generated SQL code executes in 20-50 milliseconds. Database is a little bit ugly and not very normalized, but SQL queries execute quite quickly. Also (if it is important) db is not big, smth abount 40.000 rows in some biggest tables.

Here is simple EF query, it takes 24 seconds:

```<code>var list = await context.SomeObjects
            .Include(x => x.FirstJoinedEntity)
            .Include(x => x.SecondJoinedEntity)
            .Include(x => x.ThirdJoinedEntity)
            .ToListAsync();
</code>```

It generates quite simple SQL and it takes about 160 ms to load all rows:

```<code>SELECT "A lot of columns"
FROM some_object AS o
     LEFT JOIN first AS f ON o.id = f.object_id
     LEFT JOIN second AS s ON o.id = s.object_id
     LEFT JOIN third AS t ON o.id = t.object_id
</code>```

Very simple and fast.

Is there any profiler which can show what exactly takes a lot of time in EF Core Npgsql? Or any way how to just understand why EF Core slows so much? I can't change it to code-first and recreate database, but tried Npgsql command to autogenerate Context and all entities for exisiting database to match all Postgres -> C# types:

```<code>dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL
</code>```

But it didn't help: result is the same.

The question is how to diagnose reason of that problem.

Body:
There is a problem with queries to existing Postgres database using Npgsql EF Core (.NET 6). Even simple EF queries are extremely slow (from 25  sec to several minutes for big expressions). At the same time generated SQL code executes in 20-50 milliseconds. Database is a little bit ugly and not very normalized, but SQL queries execute quite quickly. Also (if it is important) db is not big, smth abount 40.000 rows in some biggest tables.

Here is simple EF query, it takes 24 seconds:

var list = await context.SomeObjects
            .Include(x => x.FirstJoinedEntity)
            .Include(x => x.SecondJoinedEntity)
            .Include(x => x.ThirdJoinedEntity)
            .ToListAsync();

It generates quite simple SQL and it takes about 160 ms to load all rows:

SELECT "A lot of columns"
FROM some_object AS o
     LEFT JOIN first AS f ON o.id = f.object_id
     LEFT JOIN second AS s ON o.id = s.object_id
     LEFT JOIN third AS t ON o.id = t.object_id

Very simple and fast.

Is there any profiler which can show what exactly takes a lot of time in EF Core Npgsql? Or any way how to just understand why EF Core slows so much? I can't change it to code-first and recreate database, but tried Npgsql command to autogenerate Context and all entities for exisiting database to match all Postgres -> C# types:

dotnet ef dbcontext scaffold "Host=my_host;Database=my_db;Username=my_user;Password=my_pw" Npgsql.EntityFrameworkCore.PostgreSQL

But it didn't help: result is the same.

The question is how to diagnose reason of that problem.


问:
Conda install Mamba Error: Collecting package metadata (repodata.json): / Killed
I am trying to install mamba through conda on my linux terminal on my chormebook. Please help. I need to install this for a final exmam. My professor just tells me look online. I am not a programmer and I am new to bioinformatics so please provide explanantions with suggestions.

I keep getting an error message. I have tried reassigning space according to another thread and it did not work:
Collecting package metadata (repodata.json): / Killed

```<code>sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
</code>```

The output was after '''sudo swapon /swapfile''' was 'swapon: /swapfile: swapon failed: Function not implemented'

I tried '''curl -H 'Cache-Control: no-cache' https://repo.anaconda.com/pkgs/r/noarch/repodata.json'''

I got a bunch of script then tried '''conda create -n py34d20 python=3.4 pip=9 django -c conda-forge''' per this thread: https://github.com/conda/conda/issues/9728

I get the same results which are:
'Collecting package metadata (current_repodata.json): done
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): - Killed '

The instructions my professor gave to download to show what I should get.

enter image description here

The point is to install clustal environment using mamba to align genes.

enter image description here

Body:
I am trying to install mamba through conda on my linux terminal on my chormebook. Please help. I need to install this for a final exmam. My professor just tells me look online. I am not a programmer and I am new to bioinformatics so please provide explanantions with suggestions.

I keep getting an error message. I have tried reassigning space according to another thread and it did not work:
Collecting package metadata (repodata.json): / Killed

sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

The output was after '''sudo swapon /swapfile''' was 'swapon: /swapfile: swapon failed: Function not implemented'

I tried '''curl -H 'Cache-Control: no-cache' https://repo.anaconda.com/pkgs/r/noarch/repodata.json'''

I got a bunch of script then tried '''conda create -n py34d20 python=3.4 pip=9 django -c conda-forge''' per this thread: https://github.com/conda/conda/issues/9728

I get the same results which are:
'Collecting package metadata (current_repodata.json): done
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): - Killed '

The instructions my professor gave to download to show what I should get.

enter image description here

The point is to install clustal environment using mamba to align genes.

enter image description here


问:
Batch merge two subtitles into one
I have this Python script which merges two different .srt files into one and it worked fine,
but I want it keep doing it for other subtitles in a folder too.

For example, a.de.srt and  a.en.srt will merge with this code with no problem, but what I want a .bat file that merges other srt files in a folder like this:

anyNAME.1.srt with anyNAME.1.srt to Merged.1.srt

anyNAME.2.srt with anyNAME.2.srt to Merged.2.srt

.
.
.
and everything else with this format.

Python script from github:

```<code>#!/usr/bin/env python

import srt  # for srt format handling
import glob  # for unix style filename matching
import sys  # input arguments
import getopt  # to raise error in case of incorrect arguments

def main(argv):
    # Parse arguments
    primary_language = ''
    secondary_language = ''
    try:
        opts, args = getopt.getopt(
            argv, "hp:s:", ["primary-language=", "secondary-language="])
    except getopt.GetoptError:
        print ('merge_subtitles.py -p <primary_language>'
               '-s <secondary_language>')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print ('merge_subtitles.py -p <primary_language>'
                   ' -s <secondary_language>')
            sys.exit()
        elif opt in ("-p", "--primary-language"):
            primary_language = arg
        elif opt in ("-s", "--secondary-language"):
            secondary_language = arg

    # Read files and convert to list
    primary_path = glob.glob('./*.' + primary_language + '.srt')[0]
    secondary_path = glob.glob('./*.' + secondary_language + '.srt')[0]
    primary_file = open(primary_path, 'r', errors='ignore')
    primary_text = primary_file.read()
    primary_file.close()
    secondary_file = open(secondary_path, 'r', errors='ignore')
    secondary_text = secondary_file.read()
    secondary_file.close()
    subtitle_generator_primary = srt.parse(primary_text)
    subtitles_primary = list(subtitle_generator_primary)
    subtitle_generator_secondary = srt.parse(secondary_text)
    subtitles_secondary = list(subtitle_generator_secondary)

    # Make primary yellow
    for s in subtitles_primary:
        s.content = '<font color="#ffff54">' + s.content + '</font>'

    # Place secondary on top
    for s in subtitles_secondary:
        s.content = '{\\an8}' + s.content

    # Merge
    subtitles_merged = subtitles_primary + subtitles_secondary
    subtitles_merged = list(srt.sort_and_reindex(subtitles_merged))

    # Write merged to file
    merged_path = primary_path.replace(primary_language, 'merged')
    merged_text = srt.compose(subtitles_merged)
    merged_file = open(merged_path, 'w')
    merged_file.write(merged_text)
    merged_file.close()

if __name__ == "__main__":
    main(sys.argv[1:])
</code>```

Title: Batch merge two subtitles into one

Body:
I have this Python script which merges two different .srt files into one and it worked fine,
but I want it keep doing it for other subtitles in a folder too.

For example, a.de.srt and  a.en.srt will merge with this code with no problem, but what I want a .bat file that merges other srt files in a folder like this:

anyNAME.1.srt with anyNAME.1.srt to Merged.1.srt

anyNAME.2.srt with anyNAME.2.srt to Merged.2.srt

.
.
.
and everything else with this format.

Python script from github:

#!/usr/bin/env python

import srt  # for srt format handling
import glob  # for unix style filename matching
import sys  # input arguments
import getopt  # to raise error in case of incorrect arguments

def main(argv):
    # Parse arguments
    primary_language = ''
    secondary_language = ''
    try:
        opts, args = getopt.getopt(
            argv, "hp:s:", ["primary-language=", "secondary-language="])
    except getopt.GetoptError:
        print ('merge_subtitles.py -p <primary_language>'
               '-s <secondary_language>')
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print ('merge_subtitles.py -p <primary_language>'
                   ' -s <secondary_language>')
            sys.exit()
        elif opt in ("-p", "--primary-language"):
            primary_language = arg
        elif opt in ("-s", "--secondary-language"):
            secondary_language = arg

    # Read files and convert to list
    primary_path = glob.glob('./*.' + primary_language + '.srt')[0]
    secondary_path = glob.glob('./*.' + secondary_language + '.srt')[0]
    primary_file = open(primary_path, 'r', errors='ignore')
    primary_text = primary_file.read()
    primary_file.close()
    secondary_file = open(secondary_path, 'r', errors='ignore')
    secondary_text = secondary_file.read()
    secondary_file.close()
    subtitle_generator_primary = srt.parse(primary_text)
    subtitles_primary = list(subtitle_generator_primary)
    subtitle_generator_secondary = srt.parse(secondary_text)
    subtitles_secondary = list(subtitle_generator_secondary)

    # Make primary yellow
    for s in subtitles_primary:
        s.content = '' + s.content + ''

    # Place secondary on top
    for s in subtitles_secondary:
        s.content = '{\\an8}' + s.content

    # Merge
    subtitles_merged = subtitles_primary + subtitles_secondary
    subtitles_merged = list(srt.sort_and_reindex(subtitles_merged))

    # Write merged to file
    merged_path = primary_path.replace(primary_language, 'merged')
    merged_text = srt.compose(subtitles_merged)
    merged_file = open(merged_path, 'w')
    merged_file.write(merged_text)
    merged_file.close()

if __name__ == "__main__":
    main(sys.argv[1:])


问:
custom useMediaQuery hook does not appear to work on a phone
I am trying to write a custom useMediaQuery hook so I can use this to do things conditionally based on screen size in a react app. The hook I have written appears to be working in my browser, but I did a netlify build and it does not work correctly when I pull it up on my phone. Does anyone see any issues? Thinking this may have something to do with certain functions being used being unsupported by different browsers. I tried safari and chrome on my Iphone and both did not work.

Here is my useMediaQuery hook:

```<code>import { useEffect, useState } from "react";

// credit for this hook came from this website: https://usehooks-ts.com/react-hook/use-media-query
// I modified it a bit to remove some deprecated methods not supported by all browsers

export const useMediaQuery = (query) => {
  //returns true/false if window matches our query, if window is undefined returns false
  const getMatches = (query) => {
    // Prevents SSR issues
    if (typeof window !== "undefined") {
      return window.matchMedia(query).matches;
    }
    return false;
  };

  // piece of state telling whether or not our query matches window
  const [matches, setMatches] = useState(getMatches(query));

  // sets our state based on our query, runs initially and with the change event listener
  const handleChange = () => {
    setMatches(getMatches(query));
  }

  useEffect(() => {
    // Triggered at the first client-side load and if query changes
    handleChange();

    window.addEventListener('resize', handleChange);
    // eslint-disable-next-line
  }, [query]);

  return matches;
};
</code>```

Here is my App.js demo where I output certain text based on a media query:

```<code>import './App.css';
import { useMediaQuery } from './hooks/useMediaQuery';

const renderDeviceSizeText = (isTabletOrSmaller, isPhoneScreen) => {
  if(isTabletOrSmaller === false) {
    return <h1>Desktop</h1>
  } else if (isTabletOrSmaller === true && isPhoneScreen === false){
    return <h1>Tablet</h1>
  } else {
    return <h1>Mobile</h1>
  }
}

function App() {

  const isTabletOrSmaller = useMediaQuery('(max-width: 768px');
  const isPhoneScreen = useMediaQuery('(max-width: 480px)');

  return (
    <div>
      {
        renderDeviceSizeText(isTabletOrSmaller, isPhoneScreen)
      }
    </div>
  );
}

export default App;

</code>```

Here is the url for the netlify app I deployed using this react app: https://venerable-dieffenbachia-2cfd8b.netlify.app/

Body:
I am trying to write a custom useMediaQuery hook so I can use this to do things conditionally based on screen size in a react app. The hook I have written appears to be working in my browser, but I did a netlify build and it does not work correctly when I pull it up on my phone. Does anyone see any issues? Thinking this may have something to do with certain functions being used being unsupported by different browsers. I tried safari and chrome on my Iphone and both did not work.

Here is my useMediaQuery hook:

import { useEffect, useState } from "react";

// credit for this hook came from this website: https://usehooks-ts.com/react-hook/use-media-query
// I modified it a bit to remove some deprecated methods not supported by all browsers

export const useMediaQuery = (query) => {
  //returns true/false if window matches our query, if window is undefined returns false
  const getMatches = (query) => {
    // Prevents SSR issues
    if (typeof window !== "undefined") {
      return window.matchMedia(query).matches;
    }
    return false;
  };

  // piece of state telling whether or not our query matches window
  const [matches, setMatches] = useState(getMatches(query));

  // sets our state based on our query, runs initially and with the change event listener
  const handleChange = () => {
    setMatches(getMatches(query));
  }

  useEffect(() => {
    // Triggered at the first client-side load and if query changes
    handleChange();

    window.addEventListener('resize', handleChange);
    // eslint-disable-next-line
  }, [query]);

  return matches;
};

Here is my App.js demo where I output certain text based on a media query:

import './App.css';
import { useMediaQuery } from './hooks/useMediaQuery';

const renderDeviceSizeText = (isTabletOrSmaller, isPhoneScreen) => {
  if(isTabletOrSmaller === false) {
    return
Desktop

  } else if (isTabletOrSmaller === true && isPhoneScreen === false){
    return
Tablet

  } else {
    return
Mobile

  }
}

function App() {

  const isTabletOrSmaller = useMediaQuery('(max-width: 768px');
  const isPhoneScreen = useMediaQuery('(max-width: 480px)');

  return (

      {
        renderDeviceSizeText(isTabletOrSmaller, isPhoneScreen)
      }

  );
}

export default App;

Here is the url for the netlify app I deployed using this react app: https://venerable-dieffenbachia-2cfd8b.netlify.app/


问:
Visual Assets for publishing a Visual Studio 2022 app
I hate to appear as an idiot but I always get wrapped around the axle trying to satisfy the publish app wizard with the logos, icons, etc. that it requires to successfully create an app package for side loading. The more I try to simplify putting the correct images in the "Assets" folder, the more odd things start happening.  I am getting errors indicating that the "Payload does not include" images when they are clearly in the Assets folder and are listed in the project Assets folder from within Visual Studio. Now I have fiddled with it so much that when I open the App Manifest file in Visual Studio and try to go to the "Visual Assets" tab, the whole Visual Studio app crashes. Is there a tutorial somewhere to walk one through the process of creating the images that are required?

I have renamed image files to simple names, edited the Package.appmanifest file from outside of Visual Studio and changed filenames to my renamed simple names, I have created new images to upload, I have tried about everything I can think of.


问:
Using Lens to adjust user input in Monomer
I'm writing a GUI app in Monomer which has a textField function which accepts ALens which it uses to read/write input value into an AppModel    .

In my case AppModel looks like this:

data AppModel = AppModel
  { _activeComment :: Maybe Text
  }
  deriving (Eq, Show)
```
<p>And so I'm using this lens:</p>
<pre class="lang-hs prettyprint-override"><code>textField (activeComment . non "")
</code>```

I use non "" to get a default value, because textField requres a lens with Text focus.

Now I have these questions (I am only learning Lens):

Suppose I want to map user input and apply "h"-symbol to every key they type, how would I do that? I.e. I want to insert (\t -> t <> "h") mapping somewhere, but I can't figure out how. What is the operator I should use here? Is that from realm of Isos? (didn't learn them yet)

What if I want to perform an effect on each key press, wait for the result and then set to to a lens focus? I guess this is not possible with current types. And this is probably more of a library question than a lens question, but still.

P.S. Here's an example of using textField from library samples in case docs are not enough: example

Body:
I'm writing a GUI app in Monomer which has a textField function which accepts ALens which it uses to read/write input value into an AppModel    .

In my case AppModel looks like this:

data AppModel = AppModel
  { _activeComment :: Maybe Text
  }
  deriving (Eq, Show)

And so I'm using this lens:

textField (activeComment . non "")

I use non "" to get a default value, because textField requres a lens with Text focus.

Now I have these questions (I am only learning Lens):

Suppose I want to map user input and apply "h"-symbol to every key they type, how would I do that? I.e. I want to insert (\t -> t <> "h") mapping somewhere, but I can't figure out how. What is the operator I should use here? Is that from realm of Isos? (didn't learn them yet)

What if I want to perform an effect on each key press, wait for the result and then set to to a lens focus? I guess this is not possible with current types. And this is probably more of a library question than a lens question, but still.

P.S. Here's an example of using textField from library samples in case docs are not enough: example


问:
Why does Pycharm "Create new test.." not include references and imports to the class/method under test?
Pycharm has a convenient way to create new tests: select or click on the class-name or method then choose Shift-Command-T for Create New Test:

The test is created in a useful location by default and a dialog allows choosing which methods to test.  I wish there were a way to Select All instead of clicking one by one, but that's a  nit.

The real want/complaint here is that the new testcase method does not reference the class-under-test method. It does not even import the class!  All we get is a bare stub:

def test_create_measure():
    assert False
```

Why is this feature so hobbled?  Is there some additional configuration required to get a more reasonable result?

Body:
Pycharm has a convenient way to create new tests: select or click on the class-name or method then choose Shift-Command-T for Create New Test:

The test is created in a useful location by default and a dialog allows choosing which methods to test.  I wish there were a way to Select All instead of clicking one by one, but that's a  nit.

The real want/complaint here is that the new testcase method does not reference the class-under-test method. It does not even import the class!  All we get is a bare stub:

def test_create_measure():
    assert False

Why is this feature so hobbled?  Is there some additional configuration required to get a more reasonable result?


问:
Persistence in docker
i created a compose container with two: one for the app and one for sql...i also created a volume to persist the data and now i have a problem: is it normal that the db is written only to the volume and not on Mysql?
This is my compose:

```<code>version: "3"

services:
  server:
    image: myshop:0.0.1-SNAPSHOT
    ports:
      - "8080:8080"
    environment:
      - spring.datasource.url=jdbc:mysql://mysqldb:3306/my_shop?useSSL=false
    volumes:
     - myshopstorage:/var/lib/docker/volumes/myshop_myshopstorage/_data

    networks:
      - myshop-net
    depends_on:
      - mysqldb

  mysqldb:
    image: mysql:5.6
    volumes:
      - myshopstorage:/var/lib/mysql
    ports:
      - "3307:3306"
    networks:
      - myshop-net
    environment:
      - SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/my_shop?createDatabaseIfNotExist=true&autoReconnect=true&useSLL=false&useLegacyDatetimeCode=false
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=my_shop

networks:
  myshop-net:
    external: false

volumes:
  myshopstorage:
    external: false
</code>```

How can i write the data in the volume on the mysql database?
Right now data are persistent only in docker volume

A screen of my volume:

volume scenario

Title: Persistence in docker

Body:
i created a compose container with two: one for the app and one for sql...i also created a volume to persist the data and now i have a problem: is it normal that the db is written only to the volume and not on Mysql?
This is my compose:

version: "3"

services:
  server:
    image: myshop:0.0.1-SNAPSHOT
    ports:
      - "8080:8080"
    environment:
      - spring.datasource.url=jdbc:mysql://mysqldb:3306/my_shop?useSSL=false
    volumes:
     - myshopstorage:/var/lib/docker/volumes/myshop_myshopstorage/_data

    networks:
      - myshop-net
    depends_on:
      - mysqldb

  mysqldb:
    image: mysql:5.6
    volumes:
      - myshopstorage:/var/lib/mysql
    ports:
      - "3307:3306"
    networks:
      - myshop-net
    environment:
      - SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/my_shop?createDatabaseIfNotExist=true&autoReconnect=true&useSLL=false&useLegacyDatetimeCode=false
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=my_shop

networks:
  myshop-net:
    external: false

volumes:
  myshopstorage:
    external: false

How can i write the data in the volume on the mysql database?
Right now data are persistent only in docker volume

A screen of my volume:

volume scenario


问:
JPype, SLF4J: IncompatibleClassChangeError: LocationAwareLogger can not implement Logger
I try to start a Java application with JPype.

After adding all relevant .jars to the classpath and starting the JVM, I import all Packages necessary to run the application. Standard Java libraries and libraries written for the application run fine up until I get this error:

```<code>java.lang.java.lang.IncompatibleClassChangeError: java.lang.IncompatibleClassChangeError:
class org.slf4j.spi.LocationAwareLogger can not implement org.slf4j.Logger,
because it is not an interface
(org.slf4j.Logger is in unnamed module of loader 'app')
</code>```

My code looks something like this:

```<code>import jpype
import os

import jpype.imports
from jpype.types import *

jpype.addClassPath("absolute path to all my .jars")

jpype.startJVM(r"C:\Program Files\Java\jdk-19\bin\server\jvm.dll")

# importing a lot of javaclasses
# testing some standard java libraries

properties = Properties() #java.util.Properties
properties.put(some application specific methods)

appl = startApplication(properties)         # now the error occurs

</code>```

I am using jpype 4.1.0, python 3.9.13 and jdk-19 and also tried jdk-15.0.2, jre1.8_351 and openjdk-8u312-b07.

Both my python and the JVM run on 64bit.

According to this, IncompatibleClassChangeError should not occour, because nobody edited any class or method in question and the application itself works fine.

The apllication uses

jcl-over-slf4j-1.6.1.jar

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

I also tried different versions of those 3 jars with the same result.

According to slf4j's article about Bridging legacy APIs here, I figured, that the jar

```<code>jul-to-slf4j-1.6.1.jar
</code>```

might be missing. But adding it had no impact.

When I try JProxy

```<code>@JImplements(Logger)
class MyImpl(object):
    @JOverride
    def trace(self, value):
        return value
</code>```

I get

```<code>TypeError: 'org.slf4j.Logger' is not a Java interface
</code>```

which can't be true according to the source code. Although I am pretty sure that's not how to use @JImplements in this case.

I dont't know, if I am completley on the wrong path, or I'm missing something.

Body:
I try to start a Java application with JPype.

After adding all relevant .jars to the classpath and starting the JVM, I import all Packages necessary to run the application. Standard Java libraries and libraries written for the application run fine up until I get this error:

java.lang.java.lang.IncompatibleClassChangeError: java.lang.IncompatibleClassChangeError:
class org.slf4j.spi.LocationAwareLogger can not implement org.slf4j.Logger,
because it is not an interface
(org.slf4j.Logger is in unnamed module of loader 'app')

My code looks something like this:

import jpype
import os

import jpype.imports
from jpype.types import *

jpype.addClassPath("absolute path to all my .jars")

jpype.startJVM(r"C:\Program Files\Java\jdk-19\bin\server\jvm.dll")

# importing a lot of javaclasses
# testing some standard java libraries

properties = Properties() #java.util.Properties
properties.put(some application specific methods)

appl = startApplication(properties)         # now the error occurs

I am using jpype 4.1.0, python 3.9.13 and jdk-19 and also tried jdk-15.0.2, jre1.8_351 and openjdk-8u312-b07.

Both my python and the JVM run on 64bit.

According to this, IncompatibleClassChangeError should not occour, because nobody edited any class or method in question and the application itself works fine.

The apllication uses

jcl-over-slf4j-1.6.1.jar

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

I also tried different versions of those 3 jars with the same result.

According to slf4j's article about Bridging legacy APIs here, I figured, that the jar

jul-to-slf4j-1.6.1.jar

might be missing. But adding it had no impact.

When I try JProxy

@JImplements(Logger)
class MyImpl(object):
    @JOverride
    def trace(self, value):
        return value

I get

TypeError: 'org.slf4j.Logger' is not a Java interface

which can't be true according to the source code. Although I am pretty sure that's not how to use @JImplements in this case.

I dont't know, if I am completley on the wrong path, or I'm missing something.


问:
How to built scatter plot in Tableau with only 2 measures?
I am trying to built scatter plot in Tableau using https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv

I want all points to be plotted but Tableau is aggregating(summing) and plotting 1 point. How can I do this? I am able to get required scatter plot in seaborn/python but want to do it in Tableau


问:
invisible setMyLocationEnabled button
I'm a student and I'm doing a university project but I have a problem, i have a fragment in which I have the Map google sdk but I would like to activate the setMyLocationEnabled button on it, I did this:

public void onViewCreated(@NonNull final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        buttonBackDetailsItinerary = view.findViewById(R.id.back_detailsItinerary);
        buttonInsertReviews = view.findViewById(R.id.button_insert_review);
        buttonViewsReviews = view.findViewById(R.id.button_views_review);
        title_details_itinerary = view.findViewById(R.id.title_details_itinerary);
        hours_details_Itinerary = view.findViewById(R.id.hours_details_Itinerary);
        minutes_details_Itinerary = view.findViewById(R.id.minutes_details_Itinerary);
        difficultLivel_details_Itinerary = view.findViewById(R.id.difficultLivel_details_Itinerary);
        description_detailsItinerary = view.findViewById(R.id.description_detailsItinerary);
        seconds_details_Itinerary = view.findViewById(R.id.seconds_details_Itinerary);
        imageView_details_itinerary = view.findViewById(R.id.imageView_details_itinerary);
        progressBar_details_itinerary = view.findViewById(R.id.progressBar_details_itinerary);

        supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapview);

        initializeMap();

        detailsItinerary_presenter = new DetailsItinerary_presenter(this);

        listenToClickEvents();
        loadItineraryDetails();
    }
```
<p>And:</p>
<pre class="lang-java prettyprint-override"><code> private void initializeMap() {
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap map) {
                googleMap = map;
                googleMap.getUiSettings().setCompassEnabled(false);
                googleMap.getUiSettings().setZoomControlsEnabled(true);
                googleMap.setBuildingsEnabled(true);
                if (googleMap != null) {
                   // googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
                    if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                            , Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                            , Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    googleMap.setMyLocationEnabled(true);
                    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                    googleMap.setMinZoomPreference(DEFAULT_ZOOM);
                }
          //  }
        });
    }
</code>```

but the button on the map is not visible, why?

Title: invisible setMyLocationEnabled button

Body:
I'm a student and I'm doing a university project but I have a problem, i have a fragment in which I have the Map google sdk but I would like to activate the setMyLocationEnabled button on it, I did this:

public void onViewCreated(@NonNull final View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        buttonBackDetailsItinerary = view.findViewById(R.id.back_detailsItinerary);
        buttonInsertReviews = view.findViewById(R.id.button_insert_review);
        buttonViewsReviews = view.findViewById(R.id.button_views_review);
        title_details_itinerary = view.findViewById(R.id.title_details_itinerary);
        hours_details_Itinerary = view.findViewById(R.id.hours_details_Itinerary);
        minutes_details_Itinerary = view.findViewById(R.id.minutes_details_Itinerary);
        difficultLivel_details_Itinerary = view.findViewById(R.id.difficultLivel_details_Itinerary);
        description_detailsItinerary = view.findViewById(R.id.description_detailsItinerary);
        seconds_details_Itinerary = view.findViewById(R.id.seconds_details_Itinerary);
        imageView_details_itinerary = view.findViewById(R.id.imageView_details_itinerary);
        progressBar_details_itinerary = view.findViewById(R.id.progressBar_details_itinerary);

        supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapview);

        initializeMap();

        detailsItinerary_presenter = new DetailsItinerary_presenter(this);

        listenToClickEvents();
        loadItineraryDetails();
    }

And:

 private void initializeMap() {
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap map) {
                googleMap = map;
                googleMap.getUiSettings().setCompassEnabled(false);
                googleMap.getUiSettings().setZoomControlsEnabled(true);
                googleMap.setBuildingsEnabled(true);
                if (googleMap != null) {
                   // googleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
                    if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                            , Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
                            , Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    googleMap.setMyLocationEnabled(true);
                    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                    googleMap.setMinZoomPreference(DEFAULT_ZOOM);
                }
          //  }
        });
    }

but the button on the map is not visible, why?


问:
How do I make a view refresh when the value changes?
I have an app that displays the number of steps on the screen. However, when the view that displays the steps is initialised, the number of steps doesn't change unless the user restarts the app. To solve this I tried to use @ObservableObject & @Pubslihed but haven't been able to achieve the results I wanted.

Here is the class:

```<code>class HealthStore: ObservableObject {

    @Published var healthStore: HKHealthStore?
    @Published var query: HKStatisticsCollectionQuery?

    init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()

        }
    }

    func calculateSteps(completion: @escaping (HKStatisticsCollection?)-> Void) {

        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

        let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())

        let anchorDate = Date.mondayAt12AM()

        let daily = DateComponents(day: 1)

        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:
                                    [.init(format: "metadata.%K != YES", HKMetadataKeyWasUserEntered), predicate]

                                )
        query = HKStatisticsCollectionQuery(
           quantityType: stepType,
           quantitySamplePredicate: compoundPredicate,
           options: .cumulativeSum,
           anchorDate: anchorDate,
           intervalComponents: daily)

        query!.initialResultsHandler = { query, statisticsCollection, error in
            completion(statisticsCollection)

        }

        if let healthStore = healthStore, let query = self.query {
            healthStore.execute(query)
        }
    }

    func requestAuthorization(completion: @escaping (Bool) -> Void) {

        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

        guard let healthStore = self.healthStore else { return completion(false) }

        healthStore.requestAuthorization(toShare: [], read: [stepType]) { (success, error) in
            completion(success)
        }
    }
}
</code>```

Here is the onLoad function that makes the steps data appear on the view (not using onAppear because it duplicated the view every time the view was initialised): This is used on a view.

```<code>.onLoad {
            if let healthStore = healthStore {
                healthStore.requestAuthorization { success in
                    if success {
                        healthStore.calculateSteps { statisticsCollection in
                            if let statisticsCollection = statisticsCollection {
                                // update the UI
                                updateUIFromStatistics(statisticsCollection)
                            }
                        }
                    }
                }
            }
        }

</code>```

Here is the code for the onLoad function:

```<code>struct ViewDidLoadModifier: ViewModifier {

    @State private var didLoad = false
    private let action: (() -> Void)?

    init(perform action: (() -> Void)? = nil) {
        self.action = action
    }

    func body(content: Content) -> some View {
        content.onAppear {
            if didLoad == false {
                didLoad = true
                action?()
            }
        }
    }
}

extension View {

    func onLoad(perform action: (() -> Void)? = nil) -> some View {
        modifier(ViewDidLoadModifier(perform: action))
    }

}

</code>```

Any ideas on how to get the values to refresh in the view when they change?

Body:
I have an app that displays the number of steps on the screen. However, when the view that displays the steps is initialised, the number of steps doesn't change unless the user restarts the app. To solve this I tried to use @ObservableObject & @Pubslihed but haven't been able to achieve the results I wanted.

Here is the class:

class HealthStore: ObservableObject {

    @Published var healthStore: HKHealthStore?
    @Published var query: HKStatisticsCollectionQuery?

    init() {
        if HKHealthStore.isHealthDataAvailable() {
            healthStore = HKHealthStore()

        }
    }

    func calculateSteps(completion: @escaping (HKStatisticsCollection?)-> Void) {

        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

        let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())

        let anchorDate = Date.mondayAt12AM()

        let daily = DateComponents(day: 1)

        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:
                                    [.init(format: "metadata.%K != YES", HKMetadataKeyWasUserEntered), predicate]

                                )
        query = HKStatisticsCollectionQuery(
           quantityType: stepType,
           quantitySamplePredicate: compoundPredicate,
           options: .cumulativeSum,
           anchorDate: anchorDate,
           intervalComponents: daily)

        query!.initialResultsHandler = { query, statisticsCollection, error in
            completion(statisticsCollection)

        }

        if let healthStore = healthStore, let query = self.query {
            healthStore.execute(query)
        }
    }

    func requestAuthorization(completion: @escaping (Bool) -> Void) {

        let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

        guard let healthStore = self.healthStore else { return completion(false) }

        healthStore.requestAuthorization(toShare: [], read: [stepType]) { (success, error) in
            completion(success)
        }
    }
}

Here is the onLoad function that makes the steps data appear on the view (not using onAppear because it duplicated the view every time the view was initialised): This is used on a view.

.onLoad {
            if let healthStore = healthStore {
                healthStore.requestAuthorization { success in
                    if success {
                        healthStore.calculateSteps { statisticsCollection in
                            if let statisticsCollection = statisticsCollection {
                                // update the UI
                                updateUIFromStatistics(statisticsCollection)
                            }
                        }
                    }
                }
            }
        }

Here is the code for the onLoad function:

struct ViewDidLoadModifier: ViewModifier {

    @State private var didLoad = false
    private let action: (() -> Void)?

    init(perform action: (() -> Void)? = nil) {
        self.action = action
    }

    func body(content: Content) -> some View {
        content.onAppear {
            if didLoad == false {
                didLoad = true
                action?()
            }
        }
    }
}

extension View {

    func onLoad(perform action: (() -> Void)? = nil) -> some View {
        modifier(ViewDidLoadModifier(perform: action))
    }

}

Any ideas on how to get the values to refresh in the view when they change?


问:
Run automatic tasks with quartz in springboot changing the intervals dynamically
I'm new using Quartz with SpringBoot.

I want to send certain messages automaticaylly based on a time interval calculation.

For example if I have a list with 2 elements, I want to send the first element message at first, "hello" for example.

But then when I calculate the difference in time between the first element and the second one, let's say that between the first element "hello" message and the second message "how are you" are 21 minutes of difference, I will want to send the second message "how are you" when the 21 minutes has passed.

There is a way for doing something like this with Quartz and SpringBoot?.

Thank you so much guys!

For now I've only read the Quartz documentation and saw some examples, but I don't have yet clear how to do it.


问:
Django filter queryset
Django framework has a product model with about ten values that need to be filtered (color, type..). I'm trying to create a filter like this:
views:
`

```<code>class FilterCctvView(QuerySetsFromCctv, ListView):
    paginate_by = 32
    def get_queryset(self):
        queryset = Cam.objects.filter(
                                Q(maker__in = self.request.GET.getlist("maker")) |
                                Q(type_of_cam__in = self.request.GET.getlist("type_of_cam"))
        )
        return queryset
</code>```

in html:

```<code>  <form action="{% url 'filter' %}" method = 'GET'>
            <ul>
                <p><strong>Manufacturers</strong></p>
                {% for cam in view.get_cctv_makers %}
                    <li>
                        <input type="checkbox" class="checked" name="maker" value="{{cam.maker}}">
                        <span>{{cam.maker}}</span>
                    </li>
                {% endfor %}

            </ul>
            <ul>
                <p><strong>Type of cameras</strong></p>

                {% for cam in view.get_cctv_type %}
                    <li>
                        <input type="checkbox" class="checked" name="type_of_cam" value="{{cam.type_of_cam}}">
                        <span>{{ cam.type_of_cam}}</span>
                    </li>
                {% endfor %}
            </ul>
            <button class="btn btn-success btn-sm" type="submit">Find</button>
        </form>
</code>```

`
enter image description here

But the filter doesn't work correctly, when I select more than two option
How do I do this correctly?

Title: Django filter queryset

Body:
Django framework has a product model with about ten values that need to be filtered (color, type..). I'm trying to create a filter like this:
views:
`

class FilterCctvView(QuerySetsFromCctv, ListView):
    paginate_by = 32
    def get_queryset(self):
        queryset = Cam.objects.filter(
                                Q(maker__in = self.request.GET.getlist("maker")) |
                                Q(type_of_cam__in = self.request.GET.getlist("type_of_cam"))
        )
        return queryset

in html:

  <form action="{% url 'filter' %}" method = 'GET'>

Manufacturers

                {% for cam in view.get_cctv_makers %}

                        <input type="checkbox" class="checked" name="maker" value="{{cam.maker}}">
                        {{cam.maker}}

                {% endfor %}

Type of cameras

                {% for cam in view.get_cctv_type %}

                        <input type="checkbox" class="checked" name="type_of_cam" value="{{cam.type_of_cam}}">
                        {{ cam.type_of_cam}}

                {% endfor %}

            <button class="btn btn-success btn-sm" type="submit">Find</button>
        </form>

`
enter image description here

But the filter doesn't work correctly, when I select more than two option
How do I do this correctly?


问:
retrieve a value with associate with a given key from play.api.libs.json.JsValue
scala.html file contains bellow line

```<code>@{field.indexes.map(x => field("[" + x + "].id").value.orElse(field("[" + x + "]").value.map(Json.parse(_))).getOrElse(""))}
</code>```

this return ArrayBuffer({"id":"1234323","version":"12365"},{"id":"56482","version":"876586"}).
but my requirment is filtering values which mapping with id and return as a list

expected output is ArrayBuffer(1234323,56482)

.scala.html file contains bellow line

```<code>@{field.indexes.map(x => field("[" + x + "].id").value.orElse(field("[" + x + "]").value.map(Json.parse(_))).getOrElse(""))}
</code>```

this return ArrayBuffer({"id":"1234323","version":"12365"},{"id":"56482","version":"876586"}).
but my requirment is filtering values which mapping with id and return as a list

expected output is ArrayBuffer(1234323,56482)

Body:
scala.html file contains bellow line

@{field.indexes.map(x => field("[" + x + "].id").value.orElse(field("[" + x + "]").value.map(Json.parse(_))).getOrElse(""))}

this return ArrayBuffer({"id":"1234323","version":"12365"},{"id":"56482","version":"876586"}).
but my requirment is filtering values which mapping with id and return as a list

expected output is ArrayBuffer(1234323,56482)

.scala.html file contains bellow line

@{field.indexes.map(x => field("[" + x + "].id").value.orElse(field("[" + x + "]").value.map(Json.parse(_))).getOrElse(""))}

this return ArrayBuffer({"id":"1234323","version":"12365"},{"id":"56482","version":"876586"}).
but my requirment is filtering values which mapping with id and return as a list

expected output is ArrayBuffer(1234323,56482)


问:
instance in Django not working properly unable to get pre populate data
i am trying to populate the fileds in django automatically using the instance but its not working for me so someone help to solve this issue

so here is the code

```<code>     def Editquestion(request):

          askit = askm.objects.get(question = "apple")
          print(askit)
          getformdata =  editquestf(instance = askit)
          return render(request, "editquestpage.html", {'edit':getformdata})
</code>```

Body:
i am trying to populate the fileds in django automatically using the instance but its not working for me so someone help to solve this issue

so here is the code

     def Editquestion(request):

          askit = askm.objects.get(question = "apple")
          print(askit)
          getformdata =  editquestf(instance = askit)
          return render(request, "editquestpage.html", {'edit':getformdata})


问:
Why does ReturnType<typeof setTimeout> differ from return type of setTimeout?
I am creating a hook but it's failing typing.

```<code>import { useEffect, useRef } from "react";

export function useTimeoutEffect<TArgs extends any[]>(
  callback: (...args: TArgs) => void,
  ms?: number,
  ...args: TArgs
): void {
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
  useEffect(() => {
    if (timeoutRef.current !== undefined) {
      clearTimeout(timeoutRef.current);
    }
    // Type 'number' is not assignable to type 'Timeout' on next line.
    timeoutRef.current = setTimeout(callback, ms, args);
    return () => {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = undefined;
    };
  }, [ms, args]);
}

</code>```

I used ReturnType<typeof setTimeout>

I don't explicitly add {types: node}

My tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": false,
    "skipLibCheck": true,
    "declarationMap": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "declaration": true,
    "outDir": "./dist",
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "noEmit": true
  },
  "include": [
    "src"
  ],
  "exclude": [
    "**/*.test.ts",
    "**/*.test.tsx",
    "src/test-support/*"
  ]
}
```
<p>I do have <code>@types/node</code> in my node_modules but it appears to be added by jest.</p>
<p>For now I worked aounrd it by typecasting as <code>any</code> but I'd like to avoid that.</p>
```timeoutRef.current = setTimeout(callback, ms, args) as any;
```
<p>The full error is</p>
```$ C:\p\spring-docker\node_modules\.bin\tsc
src/useTimeoutEffect/useTimeoutEffect.ts:19:5 - error TS2322: Type 'number' is not assignable to type 'Timeout'.

19     timeoutRef.current = setTimeout(callback, ms, args);
       ~~~~~~~~~~~~~~~~~~

Found 1 error in src/useTimeoutEffect/useTimeoutEffect.ts:19
```
<p>Code in https://github.com/trajano/react-hooks/blob/master/src/useTimeoutEffect/useTimeoutEffect.ts</p>
<p>I also tried explicitly emptying the types by adding the following to tsconfig.json and still the same error.</p>
```"types": []
```

Body:
I am creating a hook but it's failing typing.

import { useEffect, useRef } from "react";

export function useTimeoutEffect<TArgs extends any[]>(
  callback: (...args: TArgs) => void,
  ms?: number,
  ...args: TArgs
): void {
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
  useEffect(() => {
    if (timeoutRef.current !== undefined) {
      clearTimeout(timeoutRef.current);
    }
    // Type 'number' is not assignable to type 'Timeout' on next line.
    timeoutRef.current = setTimeout(callback, ms, args);
    return () => {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = undefined;
    };
  }, [ms, args]);
}

I used ReturnType<typeof setTimeout>

I don't explicitly add {types: node}

My tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": false,
    "skipLibCheck": true,
    "declarationMap": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "declaration": true,
    "outDir": "./dist",
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "noEmit": true
  },
  "include": [
    "src"
  ],
  "exclude": [
    "**/*.test.ts",
    "**/*.test.tsx",
    "src/test-support/*"
  ]
}

I do have @types/node in my node_modules but it appears to be added by jest.

For now I worked aounrd it by typecasting as any but I'd like to avoid that.

timeoutRef.current = setTimeout(callback, ms, args) as any;

The full error is

$ C:\p\spring-docker\node_modules\.bin\tsc
src/useTimeoutEffect/useTimeoutEffect.ts:19:5 - error TS2322: Type 'number' is not assignable to type 'Timeout'.

19     timeoutRef.current = setTimeout(callback, ms, args);
       ~~~~~~~~~~~~~~~~~~

Found 1 error in src/useTimeoutEffect/useTimeoutEffect.ts:19

Code in https://github.com/trajano/react-hooks/blob/master/src/useTimeoutEffect/useTimeoutEffect.ts

I also tried explicitly emptying the types by adding the following to tsconfig.json and still the same error.

"types": []


问:
Counter resets everytime I use a specific command
I made a bot that got some diffrent features. The bot is able to count everytime I use a specific command, and adds it to a personal counter of that member that uses the command. It also got a leaderboard that shows how many time the discord member used the specific command.

I ran in to a problem when using the command !check-in and then after uses the !check-out it adds +1 to the counter that I see with the command !info. But when repeating the process the counter just resets to 0 like a loop.

Can someone tell me how to fix this problem?

```<code>import discord
from discord.ext.commands import Bot

client = discord.Client()

check-ins
check_ins = {}

@client.event
async def on_message(message):
    if message.content.startswith("!"):
        command, *args = message.content.split()

        if command == "!check-ind":

            check_ins[message.author] = False

            await message.channel.send(f"{message.author.name} er gået på arbejde")

        elif command == "!check-ud":

            if message.author not in check_ins:
                await message.channel.send("Du skal check-in før du kan check-ud")
            else:

                check_ins[message.author] = True

                await message.channel.send(f"{message.author.name} er gået af arbejde")

        elif command == "!info":
            check_in_count = sum(check_ins[user] for user in check_ins if user == message.author)
            await message.channel.send(f"Du har været på arbejde {check_in_count} gange!")

        elif command == "!leaderboard":
            sorted_check_ins = sorted(check_ins, key=lambda user: sum(check_ins[user] for user in check_ins if user == message.author), reverse=True)

            leaderboard_message = "Leaderboard:\n"
            for i, user in enumerate(sorted_check_ins):
                check_in_count = sum(check_ins[user] for user in check_ins if user == message.author)
                leaderboard_message += f"{i + 1}. {user}: {check_in_count}\n"

            await message.channel.send(leaderboard_message)
</code>```

Body:
I made a bot that got some diffrent features. The bot is able to count everytime I use a specific command, and adds it to a personal counter of that member that uses the command. It also got a leaderboard that shows how many time the discord member used the specific command.

I ran in to a problem when using the command !check-in and then after uses the !check-out it adds +1 to the counter that I see with the command !info. But when repeating the process the counter just resets to 0 like a loop.

Can someone tell me how to fix this problem?

import discord
from discord.ext.commands import Bot

client = discord.Client()

check-ins
check_ins = {}

@client.event
async def on_message(message):
    if message.content.startswith("!"):
        command, *args = message.content.split()

        if command == "!check-ind":

            check_ins[message.author] = False

            await message.channel.send(f"{message.author.name} er gået på arbejde")

        elif command == "!check-ud":

            if message.author not in check_ins:
                await message.channel.send("Du skal check-in før du kan check-ud")
            else:

                check_ins[message.author] = True

                await message.channel.send(f"{message.author.name} er gået af arbejde")

        elif command == "!info":
            check_in_count = sum(check_ins[user] for user in check_ins if user == message.author)
            await message.channel.send(f"Du har været på arbejde {check_in_count} gange!")

        elif command == "!leaderboard":
            sorted_check_ins = sorted(check_ins, key=lambda user: sum(check_ins[user] for user in check_ins if user == message.author), reverse=True)

            leaderboard_message = "Leaderboard:\n"
            for i, user in enumerate(sorted_check_ins):
                check_in_count = sum(check_ins[user] for user in check_ins if user == message.author)
                leaderboard_message += f"{i + 1}. {user}: {check_in_count}\n"

            await message.channel.send(leaderboard_message)


问:
How to make javascript read 0 as a number
I am having this issue where I am trying to create GIF's based off a images in a file directory and those images go based off numbers starting with 0, the whole function works perfectly besides when the user want's the start time to be 0, then the gif function doesn't work, I suspect this is because js is reading 0 as false and not a number, I tried Number() and parseInt() but neither is working. I see in the console log when a user selects any other hour than 0 to start, it works, but when they select 0 to start, the consolelog of the image array doesn't pop up.

document.getElementById('button').addEventListener('click', function() {
  // show the box if it's hidden, or hide it if it's visible
  document.getElementById('box').style.display =
    document.getElementById('box').style.display === 'none' ? 'block' : 'none';
});

    // close the box when the user clicks outside of it
document.addEventListener('click', function(event) {
  // check if the clicked element is the button or is inside the open box
  var isButton = event.target.closest('#button') !== null;
  var isInsideBox = event.target.closest('#box') !== null;

  // if the clicked element is not the button or inside the box, hide the box
  if (!isButton && !isInsideBox) {
    document.getElementById('box').style.display = 'none';
  }
});
// declare the selectedValue variable
var selectedValue1;
var dropdown1 = document.getElementById('dropdown1');

// add an event listener for the 'change' event on the dropdown menu
dropdown1.addEventListener('change', function() {
  // get the selected option
  var selectedOption1 = this.options[this.selectedIndex].value;

  // save the selected option as a variable
  selectedValue1 = parseInt(selectedOption1);
});

var selectedValue2;
var dropdown2 = document.getElementById('dropdown2');

// add an event listener for the 'change' event on the dropdown menu
dropdown2.addEventListener('change', function() {
  // get the selected option
  var selectedOption2 = this.options[this.selectedIndex].value;

  // save the selected option as a variable
  selectedValue2 = parseInt(selectedOption2);
      // check if the selected option is the top option

});
// create a string that points to the directory
    var directory = 'path/to/images/';
// add an event listener for the 'change' event on the dropdown menu
dropdown2.addEventListener('change', function() {

    // check if the selectedValue1 and selectedValue2 variables have been assigned values
    if (selectedValue1 && selectedValue2) {

        // create an array of images
        var images = [];

        // set the starting image
        var startImage = parseInt(selectedValue1);

        // set the ending image
        var endImage = parseInt(selectedValue2);

        // set the step size for the images
        var step = 6;

        // create a loop to add the images to the array
        for (var i = startImage; i <= endImage; i += step) {
          var filePath = directory +"gfs_6hr_2m_temp_hour_"+i+ '.png';
          // add the image to the array
          images.push(filePath);
        }
          const downloadButton = document.getElementById('download-button');

        // Handle the button click
        downloadButton.addEventListener('click', function () {
          /// Generate gif
        gifshot.createGIF({
          'images': images,
          'gifWidth': 1144,
          'gifHeight': 894,
          'interval': 0.33
        },function(obj) {
          if(!obj.error) {

              saveAs(obj.image, 'my-gif.gif');
          }
        });

        });

        console.log(images);
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  display: none;
    background-color: grey;
    padding: 10px;/* hide the box by default */
     max-width: 200px; /* set a maximum width for the box */
  overflow: hidden; /* hide any content that overflows the box */
}
#button:hover {
  cursor: pointer;
}
#download-button:hover {
  cursor: pointer;
}</code>```

<button id="button">Open Box</button>

    Starting Hour:
  <select id="dropdown1">
    <option value="">Select Hour</option>
    <option value="0">0</option>
    <option value="6">6</option>
  </select>

    Ending Hour:
  <select id="dropdown2">
    <option value="">Select Hour</option>
    <option value="6">6</option>
    <option value="12">12</option>
  </select>

    <button id="download-button">Download GIF</button>

```

Body:
I am having this issue where I am trying to create GIF's based off a images in a file directory and those images go based off numbers starting with 0, the whole function works perfectly besides when the user want's the start time to be 0, then the gif function doesn't work, I suspect this is because js is reading 0 as false and not a number, I tried Number() and parseInt() but neither is working. I see in the console log when a user selects any other hour than 0 to start, it works, but when they select 0 to start, the consolelog of the image array doesn't pop up.

document.getElementById('button').addEventListener('click', function() {
  // show the box if it's hidden, or hide it if it's visible
  document.getElementById('box').style.display =
    document.getElementById('box').style.display === 'none' ? 'block' : 'none';
});

    // close the box when the user clicks outside of it
document.addEventListener('click', function(event) {
  // check if the clicked element is the button or is inside the open box
  var isButton = event.target.closest('#button') !== null;
  var isInsideBox = event.target.closest('#box') !== null;

  // if the clicked element is not the button or inside the box, hide the box
  if (!isButton && !isInsideBox) {
    document.getElementById('box').style.display = 'none';
  }
});
// declare the selectedValue variable
var selectedValue1;
var dropdown1 = document.getElementById('dropdown1');

// add an event listener for the 'change' event on the dropdown menu
dropdown1.addEventListener('change', function() {
  // get the selected option
  var selectedOption1 = this.options[this.selectedIndex].value;

  // save the selected option as a variable
  selectedValue1 = parseInt(selectedOption1);
});

var selectedValue2;
var dropdown2 = document.getElementById('dropdown2');

// add an event listener for the 'change' event on the dropdown menu
dropdown2.addEventListener('change', function() {
  // get the selected option
  var selectedOption2 = this.options[this.selectedIndex].value;

  // save the selected option as a variable
  selectedValue2 = parseInt(selectedOption2);
      // check if the selected option is the top option

});
// create a string that points to the directory
    var directory = 'path/to/images/';
// add an event listener for the 'change' event on the dropdown menu
dropdown2.addEventListener('change', function() {

    // check if the selectedValue1 and selectedValue2 variables have been assigned values
    if (selectedValue1 && selectedValue2) {

        // create an array of images
        var images = [];

        // set the starting image
        var startImage = parseInt(selectedValue1);

        // set the ending image
        var endImage = parseInt(selectedValue2);

        // set the step size for the images
        var step = 6;

        // create a loop to add the images to the array
        for (var i = startImage; i <= endImage; i += step) {
          var filePath = directory +"gfs_6hr_2m_temp_hour_"+i+ '.png';
          // add the image to the array
          images.push(filePath);
        }
          const downloadButton = document.getElementById('download-button');

        // Handle the button click
        downloadButton.addEventListener('click', function () {
          /// Generate gif
        gifshot.createGIF({
          'images': images,
          'gifWidth': 1144,
          'gifHeight': 894,
          'interval': 0.33
        },function(obj) {
          if(!obj.error) {

              saveAs(obj.image, 'my-gif.gif');
          }
        });

        });

        console.log(images);
    }
})

#box {
  display: none;
    background-color: grey;
    padding: 10px;/* hide the box by default */
     max-width: 200px; /* set a maximum width for the box */
  overflow: hidden; /* hide any content that overflows the box */
}
#button:hover {
  cursor: pointer;
}
#download-button:hover {
  cursor: pointer;
}

<button id="button">Open Box</button>

    Starting Hour:
  <select id="dropdown1">
    <option value="">Select Hour</option>
    <option value="0">0</option>
    <option value="6">6</option>
  </select>

    Ending Hour:
  <select id="dropdown2">
    <option value="">Select Hour</option>
    <option value="6">6</option>
    <option value="12">12</option>
  </select>

    <button id="download-button">Download GIF</button>