问:
Cant render react google maps data before refresh page
In may app I have to show a list of markers and markers that are already stored in sessionStorage, but I cant set markers, zoom and center of the map at first render of the page, I nees refresh the page to see data on it.

FIRST RENDER:

AFTER REFRESH:

Part of the code is justa above, I have a loadMap where I instaciate map with useLoadScript, I can post it here too if it's necessary!

```<code>import React, { useState, useEffect } from "react"
import { GoogleMap, Marker } from "@react-google-maps/api"
import { Trash } from "phosphor-react"
import { useNavigate } from "react-router-dom"

var tempMarker

function Map({
  markers,
  setMarkers,
  wayPoints,
  setWayPoints,
  routeHead,
  setRouteHead,
}) {
  const [isMounted, setIsMounted] = useState(false)
  const [reload, setReload] = useState(false)

  const navigate = useNavigate()
  let marker

  function refreshPage() {
    console.log("passei aqui refresh")
    window.location.reload(false)
  }

  const onChangeMarkers = () => {
    if (markers) {
      if (markers.length > 0) {
        setWayPoints(markers)
        sessionStorage.removeItem("markers")
        sessionStorage.setItem("markers", JSON.stringify(markers))
        if (reload) {
          refreshPage()
          setReload(false)
        }
      }
    }
  }

  useEffect(() => {
    if (!isMounted) {
      setIsMounted(true)
      setReload(false)
      onChangeMarkers()
    }
  }, [])

  const handleOnLoad = (map) => {
    onChangeMarkers()
    const bounds = new window.google.maps.LatLngBounds()
    if (markers) {
      if (markers.length > 0) {
        markers.forEach(({ latitude, longitude }) => {
          let pos = new window.google.maps.LatLng(latitude, longitude)
          bounds.extend(pos)
        })
      } else {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
              }
              map.setZoom(13)
              map.setCenter(pos)
            },
            (e) => {
              console.log(e)
            },
            { maximumAge: 15000, timeout: 60000, enableHighAccuracy: true }
          )
        } else {
          let pos = new window.google.maps.latLng()
          pos = { lat: -16.6446324, lng: -49.416115 }
          map.setZoom(10)
          map.setCenter(pos)
        }
      }
    }
    map.fitBounds(bounds)
    map.addListener("click", function (e) {
      placeMarker(e.latLng, map)
    })
  }

  const handleSubmit = async (event) => {
    navigate("/WayPointsTable", { replace: false })
  }

  function placeMarker(location, map) {
    if (marker == null) {
      marker = new window.google.maps.Marker({
        position: location,
        map: map,
      })
    } else {
      marker.setPosition(location)
    }
    const markerId = markers.length
    const markerQtde = markerId + 1
    tempMarker = {
      idRota: routeHead.idRota,
      idVeiculo: routeHead.idVeiculo,
      idFrota: routeHead.idFrota,
      idMotorista: routeHead.idMotorista,
      idAjudante1: routeHead.idAjudante1,
      idAjudante2: routeHead.idAjudante2,
      idAjudante3: routeHead.idAjudante3,
      idCarga: routeHead.idCarga,
      idPonto: markerQtde,
      latitude: parseFloat(marker.getPosition().lat().toFixed(6)),
      longitude: parseFloat(marker.getPosition().lng().toFixed(6)),
      cpfCNPJ: "CPF/CNPJ",
      nome: "PONTO " + markerQtde,
      endereco: "informe o endereco",
      distanciaMinima: "100",
      horarioParada: "00:00",
      dataHoraInicio: routeHead.dtHrInicio,
      dataHoraFim: routeHead.dtHrFim,
      observacao: "",
      valorAReceber: 0,
      custoPernoite: 0,
      idSequencia: markerQtde,
      distanciaEmKm: 1,
      tipoRegistro: "2.ENTREGA",
    }
    console.log(tempMarker)
    markers.push(tempMarker)
    map.setZoom(14)
    let pos = new window.google.maps.LatLng(
      parseFloat(marker.getPosition().lat().toFixed(6)),
      parseFloat(marker.getPosition().lng().toFixed(6))
    )
    map.setCenter(pos)
    setReload(true)
    onChangeMarkers()
  }

  const handleMarkerClick = (evt) => {
    console.log(evt)
  }

  const handleMarkerDrag = (mk, index) => {
    const newLat = parseFloat(mk.latLng.lat().toFixed(6))
    const newLng = parseFloat(mk.latLng.lng().toFixed(6))
    markers = markers.map((marker, i) => {
      if (i === index) {
        marker = { ...marker, latitude: newLat, longitude: newLng }
      }
      return marker
    })
    setMarkers(markers)
    setReload(false)
    onChangeMarkers()
  }

  const handleDeleteMarker = (index) => {
    if (index !== undefined) {
      markers = markers
        .filter((marker, i) => i !== index)
        .map((marker, i) => {
          marker = { ...marker, id: i }
          return marker
        })
      setMarkers(markers)
      setReload(true)
      onChangeMarkers()
    }
  }

  return (
    <div className="flex flex-row">
      <div className="bg-zinc-300 w-1/4">
        <h2 className="text-center text-black font-bold p-2">
          PONTOS DE ENTREGA
        </h2>
        <div className="flex flex-col">
          <div className="overflow-x-auto sm:-mx-6 lg:-mx-8">
            <div className="py-2 inline-block min-w-full sm:px-6 lg:px-8">
              <div className="overflow-hidden">
                <table className="min-w-full">
                  <tbody className="text-black font-semibold">
                    {isMounted &&
                      wayPoints &&
                      wayPoints.length > 0 &&
                      wayPoints.map(({ nome }, index) => {
                        return (
                          <tr key={index}>
                            <td>{index + 1} - </td>
                            <td>{nome.substr(0, 18)}</td>
                            <td>
                              <div
                                key={index}
                                className="inline-block align-middle w-4 bg-red-700 text-white rounded "
                                onClick={() => handleDeleteMarker(index)}
                              >
                                <Trash size={16} alt="Excluir" />
                              </div>
                            </td>
                          </tr>
                        )
                      })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <div className="flex flex-col items-center">
          <button
            onClick={() => handleSubmit()}
            className=" bg-red-500 hover:bg-red-700 py-2 px-4 mt-3 rounded text-zinc-100 font-bold "
          >
            Enviar
          </button>
        </div>
      </div>
      <GoogleMap
        onLoad={handleOnLoad}
        afterLoad={refreshPage}
        mapContainerStyle={{ width: "100vw", height: "100vh" }}
      >
        {isMounted &&
          wayPoints &&
          wayPoints.length > 0 &&
          wayPoints.map(({ nome, idSequencia, latitude, longitude }, index) => (
            <Marker
              key={index}
              position={{ lat: latitude, lng: longitude }}
              title={nome}
              addListener
              draggable
              onClick={handleMarkerClick}
              onDragEnd={(marker) => handleMarkerDrag(marker, index)}
              icon={
                "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" +
                idSequencia +
                "|FF0000|000000"
              }
            ></Marker>
          ))}
      </GoogleMap>
    </div>
  )
}

export default Map
</code>```

Body:
In may app I have to show a list of markers and markers that are already stored in sessionStorage, but I cant set markers, zoom and center of the map at first render of the page, I nees refresh the page to see data on it.

FIRST RENDER:

AFTER REFRESH:

Part of the code is justa above, I have a loadMap where I instaciate map with useLoadScript, I can post it here too if it's necessary!

import React, { useState, useEffect } from "react"
import { GoogleMap, Marker } from "@react-google-maps/api"
import { Trash } from "phosphor-react"
import { useNavigate } from "react-router-dom"

var tempMarker

function Map({
  markers,
  setMarkers,
  wayPoints,
  setWayPoints,
  routeHead,
  setRouteHead,
}) {
  const [isMounted, setIsMounted] = useState(false)
  const [reload, setReload] = useState(false)

  const navigate = useNavigate()
  let marker

  function refreshPage() {
    console.log("passei aqui refresh")
    window.location.reload(false)
  }

  const onChangeMarkers = () => {
    if (markers) {
      if (markers.length > 0) {
        setWayPoints(markers)
        sessionStorage.removeItem("markers")
        sessionStorage.setItem("markers", JSON.stringify(markers))
        if (reload) {
          refreshPage()
          setReload(false)
        }
      }
    }
  }

  useEffect(() => {
    if (!isMounted) {
      setIsMounted(true)
      setReload(false)
      onChangeMarkers()
    }
  }, [])

  const handleOnLoad = (map) => {
    onChangeMarkers()
    const bounds = new window.google.maps.LatLngBounds()
    if (markers) {
      if (markers.length > 0) {
        markers.forEach(({ latitude, longitude }) => {
          let pos = new window.google.maps.LatLng(latitude, longitude)
          bounds.extend(pos)
        })
      } else {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const pos = {
                lat: position.coords.latitude,
                lng: position.coords.longitude,
              }
              map.setZoom(13)
              map.setCenter(pos)
            },
            (e) => {
              console.log(e)
            },
            { maximumAge: 15000, timeout: 60000, enableHighAccuracy: true }
          )
        } else {
          let pos = new window.google.maps.latLng()
          pos = { lat: -16.6446324, lng: -49.416115 }
          map.setZoom(10)
          map.setCenter(pos)
        }
      }
    }
    map.fitBounds(bounds)
    map.addListener("click", function (e) {
      placeMarker(e.latLng, map)
    })
  }

  const handleSubmit = async (event) => {
    navigate("/WayPointsTable", { replace: false })
  }

  function placeMarker(location, map) {
    if (marker == null) {
      marker = new window.google.maps.Marker({
        position: location,
        map: map,
      })
    } else {
      marker.setPosition(location)
    }
    const markerId = markers.length
    const markerQtde = markerId + 1
    tempMarker = {
      idRota: routeHead.idRota,
      idVeiculo: routeHead.idVeiculo,
      idFrota: routeHead.idFrota,
      idMotorista: routeHead.idMotorista,
      idAjudante1: routeHead.idAjudante1,
      idAjudante2: routeHead.idAjudante2,
      idAjudante3: routeHead.idAjudante3,
      idCarga: routeHead.idCarga,
      idPonto: markerQtde,
      latitude: parseFloat(marker.getPosition().lat().toFixed(6)),
      longitude: parseFloat(marker.getPosition().lng().toFixed(6)),
      cpfCNPJ: "CPF/CNPJ",
      nome: "PONTO " + markerQtde,
      endereco: "informe o endereco",
      distanciaMinima: "100",
      horarioParada: "00:00",
      dataHoraInicio: routeHead.dtHrInicio,
      dataHoraFim: routeHead.dtHrFim,
      observacao: "",
      valorAReceber: 0,
      custoPernoite: 0,
      idSequencia: markerQtde,
      distanciaEmKm: 1,
      tipoRegistro: "2.ENTREGA",
    }
    console.log(tempMarker)
    markers.push(tempMarker)
    map.setZoom(14)
    let pos = new window.google.maps.LatLng(
      parseFloat(marker.getPosition().lat().toFixed(6)),
      parseFloat(marker.getPosition().lng().toFixed(6))
    )
    map.setCenter(pos)
    setReload(true)
    onChangeMarkers()
  }

  const handleMarkerClick = (evt) => {
    console.log(evt)
  }

  const handleMarkerDrag = (mk, index) => {
    const newLat = parseFloat(mk.latLng.lat().toFixed(6))
    const newLng = parseFloat(mk.latLng.lng().toFixed(6))
    markers = markers.map((marker, i) => {
      if (i === index) {
        marker = { ...marker, latitude: newLat, longitude: newLng }
      }
      return marker
    })
    setMarkers(markers)
    setReload(false)
    onChangeMarkers()
  }

  const handleDeleteMarker = (index) => {
    if (index !== undefined) {
      markers = markers
        .filter((marker, i) => i !== index)
        .map((marker, i) => {
          marker = { ...marker, id: i }
          return marker
        })
      setMarkers(markers)
      setReload(true)
      onChangeMarkers()
    }
  }

  return (

          PONTOS DE ENTREGA

                    {isMounted &&
                      wayPoints &&
                      wayPoints.length > 0 &&
                      wayPoints.map(({ nome }, index) => {
                        return (

                            {index + 1} -
                            {nome.substr(0, 18)}

 handleDeleteMarker(index)}
                              >
                                <Trash size={16} alt="Excluir" />

                        )
                      })}

          <button
            onClick={() => handleSubmit()}
            className=" bg-red-500 hover:bg-red-700 py-2 px-4 mt-3 rounded text-zinc-100 font-bold "
          >
            Enviar
          </button>

      <GoogleMap
        onLoad={handleOnLoad}
        afterLoad={refreshPage}
        mapContainerStyle={{ width: "100vw", height: "100vh" }}
      >
        {isMounted &&
          wayPoints &&
          wayPoints.length > 0 &&
          wayPoints.map(({ nome, idSequencia, latitude, longitude }, index) => (
            <Marker
              key={index}
              position={{ lat: latitude, lng: longitude }}
              title={nome}
              addListener
              draggable
              onClick={handleMarkerClick}
              onDragEnd={(marker) => handleMarkerDrag(marker, index)}
              icon={
                "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=" +
                idSequencia +
                "|FF0000|000000"
              }
            ></Marker>
          ))}
      </GoogleMap>

  )
}

