问:
Trying to apply zoom on click with react-leaflet
I'm trying to replicate some functions of the leaflet map https://leafletjs.com/examples/choropleth/ to react/typeScript but I'm getting an error when I try to add the function to zoom on a Feature it breaks, this is the code I'm working on

```<code>import Leaflet from 'leaflet';
import React, {
  useRef, RefObject,
} from 'react';
import {
  MapContainer, TileLayer, GeoJSON, useMap,
} from 'react-leaflet';
import styled from 'styled-components';

import { statesData } from './statesData';
import './style.css';

const EmployerLocationMap = () => {
  const geoJson: RefObject<Leaflet.GeoJSON> = useRef(null);
  const map = useMap();

  const highlightFeature = (e: Leaflet.LeafletMouseEvent) => {
    const layer = e.target;

    layer.setStyle({
      color: '#666',
      dashArray: '',
      fillOpacity: 0.7,
      weight: 5,
    });
  };

  const resetHighlight = (e: Leaflet.LeafletMouseEvent) => {
    geoJson.current?.resetStyle(e.target);
  };

  const zoomToFeature = (e: Leaflet.LeafletMouseEvent) => {
    map.fitBounds(e.target.getBounds());
  };

  return (
    <CardContainer>
      <Row>
        <Col width='60%'>
          <MapContainer
            center={[37.8, -96]}
            zoom={3}
          >
            <TileLayer
              attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
            <GeoJSON
              data={statesData}
              key='usa-states'
              ref={geoJson}
              style={() => {
                return {
                  color: 'white',
                  dashArray: '3',
                  fillColor: '#f0f0f0',
                  fillOpacity: 0.7,
                  opacity: 1,
                  weight: 2,
                };
              }}
              onEachFeature={(__, layer) => {
                layer.on({
                  click: (e) => {
                    zoomToFeature(e);
                  },
                  mouseout: (e) => {
                    resetHighlight(e);
                  },
                  mouseover: (e) => {
                    highlightFeature(e);
                  },
                });
              }}
            />
          </MapContainer>
        </Col>
      </Row>

    </CardContainer>
  );
};

export default EmployerLocationMap;
</code>```

and when I start the frontend i get this error on the console:

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

at useLeafletContext

I don't get what could be wrong, I've seen several implementations on this and it looks the same.

答:
useMap can only be used within a component that is itself a child/descendant of <MapContainer>.
https://react-leaflet.js.org/docs/api-map/#usemap

Hook providing the Leaflet Map instance in any descendant of a MapContainer.

Here you try calling useMap in your EmployerLocationMap component, which contains a <MapContainer>, but which is obviously not a descendant of one.

A solution for your case could be to separate the map logic in another component that you can place inside the <MapContainer>:

```<code>const EmployerLocationMap = () => {
  return (
    <CardContainer>
      <Row>
        <Col width='60%'>
          <MapContainer
            center={[37.8, -96]}
            zoom={3}
          >
            <TileLayer
              attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
            <MapContent />
          </MapContainer>
        </Col>
      </Row>

    </CardContainer>
  );
};

const MapContent = () => {
  const geoJson: RefObject<Leaflet.GeoJSON> = useRef(null);
  const map = useMap();

  const highlightFeature = (e: Leaflet.LeafletMouseEvent) => {
    const layer = e.target;

    layer.setStyle({
      color: '#666',
      dashArray: '',
      fillOpacity: 0.7,
      weight: 5,
    });
  };

  const resetHighlight = (e: Leaflet.LeafletMouseEvent) => {
    geoJson.current?.resetStyle(e.target);
  };

  const zoomToFeature = (e: Leaflet.LeafletMouseEvent) => {
    map.fitBounds(e.target.getBounds());
  };

  return (
            <GeoJSON
              data={statesData}
              key='usa-states'
              ref={geoJson}
              style={() => {
                return {
                  color: 'white',
                  dashArray: '3',
                  fillColor: '#f0f0f0',
                  fillOpacity: 0.7,
                  opacity: 1,
                  weight: 2,
                };
              }}
              onEachFeature={(__, layer) => {
                layer.on({
                  click: (e) => {
                    zoomToFeature(e);
                  },
                  mouseout: (e) => {
                    resetHighlight(e);
                  },
                  mouseover: (e) => {
                    highlightFeature(e);
                  },
                });
              }}
            />
  );
};
</code>```

Body:
I'm trying to replicate some functions of the leaflet map https://leafletjs.com/examples/choropleth/ to react/typeScript but I'm getting an error when I try to add the function to zoom on a Feature it breaks, this is the code I'm working on

import Leaflet from 'leaflet';
import React, {
  useRef, RefObject,
} from 'react';
import {
  MapContainer, TileLayer, GeoJSON, useMap,
} from 'react-leaflet';
import styled from 'styled-components';

import { statesData } from './statesData';
import './style.css';

const EmployerLocationMap = () => {
  const geoJson: RefObject<Leaflet.GeoJSON> = useRef(null);
  const map = useMap();

  const highlightFeature = (e: Leaflet.LeafletMouseEvent) => {
    const layer = e.target;

    layer.setStyle({
      color: '#666',
      dashArray: '',
      fillOpacity: 0.7,
      weight: 5,
    });
  };

  const resetHighlight = (e: Leaflet.LeafletMouseEvent) => {
    geoJson.current?.resetStyle(e.target);
  };

  const zoomToFeature = (e: Leaflet.LeafletMouseEvent) => {
    map.fitBounds(e.target.getBounds());
  };

  return (
    <CardContainer>
      <Row>
        <Col width='60%'>
          <MapContainer
            center={[37.8, -96]}
            zoom={3}
          >
            <TileLayer
              attribution='© OpenStreetMap contributors'
              url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
            <GeoJSON
              data={statesData}
              key='usa-states'
              ref={geoJson}
              style={() => {
                return {
                  color: 'white',
                  dashArray: '3',
                  fillColor: '#f0f0f0',
                  fillOpacity: 0.7,
                  opacity: 1,
                  weight: 2,
                };
              }}
              onEachFeature={(__, layer) => {
                layer.on({
                  click: (e) => {
                    zoomToFeature(e);
                  },
                  mouseout: (e) => {
                    resetHighlight(e);
                  },
                  mouseover: (e) => {
                    highlightFeature(e);
                  },
                });
              }}
            />
          </MapContainer>
        </Col>
      </Row>

    </CardContainer>
  );
};

export default EmployerLocationMap;

and when I start the frontend i get this error on the console:

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

at useLeafletContext

I don't get what could be wrong, I've seen several implementations on this and it looks the same.

Body:
useMap can only be used within a component that is itself a child/descendant of <MapContainer>.
https://react-leaflet.js.org/docs/api-map/#usemap

Hook providing the Leaflet Map instance in any descendant of a MapContainer.

Here you try calling useMap in your EmployerLocationMap component, which contains a <MapContainer>, but which is obviously not a descendant of one.

A solution for your case could be to separate the map logic in another component that you can place inside the <MapContainer>:

const EmployerLocationMap = () => {
  return (
    <CardContainer>
      <Row>
        <Col width='60%'>
          <MapContainer
            center={[37.8, -96]}
            zoom={3}
          >
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
            />
            <MapContent />
          </MapContainer>
        </Col>
      </Row>

    </CardContainer>
  );
};

const MapContent = () => {
  const geoJson: RefObject<Leaflet.GeoJSON> = useRef(null);
  const map = useMap();

  const highlightFeature = (e: Leaflet.LeafletMouseEvent) => {
    const layer = e.target;

    layer.setStyle({
      color: '#666',
      dashArray: '',
      fillOpacity: 0.7,
      weight: 5,
    });
  };

  const resetHighlight = (e: Leaflet.LeafletMouseEvent) => {
    geoJson.current?.resetStyle(e.target);
  };

  const zoomToFeature = (e: Leaflet.LeafletMouseEvent) => {
    map.fitBounds(e.target.getBounds());
  };

  return (
            <GeoJSON
              data={statesData}
              key='usa-states'
              ref={geoJson}
              style={() => {
                return {
                  color: 'white',
                  dashArray: '3',
                  fillColor: '#f0f0f0',
                  fillOpacity: 0.7,
                  opacity: 1,
                  weight: 2,
                };
              }}
              onEachFeature={(__, layer) => {
                layer.on({
                  click: (e) => {
                    zoomToFeature(e);
                  },
                  mouseout: (e) => {
                    resetHighlight(e);
                  },
                  mouseover: (e) => {
                    highlightFeature(e);
                  },
                });
              }}
            />
  );
};


来源: stackexchange

问:
Helm Chart - Process File result with multiple lines
I have a ConfigMap where I am including a file in its data attribute and I need to replace several strings from it. But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

This is what I don't want:

```<code>apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 | replace "var1_enabled" (toString .Values.myVar1.enabled) | replace "var2_enabled" (toString .Values.myVar2.enabled) }}
</code>```

This is what I'm trying to do:

```<code>apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 |
  replace "var1_enabled" (toString .Values.myVar1.enabled) |
  replace "var2_enabled" (toString .Values.myVar2.enabled) }}
</code>```

What is the right syntax to do this?

答:
As is not possible to split the expression into multiple lines at the ConfigMap, I finally got a solution using the _helpers.tpl file.

Basically I created a dictionary with all the variables I want to replace and the respective new value to replace, and then I iterated over that dict and did the replace at my files's config:

```<code>{{/*
Manage the files and replace some variables
*/}}
{{- define "myFiles" -}}
{{ $filesConfig := (.Files.Glob "myFolder/*.json").AsConfig }}

{{ $myVars := dict "var1_enabled" (toString .Values.myVar1.enabled) }}
{{ $myVars = merge $myVars (dict "var2_enabled" (toString .Values.myVar2.enabled)) }}

{{ range $key, $value := $myVars }}
{{ $filesConfig = ($filesConfig | replace $key $value) }}
{{ end }}

{{ $filesConfig }}
{{- end -}}
</code>```

And then I changed my ConfigMap to something like this:

```<code>{{- $myFiles := include "myFiles" . -}}
apiVersion: v1
kind: ConfigMap
data:
  {{ $myFiles }}
</code>```

I don't nothing about this kind of language, so if you know how to improve this, please feel free to comment.

ContentLicense: CC BY-SA 4.0

Body:
I have a ConfigMap where I am including a file in its data attribute and I need to replace several strings from it. But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

This is what I don't want:

apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 | replace "var1_enabled" (toString .Values.myVar1.enabled) | replace "var2_enabled" (toString .Values.myVar2.enabled) }}

This is what I'm trying to do:

apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 |
  replace "var1_enabled" (toString .Values.myVar1.enabled) |
  replace "var2_enabled" (toString .Values.myVar2.enabled) }}