export default Map


来源: stackexchange

问:
How to just show an alert with react-error-boundary, leaving the children untouched?
I've a <CartIconButton> which opens a <VariantsDialog> component. I've wrapped the dialog inside the <ErrorBoundary> component. The trigger prop is the actual button which opens the dialog:

<ErrorBoundary>
  <VariantsDialog productId={product.id}
    trigger={props => <CartIconButton {...props} />} />
</ErrorBoundary>
```
<p>The dialog itself is using <code>useErrorHandler()</code> <strong>(1)</strong> to signal the parent that something went wrong during it's async operation. It renders the trigger too:</p>
<pre class="lang-js prettyprint-override"><code>export const VariantsDialog = ({ productId, trigger }) => {
  const [loading, error, data] = useFetch(`/api/variats/${productId}`);
  useErrorHandler(error); // (1)

  return (
    <>
      {trigger(bindTrigger(popupState))}
      <Dialog>{/* dialog content */}</Dialog>
    </>
  );
};
</code>```

I don't really want to replace the content inside <ErrorBoundary> (that is, the rendered <CartIconButton> should remain). I'd like to just show a notification.

Would be possibile to istruct the library to "just call this method when something bad happens, but still render the children" ?

ContentLicense: CC BY-SA 4.0

Body:
I've a <CartIconButton> which opens a <VariantsDialog> component. I've wrapped the dialog inside the <ErrorBoundary> component. The trigger prop is the actual button which opens the dialog:

<ErrorBoundary>
  <VariantsDialog productId={product.id}
    trigger={props => <CartIconButton {...props} />} />
</ErrorBoundary>

The dialog itself is using useErrorHandler() (1) to signal the parent that something went wrong during it's async operation. It renders the trigger too:

export const VariantsDialog = ({ productId, trigger }) => {
  const [loading, error, data] = useFetch(`/api/variats/${productId}`);
  useErrorHandler(error); // (1)

  return (
    <>
      {trigger(bindTrigger(popupState))}
      <Dialog>{/* dialog content */}</Dialog>
    </>
  );
};

I don't really want to replace the content inside <ErrorBoundary> (that is, the rendered <CartIconButton> should remain). I'd like to just show a notification.

Would be possibile to istruct the library to "just call this method when something bad happens, but still render the children" ?


问:
Why does printing the DecisionTreeClassifier not display more detail
I am working from this tutorial: https://dataaspirant.com/visualize-decision-tree-python-graphviz/

The code:

```<code>import pandas as pd
import numpy as np
from sklearn import tree
fruit_data_set = pd.DataFrame()
# 1 is an apple, 0 is an orange
fruit_data_set["fruit"] = np.array([   1,   1,   1,   1,   1,   0,   0,   0,   0,   0])
fruit_data_set["weight"] = np.array([170, 175, 180, 178, 182, 130, 120, 130, 138, 145])
fruit_data_set["smooth"] = np.array([  9,  10,   8,   8,   7,   3,   4,   2,   5,   6])
fruit_classifier = tree.DecisionTreeClassifier()
fruit_classifier.fit(fruit_data_set[["weight", "smooth"]], fruit_data_set["fruit"])

print (fruit_classifier)
</code>```

My output is this:

```<code>DecisionTreeClassifier()
</code>```

The output according to the tutorial should be:

```<code>DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False, random_state=None, splitter='best')
</code>```

Body:
I am working from this tutorial: https://dataaspirant.com/visualize-decision-tree-python-graphviz/

The code:

import pandas as pd
import numpy as np
from sklearn import tree
fruit_data_set = pd.DataFrame()
# 1 is an apple, 0 is an orange
fruit_data_set["fruit"] = np.array([   1,   1,   1,   1,   1,   0,   0,   0,   0,   0])
fruit_data_set["weight"] = np.array([170, 175, 180, 178, 182, 130, 120, 130, 138, 145])
fruit_data_set["smooth"] = np.array([  9,  10,   8,   8,   7,   3,   4,   2,   5,   6])
fruit_classifier = tree.DecisionTreeClassifier()
fruit_classifier.fit(fruit_data_set[["weight", "smooth"]], fruit_data_set["fruit"])

print (fruit_classifier)

My output is this:

DecisionTreeClassifier()

The output according to the tutorial should be:

DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            presort=False, random_state=None, splitter='best')


问:
Check box field in django forms showing error
Based on my django project I want to add multiple users to a group and I'm trying to do this using a form. But when I try adding choices via CheckBoxSelectMultiple() widget its not working as expected.

models.py file

```<code>from django.db import models
from members.models import User
from django.contrib.auth.models import Group

class Sprint(models.Model):

    status_choice = [('Working','Working'), ('Closed','Closed')]

    sprint_name = models.CharField(max_length=180)
    sprint_created = models.DateTimeField(auto_now= True)
    lead = models.ForeignKey(User, on_delete=models.CASCADE,
                                        related_name='team_lead')
    sprint_members = models.ForeignKey(Group, on_delete=models.CASCADE, related_name = "member")
    sprint_period = models.PositiveIntegerField()
    sprint_status = models.CharField(max_length=10, choices=status_choice, default='Working')
</code>```

forms.py file

```<code>from django import forms
from .models import Sprint
from members.models import User
from django.core.exceptions import ValidationError
from django.contrib.auth.models import Group

class SprintForm(forms.Form):

    sprint_name = forms.CharField()
    sprint_period = forms.IntegerField(label="Sprint period (in days)", min_value=7)
    lead = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'),
label="Team Lead")
    sprint_members = forms.ModelChoiceField(queryset= User.objects.filter(role =
'Developer'),  widget= forms.CheckboxSelectMultiple(), label="Team members")
# class Meta:
#     model = Sprint
#     fields = ['sprint_name', 'lead', 'sprint_period', 'sprint_members']

def clean(self):
    cleaned_data = super().clean()
    lead = cleaned_data.get('lead')
    team = cleaned_data.get('sprint_members')
    if team and lead:
        if lead in team:
            raise ValidationError('Team lead cant be in team')

def save(self):
    team = Group.objects.get_or_create(name=f'team{self.cleaned_data["sprint_name"]}')[0]
    for team_member in self.cleaned_data['sprint_members']:
        team.user_set.add(team_member)
    Sprint.objects.update_or_create(
        sprint_name=self.cleaned_data["sprint_name"],
        lead=self.cleaned_data["lead"],
        sprint_period=self.cleaned_data["sprint_period"],
        _members=team
    )
</code>```

views.py file

```<code>class SprintCreationView(generic.FormView):
    model = Sprint
    template_name = 'sprint_creation.html'
    form_class = SprintForm

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)
</code>```

When trying to submit the form it is showing "Select a valid choice. That choice is not one of the available choices."

Body:
Based on my django project I want to add multiple users to a group and I'm trying to do this using a form. But when I try adding choices via CheckBoxSelectMultiple() widget its not working as expected.

models.py file

from django.db import models
from members.models import User
from django.contrib.auth.models import Group

class Sprint(models.Model):

    status_choice = [('Working','Working'), ('Closed','Closed')]

    sprint_name = models.CharField(max_length=180)
    sprint_created = models.DateTimeField(auto_now= True)
    lead = models.ForeignKey(User, on_delete=models.CASCADE,
                                        related_name='team_lead')
    sprint_members = models.ForeignKey(Group, on_delete=models.CASCADE, related_name = "member")
    sprint_period = models.PositiveIntegerField()
    sprint_status = models.CharField(max_length=10, choices=status_choice, default='Working')

forms.py file

from django import forms
from .models import Sprint
from members.models import User
from django.core.exceptions import ValidationError
from django.contrib.auth.models import Group