What is the right syntax to do this?

Body:
As is not possible to split the expression into multiple lines at the ConfigMap, I finally got a solution using the _helpers.tpl file.

Basically I created a dictionary with all the variables I want to replace and the respective new value to replace, and then I iterated over that dict and did the replace at my files's config:

{{/*
Manage the files and replace some variables
*/}}
{{- define "myFiles" -}}
{{ $filesConfig := (.Files.Glob "myFolder/*.json").AsConfig }}

{{ $myVars := dict "var1_enabled" (toString .Values.myVar1.enabled) }}
{{ $myVars = merge $myVars (dict "var2_enabled" (toString .Values.myVar2.enabled)) }}

{{ range $key, $value := $myVars }}
{{ $filesConfig = ($filesConfig | replace $key $value) }}
{{ end }}

{{ $filesConfig }}
{{- end -}}

And then I changed my ConfigMap to something like this:

{{- $myFiles := include "myFiles" . -}}
apiVersion: v1
kind: ConfigMap
data:
  {{ $myFiles }}

I don't nothing about this kind of language, so if you know how to improve this, please feel free to comment.


问:
custom sort using linq based on Ranks
I am trying to sort data in a table based on Ranks. Not sure how to achieve this in linq's

Input Table:

Rank Table:

Based on the Input & Rank table, I am expecting the output as below:

答:
If your classes are defined as follows:

```<code>public class StateAndCodes
{
    public string State { get; set; }
    public int? Codes { get; set; }
}

public class RankAndCodes
{
    public int Rank { get; set; }
    public int Codes { get; set; }
}
</code>```

, your input and rank tables may be represented as follows:

```<code>var input = new List<StateAndCodes>
{
    new StateAndCodes { State = "GA" },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30112 },
    new StateAndCodes { State = "GA", Codes = 30093 },
    new StateAndCodes { State = "GA", Codes = 31088 },
    new StateAndCodes { State = "GA", Codes = 31088 }, // Assuming 30188 was a typo in original post?
    new StateAndCodes { State = "GA", Codes = 30363 },
    new StateAndCodes { State = "GA", Codes = 30363 },
    new StateAndCodes { State = "GA", Codes = 30363 },
};

var rank = new List<RankAndCodes>
{
    new RankAndCodes { Rank = 1, Codes = 30115 },
    new RankAndCodes { Rank = 2, Codes = 30363 },
    new RankAndCodes { Rank = 3, Codes = 31088 },
    new RankAndCodes { Rank = 4, Codes = 30223 },
};
</code>```

You could then

group the Codess in your input table by Codes

sort the Codes groups so that groups that have no Codes (Codes == null) come after groups that do have a Codes value

then, sort the groups that do have a Codes value according to their matching Rank value in the rank table (if a matching Rank value exists; if not, sort last)

flattening the results (the groupings are dissolved)

converting the results to a list

as follows:

```<code>var output = input
    .GroupBy(entry => entry.Codes)
    .OrderByDescending(gr => gr.Key.HasValue)
    .ThenBy(gr =>
        rank.SingleOrDefault(r => r.Codes == gr.Key)?.Rank ??
        rank.Max(r => r.Rank) + 1)
    .SelectMany(gr => gr.Select(entry => entry))
    .ToList();
</code>```

Title: custom sort using linq based on Ranks

Body:
If your classes are defined as follows:

public class StateAndCodes
{
    public string State { get; set; }
    public int? Codes { get; set; }
}

public class RankAndCodes
{
    public int Rank { get; set; }
    public int Codes { get; set; }
}

, your input and rank tables may be represented as follows:

var input = new List<StateAndCodes>
{
    new StateAndCodes { State = "GA" },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30223 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30115 },
    new StateAndCodes { State = "GA", Codes = 30112 },
    new StateAndCodes { State = "GA", Codes = 30093 },
    new StateAndCodes { State = "GA", Codes = 31088 },
    new StateAndCodes { State = "GA", Codes = 31088 }, // Assuming 30188 was a typo in original post?
    new StateAndCodes { State = "GA", Codes = 30363 },
    new StateAndCodes { State = "GA", Codes = 30363 },
    new StateAndCodes { State = "GA", Codes = 30363 },
};

var rank = new List<RankAndCodes>
{
    new RankAndCodes { Rank = 1, Codes = 30115 },
    new RankAndCodes { Rank = 2, Codes = 30363 },
    new RankAndCodes { Rank = 3, Codes = 31088 },
    new RankAndCodes { Rank = 4, Codes = 30223 },
};

You could then

group the Codess in your input table by Codes

sort the Codes groups so that groups that have no Codes (Codes == null) come after groups that do have a Codes value

then, sort the groups that do have a Codes value according to their matching Rank value in the rank table (if a matching Rank value exists; if not, sort last)

flattening the results (the groupings are dissolved)

converting the results to a list

as follows:

var output = input
    .GroupBy(entry => entry.Codes)
    .OrderByDescending(gr => gr.Key.HasValue)
    .ThenBy(gr =>
        rank.SingleOrDefault(r => r.Codes == gr.Key)?.Rank ??
        rank.Max(r => r.Rank) + 1)
    .SelectMany(gr => gr.Select(entry => entry))
    .ToList();


问:
Why is `Properties` not a valid field name in ksql?
https://docs.confluent.io/5.4.1/ksql/docs/developer-guide/syntax-reference.html#struct-overview Confluent docs say they don't accept Properties as a valid field name, but why?

What if I do have a schema with Properties, what can I do then?

答:
It's a keyword/reserved word in the language. I'm not familiar with ksql specifically, but most sql distributions provide backticks to escape references for this reason (and more). Without those, it'd make sense you couldn't use it.

As an example of using backticks in a pretty standard sql statement:

```<code>SELECT `table`.`properties` FROM `table` ...
</code>```

Body:
It's a keyword/reserved word in the language. I'm not familiar with ksql specifically, but most sql distributions provide backticks to escape references for this reason (and more). Without those, it'd make sense you couldn't use it.

As an example of using backticks in a pretty standard sql statement:

SELECT `table`.`properties` FROM `table` ...


问:
Question on workflow Bookmarks
I want to know how can i pass more than one Input Argument in a workflow bookmark. i have this code

```<code>   public sealed class CodeActivity1 : NativeActivity<String>
{
    [RequiredArgument]
    public InArgument<string> BookmarkName { get; set; }

    protected override void Execute(NativeActivityContext context)
    {

        context.CreateBookmark(BookmarkName.Get(context),
            new BookmarkCallback(OnResumeBookmark));
    }

    // NativeActivity derived activities that do asynchronous operations by calling
    // one of the CreateBookmark overloads defined on System.Activities.NativeActivityContext

    protected override bool CanInduceIdle
    {
        get { return true; }
    }

    public void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object obj)
    {
        Result.Set(context, (string)obj);
    }
}
</code>```

When I resume it like app.ResumeBookmark("Test", "inputTest");. But what if i have for example 2 output Arguments like

```<code>        public InArgument<string> BookmarkName { get; set; }
        public OutArgument<string> Test1 {get; set;}
        public OutArgument<string> Test2 {get; set;}
</code>```

How can i call this bookmark with app.ResumeBookmark()? and set the 2 OutArguments with stirngs from outside?. Like app.ResumeBookmark("Test","Inputtest1","Inputtest2")?
Thx for your time

答: You can pass any object you want into the ResumeBookmark() call. So just create a class with three properties and use an instance of that class.</p>

ContentLicense: CC BY-SA 3.0

Title: Question on workflow Bookmarks

Body:
I want to know how can i pass more than one Input Argument in a workflow bookmark. i have this code

   public sealed class CodeActivity1 : NativeActivity<String>
{
    [RequiredArgument]
    public InArgument<string> BookmarkName { get; set; }

    protected override void Execute(NativeActivityContext context)
    {

        context.CreateBookmark(BookmarkName.Get(context),
            new BookmarkCallback(OnResumeBookmark));
    }

    // NativeActivity derived activities that do asynchronous operations by calling
    // one of the CreateBookmark overloads defined on System.Activities.NativeActivityContext

    protected override bool CanInduceIdle
    {
        get { return true; }
    }

    public void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object obj)
    {
        Result.Set(context, (string)obj);
    }
}

When I resume it like app.ResumeBookmark("Test", "inputTest");. But what if i have for example 2 output Arguments like

        public InArgument<string> BookmarkName { get; set; }
        public OutArgument<string> Test1 {get; set;}
        public OutArgument<string> Test2 {get; set;}

How can i call this bookmark with app.ResumeBookmark()? and set the 2 OutArguments with stirngs from outside?. Like app.ResumeBookmark("Test","Inputtest1","Inputtest2")?
Thx for your time


问:
Simplest way to determine if the user has internet connection? Navigation.onLine doesn't work since it always returns true on some OS
I am trying to create a function that tells me if the user currently has internet connection. The first thing that came to mind was to use navigation.onLine, however, it turned out that on Windows 11 and Linux with Chrome, it always returns true, so this is unusable.

My second idea is to make a GET request to some resource and assume that the user has no connection if the request fails, but that seems very crude to me.

Do I have any other alternatives?

答:
You will need to perform a GET request and if that request is successful do something, while if that request times out, do something else.

It is advisable to request to the same domain that's opened or which accepts requests.

EDIT

As @Corey Ogburn pointed out in the comment section, a HEAD request is better in terms of performance than a GET request.


问:
i've got error during making metronome in python
i'm new here so please understand my stupid format :)

Let's get down to the business.

i was studying and trying to make metronome programm by Kwisses on github.

when i complied the code it says

"line 29 def interface(self):
^
IndentationError: unindent does not match any outer indentation level"

i develop on windows with pycharm and here is the code

```<code>import tkinter
from tkinter import *
from winsound import Beep

class Metronome:
    """Create Metronome app with class instance."""

    def __init__(self,root,beats):
        """initiate default values for class and call interface()."""

        self.root=root
        self.beats=beats

        self.start=False
        self.bpm=0
        self.count=0
        self.beat=0
        self.time=0

        self.var=StringVar()
        self.var.set(self.count)

        self.interface()

     def interface(self):

         frame=Frame()
         frame.pack()

         entry=Entry(frame,width=8,justify="center")
         entry.insert(0,"60")
             entry.grid(row=0,column=1,sticky="E")

         spinbox=Spinbox(frame,width=5,values=self.beats,wrap=True)
         spinbox.grid(row=0,column=1,sticky="E")

         label_bpm=Label(frame,text="BPM:")
         label_bpm.grid(row=0,column=0,sticky="W")

         label_time=Label(frame,text="Time:")
         label_time.grid(row=0,column=1,padx=5,sticky="W")

         label_count=Label(frame,textvariable=self.var,font=("Arial",30))
         label_count.grid(row=1,column=0,columnspan=2)

         button_start=Button(frame,text="Start",width=10,height=2,
         command=lambda:self.start_counter(entry,spinbox))
         button_start.grid(row=2,column=0,padx=10,sticky="W")

         button_stop=Button(frame,text="Stop",width=10,height=2,
         command=lambda:self.stop_counter())
         button_stop.grid(row=2,column=1,padx=10,sticky="E")

    def start_counter(self,entry,spinbox):
        if not self.start:
            try:
                self.bpm=int(entry.get())
            except ValueError:
                self.bpm=60
            else:
                if self.bpm>300:
                    self.bpm=300

            self.start=True
            self.counter(spinbox)

    def stop_counter(self):
        self.start=False

    def counter(self,spinbox):
        if self.beat==6:
            self.time=int(((60/(self.bpm/.5)-0.1))*1000)
        else:
            self.time=int((60/self.bpm-0.1)*1000)

        self.count +=1
        self.var.set(self.count)

        if self.count==1:
            Beep(880,100)
        elif self.count >=self.beat:
            self.count=0
            Beep(440,100)
        else:
            Beep(440,100)

        self.root.after(self.time,lambda :self.count(spinbox))

def main():
    root=Tk()
    root.title("Metronome")

    beats=["4/4","6/8","2/4","3/4"]
    Metronome(root,beats)

    root.mainloop()

if __name__=="__main__":
    main()
</code>```

答:
If the problem is about the spaces and tabs, it might work better like this :

```<code>import tkinter
from tkinter import *
from winsound import Beep

class Metronome:
    """Create Metronome app with class instance."""

    def __init__(self, root, beats):
        """initiate default values for class and call interface()."""

        self.root = root
        self.beats = beats

        self.start = False
        self.bpm = 0
        self.count = 0
        self.beat = 0
        self.time = 0

        self.var = StringVar()
        self.var.set(self.count)

        self.interface()

    def interface(self):

        frame=Frame()
        frame.pack()

        entry=Entry(frame,width=8,justify="center")
        entry.insert(0,"60")
        entry.grid(row=0,column=1,sticky="E")

        spinbox=Spinbox(frame,width=5,values=self.beats,wrap=True)
        spinbox.grid(row=0,column=1,sticky="E")

        label_bpm=Label(frame,text="BPM:")
        label_bpm.grid(row=0,column=0,sticky="W")

        label_time=Label(frame,text="Time:")
        label_time.grid(row=0,column=1,padx=5,sticky="W")

        label_count=Label(frame,textvariable=self.var,font=("Arial",30))
        label_count.grid(row=1,column=0,columnspan=2)

        button_start=Button(frame,text="Start",width=10,height=2,
        command=lambda:self.start_counter(entry,spinbox))
        button_start.grid(row=2,column=0,padx=10,sticky="W")

        button_stop=Button(frame,text="Stop",width=10,height=2,
        command=lambda:self.stop_counter())
        button_stop.grid(row=2,column=1,padx=10,sticky="E")

    def start_counter(self,entry,spinbox):
        if not self.start:
            try:
                self.bpm=int(entry.get())
            except ValueError:
                self.bpm=60
            else:
                if self.bpm>300:
                    self.bpm=300

            self.start=True
            self.counter(spinbox)

    def stop_counter(self):
        self.start=False

    def counter(self,spinbox):
        if self.beat==6:
            self.time=int(((60/(self.bpm/.5)-0.1))*1000)
        else:
            self.time=int((60/self.bpm-0.1)*1000)

        self.count +=1
        self.var.set(self.count)

        if self.count==1:
            Beep(880,100)
        elif self.count >=self.beat:
            self.count=0
            Beep(440,100)
        else:
            Beep(440,100)

        self.root.after(self.time,lambda :self.counter(spinbox))

def main():
    root=Tk()
    root.title("Metronome")

    beats=["4/4","6/8","2/4","3/4"]
    Metronome(root,beats)

    root.mainloop()

if __name__=="__main__":
    main()
</code>```

Also there was an error on the 90th line it was written

```<code>self.root.after(self.time,lambda :self.count(spinbox))
</code>```

instead of

```<code>self.root.after(self.time,lambda :self.counter(spinbox))
</code>```

Body:
i'm new here so please understand my stupid format :)

Let's get down to the business.

i was studying and trying to make metronome programm by Kwisses on github.

when i complied the code it says

"line 29 def interface(self):
^
IndentationError: unindent does not match any outer indentation level"

i develop on windows with pycharm and here is the code

import tkinter
from tkinter import *
from winsound import Beep

class Metronome:
    """Create Metronome app with class instance."""

    def __init__(self,root,beats):
        """initiate default values for class and call interface()."""

        self.root=root
        self.beats=beats

        self.start=False
        self.bpm=0
        self.count=0
        self.beat=0
        self.time=0

        self.var=StringVar()
        self.var.set(self.count)

        self.interface()

     def interface(self):

         frame=Frame()
         frame.pack()

         entry=Entry(frame,width=8,justify="center")
         entry.insert(0,"60")
             entry.grid(row=0,column=1,sticky="E")

         spinbox=Spinbox(frame,width=5,values=self.beats,wrap=True)
         spinbox.grid(row=0,column=1,sticky="E")

         label_bpm=Label(frame,text="BPM:")
         label_bpm.grid(row=0,column=0,sticky="W")

         label_time=Label(frame,text="Time:")
         label_time.grid(row=0,column=1,padx=5,sticky="W")

         label_count=Label(frame,textvariable=self.var,font=("Arial",30))
         label_count.grid(row=1,column=0,columnspan=2)

         button_start=Button(frame,text="Start",width=10,height=2,
         command=lambda:self.start_counter(entry,spinbox))
         button_start.grid(row=2,column=0,padx=10,sticky="W")

         button_stop=Button(frame,text="Stop",width=10,height=2,
         command=lambda:self.stop_counter())
         button_stop.grid(row=2,column=1,padx=10,sticky="E")

    def start_counter(self,entry,spinbox):
        if not self.start:
            try:
                self.bpm=int(entry.get())
            except ValueError:
                self.bpm=60
            else:
                if self.bpm>300:
                    self.bpm=300

            self.start=True
            self.counter(spinbox)

    def stop_counter(self):
        self.start=False

    def counter(self,spinbox):
        if self.beat==6:
            self.time=int(((60/(self.bpm/.5)-0.1))*1000)
        else:
            self.time=int((60/self.bpm-0.1)*1000)

        self.count +=1
        self.var.set(self.count)

        if self.count==1:
            Beep(880,100)
        elif self.count >=self.beat:
            self.count=0
            Beep(440,100)
        else:
            Beep(440,100)

        self.root.after(self.time,lambda :self.count(spinbox))

def main():
    root=Tk()
    root.title("Metronome")

    beats=["4/4","6/8","2/4","3/4"]
    Metronome(root,beats)

    root.mainloop()

if __name__=="__main__":
    main()

Body:
If the problem is about the spaces and tabs, it might work better like this :

import tkinter
from tkinter import *
from winsound import Beep

class Metronome:
    """Create Metronome app with class instance."""

    def __init__(self, root, beats):
        """initiate default values for class and call interface()."""

        self.root = root
        self.beats = beats

        self.start = False
        self.bpm = 0
        self.count = 0
        self.beat = 0
        self.time = 0

        self.var = StringVar()
        self.var.set(self.count)

        self.interface()

    def interface(self):

        frame=Frame()
        frame.pack()

        entry=Entry(frame,width=8,justify="center")
        entry.insert(0,"60")
        entry.grid(row=0,column=1,sticky="E")

        spinbox=Spinbox(frame,width=5,values=self.beats,wrap=True)
        spinbox.grid(row=0,column=1,sticky="E")

        label_bpm=Label(frame,text="BPM:")
        label_bpm.grid(row=0,column=0,sticky="W")

        label_time=Label(frame,text="Time:")
        label_time.grid(row=0,column=1,padx=5,sticky="W")

        label_count=Label(frame,textvariable=self.var,font=("Arial",30))
        label_count.grid(row=1,column=0,columnspan=2)

        button_start=Button(frame,text="Start",width=10,height=2,
        command=lambda:self.start_counter(entry,spinbox))
        button_start.grid(row=2,column=0,padx=10,sticky="W")

        button_stop=Button(frame,text="Stop",width=10,height=2,
        command=lambda:self.stop_counter())
        button_stop.grid(row=2,column=1,padx=10,sticky="E")

    def start_counter(self,entry,spinbox):
        if not self.start:
            try:
                self.bpm=int(entry.get())
            except ValueError:
                self.bpm=60
            else:
                if self.bpm>300:
                    self.bpm=300

            self.start=True
            self.counter(spinbox)

    def stop_counter(self):
        self.start=False

    def counter(self,spinbox):
        if self.beat==6:
            self.time=int(((60/(self.bpm/.5)-0.1))*1000)
        else:
            self.time=int((60/self.bpm-0.1)*1000)

        self.count +=1
        self.var.set(self.count)

        if self.count==1:
            Beep(880,100)
        elif self.count >=self.beat:
            self.count=0
            Beep(440,100)
        else:
            Beep(440,100)

        self.root.after(self.time,lambda :self.counter(spinbox))

def main():
    root=Tk()
    root.title("Metronome")

    beats=["4/4","6/8","2/4","3/4"]
    Metronome(root,beats)

    root.mainloop()

if __name__=="__main__":
    main()

Also there was an error on the 90th line it was written

self.root.after(self.time,lambda :self.count(spinbox))

instead of

self.root.after(self.time,lambda :self.counter(spinbox))


问:
Flutter: Minimum height on horizontal list view
I'm trying to create a horizontal scrolling list of items in Flutter, and I want that list to only take up the necessary height based on its children. By design “ListView tries to expand to fit the space available in its cross-direction” (from the Flutter docs), which I also notice in that it takes up the whole height of the viewport, but is there a way to make it not do this? Ideally something similar to this (which obviously doesn't work):

new ListView(
  scrollDirection: Axis.horizontal,
  crossAxisSize: CrossAxisSize.min,
  children: <Widget>[
    new ListItem(),
    new ListItem(),
    // ...
  ],
);
```

<hr>

<p>I realize that one way to do this is by wrapping the <code>ListView</code> in a <code>Container</code> with a fixed height. However, I don't necessarily know the height of the items:</p>

<pre class="lang-dart prettyprint-override"><code>new Container(
  height: 97.0,
  child: new ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      new ListItem(),
      new ListItem(),
      // ...
    ],
  ),
);
</code>```

I was able to hack together a “solution” by nesting a Row in a SingleChildScrollView in a Column with a mainAxisSize: MainAxisSize.min. However, this doesn't feel like a solution, to me:

new Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    new SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: new Row(
        children: <Widget>[
          new ListItem(),
          new ListItem(),
          // ...
        ],
      ),
    ),
  ],
);
```

答:
(This answer covers a workaround when items have different sizes. If your items have the same size/height, see this answer for a ListView approach.)

If the items have different sizes, it should not be done with a ListView, and for a good reason:

A ListView could potentially have a lot of items (or even unlimited), but figuring out "the biggest one" requires going through every item, which is against the whole point of using a ListView (dynamically load each item using the builder method).

On the other hand, a Row widget always lay out all children at once, so it's easy to find the biggest one. So if you don't have too many items (perhaps less than 100 items or so), you can use Row instead. If you need scrolling, wrap Row with a SingleChildScrollView.

Code used in the example:

```<code>Column(
  children: [
    Container(
      color: Colors.green.shade100,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            FlutterLogo(),
            FlutterLogo(size: 100),
            for (int i = 0; i < 50; i++) FlutterLogo(),
          ],
        ),
      ),
    ),
    const Text('The row has ended.'),
  ],
)
</code>```

Body:
I'm trying to create a horizontal scrolling list of items in Flutter, and I want that list to only take up the necessary height based on its children. By design “ListView tries to expand to fit the space available in its cross-direction” (from the Flutter docs), which I also notice in that it takes up the whole height of the viewport, but is there a way to make it not do this? Ideally something similar to this (which obviously doesn't work):

new ListView(
  scrollDirection: Axis.horizontal,
  crossAxisSize: CrossAxisSize.min,
  children: <Widget>[
    new ListItem(),
    new ListItem(),
    // ...
  ],
);

I realize that one way to do this is by wrapping the ListView in a Container with a fixed height. However, I don't necessarily know the height of the items:

new Container(
  height: 97.0,
  child: new ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      new ListItem(),
      new ListItem(),
      // ...
    ],
  ),
);

I was able to hack together a “solution” by nesting a Row in a SingleChildScrollView in a Column with a mainAxisSize: MainAxisSize.min. However, this doesn't feel like a solution, to me:

new Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    new SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: new Row(
        children: <Widget>[
          new ListItem(),
          new ListItem(),
          // ...
        ],
      ),
    ),
  ],
);

Body:
(This answer covers a workaround when items have different sizes. If your items have the same size/height, see this answer for a ListView approach.)

If the items have different sizes, it should not be done with a ListView, and for a good reason:

A ListView could potentially have a lot of items (or even unlimited), but figuring out "the biggest one" requires going through every item, which is against the whole point of using a ListView (dynamically load each item using the builder method).

On the other hand, a Row widget always lay out all children at once, so it's easy to find the biggest one. So if you don't have too many items (perhaps less than 100 items or so), you can use Row instead. If you need scrolling, wrap Row with a SingleChildScrollView.

Code used in the example:

Column(
  children: [
    Container(
      color: Colors.green.shade100,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            FlutterLogo(),
            FlutterLogo(size: 100),
            for (int i = 0; i < 50; i++) FlutterLogo(),
          ],
        ),
      ),
    ),
    const Text('The row has ended.'),
  ],
)


问:
How to determine if daylight saving time is active in C?
I have a C application running on cross platforms. In this program, I need to write a function which determines if the given date is DST or not.

Actually, i try to find DST begin-DST end dates in pure C. Is there any simple and standard way to do this?

答:
time.h provides tm structs with a tm_isdst flag. Use time to get the current time, localtime to get a tm struct with the time adjusted to the current locale and read the tm_isdst flag.

From the manpage:

```<code>tm_isdst  A flag that indicates whether daylight saving time is in effect at the
time described.  The value is positive if daylight saving time is in effect, zero
if it is not, and negative if the information is not available.
</code>```

Body:
time.h provides tm structs with a tm_isdst flag. Use time to get the current time, localtime to get a tm struct with the time adjusted to the current locale and read the tm_isdst flag.

From the manpage:

tm_isdst  A flag that indicates whether daylight saving time is in effect at the
time described.  The value is positive if daylight saving time is in effect, zero
if it is not, and negative if the information is not available.


问:
How do I update pictures using Tkinter?
I've been having a problem with updating a picture in python using Tkinter. This program is creating a QR code and is displaying it on the window. I have no idea how to update it when it changes, the file name stays the same it just changes.
This is what activates the creation of a QR code

```<code>def GenerateQRCode():
    # qr code maker 3000
    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")
    resize_image = img.resize((150, 150))
    img2 = ImageTk.PhotoImage(img)
    label1 = Label(root, image=img2)
    label1.image = img2
    label1.pack(pady=50)
</code>```

It does the job of creating the QR code and dispalying it, however, like I said, no clue how to update it while the file name would stay the same. I could make qrcode1.png, then if new QR code is requested, check if it exists, if so, delete it and make qrcode2.png and display it, viceversa. But I'm sure there is a way how to do it with just one file and maybe even creating the file might be unnecessary. Any comment is welcome. Thank you.

答:
You should create the label with the qr code once, and then update the label whenever you create the new qr code. Here's an example based off of your code:</p>
```<code>import tkinter as tk
import qrcode
from PIL import ImageTk

def GenerateQRCode():
    global qr_image

    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")

    resize_image = img.resize((150, 150))
    qr_image = ImageTk.PhotoImage(img)
    qr_label.configure(image=qr_image)

root = tk.Tk()
input = tk.Entry(root)
qr_image = tk.PhotoImage()
qr_label = tk.Label(root, image=qr_image, width=300, height=300)
button = tk.Button(root, text="Generate code", command=GenerateQRCode)

input.pack(side="top", fill="x")
qr_label.pack(side="top")
button.pack(side="bottom")

root.mainloop()
</code>```

Title: How do I update pictures using Tkinter?

Body:
I've been having a problem with updating a picture in python using Tkinter. This program is creating a QR code and is displaying it on the window. I have no idea how to update it when it changes, the file name stays the same it just changes.
This is what activates the creation of a QR code

def GenerateQRCode():
    # qr code maker 3000
    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")
    resize_image = img.resize((150, 150))
    img2 = ImageTk.PhotoImage(img)
    label1 = Label(root, image=img2)
    label1.image = img2
    label1.pack(pady=50)

It does the job of creating the QR code and dispalying it, however, like I said, no clue how to update it while the file name would stay the same. I could make qrcode1.png, then if new QR code is requested, check if it exists, if so, delete it and make qrcode2.png and display it, viceversa. But I'm sure there is a way how to do it with just one file and maybe even creating the file might be unnecessary. Any comment is welcome. Thank you.

Body:
You should create the label with the qr code once, and then update the label whenever you create the new qr code. Here's an example based off of your code:

import tkinter as tk
import qrcode
from PIL import ImageTk

def GenerateQRCode():
    global qr_image

    qr = qrcode.QRCode()
    qr.add_data("brush")
    img = qrcode.make(input.get())
    img.save("qrcode.png")

    resize_image = img.resize((150, 150))
    qr_image = ImageTk.PhotoImage(img)
    qr_label.configure(image=qr_image)

root = tk.Tk()
input = tk.Entry(root)
qr_image = tk.PhotoImage()
qr_label = tk.Label(root, image=qr_image, width=300, height=300)
button = tk.Button(root, text="Generate code", command=GenerateQRCode)

input.pack(side="top", fill="x")
qr_label.pack(side="top")
button.pack(side="bottom")

root.mainloop()


问:
How to use a generic type with `typeof Node<T>`?
Let's say we have some Java Node, StringNode and NodeFactory classes:

public class Node<T> {
    private T value;

    public void init(T value){
        this.value = value;
    }
}

public class StringNode extends Node<String> {}

public class NodeFactory {
    public static <T> Node<T> createNode(Class<? extends Node<T>> nodeClass, T value) throws Exception {
        Node<T> node = nodeClass.getConstructor().newInstance();
        node.init(value);
        return node;
    }
}
```
<p>So <code>NodeFactory.createNode(StringNode.class, "value1");</code> would create a <code>StringNode</code> with the value: <code>"value1"</code>.</p>
<p>How could I write such a factorymethod in typescript?</p>
<p>I tried to write a factorymethod in typescript:</p>
<pre class="lang-js prettyprint-override"><code>public static createNode<T>(NodeClass: typeof Node<T>, value: T): Node<T> {
    const node = new NodeClass();
    node.init(value);
    return node;
}
</code>```

but does not accept typeof Node<T> generic types. So I tried putting in the method's type arguments:

public static createNode<T, N extends Node<T>>(NodeClass: typeof N, value: T): Node<T> {
```

But the compiler does not accept that either: typeof N: TS2693: 'N' only refers to a type, but is being used as a value here

Is there a typesafe way to write such a factorymethod in typescript?

答:
I found a solution:

```<code>public static createNode<N extends { new(): Node<T> }, T>(NodeClass: N, value: T): Node<T> {
</code>```

apparently I just needed N to implement a interface with a new(): Node<T> method (or constructor).

Body:
Let's say we have some Java Node, StringNode and NodeFactory classes:

public class Node<T> {
    private T value;

    public void init(T value){
        this.value = value;
    }
}

public class StringNode extends Node<String> {}

public class NodeFactory {
    public static <T> Node<T> createNode(Class<? extends Node<T>> nodeClass, T value) throws Exception {
        Node<T> node = nodeClass.getConstructor().newInstance();
        node.init(value);
        return node;
    }
}

So NodeFactory.createNode(StringNode.class, "value1"); would create a StringNode with the value: "value1".

How could I write such a factorymethod in typescript?

I tried to write a factorymethod in typescript:

public static createNode<T>(NodeClass: typeof Node<T>, value: T): Node<T> {
    const node = new NodeClass();
    node.init(value);
    return node;
}

but does not accept typeof Node<T> generic types. So I tried putting in the method's type arguments:

public static createNode<T, N extends Node<T>>(NodeClass: typeof N, value: T): Node<T> {

But the compiler does not accept that either: typeof N: TS2693: 'N' only refers to a type, but is being used as a value here

Is there a typesafe way to write such a factorymethod in typescript?

Body:
I found a solution:

public static createNode<N extends { new(): Node<T> }, T>(NodeClass: N, value: T): Node<T> {

apparently I just needed N to implement a interface with a new(): Node<T> method (or constructor).


问:
set is unordered but why there two variable are always printed in same order?
```<code>x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}

a=((x1.union(x2)))
b=(x1 | x2)
print(a)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
print(b)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
# a and b are always printed in a same order

print(a is b)  #false
</code>```

the order of a and b on each execution will change, but their order are always same when they printed.

as set is unordered I expected the order of a and b on print, should be different.

i have read these 2 associated links, but couldn't find a answer:

Why does a set display in same order if sets are unordered?

Why is the order in dictionaries and sets arbitrary?

答: Every string gets translated into a number (a hash). Then, when calling a for each procedure on the hash table, the elements are presumably enumerated from the lowest hash to the highest hash. That's why it doesn't matter what order you insert them in and why the order of enumeration for same elements is always the same. There is no intrinsic "randomness" in hashtables, hash computations are deterministic, just like enumeration.

Body:
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}

a=((x1.union(x2)))
b=(x1 | x2)
print(a)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
print(b)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
# a and b are always printed in a same order

print(a is b)  #false

the order of a and b on each execution will change, but their order are always same when they printed.

as set is unordered I expected the order of a and b on print, should be different.

i have read these 2 associated links, but couldn't find a answer:

Why does a set display in same order if sets are unordered?

Why is the order in dictionaries and sets arbitrary?


问:
Sparql - How to specifiy Property paths with regex
Imagine I would like to query all descendants of Otto Bismarck until generation 3.
How could I write the sparql code with regex? In this tutorial it says that we can use regex but I don't know how.

I tried to use "{3}":

```<code>SELECT ?descendant ?descendantLabel
WHERE
{
  wd:Q8442 wdt:P40{3} ?descendant.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</code>```

However, this does not work. The output should be this:
try here

答:
It's not possible to write queries with REGEX, but the REGEX syntax can look similar to property paths, hence why you might have been confused.

As for writing paths of length of up to 3, the syntax you are using did not actually make it in the standard, even though it does appear in a few documents.

I'd use something like:

```<code>SELECT DISTINCT ?descendant ?descendantLabel
WHERE
{
  wd:Q8442 wdt:P40/wdt:P40?/wdt:P40? ?descendant.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
</code>```

This will give us the paths of length 1, 2, and 3. ? means 'zero or one instances' of the property.
This trick can work with relatively short paths.

Body:
Imagine I would like to query all descendants of Otto Bismarck until generation 3.
How could I write the sparql code with regex? In this tutorial it says that we can use regex but I don't know how.

I tried to use "{3}":

SELECT ?descendant ?descendantLabel
WHERE
{
  wd:Q8442 wdt:P40{3} ?descendant.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

However, this does not work. The output should be this:
try here

Body:
It's not possible to write queries with REGEX, but the REGEX syntax can look similar to property paths, hence why you might have been confused.

As for writing paths of length of up to 3, the syntax you are using did not actually make it in the standard, even though it does appear in a few documents.

I'd use something like:

SELECT DISTINCT ?descendant ?descendantLabel
WHERE
{
  wd:Q8442 wdt:P40/wdt:P40?/wdt:P40? ?descendant.
  SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}

This will give us the paths of length 1, 2, and 3. ? means 'zero or one instances' of the property.
This trick can work with relatively short paths.


问:
C++ vector member initialization
I am confused about the output in the following program about the vec in Test. Why it's a vector with size 100 instead of 1? I thought std::vector<T> var{a} is the same as std::vector<T> var = {a}.

```<code>#include <iostream>
#include <vector>

using namespace std;
struct Value {
   int a;
   int b;
};

class Test {
  public:
    std::vector<struct Value> vec{100};
};

class Test2 {
  public:
    std::vector<int> vec{100};
};

int main()
{
    Test test;
    std::cout << "test size: " << test.vec.size() << std::endl;
    Test2 test2;
    std::cout << "test2 size: " << test2.vec.size();

    return 0;
}
</code>```

Output:

```<code>test size: 100
test2 size: 1
</code>```

答:
As you discovered the meaning of {100}, changes for T == int.

To answer your question briefly:

The 100 in vector<Value>{100} cannot be interpreted as a Value and therefore the size constructor takes precedence.

If you insist, {100} can be interpreted as Value, so you may need an extra curly braces, vector<Value>{ {100} }.

See the illustration here: https://godbolt.org/z/xcMT1oc5z

My advice, avoiding further discussion on legalities, is the following:

To keep the meaning across types, initialize consistently parenthesis for size-initialization and brackets for element(s), which forces you to do this:

```<code>    std::vector<int> vec = std::vector<int>(100);
</code>```

And in general:

```<code>    std::vector<T> vec = std::vector<T>(100);
</code>```

In this case 100 is always the size.

Title: C++ vector member initialization

Body:
I am confused about the output in the following program about the vec in Test. Why it's a vector with size 100 instead of 1? I thought std::vector<T> var{a} is the same as std::vector<T> var = {a}.

#include <iostream>
#include <vector>

using namespace std;
struct Value {
   int a;
   int b;
};

class Test {
  public:
    std::vector<struct Value> vec{100};
};

class Test2 {
  public:
    std::vector<int> vec{100};
};

int main()
{
    Test test;
    std::cout << "test size: " << test.vec.size() << std::endl;
    Test2 test2;
    std::cout << "test2 size: " << test2.vec.size();

    return 0;
}

Output:

test size: 100
test2 size: 1

Body:
As you discovered the meaning of {100}, changes for T == int.

To answer your question briefly:

The 100 in vector<Value>{100} cannot be interpreted as a Value and therefore the size constructor takes precedence.

If you insist, {100} can be interpreted as Value, so you may need an extra curly braces, vector<Value>{ {100} }.

See the illustration here: https://godbolt.org/z/xcMT1oc5z

My advice, avoiding further discussion on legalities, is the following:

To keep the meaning across types, initialize consistently parenthesis for size-initialization and brackets for element(s), which forces you to do this:

    std::vector<int> vec = std::vector<int>(100);

And in general:

    std::vector<T> vec = std::vector<T>(100);

In this case 100 is always the size.


问:
mongoDB error: Error: failed to connect to [localhost:27017]
I'm trying to install habitrpg locally but I keep getting a mongoDB error after typing node src/seed.js:

```<code>Error: failed to connect to [localhost:27017]
</code>```

I saw on other questions with the same error people have suggested typing in 'mongod' and that fixes it by creating a local server. I get the error:

```<code>-bash: mongod: command not found
</code>```

Can't figure out what's wrong. Any ideas?

答:
my problem is the connectoon is down, run script:

```<code>brew services start mongodb-community
</code>```

And up mongoDB Compass and works.

Body:
I'm trying to install habitrpg locally but I keep getting a mongoDB error after typing node src/seed.js:

Error: failed to connect to [localhost:27017]

I saw on other questions with the same error people have suggested typing in 'mongod' and that fixes it by creating a local server. I get the error:

-bash: mongod: command not found

Can't figure out what's wrong. Any ideas?

Body:
my problem is the connectoon is down, run script:

brew services start mongodb-community

And up mongoDB Compass and works.


问:
How to shift a tensor like pandas.shift in tensorflow / keras? (Without shift the last row to first row, like tf.roll)
I want to shift a tensor in a given axis. It's easy to do this in pandas or numpy. Like this:

```<code>import numpy as np
import pandas as pd

data = np.arange(0, 6).reshape(-1, 2)
pd.DataFrame(data).shift(1).fillna(0).values
</code>```

Output is:

array([[0., 0.],

[0., 1.],

[2., 3.]])

But in tensorflow, the closest solution I found is tf.roll. But it shift the last row to the first row. (I don't want that). So I have to use something like

tf.roll + tf.slice(remove the last row) + tf.concat(add tf.zeros to the first row).

It's really ugly.

Is there a better way to handle shift in tensorflow or keras?

Thanks.

答:
Generalizing the accepted answer to arbitrary tensor shapes, desired shift, and axis to shift:

```<code>import tensorflow as tf

def tf_shift(tensor, shift=1, axis=0):
    dim = len(tensor.shape)

    if axis > dim:
        raise ValueError(
            f'Value of axis ({axis}) must be <= number of tensor axes ({dim})'
        )

    mask_dim = dim - axis
    mask_shape = tensor.shape[-mask_dim:]
    zero_dim = min(shift, mask_shape[0])

    mask = tf.concat(
        [tf.zeros(tf.TensorShape(zero_dim) + mask_shape[1:]),
         tf.ones(tf.TensorShape(mask_shape[0] - zero_dim) + mask_shape[1:])],
        axis=0
    )

    for i in range(dim - mask_dim):
        mask = tf.expand_dims(mask, axis=0)

    return tf.multiply(
        tf.roll(tensor, shift, axis),
        mask
    )
</code>```

EDIT:
This code above doesn't allow for negative shift values, and is pretty slow. Here is a more efficient version utilizing tf.roll and tf.concat without creating a mask and multiplying the tensor of interest by it.

```<code>import tensorflow as tf

def tf_shift(values: tf.Tensor, shift: int = 1, axis: int = 0):
    pad = tf.zeros([val if i != axis else abs(shift) for i, val in enumerate(values.shape)],
                   dtype=values.dtype)
    size = [-1 if i != axis else val - abs(shift) for i, val in enumerate(values.shape)]

    if shift > 0:
        shifted = tf.concat(
            [pad, tf.slice(values, [0] * len(values.shape), size)],
            axis=axis
        )
    elif shift < 0:
        shifted = tf.concat(
            [tf.slice(values, [0 if i != axis else abs(shift) for i, _ in enumerate(values.shape)], size), pad],
            axis=axis
        )
    else:
        shifted = values

    return shifted
</code>```

Body:
I want to shift a tensor in a given axis. It's easy to do this in pandas or numpy. Like this:

import numpy as np
import pandas as pd

data = np.arange(0, 6).reshape(-1, 2)
pd.DataFrame(data).shift(1).fillna(0).values

Output is:

array([[0., 0.],

[0., 1.],

[2., 3.]])

But in tensorflow, the closest solution I found is tf.roll. But it shift the last row to the first row. (I don't want that). So I have to use something like

tf.roll + tf.slice(remove the last row) + tf.concat(add tf.zeros to the first row).

It's really ugly.

Is there a better way to handle shift in tensorflow or keras?

Thanks.

Body:
Generalizing the accepted answer to arbitrary tensor shapes, desired shift, and axis to shift:

import tensorflow as tf

def tf_shift(tensor, shift=1, axis=0):
    dim = len(tensor.shape)

    if axis > dim:
        raise ValueError(
            f'Value of axis ({axis}) must be <= number of tensor axes ({dim})'
        )

    mask_dim = dim - axis
    mask_shape = tensor.shape[-mask_dim:]
    zero_dim = min(shift, mask_shape[0])

    mask = tf.concat(
        [tf.zeros(tf.TensorShape(zero_dim) + mask_shape[1:]),
         tf.ones(tf.TensorShape(mask_shape[0] - zero_dim) + mask_shape[1:])],
        axis=0
    )

    for i in range(dim - mask_dim):
        mask = tf.expand_dims(mask, axis=0)

    return tf.multiply(
        tf.roll(tensor, shift, axis),
        mask
    )

EDIT:
This code above doesn't allow for negative shift values, and is pretty slow. Here is a more efficient version utilizing tf.roll and tf.concat without creating a mask and multiplying the tensor of interest by it.

import tensorflow as tf

def tf_shift(values: tf.Tensor, shift: int = 1, axis: int = 0):
    pad = tf.zeros([val if i != axis else abs(shift) for i, val in enumerate(values.shape)],
                   dtype=values.dtype)
    size = [-1 if i != axis else val - abs(shift) for i, val in enumerate(values.shape)]

    if shift > 0:
        shifted = tf.concat(
            [pad, tf.slice(values, [0] * len(values.shape), size)],
            axis=axis
        )
    elif shift < 0:
        shifted = tf.concat(
            [tf.slice(values, [0 if i != axis else abs(shift) for i, _ in enumerate(values.shape)], size), pad],
            axis=axis
        )
    else:
        shifted = values

    return shifted


问:
GEdit - Plugin to find and open a partial under cursor?
GMate contains a plugin to extract portion of code into a partial. But is there anything to do the opposite, IE, to find a partial on disk and automatically open it?</p>

答:
Use the external tool 'jump' for it.
You will find it on github</p>

ContentLicense: CC BY-SA 2.5


问:
Remove product title when product is "out of stock" on WooCommerce shop and archives pages
I am running an art gallery website using WooCommerce and the owner does not want to show the product name/title if the product has been sold/out of stock.

I have got this far with putting together a function, but it doesn't work. I wondered if anyone could give me any tips?

// Hides title on Sold products
add_filter( 'woocommerce_shop_loop_item_title', 'remove_name', 10, 2 );
function remove_name ( $product ) {
    if ( ! $product->is_in_stock()) {
        $title = '';
    }
    return $title;
}
```

答:
Your code contains some errors and mistakes:

woocommerce_shop_loop_item_title is NOT an filter but an action hook

No arguments are passed to this hook , while your code says there would be 2

$product is undefined, use global $product;

Note: I've added a line with debug information, it can be removed

So you get:

function action_woocommerce_shop_loop_item_title() {
    global $product;

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Should be removed but may be useful towards debugging
        echo '
DEBUG information: ' . $product->get_stock_status() . '
';

        // NOT in stock
        if ( ! $product->is_in_stock() ) {
            // Removes a function from a specified action hook.
            remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
        }
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );
```

Body:
Your code contains some errors and mistakes:

woocommerce_shop_loop_item_title is NOT an filter but an action hook

No arguments are passed to this hook , while your code says there would be 2

$product is undefined, use global $product;

Note: I've added a line with debug information, it can be removed

So you get:

function action_woocommerce_shop_loop_item_title() {
    global $product;

    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Should be removed but may be useful towards debugging
        echo '<p style="color: red; font-size: 20px;">DEBUG information: ' . $product->get_stock_status() . '</p>';

        // NOT in stock
        if ( ! $product->is_in_stock() ) {
            // Removes a function from a specified action hook.
            remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
        }
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );


问:
Azure DevOps build With IIS Physical path Failing
I have an Azure Devops build which tries to build a .NET 4 solution on my build server. The issue is this .NET 4 project doesn't run through IIS Express, but IIS itself, requiring a website with a physical path to be set up.

I'm having trouble figuring out what the physical path would be, as the path changes. One build it could be D:/agent1/s/19/... another build it could be D:/agent1/s/29/...

Has anyone tackled this issue before? I'm finding sparse info on the net.

答:
I believe you should use this parameter in the build for the folder you want

/p:OutDir="your folder" (to plan output)

/p:PackageLocation="your folder" (to zip output)

```<code>- task: VSBuild@1
  displayName: 'Build solution'
  inputs:
    solution: xxxx.csproj
    msbuildArgs: '/p:OutDir="your folder"'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'
</code>```

Body:
I believe you should use this parameter in the build for the folder you want

/p:OutDir="your folder" (to plan output)

/p:PackageLocation="your folder" (to zip output)

- task: VSBuild@1
  displayName: 'Build solution'
  inputs:
    solution: xxxx.csproj
    msbuildArgs: '/p:OutDir="your folder"'
    platform: '$(BuildPlatform)'
    configuration: '$(BuildConfiguration)'


问:
What Is Can Order In Django Formsets Actually For?
I've spent a fair amount of time the last day or so exploring the can order field with Django Formsets but I can't for the life of me actually figure out what it's for.  Apparently it doesn't update the database...and it does put an order number field with the form....but beyond that what is it for?

I can't find any useful documentation on how to actually use this field.  Do I have to write Javascript in order to get this field to do anything actually meaningful?

I get the delete option...and you have to add code in to delete the record...So I guess I'm to take it the same is required for the can_order field?

Sorry if this is a silly question but I've spent more time trying to figure this out than what would be reasonable by now.

答:
All it does is add an integer ORDER field to each form in the formset so you can manually order them after instantiating the formset. Just imagine your forms have a title with this imaginary formset data. You can use ordered_forms to iterate through each form, inspect its cleaned_data, and change it's ordering before returning the form in your context.</p>
```<code>formset = ArticleFormSet(data)

if formset.is_valid():
    for form in formset.ordered_forms:
        if form.cleaned_data['title'] = 'My form title'
            form.cleaned_data['ORDER'] = 2
            form.save()
</code>```

Body:
All it does is add an integer ORDER field to each form in the formset so you can manually order them after instantiating the formset. Just imagine your forms have a title with this imaginary formset data. You can use ordered_forms to iterate through each form, inspect its cleaned_data, and change it's ordering before returning the form in your context.

formset = ArticleFormSet(data)

if formset.is_valid():
    for form in formset.ordered_forms:
        if form.cleaned_data['title'] = 'My form title'
            form.cleaned_data['ORDER'] = 2
            form.save()


问:
Wrapping CompletableFuture to Mono with DynamoDb
I know the java DynamoDB's SDK is considered async non blocking but my question is:

Q. Does the dynamo update still need to be  on another thread with operator publishOn to be safer in a reactive context?

Mono.fromFuture(table.update()).publishOn();

答:
Assuming that you are using the AWS Java SDK v2, you don't need to worry about delegating to a thread pool. AWS SDK already makes sure that you don't block an important thread. See documentation for details:

The AWS SDK for Java 2.x uses Netty, an asynchronous event-driven
network application framework, to handle I/O threads. The AWS SDK for
Java 2.x creates an ExecutorService behind Netty, to complete the
futures returned from the HTTP client request through to the Netty
client. This abstraction reduces the risk of an application breaking
the async process if developers choose to stop or sleep threads. By
default, 50 Threads are generated for each asynchronous client, and
managed in a queue within the ExecutorService.

Actually, it even use more threads than it would be desired in a truly reactive application. Fortunately, the SDK also gives option to opt out of that behavior if needed.

One more thing that's good to be aware of is CompletableFuture is eager unlike reactive type Mono. For this reason it is better to use the lambda version of the fromFuture method:

Mono.fromFuture(() -> table.update())
```


问:
Force one tab only on web app (e.g. similar to WhatsApp and Google Messenger)
I have a strict requirement to only allow a logged in user to open my web app in one tab. I've noticed that WhatsApp and Google Messenger's web apps have implemented this. For example, trying to open those apps in more than one tab (be it on the same browser, different browser, or even different device) results in these warnings:

Anyone know how this is done? There must be some sort of sync happening between the server and the client to ensure that only one tab is open. But this would require a unique tab identifier, which can get quite complicated to build reliably. Anyone know how WhatsApp and Google Messenger are doing it? Their technique seems to work flawlessly.

答: I don't know exactly how this is done at WhatsApp and Google Messenger, but if you work with WebSockets (your post hast the tag "websocket", so I assume, you do) every tab has its single connection to the server, and if your users need to be logged in you could check if the user has already a open weboscket connection to your server.</p>


问:
Conditional redirection depending on Current URL. through html
(1)
My example Current URL along with Parameters is ----
www.example.com?fname=John&femail=john123@example.com

(2)
Through html / JavaScript
I want to check Current URL Parameter whether it contains any data in
fname

(3a)
Next, If there is No URL Parameter present then Redirect to "www.example.com/error-page"
or
(3b)
If the parameter fname have some data (No need for any Validation of data) meaning the parameter fname is not empty then should Continue with the execution of Current Page.

I tried the following successfully :

<!doctype html>

       <meta charset="UTF-8"/>

答:
Explanation:

"I want to check Current URL Parameter whether it contains any data in fname"

The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?

basically it's almost the same as your approach using the location href to parse the params

"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)

Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method

const getQueryParam = (name) => {
  if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
    return decodeURIComponent(name[1]);
}

let fnameParam = getQueryParam("fname");
if (!fnameParam) {
  window.location = "http://www.example.com/error-page";
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>

  <body>
    <div>
      <p id="dd"></p>
    </div>
  </body>
</head>

</html></code>```

Body:
Explanation:

"I want to check Current URL Parameter whether it contains any data in fname"

The getQueryParam function is explained here
How to get "GET" request parameters in JavaScript?

basically it's almost the same as your approach using the location href to parse the params

"If there is No URL Parameter present then Redirect to" else continue, for this you'll only need to wrap it inside a div, if the conditional is false (found param) then it'll just not run the statement inside if block (the one that will redirect user to error page)

Note that you have many other option to implement, check with the compatibility of browser, behaviour of redirection can also be changed to replace the last history page so user cannot go back to the previous URL that throw the error using window.location.replace method

const getQueryParam = (name) => {
  if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(location.search))
    return decodeURIComponent(name[1]);
}

let fnameParam = getQueryParam("fname");
if (!fnameParam) {
  window.location = "http://www.example.com/error-page";
};

<!doctype html>
<html>

<head>

  <body>
    <div>
      <p id="dd"></p>
    </div>
  </body>
</head>

</html>


问:
PowerBI next month function is not rolling over a year, any advice?
I have a column called Snapshot Effective Period (next month) which is the Nextmonth([Snapshot Period]). This function stops when the snapshot period is 12/1/2021, what I expect to see is 1/1/2022 when the snapshot period is 12/1/2021. The value is not rolling over a year. Any advice?

Snapshot effective period next month c1 is a calculated column in date format.

```<code>Snapshot Effective Period (Next Month) c1 = NEXTMONTH('Forecast Detail'[Snapshot Period])
</code>```

答:
NEXTMONTH function should be used on Calendar

Notes In order to use any time intelligence calculation, you need a
well-formed date table. The Date table must satisfy the following
requirements:

All dates need to be present for the years required. The Date table
must always start on January 1 and end on December 31, including all
the days in this range. If the report only references fiscal years,
then the date table must include all the dates from the first to the
last day of a fiscal year. For example, if the fiscal year 2008 starts
on July 1, 2007, then the Date table must include all the days from
July 1, 2007 to June 30, 2008. There needs to be a column with a
DateTime or Date data type containing unique values. This column is
usually called Date. Even though the Date column is often used to
define relationships with other tables, this is not required. Still,
the Date column must contain unique values and should be referenced by
the Mark as Date Table feature. In case the column also contains a
time part, no time should be used – for example, the time should
always be 12:00 am. The Date table must be marked as a date table in
the model, in case the relationship between the Date table and any
other table is not based on the Date.

https://dax.guide/nextmonth/

Instead of NEXTMONTH use  DATE

```<code>Snapshot Effective Period (Next Month) c1 = DATE( YEAR('Forecast Detail'[Snapshot Period]), MONTH('Forecast Detail'[Snapshot Period]) +1, DAY('Forecast Detail'[Snapshot Period]))
</code>```

Body:
I have a column called Snapshot Effective Period (next month) which is the Nextmonth([Snapshot Period]). This function stops when the snapshot period is 12/1/2021, what I expect to see is 1/1/2022 when the snapshot period is 12/1/2021. The value is not rolling over a year. Any advice?

Snapshot effective period next month c1 is a calculated column in date format.

Snapshot Effective Period (Next Month) c1 = NEXTMONTH('Forecast Detail'[Snapshot Period])

Body:
NEXTMONTH function should be used on Calendar

Notes In order to use any time intelligence calculation, you need a
well-formed date table. The Date table must satisfy the following
requirements:

All dates need to be present for the years required. The Date table
must always start on January 1 and end on December 31, including all
the days in this range. If the report only references fiscal years,
then the date table must include all the dates from the first to the
last day of a fiscal year. For example, if the fiscal year 2008 starts
on July 1, 2007, then the Date table must include all the days from
July 1, 2007 to June 30, 2008. There needs to be a column with a
DateTime or Date data type containing unique values. This column is
usually called Date. Even though the Date column is often used to
define relationships with other tables, this is not required. Still,
the Date column must contain unique values and should be referenced by
the Mark as Date Table feature. In case the column also contains a
time part, no time should be used – for example, the time should
always be 12:00 am. The Date table must be marked as a date table in
the model, in case the relationship between the Date table and any
other table is not based on the Date.

https://dax.guide/nextmonth/

Instead of NEXTMONTH use  DATE

Snapshot Effective Period (Next Month) c1 = DATE( YEAR('Forecast Detail'[Snapshot Period]), MONTH('Forecast Detail'[Snapshot Period]) +1, DAY('Forecast Detail'[Snapshot Period]))


问:
How do I add left and right inset to UICollectionView contentInset?
I am having an issue with the content inset of UICollectionView:

```<code>private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsets(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minimumLineSpacing: CGFloat = 12.0
    static let minimumInteritemSpacing: CGFloat = 16.0
    static let cellHeight: CGFloat = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = Constants.collectionViewContentInsets
</code>```

For the cell size:

```<code>func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: Constants.cellHeight)
}
</code>```

The vertical inset of 24.0 works with no issue, but the horizontal insets of 16.0 do not work. What am I doing wrong here?

答:
You are not accounting for left and right insets in cell size. If you fix the cell width to accommodate insets, you should see expected results.</p>
```<code>func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
    let insets = collectionView.contentInset
    let width = collectionView.bounds.width - insets.left - insets.right
    return CGSize(width: width, height: Constants.cellHeight)
}
</code>```

Body:
I am having an issue with the content inset of UICollectionView:

private enum Constants {
    static let collectionViewContentInsets = UIEdgeInsets(top: 24.0, left: 16.0, bottom: 0.0, right: 16.0)
    static let minimumLineSpacing: CGFloat = 12.0
    static let minimumInteritemSpacing: CGFloat = 16.0
    static let cellHeight: CGFloat = 119.0
}

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = Constants.minimumLineSpacing
layout.minimumInteritemSpacing = Constants.minimumInteritemSpacing

let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.contentInset = Constants.collectionViewContentInsets

For the cell size:

func collectionView(
    _ collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAt indexPath: IndexPath
) -> CGSize {
    return CGSize(width: collectionView.bounds.width, height: Constants.cellHeight)
}

The vertical inset of 24.0 works with no issue, but the horizontal insets of 16.0 do not work. What am I doing wrong here?

Body:
You are not accounting for left and right insets in cell size. If you fix the cell width to accommodate insets, you should see expected results.

func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
    let insets = collectionView.contentInset
    let width = collectionView.bounds.width - insets.left - insets.right
    return CGSize(width: width, height: Constants.cellHeight)
}


问:
Reading lines in txt file and comparing in Java(Android Studio)
So im trying to read 60k+ lines text file with single word on each line (dictionary) and compare it with given word. I need to do it as fast as possible. Yhe current script takes 5 seconds to run which is really bad result:

```<code>Scanner in = new Scanner(getResources().openRawResource(getResources().getIdentifier("dictionary", "raw", getPackageName())));
while(in.hasNext()){
        String word = in.next();
        if(word.equals(some_word)){
            TextView text = (TextView) findViewById(R.id.text);
            text.setText(word);
        }
    }
    TextView timeTV = (TextView) findViewById(R.id.time);
</code>```

Im searching for a best results possible while keeping a txt file in /raw folder of a project.

Im thinking about BufferedReader but have no idea how to pass it my txt file

答:
Solved by using BufferedString.

Here is the way i implemented it, takes about 50ms to scroll trough the entire list of words:

```<code>InputStream is = getResources().openRawResource(getResources().getIdentifier("dictionary", "raw", getPackageName()));
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line;
        while ((line = reader.readLine()) != null){
            if (line.equals("some_word")){
                TextView text = (TextView) findViewById(R.id.text);
                textt.setText(line);
                break;
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Body:
So im trying to read 60k+ lines text file with single word on each line (dictionary) and compare it with given word. I need to do it as fast as possible. Yhe current script takes 5 seconds to run which is really bad result:

Scanner in = new Scanner(getResources().openRawResource(getResources().getIdentifier("dictionary", "raw", getPackageName())));
while(in.hasNext()){
        String word = in.next();
        if(word.equals(some_word)){
            TextView text = (TextView) findViewById(R.id.text);
            text.setText(word);
        }
    }
    TextView timeTV = (TextView) findViewById(R.id.time);

Im searching for a best results possible while keeping a txt file in /raw folder of a project.

Im thinking about BufferedReader but have no idea how to pass it my txt file

Body:
Solved by using BufferedString.

Here is the way i implemented it, takes about 50ms to scroll trough the entire list of words:

InputStream is = getResources().openRawResource(getResources().getIdentifier("dictionary", "raw", getPackageName()));
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line;
        while ((line = reader.readLine()) != null){
            if (line.equals("some_word")){
                TextView text = (TextView) findViewById(R.id.text);
                textt.setText(line);
                break;
            }

        }
    } catch (IOException e) {
        e.printStackTrace();
    }


答:
The generic parameter of a class applies to to instances and not the static class itself. And the value is also for instances. So NodeClass needs to be a "newable" type, that returns an instance with the right generic.

That means this will work:

```<code>function createNode<T>(NodeClass: { new (): MyNode<T> }, value: T): MyNode<T> {
    const node = new NodeClass();
    node.init(value)
    return node;
}
</code>```

Testing:

```<code>// good
const a = createNode(StringNode, "asd")
const b = createNode(NumberNode, 123)
const c = createNode(FunctionNode, () => 'hello world')
const d = createNode(MyNode, true) // MyNode<boolean>

// error, as expected
const bad = createNode(StringNode, 123)
</code>```

createNode(MyNode, true) is a nice bonus. Typescript picks up T from the second argument, and puts it in the NodeClass for you.

Playground

Title: How to use a generic type with `typeof Node<T>`?

Body:
Let's say we have some Java Node, StringNode and NodeFactory classes:

public class Node<T> {
    private T value;

    public void init(T value){
        this.value = value;
    }
}

public class StringNode extends Node<String> {}

public class NodeFactory {
    public static <T> Node<T> createNode(Class<? extends Node<T>> nodeClass, T value) throws Exception {
        Node<T> node = nodeClass.getConstructor().newInstance();
        node.init(value);
        return node;
    }
}

So NodeFactory.createNode(StringNode.class, "value1"); would create a StringNode with the value: "value1".

How could I write such a factorymethod in typescript?

I tried to write a factorymethod in typescript:

public static createNode<T>(NodeClass: typeof Node<T>, value: T): Node<T> {
    const node = new NodeClass();
    node.init(value);
    return node;
}

but does not accept typeof Node<T> generic types. So I tried putting in the method's type arguments:

public static createNode<T, N extends Node<T>>(NodeClass: typeof N, value: T): Node<T> {

But the compiler does not accept that either: typeof N: TS2693: 'N' only refers to a type, but is being used as a value here

Is there a typesafe way to write such a factorymethod in typescript?

Body:
The generic parameter of a class applies to to instances and not the static class itself. And the value is also for instances. So NodeClass needs to be a "newable" type, that returns an instance with the right generic.

That means this will work:

function createNode<T>(NodeClass: { new (): MyNode<T> }, value: T): MyNode<T> {
    const node = new NodeClass();
    node.init(value)
    return node;
}

Testing:

// good
const a = createNode(StringNode, "asd")
const b = createNode(NumberNode, 123)
const c = createNode(FunctionNode, () => 'hello world')
const d = createNode(MyNode, true) // MyNode<boolean>

// error, as expected
const bad = createNode(StringNode, 123)

createNode(MyNode, true) is a nice bonus. Typescript picks up T from the second argument, and puts it in the NodeClass for you.

<a href="https://www.typescriptlang.org/play?ssl=18&ssc=1&pln=26&pc=40#code/MYGwhgzhAECyCeA5A9gEwKYB4AqA+aA3gFDTQBuYIArugFzTbQA+0AdlSCNALxschES0AJathAFwAUFanQYBKQkNLiAFsIgA6GTR7lKNIQF8iJoqEgwAyuIBOogOYoM0dAA9x6VqhgJnWCDtHfAITCyhoRCoAWwAjdFt-Vw8vHzgkNCx2OISQsPAIgDEqVmBxYWRWJPdPb18MjExJRW58MmRhVDzBADMSsorWaGBbdDBPfxxcSX8AYQKIegI2dAB3aGb6P0yp6CMAGn1Zemx5LYasPCVSUmBKwLZMvVY1yMz5y2aAbmVHjE1RBJpAZ0PJfqNxFRbENWJkfmYAPQI6AOZBocz3cTQMB6EZjCaZSQ2eysJyZQ4AIkgqApYLurAesVxo3G6H8Mxi8US5OgAEYAEwAZjpmOGzPxbMJxVK5Uq-kOzR4+AA5Kp0JxkNBVshbCBUMqRQysahxaz2dsMIc7DRFEj0pNYmiQGNWLhBHaErYdYdIMkAA7oMroVAYo3QWJgE28PFmwnExzyvlC+RAA" rel="nofollow noreferrer">Playground


问:
Calculate number of NA and non-NA values in a raster but with new resolution and extent
I need to calculate the number of NA and non-NA values in a raster with original resolution of 1 x 0.00811 but aggregated to 2 degrees and with a new extent.

The original raster (available here: https://datadryad.org/stash/dataset/doi:10.5061/dryad.052q5, see output 1) was merged with another dataset (unfortunately, not open-source) to produce a raster in Output 2:

Output 1

```<code>class      : RasterLayer
dimensions : 19142, 35738, 684096796  (nrow, ncol, ncell)
resolution : 0.01, 0.00811  (x, y)
extent     : -178.6931, 178.6869, -65.29534, 89.94628  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : HumanFootprintWGS84.tif
names      : HumanFootprintWGS84
values     : 0, 50  (min, max)
</code>```

Output 2

```<code>dimensions : 19142, 35738, 684096796  (nrow, ncol, ncell)
resolution : 0.01, 0.00811  (x, y)
extent     : -178.6931, 178.6869, -65.29534, 89.94628  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : r_tmp_2022-02-10_145403_42352_01781.grd
names      : layer
values     : 0.6730382, 1  (min, max)
</code>```

The raster I used for re-sampling was a dummy and is as follows:

Output 3

```<code>class      : RasterLayer
dimensions : 65, 180, 11700  (nrow, ncol, ncell)
resolution : 2, 2  (x, y)
extent     : -180, 180, -65, 65  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
</code>```

Unfortunately, the merged and therefore the re-sampled raster has a lot of NA values on the coastline and near the lakes; and the averaging method in st_warp converts NA values to 0s, which skews the calculation of the mean of some of the cells.

I've decided to adjust the values resulting from averaging by multiplying the averaged values by Number of Non-NA values/(Number of Non-NAs - number of NAs), i.e.:

average x {Number of non-NA values/(Number of non-NA values/ number of NA values)}

For that I need to know the number of non-NA and NA values is the original merged raster (Output 2) but at 2 degree resolution and the extent in Output 3 (-180, 180, -65, 65).

I'm new to mapping and rasters so apologies if this is a basic question.

I've tried to rasterize with coordinates of original dataset and the dummy grid, but this would not get me the number of NA values, just the number of cells (plus the merged raster is over 5.1 Gb). I've tried to trim NA values (stupid idea), and st_warp but without averaging (uses nearest neighbour anyway).

If anyone has any ideas or have got a more elegant solution, I'd really appreciate it.

Thank you sincerely,

Edit: Through trial and error, I found that it makes a difference for both re-sampling (thank you again, @Robert Hijmans) and st_warp, whether the values are loaded in the memory or not.

Here are example outputs, with and without values loaded:

terra::resample with averaging without data loaded in memory

terra::resample with averaging with data loaded in memory

答:
Example data

```<code>library(terra)
#terra 1.5.20
library(geodata)
w <- world(path=".")
# input raster
x <- rast(res=3)
x <- rasterize(w, x, field=1)

# output raster
r <- rast(res=10)
</code>```

Solution:

```<code>rs <- resample(x, r, "sum")

rs
#class       : SpatRaster
#dimensions  : 18, 36, 1  (nrow, ncol, nlyr)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84
#source      : memory
#name        :     layer
#min value   : 0.1111111
#max value   :  11.11111

plot(rs)
</code>```

You need terra 1.5.20 for this. That is currently the development version. The easiest way to install it on Windows or OSX is with install.packages('terra', repos='https://rspatial.r-universe.dev')

Earlier versions of terra ignore the "sum" option.

In response to your comment: I get the same results with sum and average when I use a file as data source:

```<code>xx <- writeRaster(x, "test.tif", overwrite=T)
rs <- resample(xx, r, "sum")
</code>```

We can compare the result with exact extraction with polygons (that also works, but will choke R on big datasets)

```<code>p <- as.polygons(r)
e <- extract(x, p, exact=TRUE, fun=sum, na.rm=TRUE)
re <- rast(r)
re[e[,1]] <- e[,2]

plot(rs, re, xlab="resample", ylab="extract")
</code>```

Body:
I need to calculate the number of NA and non-NA values in a raster with original resolution of 1 x 0.00811 but aggregated to 2 degrees and with a new extent.

The original raster (available here: https://datadryad.org/stash/dataset/doi:10.5061/dryad.052q5, see output 1) was merged with another dataset (unfortunately, not open-source) to produce a raster in Output 2:

Output 1

class      : RasterLayer
dimensions : 19142, 35738, 684096796  (nrow, ncol, ncell)
resolution : 0.01, 0.00811  (x, y)
extent     : -178.6931, 178.6869, -65.29534, 89.94628  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : HumanFootprintWGS84.tif
names      : HumanFootprintWGS84
values     : 0, 50  (min, max)

Output 2

dimensions : 19142, 35738, 684096796  (nrow, ncol, ncell)
resolution : 0.01, 0.00811  (x, y)
extent     : -178.6931, 178.6869, -65.29534, 89.94628  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : r_tmp_2022-02-10_145403_42352_01781.grd
names      : layer
values     : 0.6730382, 1  (min, max)

The raster I used for re-sampling was a dummy and is as follows:

Output 3

class      : RasterLayer
dimensions : 65, 180, 11700  (nrow, ncol, ncell)
resolution : 2, 2  (x, y)
extent     : -180, 180, -65, 65  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs

Unfortunately, the merged and therefore the re-sampled raster has a lot of NA values on the coastline and near the lakes; and the averaging method in st_warp converts NA values to 0s, which skews the calculation of the mean of some of the cells.

I've decided to adjust the values resulting from averaging by multiplying the averaged values by Number of Non-NA values/(Number of Non-NAs - number of NAs), i.e.:

average x {Number of non-NA values/(Number of non-NA values/ number of NA values)}

For that I need to know the number of non-NA and NA values is the original merged raster (Output 2) but at 2 degree resolution and the extent in Output 3 (-180, 180, -65, 65).

I'm new to mapping and rasters so apologies if this is a basic question.

I've tried to rasterize with coordinates of original dataset and the dummy grid, but this would not get me the number of NA values, just the number of cells (plus the merged raster is over 5.1 Gb). I've tried to trim NA values (stupid idea), and st_warp but without averaging (uses nearest neighbour anyway).

If anyone has any ideas or have got a more elegant solution, I'd really appreciate it.

Thank you sincerely,

Edit: Through trial and error, I found that it makes a difference for both re-sampling (thank you again, @Robert Hijmans) and st_warp, whether the values are loaded in the memory or not.

Here are example outputs, with and without values loaded:

terra::resample with averaging without data loaded in memory

terra::resample with averaging with data loaded in memory

Body:
Example data

library(terra)
#terra 1.5.20
library(geodata)
w <- world(path=".")
# input raster
x <- rast(res=3)
x <- rasterize(w, x, field=1)

# output raster
r <- rast(res=10)

Solution:

rs <- resample(x, r, "sum")

rs
#class       : SpatRaster
#dimensions  : 18, 36, 1  (nrow, ncol, nlyr)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84
#source      : memory
#name        :     layer
#min value   : 0.1111111
#max value   :  11.11111

plot(rs)

You need terra 1.5.20 for this. That is currently the development version. The easiest way to install it on Windows or OSX is with install.packages('terra', repos='https://rspatial.r-universe.dev')

Earlier versions of terra ignore the "sum" option.

In response to your comment: I get the same results with sum and average when I use a file as data source:

xx <- writeRaster(x, "test.tif", overwrite=T)
rs <- resample(xx, r, "sum")

We can compare the result with exact extraction with polygons (that also works, but will choke R on big datasets)

p <- as.polygons(r)
e <- extract(x, p, exact=TRUE, fun=sum, na.rm=TRUE)
re <- rast(r)
re[e[,1]] <- e[,2]

plot(rs, re, xlab="resample", ylab="extract")


问:
TDD: Static methods, dependency injection, caching, and you!
Hope I can explain this somewhat decently, as it's blowing a fuse in my brain today. I'm learning TDD in C#, so I'm still trying to rewire my brain to fit it.

Let's say I have a User class, that previously had a static method to retrieve a User object (simplified below).

```<code>public static User GetUser(string username)
{
   User user = GetUserFromCache(username);
   if(user == null)
   {
       user = GetUserFromDatabase(username);
       StoreObjectInCache(user);
   }
   return user;
}
</code>```

So I'm trying to rewrite this to use dependency injection so I can fake out the "GetUserFromDatabase" method if it needs to go there. That means I have to make the function not static. Whereas the data access layer would construct the user object from the database, mapping the returned columns to the object properties, a retrieval from cache would return a true-blue User object. However, in a non-static method, I can't just say

```<code>this = GetUserFromCache(username);
</code>```

Because it just doesn't work that way. Though I'm by no means the world expert in how to dance around this with OO, it looks like I'd almost have to grab the User object from cache and write another mapping function that would store the returned User object properties into the new User instance.

What's the solution here? Any OO magic I'm missing? Is the only solution to refactor everything to use factories instead of having the instantiation logic in the object itself? Or have I been staring at this too long and missing something completely obvious?

答:
Take a look at Refactoring static method / static field for Testing

The approach suggested there may work for you, if for some reason you can't refactor everything to separate concerns as suggested in another answer.

OwnerDisplayName: Chris

Body:
Hope I can explain this somewhat decently, as it's blowing a fuse in my brain today. I'm learning TDD in C#, so I'm still trying to rewire my brain to fit it.

Let's say I have a User class, that previously had a static method to retrieve a User object (simplified below).

public static User GetUser(string username)
{
   User user = GetUserFromCache(username);
   if(user == null)
   {
       user = GetUserFromDatabase(username);
       StoreObjectInCache(user);
   }
   return user;
}

So I'm trying to rewrite this to use dependency injection so I can fake out the "GetUserFromDatabase" method if it needs to go there. That means I have to make the function not static. Whereas the data access layer would construct the user object from the database, mapping the returned columns to the object properties, a retrieval from cache would return a true-blue User object. However, in a non-static method, I can't just say

this = GetUserFromCache(username);

Because it just doesn't work that way. Though I'm by no means the world expert in how to dance around this with OO, it looks like I'd almost have to grab the User object from cache and write another mapping function that would store the returned User object properties into the new User instance.

What's the solution here? Any OO magic I'm missing? Is the only solution to refactor everything to use factories instead of having the instantiation logic in the object itself? Or have I been staring at this too long and missing something completely obvious?

LastEditorDisplayName: Chris

OwnerDisplayName: Dennis S.