class SprintForm(forms.Form):

    sprint_name = forms.CharField()
    sprint_period = forms.IntegerField(label="Sprint period (in days)", min_value=7)
    lead = forms.ModelChoiceField(queryset= User.objects.filter(role = 'Developer'),
label="Team Lead")
    sprint_members = forms.ModelChoiceField(queryset= User.objects.filter(role =
'Developer'),  widget= forms.CheckboxSelectMultiple(), label="Team members")
# class Meta:
#     model = Sprint
#     fields = ['sprint_name', 'lead', 'sprint_period', 'sprint_members']

def clean(self):
    cleaned_data = super().clean()
    lead = cleaned_data.get('lead')
    team = cleaned_data.get('sprint_members')
    if team and lead:
        if lead in team:
            raise ValidationError('Team lead cant be in team')

def save(self):
    team = Group.objects.get_or_create(name=f'team{self.cleaned_data["sprint_name"]}')[0]
    for team_member in self.cleaned_data['sprint_members']:
        team.user_set.add(team_member)
    Sprint.objects.update_or_create(
        sprint_name=self.cleaned_data["sprint_name"],
        lead=self.cleaned_data["lead"],
        sprint_period=self.cleaned_data["sprint_period"],
        _members=team
    )

views.py file

class SprintCreationView(generic.FormView):
    model = Sprint
    template_name = 'sprint_creation.html'
    form_class = SprintForm

    def form_valid(self, form):
        form.save()
        return super().form_valid(form)

When trying to submit the form it is showing "Select a valid choice. That choice is not one of the available choices."


问:
VBA - Assign cell value equal the value of a cell in a different workbook in a different path
I am trying to perfom a simple task using VBA. I want to assign Range("A1").Value = Range("A1").Value of a different workbook, wich is in a different folder. How do I do that?

I have no idea what to try in order to accomplish this task.

I dont want to open the other file in order to do that, because I am going to loop this procedure for 500 different worksheets.


问:
Python project structure many main.py endpoints
I currently have the following project structure in python:

```<code>| project
├── module_1
│   ├── __init__.py
│   ├── class_1.py
├── module_2
│   ├── __init__.py
│   ├── class_2.py
├── main_1.py
├── main_2.py
├── ..
├── main_n.py
├── set_up.py
</code>```

Because of the vast amount of main files we use to run our scripts, I would like to organise these in different modules within the project (different module based on different usage of the endpoint). I have tried something like below:

```<code>| project
├── module_1
│   ├── __init__.py
│   ├── class_1.py
├── module_2
│   ├── __init__.py
│   ├── class_2.py
├── endpoints_1
│   ├── __init__.py
│   ├── main_1.py
│   ├── set_up.py
├── endpoints_2
│   ├── __init__.py
│   ├── main_2.py
│   ├── set_up.py

</code>```

The problem that arises however is that I would have to make a different 'set_up.py' file for each of the endpoint modules. In this set_up file I would add the project path to the sys.paths so that all imports work as expected.

So to conclude I have the following two questions:

Is there any way I can have this project structure without having to mess to much with the sys paths and having a custom 'set_up.py' for each module which contains endpoints?

Should I, to begin with, even use this kind of project structure or should I just keep the original structure and not bundle the endpoints in a module ?

Body:
I currently have the following project structure in python:

| project
├── module_1
│   ├── __init__.py
│   ├── class_1.py
├── module_2
│   ├── __init__.py
│   ├── class_2.py
├── main_1.py
├── main_2.py
├── ..
├── main_n.py
├── set_up.py

Because of the vast amount of main files we use to run our scripts, I would like to organise these in different modules within the project (different module based on different usage of the endpoint). I have tried something like below:

| project
├── module_1
│   ├── __init__.py
│   ├── class_1.py
├── module_2
│   ├── __init__.py
│   ├── class_2.py
├── endpoints_1
│   ├── __init__.py
│   ├── main_1.py
│   ├── set_up.py
├── endpoints_2
│   ├── __init__.py
│   ├── main_2.py
│   ├── set_up.py

The problem that arises however is that I would have to make a different 'set_up.py' file for each of the endpoint modules. In this set_up file I would add the project path to the sys.paths so that all imports work as expected.

So to conclude I have the following two questions:

Is there any way I can have this project structure without having to mess to much with the sys paths and having a custom 'set_up.py' for each module which contains endpoints?

Should I, to begin with, even use this kind of project structure or should I just keep the original structure and not bundle the endpoints in a module ?


问:
PhpStorm, set a custom coding standard
I have a dockerized WSL with PHP code sniffer installed. Now I stuck to set up "wordpress" coding standard.
When I run phpcs -i from WSL it then shows

The installed coding standards are PSR2, PEAR, PSR12, MySource, Squiz,
Zend, PSR1, WordPress-Core, WordPress-Docs, WordPress-Extra and
WordPress

but the "coding standards" in the settings are still Pear, PSR1, PSR12, PSR2, Squiz, Zend, Custom. How to make it understand that I have WordPress coding standard?

Title: PhpStorm, set a custom coding standard


问:
python request get updated [redirected] url
Given 3 raw and old urls:

```<code>raw_url = 'https://digi.kansalliskirjasto.fi/aikakausi/binding/498491?term=1864&term=SUOMI&language=fi'
raw_url = 'https://twitter.com/i/user/2274951674'
raw_url = 'https://youtu.be/dQw4w9WgXcQ'
</code>```

Using this code snippet in my Linux machine (different question than this post) containing both GET and HEAD methods in requests library to obtain the updated urls:

```<code>#r = requests.get(raw_url)
r = requests.head(raw_url, allow_redirects=True)
r.raise_for_status()

print(f"HTTP family: {r.status_code}\tExists: {r.ok}\thistory:{r.history}")

updated_url = r.url
print(f"Updated URL: {updated_url}") # works only for 3rd raw_url
</code>```

It seems that it only redirects and updates those urls with <Response [3XX]> (my third raw_url) not others.

My updated and expected urls in a web browser are:

```<code>https://digi.kansalliskirjasto.fi/aikakausi/binding/498491?term=1864&term=SUOMI&page=1
https://twitter.com/ozanbayram01
https://www.youtube.com/watch?v=dQw4w9WgXcQ # still different from requests updated url
</code>```

How can I get updated urls in python in such scenarios?

Cheers,

Body:
Given 3 raw and old urls:

raw_url = 'https://digi.kansalliskirjasto.fi/aikakausi/binding/498491?term=1864&term=SUOMI&language=fi'
raw_url = 'https://twitter.com/i/user/2274951674'
raw_url = 'https://youtu.be/dQw4w9WgXcQ'

Using this code snippet in my Linux machine (different question than this post) containing both GET and HEAD methods in requests library to obtain the updated urls:

#r = requests.get(raw_url)
r = requests.head(raw_url, allow_redirects=True)
r.raise_for_status()

print(f"HTTP family: {r.status_code}\tExists: {r.ok}\thistory:{r.history}")

updated_url = r.url
print(f"Updated URL: {updated_url}") # works only for 3rd raw_url

It seems that it only redirects and updates those urls with <Response [3XX]> (my third raw_url) not others.

My updated and expected urls in a web browser are:

https://digi.kansalliskirjasto.fi/aikakausi/binding/498491?term=1864&term=SUOMI&page=1
https://twitter.com/ozanbayram01
https://www.youtube.com/watch?v=dQw4w9WgXcQ # still different from requests updated url

How can I get updated urls in python in such scenarios?

Cheers,


问:
How to retrieve the last intent received by an app without using activity.onNewIntent?
Is there a way to retrieve the last intent received by the app without using activity.onNewIntent (for some obscure reasons I cannot use this event) ?</p>


问:
Checkbox doesnt stay Checked
I am having a very weird problem. I am trying to load a "Group" which has a list of devices. The devices exist in a table and a checkmark should appear when the device is inside the group.

My code looks like this:

```<code>function LoadGroup(Input)
{
    document.querySelectorAll('input[type=checkbox]').forEach(el => el.checked = false);

    console.log(Input.id);

    GroupData.find(Element => {
        if(Element["ID"] == Input.id)
        {
            Element["Devices"].forEach(Device => {
                Checkmark = document.getElementById(Device["DeviceID"]);
                Checkmark.checked = true
                console.log(Checkmark.checked);
            })
            return true;
        }
    });

    document.querySelectorAll('input[type=checkbox]').forEach(Element => console.log(Element.checked));
}
</code>```

So a group gets clicked on, I search for the right Group in my data and then go through the devices to set the Checkmark and log the current state. I get 4 true in the console.
After this I query all checkmarks and check if they are checked. I get 3 true one false.

I dont understand what the problem is. He sets all true but then one is false.
Any ideas?

Title: Checkbox doesnt stay Checked

Body:
I am having a very weird problem. I am trying to load a "Group" which has a list of devices. The devices exist in a table and a checkmark should appear when the device is inside the group.

My code looks like this:

function LoadGroup(Input)
{
    document.querySelectorAll('input[type=checkbox]').forEach(el => el.checked = false);

    console.log(Input.id);

    GroupData.find(Element => {
        if(Element["ID"] == Input.id)
        {
            Element["Devices"].forEach(Device => {
                Checkmark = document.getElementById(Device["DeviceID"]);
                Checkmark.checked = true
                console.log(Checkmark.checked);
            })
            return true;
        }
    });

    document.querySelectorAll('input[type=checkbox]').forEach(Element => console.log(Element.checked));
}

So a group gets clicked on, I search for the right Group in my data and then go through the devices to set the Checkmark and log the current state. I get 4 true in the console.
After this I query all checkmarks and check if they are checked. I get 3 true one false.

I dont understand what the problem is. He sets all true but then one is false.
Any ideas?


问:
Issue with Rails 5.2.4 translation method
The index view pushed by the Scheduler::ProductionJobsController index method contains the following request to the translation method:

```<code>  <h2> <%= t('.View') %> </h2>
</code>```

The config\locales\Scheduler\ProductionJob\ fr_OFS.yml file (which is current user's language) contains the following entries:

```<code># Code for language as declared in i18n configuration
fr_OFS:
  # Considered object from a global view
  ProductionJobs:                          "Flux de production"

  # Considered object from controller's methods. In the controller, the relative path for the term is marked by the point (.)
  scheduler:
    production_jobs:
      index:
        # Columns titles
        Code:                                   "Identifiant"
        Name:                                   "Nom"
        Description:                            "Description"
        Owner:                                  "Responsable"
        Version:                                "Mis à jour le"
        Status:                                 "Statut"
        View:                                   "Voir"
        Delete:                                 "Supprimer"
</code>```

Eventhough this looks trivial, it results in a translation missing error:

```<code><h2>
  <span class="translation_missing" title="translation missing: fr_OFS.scheduler.production_jobs.index.View">View</span>
</h2>
</code>```

Writing t('scheduler.production_jobs.index.View') does not change a thing...

Did I miss something?

Thanks for your help!

Body:
The index view pushed by the Scheduler::ProductionJobsController index method contains the following request to the translation method:

 <%= t('.View') %>

The config\locales\Scheduler\ProductionJob\ fr_OFS.yml file (which is current user's language) contains the following entries:

# Code for language as declared in i18n configuration
fr_OFS:
  # Considered object from a global view
  ProductionJobs:                          "Flux de production"

  # Considered object from controller's methods. In the controller, the relative path for the term is marked by the point (.)
  scheduler:
    production_jobs:
      index:
        # Columns titles
        Code:                                   "Identifiant"
        Name:                                   "Nom"
        Description:                            "Description"
        Owner:                                  "Responsable"
        Version:                                "Mis à jour le"
        Status:                                 "Statut"
        View:                                   "Voir"
        Delete:                                 "Supprimer"

Eventhough this looks trivial, it results in a translation missing error:

  View

Writing t('scheduler.production_jobs.index.View') does not change a thing...

Did I miss something?

Thanks for your help!


问:
Swagger UI oauth cookie interfering with Spring boot security oauth?
I added springdoc-openapi-ui 1.6.12 in my Spring Boot project. I configured oAuth2 with PKCE and everything works fine, when I click on the "authorize" button it redirects me to a sso connection page. Then, I can send requests via swagger ui.

The problem is that it interferes with my Angular front end authentication. The front loops on the /login rout, with a 401 error. Swagger oauth uses the same session cookie as Spring Security/Angular.

Is there a way to use the same session for swagger ui AND angular ? Or is the problem somewhere else ?

This is my configuration :

```<code>    springdoc:
      swagger-ui:
        path: /api-docs
        tagsSorter: alpha
        oauth:
          clientId: "XXX"
          clientSecret: "XXX"
          use-pkce-with-authorization-code-grant: true
      oAuthFlow:
        authorizationUrl: "XXX/as/authorization.oauth2"
        tokenUrl: "XXX/as/token.oauth2"
        scope : XXX profile groups XXX email
</code>```

edit :

```<code> @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and().csrf().disable()

                .headers()
                .frameOptions().disable()
                .httpStrictTransportSecurity()
                .includeSubDomains(false)
                .maxAgeInSeconds(60*60*24*5)
                .and().and()

                .authorizeRequests(a -> a
                        // Management endpoints
                        .antMatchers(
                                "/health" + MATCH_ALL,
                                "/info",
                                "/prometheus",
                                "/loggers" + MATCH_ALL,
                                "/metrics" + MATCH_ALL
                        ).permitAll()

                        // Authentication
                        .antMatchers(Routes.CURRENT_USER).permitAll()
                        .antMatchers("/oauth2/authorization/XXX").permitAll()
                        .antMatchers(Routes.LOGIN).authenticated()

                        // Preflight requests
                        .antMatchers(HttpMethod.OPTIONS).permitAll()

                        // Applications
                        .antMatchers(Routes.XXX.BASE + MATCH_ALL).hasAuthority(AuthorityUtil.AUTHORITY_XXX)
                )

                // By setting the login page here, Spring won't ask which provider we want to use
                .oauth2Login().loginPage("/oauth2/authorization/XXX")
                .and()
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken)
        ;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();
        config.setAllowedOriginPatterns(List.of("*"));
        config.setAllowedMethods(List.of("*"));
        config.setAllowedHeaders(List.of("*"));
        config.setAllowCredentials(true);
        config.setMaxAge(1800L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(MATCH_ALL, config);
        return source;
    }
</code>```

Body:
I added springdoc-openapi-ui 1.6.12 in my Spring Boot project. I configured oAuth2 with PKCE and everything works fine, when I click on the "authorize" button it redirects me to a sso connection page. Then, I can send requests via swagger ui.

The problem is that it interferes with my Angular front end authentication. The front loops on the /login rout, with a 401 error. Swagger oauth uses the same session cookie as Spring Security/Angular.

Is there a way to use the same session for swagger ui AND angular ? Or is the problem somewhere else ?

This is my configuration :

    springdoc:
      swagger-ui:
        path: /api-docs
        tagsSorter: alpha
        oauth:
          clientId: "XXX"
          clientSecret: "XXX"
          use-pkce-with-authorization-code-grant: true
      oAuthFlow:
        authorizationUrl: "XXX/as/authorization.oauth2"
        tokenUrl: "XXX/as/token.oauth2"
        scope : XXX profile groups XXX email

edit :

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().configurationSource(corsConfigurationSource())
                .and().csrf().disable()

                .headers()
                .frameOptions().disable()
                .httpStrictTransportSecurity()
                .includeSubDomains(false)
                .maxAgeInSeconds(60*60*24*5)
                .and().and()

                .authorizeRequests(a -> a
                        // Management endpoints
                        .antMatchers(
                                "/health" + MATCH_ALL,
                                "/info",
                                "/prometheus",
                                "/loggers" + MATCH_ALL,
                                "/metrics" + MATCH_ALL
                        ).permitAll()

                        // Authentication
                        .antMatchers(Routes.CURRENT_USER).permitAll()
                        .antMatchers("/oauth2/authorization/XXX").permitAll()
                        .antMatchers(Routes.LOGIN).authenticated()

                        // Preflight requests
                        .antMatchers(HttpMethod.OPTIONS).permitAll()

                        // Applications
                        .antMatchers(Routes.XXX.BASE + MATCH_ALL).hasAuthority(AuthorityUtil.AUTHORITY_XXX)
                )

                // By setting the login page here, Spring won't ask which provider we want to use
                .oauth2Login().loginPage("/oauth2/authorization/XXX")
                .and()
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken)
        ;
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.applyPermitDefaultValues();
        config.setAllowedOriginPatterns(List.of("*"));
        config.setAllowedMethods(List.of("*"));
        config.setAllowedHeaders(List.of("*"));
        config.setAllowCredentials(true);
        config.setMaxAge(1800L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(MATCH_ALL, config);
        return source;
    }


问:
SAP Flexible Workflow pre-condition value not loaded in edit mode
I've created a new pre-condition field in Workflow Flexible called Transfer Type with default domain values (T/B).

When I save the WF with T or B in this field it's OK, the value is saved.

But when I try to edit this workflow the value is cleared and we need to fill again the Transfer Type.

Question to the experts, how can I recover the value saved before in this field?

Thank you in advance!

In the OData field map:
/sap/opu/odata/sap/ZWF_FI_SEARCH_HELP_CDS/?$format=xml

<app:collection sap:creatable="false" sap:updatable="false" sap:deletable="false"
    sap:searchable="true" sap:content-version="1" href="zC_FI_Transfer_Type">
  <atom:title type="text">zC_FI_Transfer_Type</atom:title>
  <sap:member-title>Check Budget</sap:member-title>
  <atom:link href="zC_FI_Transfer_Type/OpenSearchDescription.xml" rel="search"
      type="application/opensearchdescription+xml" title="searchzC_FI_Transfer_Type" />
</app:collection>
```

In SPRO path:

Body:
I've created a new pre-condition field in Workflow Flexible called Transfer Type with default domain values (T/B).

When I save the WF with T or B in this field it's OK, the value is saved.

But when I try to edit this workflow the value is cleared and we need to fill again the Transfer Type.

Question to the experts, how can I recover the value saved before in this field?

Thank you in advance!

In the OData field map:
/sap/opu/odata/sap/ZWF_FI_SEARCH_HELP_CDS/?$format=xml

<app:collection sap:creatable="false" sap:updatable="false" sap:deletable="false"
    sap:searchable="true" sap:content-version="1" href="zC_FI_Transfer_Type">
  <atom:title type="text">zC_FI_Transfer_Type</atom:title>
  <sap:member-title>Check Budget</sap:member-title>
  <atom:link href="zC_FI_Transfer_Type/OpenSearchDescription.xml" rel="search"
      type="application/opensearchdescription+xml" title="searchzC_FI_Transfer_Type" />
</app:collection>

In SPRO path:


问:
What is the Javadoc specification for in an Eclipse user library entry?
I've created a user library in Eclipse containing one object code JAR and specifying a Javadoc JAR and a source code JAR.

I've found the source code archive is necessary and sufficient to let the Java editor display my Javadoc when code completion is used with the members I've documented.

Given that the source code archive is necessary and sufficient, what I'd like to know is: what's the purpose of adding the Javadoc JAR to the library entry?

I'd like to be able to explain it to others.


问:
how to load a Disqus profile in .NET MAUI?
Is it possible to load the profile picture/name of the currently logged in Disqus account in your .NET MAUI application?
if so, how do you do it?

I have been trying to do it for a while now but I keep finding websites that USE Disqus instead of telling how to implement it.


问:
How to use deck.gl to render a polygon layer that is using a different coordinate system than the standard LAT LONG?

Background

I am using deck.gl's PolygonLayer to render data that looks like this:

data.json:

{
    "someKey": "someValue",
    "spatialReference": {
        "wkid": 23032,
    },
    "features": [
        {
            "attributes": {
                "polygonName": "MY_POLYGON"
            },
            "geometry": {
                "rings": [
                    [
                        [421334, 7240529], ...
                    ],
                    [
                        [422656, 7250696], ...
                    ]
                ]
            }
        }
    ]
}
```
<p>Now, the problem is that decg.gl uses a latitude-longitude coordinate-system, which is different from what this polygon is expressed in.</p>
<h2>Deck.GL documentation on rendering layers with different coordinate-systems</h2>
<p>So, according to the documentation, deckGL renders each layer separately based on its coordinate system. Therefore, it was important to specify both <code>coordinateOrigin</code> and <code>coordinateSystem</code> props.</p>
<h2>Understanding the coordinate system in data.json</h2>
<p>So, as far as I understood, the <code>spacialReference</code> value in data.json represents an EPSG code. Using this website, I was able to find a value for the <code>coordinateOrigin</code> prop as <code>[63.510617, 9.210989, 0]</code>. As for the <code>coordinateSystem</code> prop, I used <code>COORDINATE_SYSTEM.METER_OFFSETS</code>. Here's the code:</p>
<p><strong>PolygonLayer.tsx:</strong></p>
<pre class="lang-ts prettyprint-override"><code>import React from "react";
import { COORDINATE_SYSTEM } from "@deck.gl/core/typed";
import { DeckLayer } from "@deck.gl/arcgis";
import { PolygonLayer } from "@deck.gl/layers/typed";
import MapView from "@arcgis/core/views/MapView";
import ArcGISMap from "@arcgis/core/Map";
import "@arcgis/core/assets/esri/themes/light/main.css";

export default function PolygonLayer({layerURL}) {
    const mapRef = React.useState(null)

    React.useEffect(() => {
        fetch(layerURL)
            .then(res => res.json())
            .then(data => {
                const blobURL = new Blob([JSON.stringify(data)], {type: "application/json",});
                const url = URL.createObjectURL(blobURL); // this is needed for the layer

                const layer = new PolygonLayer({
                    id: data["features"][0]["attributes"]["polygonName"], // correctly defined
                    data: url,
                    filled: true,
                    getLineWidth: 3,
                    getLineColor: [255, 255, 255, 0],
                    getFillColor: [234, 243, 221, 0],
                    coordinateOrigin: [63.510617, 9.210989, 0], // based on the explanation above
                    coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,
                    getPolygon: (d) => {
                        console.log(d); // doesn't log anything
                        return d.features[0].geometry.rings;
                    },
                });

                const deckLayer = new DeckLayer({
                    "deck.layers": [layer],
                });

                const arcgisMap = new ArcGISMap({
                    basemap: "topo-vector",
                    layers: [deckLayer]
                });

                new MapView({
                    container: mapRef?.current,
                    map: arcgisMap,
                    center: data["features"][0]["geometry"]["rings"][0][0], // correctly defined
                    zoom: 9
                });

            })
            .catch(err => console.log(err));
    }, [layerURL]);

    return <div ref={mapRef} style={{height: "90vh", width: "100%"}}></div>
}
</code>```

The issue with this code

The problem with this code is that it doesn't render the layer (or the base map) and there's nothing logged in the console for the value of d; as mentioned in the code above.

Making sure the code works

Now, just a sanity check, I have used this url which returns polygons data in the standard LAT LONG format, without using coordinateOrigin or coordinateSystem props as in this example and it worked. So the code is ok rendering LAT LONG system, but breaks when using METERS_OFFSET as in the code provided.

Therefore

Have I figured out the coordinateOrigin correctly? And how can I use this (or another type of) layer to render this data correctly? Any help is appreciated and apologies for the long question!

Body:
Background

I am using deck.gl's PolygonLayer to render data that looks like this:

data.json:

{
    "someKey": "someValue",
    "spatialReference": {
        "wkid": 23032,
    },
    "features": [
        {
            "attributes": {
                "polygonName": "MY_POLYGON"
            },
            "geometry": {
                "rings": [
                    [
                        [421334, 7240529], ...
                    ],
                    [
                        [422656, 7250696], ...
                    ]
                ]
            }
        }
    ]
}

Now, the problem is that decg.gl uses a latitude-longitude coordinate-system, which is different from what this polygon is expressed in.

Deck.GL documentation on rendering layers with different coordinate-systems

So, according to the documentation, deckGL renders each layer separately based on its coordinate system. Therefore, it was important to specify both coordinateOrigin and coordinateSystem props.

Understanding the coordinate system in data.json

So, as far as I understood, the spacialReference value in data.json represents an EPSG code. Using this website, I was able to find a value for the coordinateOrigin prop as [63.510617, 9.210989, 0]. As for the coordinateSystem prop, I used COORDINATE_SYSTEM.METER_OFFSETS. Here's the code:

PolygonLayer.tsx:

import React from "react";
import { COORDINATE_SYSTEM } from "@deck.gl/core/typed";
import { DeckLayer } from "@deck.gl/arcgis";
import { PolygonLayer } from "@deck.gl/layers/typed";
import MapView from "@arcgis/core/views/MapView";
import ArcGISMap from "@arcgis/core/Map";
import "@arcgis/core/assets/esri/themes/light/main.css";

export default function PolygonLayer({layerURL}) {
    const mapRef = React.useState(null)

    React.useEffect(() => {
        fetch(layerURL)
            .then(res => res.json())
            .then(data => {
                const blobURL = new Blob([JSON.stringify(data)], {type: "application/json",});
                const url = URL.createObjectURL(blobURL); // this is needed for the layer

                const layer = new PolygonLayer({
                    id: data["features"][0]["attributes"]["polygonName"], // correctly defined
                    data: url,
                    filled: true,
                    getLineWidth: 3,
                    getLineColor: [255, 255, 255, 0],
                    getFillColor: [234, 243, 221, 0],
                    coordinateOrigin: [63.510617, 9.210989, 0], // based on the explanation above
                    coordinateSystem: COORDINATE_SYSTEM.METER_OFFSETS,
                    getPolygon: (d) => {
                        console.log(d); // doesn't log anything
                        return d.features[0].geometry.rings;
                    },
                });

                const deckLayer = new DeckLayer({
                    "deck.layers": [layer],
                });

                const arcgisMap = new ArcGISMap({
                    basemap: "topo-vector",
                    layers: [deckLayer]
                });

                new MapView({
                    container: mapRef?.current,
                    map: arcgisMap,
                    center: data["features"][0]["geometry"]["rings"][0][0], // correctly defined
                    zoom: 9
                });

            })
            .catch(err => console.log(err));
    }, [layerURL]);

    return

}

The issue with this code

The problem with this code is that it doesn't render the layer (or the base map) and there's nothing logged in the console for the value of d; as mentioned in the code above.

Making sure the code works

Now, just a sanity check, I have used this url which returns polygons data in the standard LAT LONG format, without using coordinateOrigin or coordinateSystem props as in this example and it worked. So the code is ok rendering LAT LONG system, but breaks when using METERS_OFFSET as in the code provided.

Therefore

Have I figured out the coordinateOrigin correctly? And how can I use this (or another type of) layer to render this data correctly? Any help is appreciated and apologies for the long question!


问:
P value from pairwise_cor using widyr
I am using widyr package in R to perform pairwise correlations between clusters of words. I work to examine correlation among clusters (restoration, recreation ...) , which indicates how often they appear together relative to how often they appear separately in my documents (social media text).
Everthing worked fine for correlations following this tutorial (https://www.youtube.com/watch?v=mApnx5NJwQA) from 10:34 to 12:52

```<code># correlation co-occuring
correlatee <- data2 %>%
  pairwise_cor(word, line, sort = TRUE)
</code>```
```<code># A tibble: 72 x 3
   item1       item2       correlation
   <chr>       <chr>             <dbl>
 1 physical    recreation        0.321
 2 recreation  physical          0.321
 3 restoration recreation        0.304
 4 recreation  restoration       0.304
 5 physical    restoration       0.283
 6 restoration physical          0.283
 7 affection   aesthetics        0.240
 8 aesthetics  affection         0.240
 9 restoration aesthetics        0.227
10 aesthetics  restoration       0.227
# ... with 62 more rows
# i Use `print(n = ...)` to see more rows
</code>```

However, my question how I can get is p values of the correlations using pairwise_cor() or other ways to get p values in the pairwise comparison?
there is the question but the code is not working for me : pairwise_cor() in R: p value?

Thank you very much.

This link pairwise_cor() in R: p value?
but the code is not working for me

Title: P value from pairwise_cor using widyr

Body:
I am using widyr package in R to perform pairwise correlations between clusters of words. I work to examine correlation among clusters (restoration, recreation ...) , which indicates how often they appear together relative to how often they appear separately in my documents (social media text).
Everthing worked fine for correlations following this tutorial (https://www.youtube.com/watch?v=mApnx5NJwQA) from 10:34 to 12:52

# correlation co-occuring
correlatee <- data2 %>%
  pairwise_cor(word, line, sort = TRUE)

# A tibble: 72 x 3
   item1       item2       correlation
   <chr>       <chr>             <dbl>
 1 physical    recreation        0.321
 2 recreation  physical          0.321
 3 restoration recreation        0.304
 4 recreation  restoration       0.304
 5 physical    restoration       0.283
 6 restoration physical          0.283
 7 affection   aesthetics        0.240
 8 aesthetics  affection         0.240
 9 restoration aesthetics        0.227
10 aesthetics  restoration       0.227
# ... with 62 more rows
# i Use `print(n = ...)` to see more rows

However, my question how I can get is p values of the correlations using pairwise_cor() or other ways to get p values in the pairwise comparison?
there is the question but the code is not working for me : pairwise_cor() in R: p value?

Thank you very much.

This link pairwise_cor() in R: p value?
but the code is not working for me


问:
Insert script tag without always refetching the data
I am injecting an iframe, through a script tag in my React component - for the purpose of using it in a chrome extension:

```<code>const StickyBar= () => {

    const ref = useRef(null);

    useEffect(() => {
        let refValue;

        if (ref.current) {
            const script = document.createElement("script");
            script.src = "";

            ref.current.appendChild(script);
            refValue = ref.current;
        };

        return () => {
            if (refValue) {
                while (refValue.firstChild) {
                    refValue.removeChild(refValue.firstChild);
                };
            };
        };
    }, [ref,]);

    return (
        <div className="sticky-bar" >
            <div ref={ref} />
        </div>
    );
};
</code>```

The problem is that on each page change the data within the iframe refetches and it causes an unpleasant user experience. Is there any way I can always stick the bar on top of each page - without always having to create the script tag?

Thanks a lot !

Body:
I am injecting an iframe, through a script tag in my React component - for the purpose of using it in a chrome extension:

const StickyBar= () => {

    const ref = useRef(null);

    useEffect(() => {
        let refValue;

        if (ref.current) {
            const script = document.createElement("script");
            script.src = "";

            ref.current.appendChild(script);
            refValue = ref.current;
        };

        return () => {
            if (refValue) {
                while (refValue.firstChild) {
                    refValue.removeChild(refValue.firstChild);
                };
            };
        };
    }, [ref,]);

    return (

    );
};

The problem is that on each page change the data within the iframe refetches and it causes an unpleasant user experience. Is there any way I can always stick the bar on top of each page - without always having to create the script tag?

Thanks a lot !


问:
IoT edge device does not send the messages to IoT hub despite it is connected to
I have deployed IoT edge device on Raspberry Pi 3.

I have three modules

edgeAgent

edgeHub

Node-RED

All successfully run.

In the node-red I have some message processing and sending it to IoT edge through node-red module. I have already did so, but this time I faced the problem I could not solve for days.

I tried everything from updating the everything, I also did iotedge config apply because there was similar problem here with such a simple solution.

I have set the route when configuring the modules:

```<code>FROM /messages/modules/nodered/outputs/output1 INTO $upstream
</code>```

and tried this as well:

```<code>FROM /messages/modules/nodered/outputs/ INTO $upstream
</code>```

I tried to get the logs of my modules, although I was receiving

```<code>Error grabbing logs: log message is too large (168194932 > 1000000)
</code>```

The sudo iotedge check give me the following (there are some warnings and errors with connection to the hub):

```<code>Configuration checks (aziot-identity-service)
---------------------------------------------
√ keyd configuration is well-formed - OK
√ certd configuration is well-formed - OK
√ tpmd configuration is well-formed - OK
√ identityd configuration is well-formed - OK
√ daemon configurations up-to-date with config.toml - OK
√ identityd config toml file specifies a valid hostname - OK
√ aziot-identity-service package is up-to-date - OK
√ host time is close to reference time - OK
√ preloaded certificates are valid - OK
√ keyd is running - OK
√ certd is running - OK
√ identityd is running - OK
√ read all preloaded certificates from the Certificates Service - OK
√ read all preloaded key pairs from the Keys Service - OK
√ check all EST server URLs utilize HTTPS - OK
√ ensure all preloaded certificates match preloaded private keys with the same I                                                                                D - OK

Connectivity checks (aziot-identity-service)
--------------------------------------------
√ host can connect to and perform TLS handshake with iothub AMQP port - OK
√ host can connect to and perform TLS handshake with iothub HTTPS / WebSockets p                                                                                ort - OK
√ host can connect to and perform TLS handshake with iothub MQTT port - OK

Configuration checks
--------------------
√ aziot-edged configuration is well-formed - OK
√ configuration up-to-date with config.toml - OK
√ container engine is installed and functional - OK
√ configuration has correct URIs for daemon mgmt endpoint - OK
√ aziot-edge package is up-to-date - OK
√ container time is close to host time - OK
‼ DNS server - Warning
    Container engine is not configured with DNS server setting, which may impact connectivity to IoT Hub.
    Please see https://aka.ms/iotedge-prod-checklist-dns for best practices.
    You can ignore this warning if you are setting DNS server per module in the Edge deployment.
‼ production readiness: logs policy - Warning
    Container engine is not configured to rotate module logs which may cause it run out of disk space.
    Please see https://aka.ms/iotedge-prod-checklist-logs for best practices.
    You can ignore this warning if you are setting log policy per module in the Edge deployment.
‼ production readiness: Edge Agent's storage directory is persisted on the host filesystem - Warning
    The edgeAgent module is not configured to persist its /tmp/edgeAgent directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
‼ production readiness: Edge Hub's storage directory is persisted on the host filesystem - Warning
    The edgeHub module is not configured to persist its /tmp/edgeHub directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
√ Agent image is valid and can be pulled from upstream - OK
√ proxy settings are consistent in aziot-edged, aziot-identityd, moby daemon and config.toml - OK

Connectivity checks
-------------------
× container on the default network can connect to upstream AMQP port - Error
    Container on the default network could not connect to dc-hub-rnd.azure-devices.net:5671
× container on the default network can connect to upstream HTTPS / WebSockets port - Error
    Container on the default network could not connect to dc-hub-rnd.azure-devices.net:443
× container on the IoT Edge module network can connect to upstream AMQP port - Error
    Container on the azure-iot-edge network could not connect to dc-hub-rnd.azure-devices.net:5671
× container on the IoT Edge module network can connect to upstream HTTPS / WebSockets port - Error
    Container on the azure-iot-edge network could not connect to dc-hub-rnd.azure-devices.net:443
27 check(s) succeeded.
4 check(s) raised warnings. Re-run with --verbose for more details.
4 check(s) raised errors. Re-run with --verbose for more details.
2 check(s) were skipped due to errors from other checks. Re-run with --verbose for more details.
</code>```

Are there anyone who could have faced similar issue?

Body:
I have deployed IoT edge device on Raspberry Pi 3.

I have three modules

edgeAgent

edgeHub

Node-RED

All successfully run.

In the node-red I have some message processing and sending it to IoT edge through node-red module. I have already did so, but this time I faced the problem I could not solve for days.

I tried everything from updating the everything, I also did iotedge config apply because there was similar problem here with such a simple solution.

I have set the route when configuring the modules:

FROM /messages/modules/nodered/outputs/output1 INTO $upstream

and tried this as well:

FROM /messages/modules/nodered/outputs/ INTO $upstream

I tried to get the logs of my modules, although I was receiving

Error grabbing logs: log message is too large (168194932 > 1000000)

The sudo iotedge check give me the following (there are some warnings and errors with connection to the hub):

Configuration checks (aziot-identity-service)
---------------------------------------------
√ keyd configuration is well-formed - OK
√ certd configuration is well-formed - OK
√ tpmd configuration is well-formed - OK
√ identityd configuration is well-formed - OK
√ daemon configurations up-to-date with config.toml - OK
√ identityd config toml file specifies a valid hostname - OK
√ aziot-identity-service package is up-to-date - OK
√ host time is close to reference time - OK
√ preloaded certificates are valid - OK
√ keyd is running - OK
√ certd is running - OK
√ identityd is running - OK
√ read all preloaded certificates from the Certificates Service - OK
√ read all preloaded key pairs from the Keys Service - OK
√ check all EST server URLs utilize HTTPS - OK
√ ensure all preloaded certificates match preloaded private keys with the same I                                                                                D - OK

Connectivity checks (aziot-identity-service)
--------------------------------------------
√ host can connect to and perform TLS handshake with iothub AMQP port - OK
√ host can connect to and perform TLS handshake with iothub HTTPS / WebSockets p                                                                                ort - OK
√ host can connect to and perform TLS handshake with iothub MQTT port - OK

Configuration checks
--------------------
√ aziot-edged configuration is well-formed - OK
√ configuration up-to-date with config.toml - OK
√ container engine is installed and functional - OK
√ configuration has correct URIs for daemon mgmt endpoint - OK
√ aziot-edge package is up-to-date - OK
√ container time is close to host time - OK
‼ DNS server - Warning
    Container engine is not configured with DNS server setting, which may impact connectivity to IoT Hub.
    Please see https://aka.ms/iotedge-prod-checklist-dns for best practices.
    You can ignore this warning if you are setting DNS server per module in the Edge deployment.
‼ production readiness: logs policy - Warning
    Container engine is not configured to rotate module logs which may cause it run out of disk space.
    Please see https://aka.ms/iotedge-prod-checklist-logs for best practices.
    You can ignore this warning if you are setting log policy per module in the Edge deployment.
‼ production readiness: Edge Agent's storage directory is persisted on the host filesystem - Warning
    The edgeAgent module is not configured to persist its /tmp/edgeAgent directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
‼ production readiness: Edge Hub's storage directory is persisted on the host filesystem - Warning
    The edgeHub module is not configured to persist its /tmp/edgeHub directory on the host filesystem.
    Data might be lost if the module is deleted or updated.
    Please see https://aka.ms/iotedge-storage-host for best practices.
√ Agent image is valid and can be pulled from upstream - OK
√ proxy settings are consistent in aziot-edged, aziot-identityd, moby daemon and config.toml - OK

Connectivity checks
-------------------
× container on the default network can connect to upstream AMQP port - Error
    Container on the default network could not connect to dc-hub-rnd.azure-devices.net:5671
× container on the default network can connect to upstream HTTPS / WebSockets port - Error
    Container on the default network could not connect to dc-hub-rnd.azure-devices.net:443
× container on the IoT Edge module network can connect to upstream AMQP port - Error
    Container on the azure-iot-edge network could not connect to dc-hub-rnd.azure-devices.net:5671
× container on the IoT Edge module network can connect to upstream HTTPS / WebSockets port - Error
    Container on the azure-iot-edge network could not connect to dc-hub-rnd.azure-devices.net:443
27 check(s) succeeded.
4 check(s) raised warnings. Re-run with --verbose for more details.
4 check(s) raised errors. Re-run with --verbose for more details.
2 check(s) were skipped due to errors from other checks. Re-run with --verbose for more details.

Are there anyone who could have faced similar issue?


问:
Use existing key in other translate Localizely
In localizely I have few translate key with their values. I want to set new key with ICU Select where I want to use existing translations.

How can I use existing key in other translation?

I have ICU Select key like that:

```<code>{section, select, documentsSection {Document Section} favouritesSection {Favourites section} newsSection {News section} settingsSection {Settings section} other {Section}}
</code>```

And I need to use existing translate value (key) instead String "Document Section".

Body:
In localizely I have few translate key with their values. I want to set new key with ICU Select where I want to use existing translations.

How can I use existing key in other translation?

I have ICU Select key like that:

{section, select, documentsSection {Document Section} favouritesSection {Favourites section} newsSection {News section} settingsSection {Settings section} other {Section}}

And I need to use existing translate value (key) instead String "Document Section".


问:
Nexus: How to set a content-encoding for files?
I stored some js files on my nexus, which I load via script-tag:

```<code><script src="https://{linktoNexusRepo}/someFile.umd.min.js"></script>
</code>```

Also tried this:

```<code><script src="https://{linktoNexusRepo}/someFile.umd.min.js.gz"></script>
<script src="https://{linktoNexusRepo}/someFile.umd.min.js.br"></script>
</code>```

Now I want that Nexus serves those files in the right format, and more importantly tell the browser which compression was used by the Header Content-Encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding

How can do that?

The files do exist on Nexus and surprisingly it already correctly detects the correct content type.

e.g. Content type   application/x-brotli  (in the case of br).
Which my UI also correctly receives.

Body:
I stored some js files on my nexus, which I load via script-tag:

Also tried this:

Now I want that Nexus serves those files in the right format, and more importantly tell the browser which compression was used by the Header Content-Encoding:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding

How can do that?

The files do exist on Nexus and surprisingly it already correctly detects the correct content type.

e.g. Content type   application/x-brotli  (in the case of br).
Which my UI also correctly receives.


问:
Plotly color palette
I am creating Tree map in R. I work with Plotly library. Plotly has a specific palette of colors that you can see below. Below you can see my data and my code

```<code>    df1<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler",
                                  "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda",
                                  "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac",
                                  "Porsche", "Toyota", "Valiant", "Volvo"), count = c(1L, 1L, 1L,
                                                                                1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L,
                                                                                2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

treemap<-plot_ly(data = df1,
                 type= "treemap",
                 values= ~count,
                 labels= ~manuf,
                 parents=  ~test,
                 domain= list(column=0),
                 name = " ",
                 textinfo="label+value+percent parent")  %>%
  layout(title="",
         annotations =
           list(x = 0, y = -0.1,
                title = "",
                text = " ",
                showarrow = F,
                xref='paper',
                yref='paper'))

treemap
</code>```

This code produces Treemap as the map shown below. In this plot, Merc has the largest share of 22 % and is the blue color.

So far, so good. But problem arise when I change some values in the data, as shown in the data below. Now instead of Merc in the first place is AMC with 44.6 %. Below you can see the data and code

```<code>df2<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler",
                              "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda",
                              "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac",
                              "Porsche", "Toyota", "Valiant", "Volvo"), count = c(25L, 1L, 1L,
                                                                                1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L,
                                                                                2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

df2$test<-1

treemap<-plot_ly(data = df2,
                 type= "treemap",
                 values= ~count,
                 labels= ~manuf,
                 parents=  ~test,
                 domain= list(column=0),
                 name = " ",
                 #marker = list(colors = ~colr),
                 textinfo="label+value+percent parent")  %>%
  layout(title="", font = t,
         annotations =
           list(x = 0, y = -0.1,
                title = "",
                text = " ",
                showarrow = F,
                xref='paper',
                yref='paper'))

treemap
</code>```

This code produces Treemap as shown below.

Now in this Treemap, colors are different compared to the first Treemap. Namely Merc in the first plot is blue in color while in the second plot is orange.

So can anybody help me how to produce Treemap with the same colors for the same names. I prefer to have this colors as is shown in these Treemaps.

Title: Plotly color palette

Body:
I am creating Tree map in R. I work with Plotly library. Plotly has a specific palette of colors that you can see below. Below you can see my data and my code

    df1<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler",
                                  "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda",
                                  "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac",
                                  "Porsche", "Toyota", "Valiant", "Volvo"), count = c(1L, 1L, 1L,
                                                                                1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L,
                                                                                2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

treemap<-plot_ly(data = df1,
                 type= "treemap",
                 values= ~count,
                 labels= ~manuf,
                 parents=  ~test,
                 domain= list(column=0),
                 name = " ",
                 textinfo="label+value+percent parent")  %>%
  layout(title="",
         annotations =
           list(x = 0, y = -0.1,
                title = "",
                text = " ",
                showarrow = F,
                xref='paper',
                yref='paper'))

treemap

This code produces Treemap as the map shown below. In this plot, Merc has the largest share of 22 % and is the blue color.

So far, so good. But problem arise when I change some values in the data, as shown in the data below. Now instead of Merc in the first place is AMC with 44.6 %. Below you can see the data and code

df2<-structure(list(manuf = c("AMC", "Cadillac", "Camaro", "Chrysler",
                              "Datsun", "Dodge", "Duster", "Ferrari", "Fiat", "Ford", "Honda",
                              "Hornet", "Lincoln", "Lotus", "Maserati", "Mazda", "Merc", "Pontiac",
                              "Porsche", "Toyota", "Valiant", "Volvo"), count = c(25L, 1L, 1L,
                                                                                1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 7L, 1L, 1L,
                                                                                2L, 1L, 1L)), row.names = c(NA, -22L), class = c("tbl_df", "tbl",
                                                                                "data.frame"))

df2$test<-1

treemap<-plot_ly(data = df2,
                 type= "treemap",
                 values= ~count,
                 labels= ~manuf,
                 parents=  ~test,
                 domain= list(column=0),
                 name = " ",
                 #marker = list(colors = ~colr),
                 textinfo="label+value+percent parent")  %>%
  layout(title="", font = t,
         annotations =
           list(x = 0, y = -0.1,
                title = "",
                text = " ",
                showarrow = F,
                xref='paper',
                yref='paper'))

treemap

This code produces Treemap as shown below.

Now in this Treemap, colors are different compared to the first Treemap. Namely Merc in the first plot is blue in color while in the second plot is orange.

So can anybody help me how to produce Treemap with the same colors for the same names. I prefer to have this colors as is shown in these Treemaps.


问:
Running php -v on terminal opens up PhpStorm
When I try to check PHP version through terminal using php -v in Ubuntu, it opens up PhpStorm. How can I fix this issue?


问:
Error in loading .xlsx Data in R: lifecycle’ 0.2.0 is being loaded, but >= 1.0.0 is required
Whenever I try loading in my Data from an Excel sheet this error message is displayed. I tried multiple Versions and restarted R multiple times. I use the following code:

library(readxl)
Data <- read_excel("C:/Users/Tobia/Desktop/Master Thesis/Data.xlsx")
```
<p>then he shows me this error:</p>
<pre class="lang-r prettyprint-override"><code>Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  namespace ‘lifecycle’ 0.2.0 is being loaded, but >= 1.0.0 is required
</code>```

couln't find any similar problems like this through googling

I tried restarting and updating R, I reinstalled the tidyverse package.

Body:
Whenever I try loading in my Data from an Excel sheet this error message is displayed. I tried multiple Versions and restarted R multiple times. I use the following code:

library(readxl)
Data <- read_excel("C:/Users/Tobia/Desktop/Master Thesis/Data.xlsx")

then he shows me this error:

Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  namespace ‘lifecycle’ 0.2.0 is being loaded, but >= 1.0.0 is required

couln't find any similar problems like this through googling

I tried restarting and updating R, I reinstalled the tidyverse package.


问:
Chromium without disable-web-security flag and cross origin for specific host
Working with aws-chrome-lambda lib, I'm using headless chromium to render data saved on S3 with presigned url.
I'd like to block access to local files and still be able to access the presigned url.

aws-chrome-lambda has --disable-web-security set up by default. I do want web security, so removing that to achieve blocking access to local fs. The problem is that it also blocks any other origin, thus I cannot access the data in S3.

I've also tried adding the flag --unsafely-treat-insecure-origin-as-secure with the remote origin without success.
Running in a sandbox is not possible with this lib.

Any idea how to tackle it?


问:
Im trying to get xmlrpc to work with paramiko (ssh) in python -- getting an error with Transport not having attribute Request
I'm trying to get xmlrpc to work over ssh so I'm using the paramiko library in python.  I can get the connection fine, and even run programs, so my issues aren't the network or installation.

getting the error,

```<code>AttributeError: 'Transport' object has no attribute 'request'
</code>```

while calling the line result = xmlrpc_client.your_method_name()

My server code is very simple:

from xmlrpc.server import SimpleXMLRPCServer

# Create an XML-RPC server
server = SimpleXMLRPCServer(("your_hostname", your_port))

# Register a function that can be called through the XML-RPC server
def your_method_name():
    return "hello, world!"
server.register_function(your_method_name)

# Start the XML-RPC server
server.serve_forever()
```
<p>client code is a bit longer</p>
<pre class="lang-py prettyprint-override"><code>import paramiko
import xmlrpc.client

# Set the hostname, username, and password for the remote machine
HOSTNAME = "your_hostname"
USERNAME = "username"
PASSWORD=getpass("Enter password:")  # robot password
port="someport"

# Create an SSH client
ssh = paramiko.SSHClient()

# Add the remote host's hostname to the known hosts file
ssh.load_system_host_keys()

# Connect to the remote host
ssh.connect(HOSTNAME, username=USERNAME, password=PASSWORD)

# Create an XML-RPC client using the SSH transport
transport = ssh.get_transport()
xmlrpc_client = xmlrpc.client.ServerProxy(f"http://{hostname}:{port}", transport=transport)

# Call an XML-RPC method on the remote host
result = xmlrpc_client.your_method_name()

# Print the result of the XML-RPC call
print(result)

# Close the connection
ssh.close()
</code>```

getting the error,

```<code>AttributeError: 'Transport' object has no attribute 'request'
</code>```

while calling result = xmlrpc_client.your_method_name() which calls the xmlrpc/client.py in that library,

```<code>response = self.__transport.request(
   1465         self.__host,
   1466         self.__handler,
   1467         request,
   1468         verbose=self.__verbose
   1469         )
</code>```

So there seems to be some difference between the transport object in the xmlrpc.client and the one returned from the ssh object in paramiko?  Anyone have an example where they get this to work?

thanks!

```<code></code>```

Body:
I'm trying to get xmlrpc to work over ssh so I'm using the paramiko library in python.  I can get the connection fine, and even run programs, so my issues aren't the network or installation.

getting the error,

AttributeError: 'Transport' object has no attribute 'request'

while calling the line result = xmlrpc_client.your_method_name()

My server code is very simple:

from xmlrpc.server import SimpleXMLRPCServer

# Create an XML-RPC server
server = SimpleXMLRPCServer(("your_hostname", your_port))

# Register a function that can be called through the XML-RPC server
def your_method_name():
    return "hello, world!"
server.register_function(your_method_name)

# Start the XML-RPC server
server.serve_forever()

client code is a bit longer

import paramiko
import xmlrpc.client

# Set the hostname, username, and password for the remote machine
HOSTNAME = "your_hostname"
USERNAME = "username"
PASSWORD=getpass("Enter password:")  # robot password
port="someport"

# Create an SSH client
ssh = paramiko.SSHClient()

# Add the remote host's hostname to the known hosts file
ssh.load_system_host_keys()

# Connect to the remote host
ssh.connect(HOSTNAME, username=USERNAME, password=PASSWORD)

# Create an XML-RPC client using the SSH transport
transport = ssh.get_transport()
xmlrpc_client = xmlrpc.client.ServerProxy(f"http://{hostname}:{port}", transport=transport)

# Call an XML-RPC method on the remote host
result = xmlrpc_client.your_method_name()

# Print the result of the XML-RPC call
print(result)

# Close the connection
ssh.close()

getting the error,

AttributeError: 'Transport' object has no attribute 'request'

while calling result = xmlrpc_client.your_method_name() which calls the xmlrpc/client.py in that library,

response = self.__transport.request(
   1465         self.__host,
   1466         self.__handler,
   1467         request,
   1468         verbose=self.__verbose
   1469         )

So there seems to be some difference between the transport object in the xmlrpc.client and the one returned from the ssh object in paramiko?  Anyone have an example where they get this to work?

thanks!


问:
What do I do if a package version is available on npm but not on yarn?
E.g.
https://yarnpkg.com/package/object-assign
https://www.npmjs.com/package/object.assign?activeTab=versions

You can see there are new versions available on npm but not on yarn. Why? How do versions get onto yarn? Must they be manually pushed there by the maintainer? In other words, should I contact the maker of the package about that?


问:
Make a while loop with counter
I am trying to calculate the number of agents that a call center should have but the results hardly change each other.

This number of agents is calculated in the resource function, which will return a column with the results. The number of agents will increase until the desired service level is reached (gos_target). So, if gos<gostarget, the number of agents will be increased by 1 and a new value of gos will have to be computed. In order to calculate the new value of gos service_level, I need to calculate the function erlang_c.

We call the resource function as follows: resource(rate = i, duration= 103, target= 20, gos_target=85/100, interval = 3600); where all data except rate is fixed. Rate is the number of calls received, that is, in my data I have a column where in each row there is a number of calls received depending on the time, day... and what is intended is that the function go row per row obtaining the number of agents according to the number of calls.

For example, if the third row has a value of = 200. It means that 200 calls were received in that hour, therefore, with that number the intensity = 10 will be calculated, then the erlang_c = 0.6821, service_level = 0.390 and finally resource = 14 = number of agents.
The expected results must be similar to these but with notable variations depending on the number of calls. The higher the number of calls, the lower the service_level.

The problem is that when compiling I get values that are very similar to each other, which doesn't make sense. It should not be the same if you receive 7 calls an hour as if you receive 50.

Here is the data: https://drive.google.com/file/d/1mEUW3rI659_FlkqFuzXY9xzDrDxNIm2q/view?usp=sharing

Here is the code:

```<code>ds <- dataset

library(dplyr)

intensity <- function(rate, duration, interval) {
   return (rate / interval) * duration
}

erlang_c <- function(agents, rate, duration, interval) {
   int <- intensity(rate, duration, interval)
   erlang_b_inv <- 1
   for (i in 1: agents) {
     erlang_b_inv <- 1 + erlang_b_inv * i / int
   }
   erlang_b <- 1 / erlang_b_inv
   return (agents * erlang_b / (agents - int * (1 - erlang_b)))
}

service_level <- function(agents, rate, duration, target, interval) {
   pw <- erlang_c(agents, rate, duration, interval)
   int <- intensity(rate, duration, interval)
   #a <- (pw * exp(-(agents - int)))
   #b <- (target / duration)
   to <- exp(-(agents-int)*(target/duration))
   return (1 - (pw*(a)))
}

resource <- function(rate, duration, target, gos_target, interval) {
   inten <- intensity(rate, duration, interval)
   agents <- ceiling(inten + 1)
   gos <- service_level(agents, rate, duration, target, interval)

   while (gos < gos_target) {
     agents <- agents + 1
     gos <- service_level(agents, rate, duration, target, interval)
   }
   return(c(agents,gos))
}

vec_agents <- c()
gos_vec <- c()

for (i in ds$calls) {
   #print(i)
   res <-resource(rate = i, duration= 103, target= 20, gos_target=85/100, interval = 3600)
   vec_agents <- c(vec_agents, res[1])
   gos_vec <- c(gos_vec, res[2])
}

ds$agents <- vec_agents
ds$gos <- gos_vec
</code>```

I can't see what might be going on. Help me please!!
Greetings.

Title: Make a while loop with counter

Body:
I am trying to calculate the number of agents that a call center should have but the results hardly change each other.

This number of agents is calculated in the resource function, which will return a column with the results. The number of agents will increase until the desired service level is reached (gos_target). So, if gos<gostarget, the number of agents will be increased by 1 and a new value of gos will have to be computed. In order to calculate the new value of gos service_level, I need to calculate the function erlang_c.

We call the resource function as follows: resource(rate = i, duration= 103, target= 20, gos_target=85/100, interval = 3600); where all data except rate is fixed. Rate is the number of calls received, that is, in my data I have a column where in each row there is a number of calls received depending on the time, day... and what is intended is that the function go row per row obtaining the number of agents according to the number of calls.

For example, if the third row has a value of = 200. It means that 200 calls were received in that hour, therefore, with that number the intensity = 10 will be calculated, then the erlang_c = 0.6821, service_level = 0.390 and finally resource = 14 = number of agents.
The expected results must be similar to these but with notable variations depending on the number of calls. The higher the number of calls, the lower the service_level.

The problem is that when compiling I get values that are very similar to each other, which doesn't make sense. It should not be the same if you receive 7 calls an hour as if you receive 50.

Here is the data: https://drive.google.com/file/d/1mEUW3rI659_FlkqFuzXY9xzDrDxNIm2q/view?usp=sharing

Here is the code:

ds <- dataset

library(dplyr)

intensity <- function(rate, duration, interval) {
   return (rate / interval) * duration
}

erlang_c <- function(agents, rate, duration, interval) {
   int <- intensity(rate, duration, interval)
   erlang_b_inv <- 1
   for (i in 1: agents) {
     erlang_b_inv <- 1 + erlang_b_inv * i / int
   }
   erlang_b <- 1 / erlang_b_inv
   return (agents * erlang_b / (agents - int * (1 - erlang_b)))
}

service_level <- function(agents, rate, duration, target, interval) {
   pw <- erlang_c(agents, rate, duration, interval)
   int <- intensity(rate, duration, interval)
   #a <- (pw * exp(-(agents - int)))
   #b <- (target / duration)
   to <- exp(-(agents-int)*(target/duration))
   return (1 - (pw*(a)))
}

resource <- function(rate, duration, target, gos_target, interval) {
   inten <- intensity(rate, duration, interval)
   agents <- ceiling(inten + 1)
   gos <- service_level(agents, rate, duration, target, interval)

   while (gos < gos_target) {
     agents <- agents + 1
     gos <- service_level(agents, rate, duration, target, interval)
   }
   return(c(agents,gos))
}

vec_agents <- c()
gos_vec <- c()

for (i in ds$calls) {
   #print(i)
   res <-resource(rate = i, duration= 103, target= 20, gos_target=85/100, interval = 3600)
   vec_agents <- c(vec_agents, res[1])
   gos_vec <- c(gos_vec, res[2])
}

ds$agents <- vec_agents
ds$gos <- gos_vec

I can't see what might be going on. Help me please!!
Greetings.


问:
React Native real time compiling drops huge frame while developing application
I'm developing a audiobook application that users can listen books, read them, add them to their fav list and etc. My application size is too heavy, as you guess.
React Native compiles my code while I type, instead pressing cmd +s. So that makes huge frame drops in my mac. Despite my spec is enough for coding. Here is my spec:

MacBook Air

M2, 2022

Chip - Apple M2

Memory - 16 GB

macOS - Ventura 13.0.1

So, my question is: is there anyway tell react native, compile when i press cmd + s

I read some medium and geeksforgeeks article for this issue. But I couldn't find something worth.


问:
Azure AD Authentication on React Frontend with Node.js Backend
I would like to add an Azure AD configuration to my React&Node.js project. What I want is to log in  on Frontend using Azure AD and then send a request with f.e axios to my backend written in Node.js, so that Node.js knows that the user is logged in and can perform the request. I was reading tutorials/documentation on Microsoft site for all day, but I still don't know how and where to start. Basically, almost every Microsoft Tutorial is either to call a Microsoft Graph API from Node.js or from React.js. I completely do not want to use Microsoft Graph. I just want to have simple login on frontend and protected endpoints from un-logged user on backend. The other tutorials that I find are too complicated f.e  https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/3-Authorization-II/1-call-api . I understand the concept of App registration, client id, tenant id and etc. but I simply don't know how to write a code that: login, send the request with token - then is accepted/declined by Node.js .

If by any chance, somehow did an application like that, or can provide me a link to a well written tutorial, so I would understand and recreate it in my scenario, I would be grateful.


问:
ImportError: cannot import name 'aiplatform' from 'google.cloud' even though aiplatform module is installed
I am having troubles reaching aiplatform module from google.cloud

```<code>from typing import Dict

from google.cloud import aiplatform
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value

</code>```

I have properly installed pip install google-cloud-aiplatform on my windows machine, everything checks. Still, I am getting this error ImportError: cannot import name 'aiplatform' from 'google.cloud' (unknown location)

Have you ever been stuck on a case like this before?

Thanks for the help

Body:
I am having troubles reaching aiplatform module from google.cloud

from typing import Dict

from google.cloud import aiplatform
from google.protobuf import json_format
from google.protobuf.struct_pb2 import Value

I have properly installed pip install google-cloud-aiplatform on my windows machine, everything checks. Still, I am getting this error ImportError: cannot import name 'aiplatform' from 'google.cloud' (unknown location)

Have you ever been stuck on a case like this before?

Thanks for the help


问:
im try to connect wio terminal to edge impulse, ive downloaded the node
C:\Users\Maysam ALKHALAF>npm install -g edge-impulse-cli
npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path C:\Program Files\nodejs\node_modules\edge-impulse-cli
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\edge-impulse-cli'
npm ERR!  [Error: EPERM: operation not permitted, mkdir 'C:\Program Files\nodejs\node_modules\edge-impulse-cli'] {
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: 'C:\Program Files\nodejs\node_modules\edge-impulse-cli'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It's possible that the file was already in use (by a text editor or antivirus),
npm ERR! or that you lack permissions to access it.
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Maysam ALKHALAF\AppData\Local\npm-cache_logs\2022-12-07T14_11_39_963Z-debug-0.log

C:\Users\Maysam ALKHALAF>

i downloaded the node, downloaded arduino cli, and when i run the npm i get this error, they were also added to my path so i dont know what to do


问:
I am getting legacy error in chart js Vue 2 JS
I have installed vue-chart package in my vue 2 project but it is giving error like this

Vue version: 2.9.6
Vue-chart version: 5.0.1
chart.js version: 4.0.1

I installed chart but it didn't work


问:
How to get logstreams from EMR steps to CloudWatch?
We use Airflow to orchestrate aws ETL jobs. Some of these jobs start an EMR cluster and add EMR steps to that cluster. Airflow pulls logs from Cloudwatch. Logs created during an EMR step is not directly available in CloudWatch, but are only found in hidden in the cluster logs. If an EMR step fails, the logs to identify the error is therefore not readily available. We would like logs created from EMR steps to be displayed in CloudWatch. We have tried the installing the CloudWatch agent, but that does not seem to work. How can we get logstreams from EMR steps to CloudWatch?</p>


问:
Loading big parquet files on server
I am working on a VPN server for a company and they gave us their data through lots of parquet files. We are however having problems with loading all the data. Loading a few files is working for us but we have a 103 parquet files we have to load to get the full data. When we try this, the server is having a Kernel error.

We are working with python.
Has anyone had this problem before and found a solution?

We have tried to concat a few parquet files and convert that to csv so it's easier to load but this also gives us a Kernel error. The files do have a lot of string types so this does have a lot of memory in it.

We also tried loads of different commands like low_memory and loading only certain column, this however will give us the same error.

Title: Loading big parquet files on server