问:
Unable to import a function/class from wheel file
I have created a wheel file and I m trying to invoke the method in synapse but am unable to do so.On trying to call the method _buildJSONdata() using below

```<code>import cloudapi
from cloudapi import cloudalert
api=cloudalert.CloudLink()
Data = {"Name": "ABC","email":"df@example.com","subject":"Alert"}
api._buildJSONdata(Data)
</code>```

I am getting the error AttributeError: 'CloudLink' object has no attribute 'Data'.I have already defined the argument inside the definition and already using the data variable while invoking the said method

Contents of __init__.py

```<code>from .cloudalert import CloudLink
</code>```

Contents of setup.py

```<code>import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="CloudAPI",
    version="0.0.1",
    author="XYZ",
    author_email="abc@example.com",
    description="Package expose Cloud as library",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    install_requires=["adal"],
    classifiers=["Programming Language :: Python :: 3",],
    python_requires='>=3.7',
)
</code>```

Folder structure

Below is cloudalert.py content

```<code>import json
import datetime
import hashlib
import json
import sys
import traceback

import adal
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from functools import wraps
import sys
def create_logger():

    #create a logger object
    #logger = logging.getLogger()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    logfile = logging.FileHandler('exc_logger.log')
    #logfile = logging.StreamHandler(sys.stdout)

    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)

    logfile.setFormatter(formatter)
    logger.addHandler(logfile)

    return logger

logger = create_logger()

def exception(logger):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            try:
                return func(*args, **kwargs)

            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-------------------------\
                ------------------------------------------------\n"
                logger.exception(issue)
            raise

        return wrapper
    return decorator

class CloudLink(object):
    _token = None
    _instance = None
    http = None

    @staticmethod
    def getInstance():

        if not CloudLink._instance:
            CloudLink._instance = CloudLink()

        return CloudLink._instance

    def __init__(self):

        retry_strategy = Retry(
            total=3,
            backoff_factor=0,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["HEAD", "GET", "OPTIONS"],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.http = requests.Session()
        self.http.mount("https://", adapter)
        self.http.mount("http://", adapter)
        print("Inside init")

    def parseJSON(self, t):
        try:
            eData = json.loads(t)
            logger.info(f"Sending {eData} to Cloud")
            self.sendToCloud(eData)
        except ValueError as e:
            print("Error: %s Please validate JSON in https://www.jsonschemavalidator.net/"% e)
            return None  # or: raise

    def sendToCloud(self, eData):
        #from notebookutils import mssparkutils
        cloudtest = 'https://www.example.com/api/v1/event/fg'
        cloudData = {"eData": eData, "metadata": self._buildMetadata()}
        logger.info(f"Raising alert with data=({cloudData}")
        response = self.http.post(
            self.cloudtest, headers=self._buildHeaders(), json=cloudData
        )
        logger.info(f"cloud alert response={response}")
        if response.status_code == 202 or response.status_code == 200:
            logger.info("Mail sent to Cloud")
        else:
            raise Exception(f"Cloud reporting failed with Error {response}")

    def _buildJSONdata(self,Data):
        if len(self.Data) == 0:
            raise Exception("JSON is empty")
        else:
            t = json.dumps(self.Data)
            self.parseJSON(t)

    def _buildMetadata(self):
        return {
            "messageType": "Send Email",
            "messageVersion": "0.0.1",
            "sender": "Send Email",
          }

    def _buildHeaders(self):
        self._refreshADToken()

        headers = {
            "Authorization": "Bearer {}".format(self._token["accessToken"]),
            "Content-type": "application/json",
            "Accept": "text/plain",
        }
        return headers

    def _refreshADToken(self):
        def shouldRenew(token):
            """Returns True if the token should be renewed"""

            expiresOn = datetime.datetime.strptime(
                token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f"
            )
            now = datetime.datetime.now()
            return (expiresOn - now) < datetime.timedelta(minutes=5)

        if not self._token or shouldRenew(self._token):
            logger.info("Renewing credentials for Alerting")
            result = None

            try:
                #from notebookutils import mssparkutils
                cloudclient = "xxxxxxx"
                clientid = "yyyyyyyyy"
                clientcredentials = "ccccccccc"
                authority_url = "https://login.microsoftonline.com/dddddddddd/"
                context = adal.AuthenticationContext(authority_url)
                result = context.acquire_token_with_client_credentials(cloudclient, clientid,clientcredentials)
            except Exception as e:
                error = "Failed to renew client credentials."
                logger.info(error)
                raise

            if result and "accessToken" in result:
                self._token = result
            else:
                logger.error(
                    "Failed to acquire bearer token. accessToken not found in result object on renewing credentials."
                )
                raise Exception("Could not acquire a bearer token")
</code>```

Let me know in case if I m doing something wrong while invoking the function.

Body:
I have created a wheel file and I m trying to invoke the method in synapse but am unable to do so.On trying to call the method _buildJSONdata() using below

import cloudapi
from cloudapi import cloudalert
api=cloudalert.CloudLink()
Data = {"Name": "ABC","email":"df@example.com","subject":"Alert"}
api._buildJSONdata(Data)

I am getting the error AttributeError: 'CloudLink' object has no attribute 'Data'.I have already defined the argument inside the definition and already using the data variable while invoking the said method

Contents of __init__.py

from .cloudalert import CloudLink

Contents of setup.py

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="CloudAPI",
    version="0.0.1",
    author="XYZ",
    author_email="abc@example.com",
    description="Package expose Cloud as library",
    long_description=long_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    install_requires=["adal"],
    classifiers=["Programming Language :: Python :: 3",],
    python_requires='>=3.7',
)

Folder structure

Below is cloudalert.py content

import json
import datetime
import hashlib
import json
import sys
import traceback

import adal
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import logging
from functools import wraps
import sys
def create_logger():

    #create a logger object
    #logger = logging.getLogger()
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)

    logfile = logging.FileHandler('exc_logger.log')
    #logfile = logging.StreamHandler(sys.stdout)

    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    formatter = logging.Formatter(fmt)

    logfile.setFormatter(formatter)
    logger.addHandler(logfile)

    return logger

logger = create_logger()

def exception(logger):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):

            try:
                return func(*args, **kwargs)

            except:
                issue = "exception in "+func.__name__+"\n"
                issue = issue+"-------------------------\
                ------------------------------------------------\n"
                logger.exception(issue)
            raise

        return wrapper
    return decorator

class CloudLink(object):
    _token = None
    _instance = None
    http = None

    @staticmethod
    def getInstance():

        if not CloudLink._instance:
            CloudLink._instance = CloudLink()

        return CloudLink._instance

    def __init__(self):

        retry_strategy = Retry(
            total=3,
            backoff_factor=0,
            status_forcelist=[429, 500, 502, 503, 504],
            allowed_methods=["HEAD", "GET", "OPTIONS"],
        )
        adapter = HTTPAdapter(max_retries=retry_strategy)
        self.http = requests.Session()
        self.http.mount("https://", adapter)
        self.http.mount("http://", adapter)
        print("Inside init")

    def parseJSON(self, t):
        try:
            eData = json.loads(t)
            logger.info(f"Sending {eData} to Cloud")
            self.sendToCloud(eData)
        except ValueError as e:
            print("Error: %s Please validate JSON in https://www.jsonschemavalidator.net/"% e)
            return None  # or: raise

    def sendToCloud(self, eData):
        #from notebookutils import mssparkutils
        cloudtest = 'https://www.example.com/api/v1/event/fg'
        cloudData = {"eData": eData, "metadata": self._buildMetadata()}
        logger.info(f"Raising alert with data=({cloudData}")
        response = self.http.post(
            self.cloudtest, headers=self._buildHeaders(), json=cloudData
        )
        logger.info(f"cloud alert response={response}")
        if response.status_code == 202 or response.status_code == 200:
            logger.info("Mail sent to Cloud")
        else:
            raise Exception(f"Cloud reporting failed with Error {response}")

    def _buildJSONdata(self,Data):
        if len(self.Data) == 0:
            raise Exception("JSON is empty")
        else:
            t = json.dumps(self.Data)
            self.parseJSON(t)

    def _buildMetadata(self):
        return {
            "messageType": "Send Email",
            "messageVersion": "0.0.1",
            "sender": "Send Email",
          }

    def _buildHeaders(self):
        self._refreshADToken()

        headers = {
            "Authorization": "Bearer {}".format(self._token["accessToken"]),
            "Content-type": "application/json",
            "Accept": "text/plain",
        }
        return headers

    def _refreshADToken(self):
        def shouldRenew(token):
            """Returns True if the token should be renewed"""

            expiresOn = datetime.datetime.strptime(
                token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f"
            )
            now = datetime.datetime.now()
            return (expiresOn - now) < datetime.timedelta(minutes=5)

        if not self._token or shouldRenew(self._token):
            logger.info("Renewing credentials for Alerting")
            result = None

            try:
                #from notebookutils import mssparkutils
                cloudclient = "xxxxxxx"
                clientid = "yyyyyyyyy"
                clientcredentials = "ccccccccc"
                authority_url = "https://login.microsoftonline.com/dddddddddd/"
                context = adal.AuthenticationContext(authority_url)
                result = context.acquire_token_with_client_credentials(cloudclient, clientid,clientcredentials)
            except Exception as e:
                error = "Failed to renew client credentials."
                logger.info(error)
                raise

            if result and "accessToken" in result:
                self._token = result
            else:
                logger.error(
                    "Failed to acquire bearer token. accessToken not found in result object on renewing credentials."
                )
                raise Exception("Could not acquire a bearer token")

Let me know in case if I m doing something wrong while invoking the function.


来源: stackexchange

问:
How to store JWT Token in browser cache in a NUXT JS, VUEX Application i am using a NodeJs/Express API?
I am building a NUXT JS Application which uses NodeJS API for login registration. I am using AXIOS, VUEX, JWT for this. however i am not able to set the store and set JWT token properly in browser cache, Need help..

This is my Login Page

```<code><template>
    <div>
        <div class="user__wrap">
            <div class="user__left user__left-login">
                <div class="user-sta">
                    <!-- {{this.response}} -->
                    <h2>The perfect place for our pre wedding shoot it was a dream true</h2>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas vero velit possimus quos provident quaerat, asperiores tempora esse suscipit perferendis veritatis quod tempore numquam labore pariatur voluptatibus ea minus quisquam?</p>
                </div>
            </div>
            <div class="user__right">
                <div>
                    <div class="user__register-form">
                        <h2>Welcome</h2>
                        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis sapiente, nemo et molestiae quae possimus a voluptate suscipit.</p>
                        <p>If you are new, Kindly <a href="/register">register here</a></p>
                        <form action="" v-on:submit.prevent="onSubmit()" method="POST">
                            <div class="row in__register">
                                <div class="col-lg-12 mt-3 mb-3">
                                    <label for="">Email</label>
                                    <input v-model="data.email_id" type="text" class="form-control" placeholder="Enter registered email ID">
                                </div>
                                <div class="col-lg-12 mt-3 mb-3">
                                    <label for="">Password</label>
                                    <input v-model="data.password" type="text" class="form-control" placeholder="Enter Password">
                                </div>
                            </div>
                            <div class="rembr">
                                <div>
                                    <input type="checkbox" name="" id="terms">
                                    <label for="terms">Remember me</label>
                                </div>
                                <div>
                                    <a href="#">Forgot Password?</a>
                                </div>
                            </div>
                            <div class="user-action">
                                <button type="submit">Login to my account</button>
                            </div>
                        </form>
                    </div>
                    <div class="gback-link">
                        <a href="/">Go Back</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>

export default {
    layout: 'user',
    name: 'userLogin',
    data(){
        return {
            data:{
                email_id: null,
                password: null
            }
        }
    },
    computed: {

    },
    methods:{
        onSubmit(){
        this.$store.dispatch('auth/login', this.data)
        console.log(this.data)
        }
    }
}
</script>
</code>```

This is my store/index.js

```<code>export const AUTH_MUTATIONS = {
    SET_USER: 'SET_USER',
    SET_PAYLOAD: 'SET_PAYLOAD',
    LOGOUT: 'LOGOUT',
  }

  export const state = () => ({
    access_token: null, // JWT access token
    refresh_token: null, // JWT refresh token
    data:[],
    id: null, // user id
    email_address: null, // user email address
  })

  export const mutations = {
    // store the logged in user in the state
    [AUTH_MUTATIONS.SET_USER] (state, { id, email_id, data }) {
      state.id = id
      state.email_id = email_id
      state.data = data
    },

    // store new or updated token fields in the state
    [AUTH_MUTATIONS.SET_PAYLOAD] (state, { access_token, refresh_token = null }) {
      state.access_token = access_token
      // refresh token is optional, only set it if present
      if (refresh_token) {
        state.refresh_token = refresh_token
      }
    },

    [AUTH_MUTATIONS.LOGOUT] (state) {
      state.id = null
      state.email_id = null
      state.access_token = null
      state.refresh_token = null
      data = null
    },
  }

  export const actions = {
    async login ({ commit, dispatch }, { email_id, password, data }) {
        const { data: { data: { user, payload } } } = await this.$axios.post(
            'http://xx.xxx.xxx.xxx:5000/api/v1/users/login',
            {data, email_id, password})
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
      commit(AUTH_MUTATIONS.SET_USER, data.user)
      commit(AUTH_MUTATIONS.SET_PAYLOAD, payload)
    },

    // logout the user
    logout ({ commit, state }) {
      commit(AUTH_MUTATIONS.LOGOUT)
    },
  }

  export const getters = {
    isAuthenticated: (state) => {
      return state.access_token && state.access_token !== ''
    },
  }
</code>```

this is (plugins/axios.js)my axios my redirect method from the nuxt context

```<code>
export default function ({ store, app: { $axios }, redirect }) {
    $axios.onRequest((config) => {
      // check if the user is authenticated
      if (store.state.auth.data.token) {
        // set the Authorization header using the access token
        config.headers.Authorization = 'Bearer ' + store.state.auth.data.token
      }

      return config
    })
}

</code>```

my localstorage plugins/local-storage.js

```<code>import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

export default ({ store, req, isDev }) => {
  createPersistedState({
    key: 'authentication-cookie', // choose any name for your cookie
    paths: [
      'auth.access_token',
      'auth.refresh_token',
    ],
    storage: {

      getItem: key => process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie || '')[key],
      setItem: (key, value) => Cookies.set(key, value, { expires: 14, secure: !isDev }),
      removeItem: key => Cookies.remove(key)
    }
  })(store)
}
</code>```

this is my nuxt.config.js

```<code>  plugins: [
    { src: '~/plugins/all.js', ssr: false },
    { src: '~/plugins/local-storage'},
    { src: '~/plugins/axios'},
  ],
  components: true,

  buildModules: [
  ],

  modules: [
    // Doc: https://bootstrap-vue.js.org
    'bootstrap-vue/nuxt',
    '@nuxtjs/axios',
  ],

  // base URL
  axios: {
      baseURL: 'http://xx.xxx.xxx.xxx:5000'
  },
</code>```

I followed this tutorial -->> https://medium.com/swlh/jwt-authentication-in-vue-nuxt-the-right-way-486e333b1d71

I am just a beginner in vuex and jwt related stuff, Help needed

THANK YOU!..

This is the response i am getting when i hit login button

ContentLicense: CC BY-SA 4.0

Body:
I am building a NUXT JS Application which uses NodeJS API for login registration. I am using AXIOS, VUEX, JWT for this. however i am not able to set the store and set JWT token properly in browser cache, Need help..

This is my Login Page

<template>

The perfect place for our pre wedding shoot it was a dream true

Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas vero velit possimus quos provident quaerat, asperiores tempora esse suscipit perferendis veritatis quod tempore numquam labore pariatur voluptatibus ea minus quisquam?

Welcome

Lorem ipsum dolor sit amet consectetur adipisicing elit. Corporis sapiente, nemo et molestiae quae possimus a voluptate suscipit.

If you are new, Kindly register here

                        <form action="" v-on:submit.prevent="onSubmit()" method="POST">

                                    Email
                                    <input v-model="data.email_id" type="text" class="form-control" placeholder="Enter registered email ID">

                                    Password
                                    <input v-model="data.password" type="text" class="form-control" placeholder="Enter Password">

                                    <input type="checkbox" name="" id="terms">
                                    Remember me

                                    Forgot Password?

                                <button type="submit">Login to my account</button>

                        </form>

                        Go Back

</template>

This is my store/index.js

export const AUTH_MUTATIONS = {
    SET_USER: 'SET_USER',
    SET_PAYLOAD: 'SET_PAYLOAD',
    LOGOUT: 'LOGOUT',
  }

  export const state = () => ({
    access_token: null, // JWT access token
    refresh_token: null, // JWT refresh token
    data:[],
    id: null, // user id
    email_address: null, // user email address
  })

  export const mutations = {
    // store the logged in user in the state
    [AUTH_MUTATIONS.SET_USER] (state, { id, email_id, data }) {
      state.id = id
      state.email_id = email_id
      state.data = data
    },

    // store new or updated token fields in the state
    [AUTH_MUTATIONS.SET_PAYLOAD] (state, { access_token, refresh_token = null }) {
      state.access_token = access_token
      // refresh token is optional, only set it if present
      if (refresh_token) {
        state.refresh_token = refresh_token
      }
    },

    [AUTH_MUTATIONS.LOGOUT] (state) {
      state.id = null
      state.email_id = null
      state.access_token = null
      state.refresh_token = null
      data = null
    },
  }

  export const actions = {
    async login ({ commit, dispatch }, { email_id, password, data }) {
        const { data: { data: { user, payload } } } = await this.$axios.post(
            'http://xx.xxx.xxx.xxx:5000/api/v1/users/login',
            {data, email_id, password})
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.error('There was an error!', error);
        });
      commit(AUTH_MUTATIONS.SET_USER, data.user)
      commit(AUTH_MUTATIONS.SET_PAYLOAD, payload)
    },

    // logout the user
    logout ({ commit, state }) {
      commit(AUTH_MUTATIONS.LOGOUT)
    },
  }

  export const getters = {
    isAuthenticated: (state) => {
      return state.access_token && state.access_token !== ''
    },
  }

this is (plugins/axios.js)my axios my redirect method from the nuxt context

export default function ({ store, app: { $axios }, redirect }) {
    $axios.onRequest((config) => {
      // check if the user is authenticated
      if (store.state.auth.data.token) {
        // set the Authorization header using the access token
        config.headers.Authorization = 'Bearer ' + store.state.auth.data.token
      }

      return config
    })
}

my localstorage plugins/local-storage.js

import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
import cookie from 'cookie'

export default ({ store, req, isDev }) => {
  createPersistedState({
    key: 'authentication-cookie', // choose any name for your cookie
    paths: [
      'auth.access_token',
      'auth.refresh_token',
    ],
    storage: {

      getItem: key => process.client ? Cookies.getJSON(key) : cookie.parse(req.headers.cookie || '')[key],
      setItem: (key, value) => Cookies.set(key, value, { expires: 14, secure: !isDev }),
      removeItem: key => Cookies.remove(key)
    }
  })(store)
}

this is my nuxt.config.js

  plugins: [
    { src: '~/plugins/all.js', ssr: false },
    { src: '~/plugins/local-storage'},
    { src: '~/plugins/axios'},
  ],
  components: true,

  buildModules: [
  ],

  modules: [
    // Doc: https://bootstrap-vue.js.org
    'bootstrap-vue/nuxt',
    '@nuxtjs/axios',
  ],

  // base URL
  axios: {
      baseURL: 'http://xx.xxx.xxx.xxx:5000'
  },

I followed this tutorial -->> https://medium.com/swlh/jwt-authentication-in-vue-nuxt-the-right-way-486e333b1d71

I am just a beginner in vuex and jwt related stuff, Help needed

THANK YOU!..

This is the response i am getting when i hit login button


问:
How to render CSS3DObjects over WebGlRenderer Objects?
I´m trying to render an  with the CSS3DRenderer to a _3dScene in three.js, but the iframe is always overlaying the object in the WebGl scene.

How to fix this overlap issue? The iframe is right in the middle of the object, and still visible at any time.

This is how i init the CSS3DRenderer:

```<code>private _init3DRenderer()
    {
        this._3DRenderer = new CSS3DRenderer();
        this._3DRenderer.setSize(this.css3dContainer.nativeElement.clientWidth, this.css3dContainer.nativeElement.clientHeight);
        this._3DRenderer.domElement.style.position = 'absolute';
        this._3DRenderer.domElement.style.zIndex = '0';
        this._3DRenderer.domElement.style.top = "0";
        this.css3dContainer.nativeElement.appendChild(this._3DRenderer.domElement);
    }
</code>```

as well as initializing the WebGlRenderer:

```<code>private _initRenderer()
    {
        this._renderer = new WebGLRenderer({ alpha: true, antialias: true });
        this._renderer.setPixelRatio(window.devicePixelRatio);
        this._renderer.setSize(this.webglContainer.nativeElement.clientWidth, this.webglContainer.nativeElement.clientHeight);
        this._renderer.outputEncoding = sRGBEncoding;
        this._renderer.shadowMap.enabled = true;
        this._renderer.shadowMap.type = PCFSoftShadowMap;
        this.webglContainer.nativeElement.appendChild(this._renderer.domElement);
    }
</code>```

after initialization im adding an object to the WebG as well as the iframe.

```<code>let div = document.createElement("div");
        let iframe = document.createElement("iframe");
        iframe.style.width = "100%";
        iframe.style.height = "100%";
        iframe.src = url;

        div.style.width = "100%";
        div.style.height = "100%";
        div.style.zIndex = "2";
        div.style.scale = ".5";
        div.appendChild(iframe);

        let cssObject = new CSS3DObject(div);
        this._3Dscene.add(cssObject);
</code>```

the 2 different scenes, are sharing the same camera object and get rendered like so:

```<code>private _render()
    {
        this._renderer?.render(this._scene, this._camera);
        this._3DRenderer?.render(this._3Dscene, this._camera);
    }
</code>```

html template

```

Body:
I´m trying to render an  with the CSS3DRenderer to a _3dScene in three.js, but the iframe is always overlaying the object in the WebGl scene.

How to fix this overlap issue? The iframe is right in the middle of the object, and still visible at any time.

This is how i init the CSS3DRenderer:

private _init3DRenderer()
    {
        this._3DRenderer = new CSS3DRenderer();
        this._3DRenderer.setSize(this.css3dContainer.nativeElement.clientWidth, this.css3dContainer.nativeElement.clientHeight);
        this._3DRenderer.domElement.style.position = 'absolute';
        this._3DRenderer.domElement.style.zIndex = '0';
        this._3DRenderer.domElement.style.top = "0";
        this.css3dContainer.nativeElement.appendChild(this._3DRenderer.domElement);
    }

as well as initializing the WebGlRenderer:

private _initRenderer()
    {
        this._renderer = new WebGLRenderer({ alpha: true, antialias: true });
        this._renderer.setPixelRatio(window.devicePixelRatio);
        this._renderer.setSize(this.webglContainer.nativeElement.clientWidth, this.webglContainer.nativeElement.clientHeight);
        this._renderer.outputEncoding = sRGBEncoding;
        this._renderer.shadowMap.enabled = true;
        this._renderer.shadowMap.type = PCFSoftShadowMap;
        this.webglContainer.nativeElement.appendChild(this._renderer.domElement);
    }

after initialization im adding an object to the WebG as well as the iframe.

let div = document.createElement("div");
        let iframe = document.createElement("iframe");
        iframe.style.width = "100%";
        iframe.style.height = "100%";
        iframe.src = url;

        div.style.width = "100%";
        div.style.height = "100%";
        div.style.zIndex = "2";
        div.style.scale = ".5";
        div.appendChild(iframe);

        let cssObject = new CSS3DObject(div);
        this._3Dscene.add(cssObject);

the 2 different scenes, are sharing the same camera object and get rendered like so:

private _render()
    {
        this._renderer?.render(this._scene, this._camera);
        this._3DRenderer?.render(this._3Dscene, this._camera);
    }

html template


问:
initState is not being called from a model class
I'm new to flutter and I'm having trouble with the initState method of a widget I would like to use.

For some context, I'm trying to make a movie viewing app for a project, and I have to use data from tmdb. This is where things get a little funky as the design of the app should show rows of two movie posters. To do this, I made a method that would retrieve the necessary data and use them to create widgets and add them to a list. But I noticed that the initState method of those widgets is not working, I need this to work as I needed to pass the poster link. My theory is that, since it's being called from a method, it doesn't actually initialize the state; hence no values are actually being passed.

This is the code of the method

```<code>Future<List<Widget>> getSuggestedMovies() async{
    Network network = Network('$tmdUrl/trending/all/day?api_key=$apiKey');
    var suggestedMovies = await network.getData();
    List result = suggestedMovies['results'];
    int i = 1;
    List<Widget> column = [];
    List<Widget> row = [];

    result.forEach((dynamic movie) {
      Poster poster = Poster(posterLocation: 'https://image.tmdb.org/t/p/w500'+movie['poster_path']);
      row.add(poster);

      if((i % 2) == 0){
        SuggestedRow newRow = SuggestedRow(widgetsList: row);
        column.add(newRow);
        row = [];
      }

      i++;
    });

    return column;
  }
</code>```

and one of the widget classes looks like this

```<code>  class Poster extends StatefulWidget {
  final String posterLocation;

  Poster({required this.posterLocation});

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

class _PosterWidgetState extends State<Poster> {
  String? posterLocation;

  void initState(){
    super.initState();
    posterLocation = widget.posterLocation;
  }

  Widget build(BuildContext context) {
    return Container(
        child: InkWell(
      onTap: () async {},
      child: Container(
        width: 80,
        height: 250,
        margin: EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Color(0xFF292B37).withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 4,
            ),
          ],
          image: DecorationImage(
            image: NetworkImage(
              posterLocation.toString(),
            ),
          ),
        ),
      ),
    ));
  }
}
</code>```

The Poster class' (as well as the row and column) initState just doesn't work for some reason so I can't pass the value. It is also worth mentioning that the list is not null, the classes inside of them just don't have any values whatsoever.

I would love to hear what I'm doing wrong and accept your suggestions. Cheers!

EDIT: row class for more context

```<code>class _SuggestedRowState extends State<SuggestedRow>{

  List<Widget> widgetsList = [];

  void initState(){
    super.initState();
    print('---------------------------------------');
    this.widgetsList = widget.widgetsList;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: widgetsList,
    );
  }
</code>```

Body:
I'm new to flutter and I'm having trouble with the initState method of a widget I would like to use.

For some context, I'm trying to make a movie viewing app for a project, and I have to use data from tmdb. This is where things get a little funky as the design of the app should show rows of two movie posters. To do this, I made a method that would retrieve the necessary data and use them to create widgets and add them to a list. But I noticed that the initState method of those widgets is not working, I need this to work as I needed to pass the poster link. My theory is that, since it's being called from a method, it doesn't actually initialize the state; hence no values are actually being passed.

This is the code of the method

Future<List<Widget>> getSuggestedMovies() async{
    Network network = Network('$tmdUrl/trending/all/day?api_key=$apiKey');
    var suggestedMovies = await network.getData();
    List result = suggestedMovies['results'];
    int i = 1;
    List<Widget> column = [];
    List<Widget> row = [];

    result.forEach((dynamic movie) {
      Poster poster = Poster(posterLocation: 'https://image.tmdb.org/t/p/w500'+movie['poster_path']);
      row.add(poster);

      if((i % 2) == 0){
        SuggestedRow newRow = SuggestedRow(widgetsList: row);
        column.add(newRow);
        row = [];
      }

      i++;
    });

    return column;
  }

and one of the widget classes looks like this

  class Poster extends StatefulWidget {
  final String posterLocation;

  Poster({required this.posterLocation});

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

class _PosterWidgetState extends State<Poster> {
  String? posterLocation;

  void initState(){
    super.initState();
    posterLocation = widget.posterLocation;
  }

  Widget build(BuildContext context) {
    return Container(
        child: InkWell(
      onTap: () async {},
      child: Container(
        width: 80,
        height: 250,
        margin: EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Color(0xFF292B37).withOpacity(0.5),
              spreadRadius: 2,
              blurRadius: 4,
            ),
          ],
          image: DecorationImage(
            image: NetworkImage(
              posterLocation.toString(),
            ),
          ),
        ),
      ),
    ));
  }
}

The Poster class' (as well as the row and column) initState just doesn't work for some reason so I can't pass the value. It is also worth mentioning that the list is not null, the classes inside of them just don't have any values whatsoever.

I would love to hear what I'm doing wrong and accept your suggestions. Cheers!

EDIT: row class for more context

class _SuggestedRowState extends State<SuggestedRow>{

  List<Widget> widgetsList = [];

  void initState(){
    super.initState();
    print('---------------------------------------');
    this.widgetsList = widget.widgetsList;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: widgetsList,
    );
  }


问:
Because of HashChange Event Cypress throws 404 error
In my application, when I click on the link - url gets updated momentarily and then again updates with the new url.
Cypress throws 404 after clicking on the link and tries to load page with the url with # which is already gone now.

How to handle this situation?

I am trying to find a way to ignore the url with # during running the test.

Please see attached screenshot


问:
Why is my grid element in another grid place then it should?
Why is my grid area D flowing into my grid area A? I don't really know why this is happening so please help!

#wrapper {
    position: relative;
    display: grid;
    grid-template-columns: 70px 125px;
    grid-template-rows: 20px 16px 42px 20px 16px 42px;
    grid-template-areas: "A B"
                         "A C"
                         "A ."
                         "D E"
                         "D F"
                         "D .";
    width: 100vw;
    margin-top: 30px;
    justify-content: center;
}

#clothing1-div {
    height: 80px;
    width: 100vw;
    position: absolute;
    top: -10px;
    background-color: rgb(235, 235, 235);
    border-top: 1px solid rgb(80, 80, 80);
    border-bottom: 1px solid rgb(80, 80, 80);
    z-index: -1;
}

#clothing1-div:hover {
    background-color: rgb(209, 209, 209);
    border-top: 1px solid rgb(94, 94, 94);
    border-bottom: 1px solid rgb(94, 94, 94);
}

#clothing1-img {
    width: 60px;
    grid-area: A;
}

#clothing1-link {
    color: black;
    font-size: 16px;
    grid-area: B;
    text-decoration: none;
    color: black;
    font-size: 16px;
}

#clothing1-pris {
    color: black;
    font-size: 14px;
    grid-area: C;
}

#clothing2-div {
    height: 80px;
    width: 100vw;
    position: absolute;
    top: 69px;
    background-color: rgb(235, 235, 235);
    border-top: 1px solid rgb(80, 80, 80);
    border-bottom: 1px solid rgb(80, 80, 80);
    z-index: -1;
}

#clothing2-div:hover {
    background-color: rgb(209, 209, 209);
    border-top: 1px solid rgb(94, 94, 94);
    border-bottom: 1px solid rgb(94, 94, 94);
}

#clothing2-img {
    width: 60px;
    grid-area: D;
}

#clothing2-link {
    grid-area: E;
    text-decoration: none;
    color: black;
    font-size: 16px;
}

#clothing2-pris {
    color: black;
    font-size: 14px;
    grid-area: F;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
            <img src="/sticky/imgs/Svart Hoodie framsida PNG.png" alt="black-zip-up" id="clothing1-img">
            black zip-up
            <img src="/sticky/imgs/Lila Hoodie framsida PNG.png" alt="purple-zip-up" id="clothing2-img">
            purple zip-up
            <p id="clothing1-pris">500sek</p>
            <p id="clothing2-pris">500sek</p>
            <div onclick="location.href='#'" style="cursor:pointer;" id="clothing1-div"></div>
            <div onclick="location.href='#'" style="cursor:pointer;" id="clothing2-div"></div>
        </div></code>```

I really don't know I expected my grid area D to be in it's place but it isn't? As described earlier i want my element in the grid to be where they are suppost to be mainly grid area D staying in it's area. What i tried is moving stuff around and placing 2 dummy element in the punctuated grid area but none have worked.

Body:
Why is my grid area D flowing into my grid area A? I don't really know why this is happening so please help!

#wrapper {
    position: relative;
    display: grid;
    grid-template-columns: 70px 125px;
    grid-template-rows: 20px 16px 42px 20px 16px 42px;
    grid-template-areas: "A B"
                         "A C"
                         "A ."
                         "D E"
                         "D F"
                         "D .";
    width: 100vw;
    margin-top: 30px;
    justify-content: center;
}

#clothing1-div {
    height: 80px;
    width: 100vw;
    position: absolute;
    top: -10px;
    background-color: rgb(235, 235, 235);
    border-top: 1px solid rgb(80, 80, 80);
    border-bottom: 1px solid rgb(80, 80, 80);
    z-index: -1;
}

#clothing1-div:hover {
    background-color: rgb(209, 209, 209);
    border-top: 1px solid rgb(94, 94, 94);
    border-bottom: 1px solid rgb(94, 94, 94);
}

#clothing1-img {
    width: 60px;
    grid-area: A;
}

#clothing1-link {
    color: black;
    font-size: 16px;
    grid-area: B;
    text-decoration: none;
    color: black;
    font-size: 16px;
}

#clothing1-pris {
    color: black;
    font-size: 14px;
    grid-area: C;
}

#clothing2-div {
    height: 80px;
    width: 100vw;
    position: absolute;
    top: 69px;
    background-color: rgb(235, 235, 235);
    border-top: 1px solid rgb(80, 80, 80);
    border-bottom: 1px solid rgb(80, 80, 80);
    z-index: -1;
}

#clothing2-div:hover {
    background-color: rgb(209, 209, 209);
    border-top: 1px solid rgb(94, 94, 94);
    border-bottom: 1px solid rgb(94, 94, 94);
}

#clothing2-img {
    width: 60px;
    grid-area: D;
}

#clothing2-link {
    grid-area: E;
    text-decoration: none;
    color: black;
    font-size: 16px;
}

#clothing2-pris {
    color: black;
    font-size: 14px;
    grid-area: F;
}

            black zip-up

            purple zip-up

500sek

500sek

I really don't know I expected my grid area D to be in it's place but it isn't? As described earlier i want my element in the grid to be where they are suppost to be mainly grid area D staying in it's area. What i tried is moving stuff around and placing 2 dummy element in the punctuated grid area but none have worked.


问:
Compiling error in rust: failed to run custom build command
I don't quite know what I am looking at, I'm quite certain that this is not my fault

```<code>PS C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code> cargo run
   Compiling num-traits v0.2.15
   Compiling num-integer v0.1.45
error: failed to run custom build command for `num-traits v0.2.15`

Caused by:
  process didn't exit successfully: `C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code\target\debug\build\num-traits-0ab924901b158460\build-script-build` (exit code: 101)
  --- stderr
  thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: Other("output path is not a writable directory") }', C:\Users\alexa\.cargo\registry\src\github.com-1ecc6299db9ec823\autocfg-1.1.0\src\lib.rs:128:20
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
error: failed to run custom build command for `num-integer v0.1.45`

Caused by:
  process didn't exit successfully: `C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code\target\debug\build\num-integer-7dbeca75e83a8205\build-script-build` (exit code: 101)
  --- stderr
  thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: Other("output path is not a writable directory") }', C:\Users\alexa\.cargo\registry\src\github.com-1ecc6299db9ec823\autocfg-1.1.0\src\lib.rs:128:20
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
PS C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code>
</code>```

I don't really know where to begin solving this problem

Body:
I don't quite know what I am looking at, I'm quite certain that this is not my fault

PS C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code> cargo run
   Compiling num-traits v0.2.15
   Compiling num-integer v0.1.45
error: failed to run custom build command for `num-traits v0.2.15`

Caused by:
  process didn't exit successfully: `C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code\target\debug\build\num-traits-0ab924901b158460\build-script-build` (exit code: 101)
  --- stderr
  thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: Other("output path is not a writable directory") }', C:\Users\alexa\.cargo\registry\src\github.com-1ecc6299db9ec823\autocfg-1.1.0\src\lib.rs:128:20
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
error: failed to run custom build command for `num-integer v0.1.45`

Caused by:
  process didn't exit successfully: `C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code\target\debug\build\num-integer-7dbeca75e83a8205\build-script-build` (exit code: 101)
  --- stderr
  thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { kind: Other("output path is not a writable directory") }', C:\Users\alexa\.cargo\registry\src\github.com-1ecc6299db9ec823\autocfg-1.1.0\src\lib.rs:128:20
  note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
PS C:\Users\alexa\Documents\UNIVERSITEIT\2_MASTER\DECISION MAKING FOR BUSINESS\CASE_E\shift_scheduling_code>

I don't really know where to begin solving this problem


问:
R Shiny - Maintain state of dynamic bucket list when adding ranked lists
I have a bucket list with a button to add blank ranked lists to the bucket. The problem I am having is if the user drags items from one list to another and hits the button to add another list to the bucket, the dragged items reset to their initial position. Here is what I have so far:
`

```<code>library(shiny)
library(sortable)
library(tidyverse)

init_table <- tibble(
    category = c("Category 1","Category 2"),
    values = list(c('x1','x2','x3'),NA),
    ids = c('list1','list2')
)

ui <- fluidPage(
    h1("Bucketlist Module"),
    uiOutput("Dyanmic_Bucket"),
    actionButton("button1", "Add a New List")
)

server <- function(input, output, session) {
    # Reactive val with the initial table
    rv_table <- reactiveVal(init_table)

    # Add an empty new row to the reactive table with a dynamic label
    observeEvent(input$button1, {
        newRow <- tibble( category = paste0("Additional Table ", nrow(rv_table())-1),
                          values = NA, ids = paste0("list",nrow(rv_table())))
        currentTable <- rv_table()
        rv_table(rbind(newRow, currentTable))
    })

    # Rank list items for bucket list
    rank_list_items <- eventReactive(rv_table(), {
        rv_table() %>% mutate(
            rankList = pmap(list(category, values, ids), function(x,y,z){
                add_rank_list(
                    text = x,
                    labels = y ,
                    input_id = z
                )
            })
        ) %>% pull(rankList)
    })

    output$Dyanmic_Bucket <- renderUI({
        myItems <- rank_list_items()
        do.call("bucket_list", args = c(
            list(header = "",
                 group_name = "Dyanmic_Bucket",
                 orientation = "horizontal"),
            myItems
        ))

    })
}
shinyApp(ui, server)

</code>```

`

Is there a way to maintain the state of the ranked lists when the button is hit and just add a new list? I need to maintain the functionality of the user being able to add as a many new lists to the bucket as the user wants with the button.

Body:
I have a bucket list with a button to add blank ranked lists to the bucket. The problem I am having is if the user drags items from one list to another and hits the button to add another list to the bucket, the dragged items reset to their initial position. Here is what I have so far:
`

library(shiny)
library(sortable)
library(tidyverse)

init_table <- tibble(
    category = c("Category 1","Category 2"),
    values = list(c('x1','x2','x3'),NA),
    ids = c('list1','list2')
)

ui <- fluidPage(
    h1("Bucketlist Module"),
    uiOutput("Dyanmic_Bucket"),
    actionButton("button1", "Add a New List")
)

server <- function(input, output, session) {
    # Reactive val with the initial table
    rv_table <- reactiveVal(init_table)

    # Add an empty new row to the reactive table with a dynamic label
    observeEvent(input$button1, {
        newRow <- tibble( category = paste0("Additional Table ", nrow(rv_table())-1),
                          values = NA, ids = paste0("list",nrow(rv_table())))
        currentTable <- rv_table()
        rv_table(rbind(newRow, currentTable))
    })

    # Rank list items for bucket list
    rank_list_items <- eventReactive(rv_table(), {
        rv_table() %>% mutate(
            rankList = pmap(list(category, values, ids), function(x,y,z){
                add_rank_list(
                    text = x,
                    labels = y ,
                    input_id = z
                )
            })
        ) %>% pull(rankList)
    })

    output$Dyanmic_Bucket <- renderUI({
        myItems <- rank_list_items()
        do.call("bucket_list", args = c(
            list(header = "",
                 group_name = "Dyanmic_Bucket",
                 orientation = "horizontal"),
            myItems
        ))

    })
}
shinyApp(ui, server)

`

Is there a way to maintain the state of the ranked lists when the button is hit and just add a new list? I need to maintain the functionality of the user being able to add as a many new lists to the bucket as the user wants with the button.


问:
How to read a table from a word document by title or name instead of index
Is it possible to read a table from a word document using the 'Table Title or Table Name'?

Currently, I am using a script that uses 'docx'.
The tables are being read by table number. For example:

```<code>doc1 = Document(name of file.docx)

Data = [[cell.text for cell in row.cells] for row in doc2.tables[0].rows]
</code>```

Would it be possible to do something like this:

```<code>table name = Description

Data = [[cell.text for cell in row.cells] for row in doc2.Description.rows]
</code>```

Body:
Is it possible to read a table from a word document using the 'Table Title or Table Name'?

Currently, I am using a script that uses 'docx'.
The tables are being read by table number. For example:

doc1 = Document(name of file.docx)

Data = [[cell.text for cell in row.cells] for row in doc2.tables[0].rows]

Would it be possible to do something like this:

table name = Description

Data = [[cell.text for cell in row.cells] for row in doc2.Description.rows]


问:
Can we upgrade to tomcat 10 with servlet 3.0?
we have our monolith application hosted with tomcat vision 8 and servlet version 3.0 . We are looking forward to upgrade it to tomcat 10. Is it mandatory to upgrade the servlet version or can we still start the application with prior servlet version?</p>


问:
Problem when using data_format='channels_first' and strides=2 with Conv1D layer
This is my model:

```<code>model = Sequential([
     Input(shape=(80,23,5)),
     Conv1D(filters=64, kernel_size=3, strides=2, padding='same',data_format='channels_first'),
     Dense(128, activation='linear'),
     Dense(11, activation='softmax')
])

print (model.summary())
</code>```

If I set strides=1, it doesn't give any error. And if I remove data_format='channels_first'), it still doesn't give any error. But when I set Conv1D layer with both data_format='channels_first') and strides=1, the error happens like this:

```<code>ValueError: Exception encountered when calling layer "conv1d_243" (type Conv1D).

Dimension 3 in both shapes must be equal, but are 5 and 3. Shapes are [?,80,64,5] and [?,80,64,3].

Call arguments received by layer "conv1d_243" (type Conv1D):
  • inputs=tf.Tensor(shape=(None, 80, 23, 5), dtype=float32)
</code>```

Please help me to fix this.

Body:
This is my model:

model = Sequential([
     Input(shape=(80,23,5)),
     Conv1D(filters=64, kernel_size=3, strides=2, padding='same',data_format='channels_first'),
     Dense(128, activation='linear'),
     Dense(11, activation='softmax')
])

print (model.summary())

If I set strides=1, it doesn't give any error. And if I remove data_format='channels_first'), it still doesn't give any error. But when I set Conv1D layer with both data_format='channels_first') and strides=1, the error happens like this:

ValueError: Exception encountered when calling layer "conv1d_243" (type Conv1D).

Dimension 3 in both shapes must be equal, but are 5 and 3. Shapes are [?,80,64,5] and [?,80,64,3].

Call arguments received by layer "conv1d_243" (type Conv1D):
  • inputs=tf.Tensor(shape=(None, 80, 23, 5), dtype=float32)

Please help me to fix this.


问:
Python singledispatchmethod default keyword if not present
I am looking for a way to skip or default a singledispatchmethod when calling the method.

My aim is to have a set() method that can have an optional index and some text. If the index is not present then it should default to None or 0.

Because of the multiple types that all need to do different things I don't want to use and endless if statement.

    @singledispatchmethod
    def set(self, index=0, text=""):
        raise Exception(f'set((index), text): index defaults to 0 if not set')
    @set.register
    def _(self, index:None, text:str): #issue with this one <<<
        print("got text with no index")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index: str, text):
        print("got index as a string")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index: int, text):
        print("got index as an int")#
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index:float, text):
        print("got index as a float")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index:list, text):
        print("got index as a list")
        print(f'{index=}, {text=}')
```
<p>example use:</p>
<pre class="lang-py prettyprint-override"><code>item.set(0, "This is some text")
item.set("This is some text")
item.set([0, 5], "This is some text")
item.set(0.5, "This is some text")
item.set("1" "This is some text")
</code>```

if item is a string:

```<code>int -> index in string to insert text
None-> index is 0 and is index in string to insert text
list-> start/stop index to cut and insert text into string
float->split string and insert text into line.index
string-> convert to float or int where possible, else raise exceptoion.
</code>```

Body:
I am looking for a way to skip or default a singledispatchmethod when calling the method.

My aim is to have a set() method that can have an optional index and some text. If the index is not present then it should default to None or 0.

Because of the multiple types that all need to do different things I don't want to use and endless if statement.

    @singledispatchmethod
    def set(self, index=0, text=""):
        raise Exception(f'set((index), text): index defaults to 0 if not set')
    @set.register
    def _(self, index:None, text:str): #issue with this one <<<
        print("got text with no index")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index: str, text):
        print("got index as a string")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index: int, text):
        print("got index as an int")#
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index:float, text):
        print("got index as a float")
        print(f'{index=}, {text=}')
    @set.register
    def _(self, index:list, text):
        print("got index as a list")
        print(f'{index=}, {text=}')

example use:

item.set(0, "This is some text")
item.set("This is some text")
item.set([0, 5], "This is some text")
item.set(0.5, "This is some text")
item.set("1" "This is some text")

if item is a string:

int -> index in string to insert text
None-> index is 0 and is index in string to insert text
list-> start/stop index to cut and insert text into string
float->split string and insert text into line.index
string-> convert to float or int where possible, else raise exceptoion.


问:
How to render inovua/reactdatagrid inside a div with absolute position?
I am trying to render inovua/reactdatagrid inside the popover component of headless-ui that has absolute position, which is not working.

I tried to use a separate div to render the grid but it does not show up on ui, if the div has absolute or fixed position but it does show up as soon as I change the positioning to relative. Although the grid is added to the dom, it's just isn't visible.


问:
How to map a function over a tree in haskell?
```<code>data Tree a = Empty | Node a (Tree a) (Tree a)
  deriving (Show, Eq)

mapTree :: (a -> b) -> Tree a -> Tree b
maptree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r)
</code>```

This is the function I've written to try to map a function over a tree but it doesn't work as expected

Why does my function return "Non-exhaustive patterns in function mapTree"?

Body:
data Tree a = Empty | Node a (Tree a) (Tree a)
  deriving (Show, Eq)

mapTree :: (a -> b) -> Tree a -> Tree b
maptree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r)

This is the function I've written to try to map a function over a tree but it doesn't work as expected

Why does my function return "Non-exhaustive patterns in function mapTree"?


问:
Error: SQLITE_ERROR: no such function: YEAR
I have an SQLite database with a table named BoxActivity. I need to query this DB to fetch records of a specific month of a year to make a report.
I've written the query:

BoxActivity.findAll({
    attributes: [
      [sequelize.fn('SUM', sequelize.col('boxActivity.quantity')), 'total_qty']
    ],
    where: {
      quantity: {
        [Op.lt]: 0
      },
      [Op.and]: [
        {
          createdAt: sequelize.where(sequelize.fn('YEAR', sequelize.col('boxActivity.createdAt')), year),
        },
        {
          createdAt: sequelize.where(sequelize.fn('MONTH', sequelize.col('boxActivity.createdAt')), month),
        }
      ]
    },
    group: ['box->reagent.id'],
    include: [
      {
        model: Box,
        required: false,
        include: [
          {
            model: Reagent,
            required: false,
          }
        ]
      }
    ]
  })
```

But I'm facing this error:

[Error: SQLITE_ERROR: no such function: YEAR]

I think the YEAR and MONTH functions aren't supported in SQLite.

Is there a way or a hack to transcend this problem?

Body:
I have an SQLite database with a table named BoxActivity. I need to query this DB to fetch records of a specific month of a year to make a report.
I've written the query:

BoxActivity.findAll({
    attributes: [
      [sequelize.fn('SUM', sequelize.col('boxActivity.quantity')), 'total_qty']
    ],
    where: {
      quantity: {
        [Op.lt]: 0
      },
      [Op.and]: [
        {
          createdAt: sequelize.where(sequelize.fn('YEAR', sequelize.col('boxActivity.createdAt')), year),
        },
        {
          createdAt: sequelize.where(sequelize.fn('MONTH', sequelize.col('boxActivity.createdAt')), month),
        }
      ]
    },
    group: ['box->reagent.id'],
    include: [
      {
        model: Box,
        required: false,
        include: [
          {
            model: Reagent,
            required: false,
          }
        ]
      }
    ]
  })

But I'm facing this error:

[Error: SQLITE_ERROR: no such function: YEAR]

I think the YEAR and MONTH functions aren't supported in SQLite.

Is there a way or a hack to transcend this problem?


问:
how to get current group name at run time, I have around 6-7 groups mentioned in my testng.xml
I have to take some decision based on group like different app installation for appium based test, depending on type of group being executed.

```<code>@BeforeClass
public void printCurrentGroup(ITestContext itestCOntext){
    System.out.println(itestCOntext.getIncludedGroups());
}
</code>```

itestCOntext.getIncludedGroups() : This is String array of all included group not currently executed group.

Body:
I have to take some decision based on group like different app installation for appium based test, depending on type of group being executed.

@BeforeClass
public void printCurrentGroup(ITestContext itestCOntext){
    System.out.println(itestCOntext.getIncludedGroups());
}

itestCOntext.getIncludedGroups() : This is String array of all included group not currently executed group.


问:
Docker plugins misfunctioning with mdns?
I have the following set-up:

I run the Docker daemon in a VM on my Macbook (M1, MacOS Monterey version 12.6). The VM advertises the "docker.local" service (not entirely sure this is the correct terminology).

I then try to interact with the Docker daemon from my Macbook.

I observe the following:

```<code>user@host ~ $ DOCKER_HOST=tcp://docker.local:2375 docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
user@host ~ $ DOCKER_HOST=tcp://docker.local:2375 docker-compose ls
error during connect: Get "http://docker.local:2375/v1.24/containers/json?filters=%7B%22label%22%3A%7B%22com.docker.compose.project%22%3Atrue%7D%7D": dial tcp: lookup docker.local on 10.0.0.1:53: no such host
</code>```

So when I used docker (client version 20.10.10), communication works as expected. But if use docker-compose (version  v2.14.0) then I get this no such host error. I see the same behavior with docker buildx for example.

However:

```<code>user@host ~ $ dscacheutil -q host -a name docker.local
name: docker.local
ipv6_address: fd05:60e3:4cfd:5e54:5054:ff:fe15:ff48

name: docker.local
ip_address: 192.168.205.85
</code>```

So to me, it looks like the service is advertised appropriately.
So I can only assume docker and docker-compose try to resolve differently.
In the case of docker-compose, it looks like the gateway is actually used as a DNS server. However the gateway does know about this service because the VM is running on my MAC.

Do you have any idea why this is and if there is a work-around?
I have spent quite a bit of time looking into it (tcpdumping, editing DNS settings, ...) but I'm still confused how to make this work. Good thing about it, is I got to learn about mdns (pretty cool stuff!).

Thanks in advance,

Body:
I have the following set-up:

I run the Docker daemon in a VM on my Macbook (M1, MacOS Monterey version 12.6). The VM advertises the "docker.local" service (not entirely sure this is the correct terminology).

I then try to interact with the Docker daemon from my Macbook.

I observe the following:

user@host ~ $ DOCKER_HOST=tcp://docker.local:2375 docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
user@host ~ $ DOCKER_HOST=tcp://docker.local:2375 docker-compose ls
error during connect: Get "http://docker.local:2375/v1.24/containers/json?filters=%7B%22label%22%3A%7B%22com.docker.compose.project%22%3Atrue%7D%7D": dial tcp: lookup docker.local on 10.0.0.1:53: no such host

So when I used docker (client version 20.10.10), communication works as expected. But if use docker-compose (version  v2.14.0) then I get this no such host error. I see the same behavior with docker buildx for example.

However:

user@host ~ $ dscacheutil -q host -a name docker.local
name: docker.local
ipv6_address: fd05:60e3:4cfd:5e54:5054:ff:fe15:ff48

name: docker.local
ip_address: 192.168.205.85

So to me, it looks like the service is advertised appropriately.
So I can only assume docker and docker-compose try to resolve differently.
In the case of docker-compose, it looks like the gateway is actually used as a DNS server. However the gateway does know about this service because the VM is running on my MAC.

Do you have any idea why this is and if there is a work-around?
I have spent quite a bit of time looking into it (tcpdumping, editing DNS settings, ...) but I'm still confused how to make this work. Good thing about it, is I got to learn about mdns (pretty cool stuff!).

Thanks in advance,


问:
How to save data from API in device Flutter
In my application a lot of data received from the api, how to save data on device when app starts, and take this data from device and take data from the device without making an api call every time.
I can show on the example of my futureBuilder, every time when I go to UserPage, my user data is loaded, how can I save it?</p>
```<code>late Future<User> userFuture = getUser();
  static Future<User> getUser() async {
    var url = '${Constants.API_URL_DOMAIN}action=user_profile&token=${Constants.USER_TOKEN}';
    print(Constants.USER_TOKEN);
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    return User.fromJson(body['data']);
  }

              FutureBuilder<User>(
                future: userFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return buildProfileShimmer();
                    // Center(child: CircularProgressIndicator());
                  } else if (snapshot.hasData) {
                    final user = snapshot.data!;
                    return buildUser(user);
                  } else {
                    return Text("No widget to build");
                  }
                },
              )
</code>```

Body:
In my application a lot of data received from the api, how to save data on device when app starts, and take this data from device and take data from the device without making an api call every time.
I can show on the example of my futureBuilder, every time when I go to UserPage, my user data is loaded, how can I save it?

late Future<User> userFuture = getUser();
  static Future<User> getUser() async {
    var url = '${Constants.API_URL_DOMAIN}action=user_profile&token=${Constants.USER_TOKEN}';
    print(Constants.USER_TOKEN);
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    return User.fromJson(body['data']);
  }

              FutureBuilder<User>(
                future: userFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return buildProfileShimmer();
                    // Center(child: CircularProgressIndicator());
                  } else if (snapshot.hasData) {
                    final user = snapshot.data!;
                    return buildUser(user);
                  } else {
                    return Text("No widget to build");
                  }
                },
              )


问:
Sum with for loop in MATLAB
(https://i.stack.imgur.com/vkYy6.png)

How should I implement this sum with for loops in matlab, for i = 1:20 , N = 20 and ε is a vector, I have to avoid ε[0] so should I write a for loop, for each  R?

```<code>for i=1:1:20

        R (i) =symsum(e(k)-e(k-i),k+i,0,N);
end
</code>```

Title: Sum with for loop in MATLAB

Body:
(https://i.stack.imgur.com/vkYy6.png)

How should I implement this sum with for loops in matlab, for i = 1:20 , N = 20 and ε is a vector, I have to avoid ε[0] so should I write a for loop, for each  R?

for i=1:1:20

        R (i) =symsum(e(k)-e(k-i),k+i,0,N);
end


问:
flutter video_player is not working on IOS devices. Even though it works on android devices
I'm trying to use video_player in flutter to show network videos in mp4 format (https://www.heygold.com/media/reel/ThisorThat.mp4). On IOS devices it never sets  _controller.value.isInitialized to true.

I'm using:

```<code>video_player: 2.4.7
</code>```

Output of flutter doctor -v:

```<code>[✓] Flutter (Channel stable, 3.3.9, on macOS 12.6 21G115 darwin-arm, locale en-DE)
    • Flutter version 3.3.9 on channel stable at /Users/casparbaumeister/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (2 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/casparbaumeister/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • Java binary at: /Users/casparbaumeister/development/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Users/casparbaumeister/development/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.73.1)
    • VS Code at /Users/casparbaumeister/development/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 12 (API 32) (emulator)
    • macOS (desktop)             • macos         • darwin-arm64   • macOS 12.6 21G115 darwin-arm
    • Chrome (web)                • chrome        • web-javascript • Google Chrome 108.0.5359.94

[✓] HTTP Host Availability
    • All required HTTP hosts are available
</code>```

Video player page:

```<code>class ReelsPage extends StatefulWidget {
  const ReelsPage({Key? key, required this.videoUrl}) : super(key: key);

  final String videoUrl;
  @override
  _ReelsPageState createState() => _ReelsPageState();
}

class _ReelsPageState extends State<ReelsPage> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(widget.videoUrl)
      ..addListener(() => setState(() {}))
      ..setLooping(true)
      ..initialize().then((_) => _controller.play());
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios_new_rounded, color: GOLDISH),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          automaticallyImplyLeading: true,
          backgroundColor: Colors.black,
          elevation: 0,
        ),
        body:
              _controller.value.isInitialized
                  ? show video
                  : Loading <- never leaves this state

        )
        );
  }
}
</code>```

My info.plist includes the following lines:

```<code><key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
    </dict>
</code>```

It works totally fine on android emulator and device. I know that it doest work on IOS emulators, but it also does not work on IOS devices. Every help is welcomed, also recommendations for other video player packages! Thanks in regard.

Body:
I'm trying to use video_player in flutter to show network videos in mp4 format (https://www.heygold.com/media/reel/ThisorThat.mp4). On IOS devices it never sets  _controller.value.isInitialized to true.

I'm using:

video_player: 2.4.7

Output of flutter doctor -v:

[✓] Flutter (Channel stable, 3.3.9, on macOS 12.6 21G115 darwin-arm, locale en-DE)
    • Flutter version 3.3.9 on channel stable at /Users/casparbaumeister/development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (2 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    • Android SDK at /Users/casparbaumeister/Library/Android/sdk
    • Platform android-33, build-tools 32.1.0-rc1
    • Java binary at: /Users/casparbaumeister/development/Android Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14B47b
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1)
    • Android Studio at /Users/casparbaumeister/development/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7772763)

[✓] VS Code (version 1.73.1)
    • VS Code at /Users/casparbaumeister/development/Visual Studio Code.app/Contents
    • Flutter extension version 3.54.0

[✓] Connected device (3 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 12 (API 32) (emulator)
    • macOS (desktop)             • macos         • darwin-arm64   • macOS 12.6 21G115 darwin-arm
    • Chrome (web)                • chrome        • web-javascript • Google Chrome 108.0.5359.94

[✓] HTTP Host Availability
    • All required HTTP hosts are available

Video player page:

class ReelsPage extends StatefulWidget {
  const ReelsPage({Key? key, required this.videoUrl}) : super(key: key);

  final String videoUrl;
  @override
  _ReelsPageState createState() => _ReelsPageState();
}

class _ReelsPageState extends State<ReelsPage> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();
    _controller = VideoPlayerController.network(widget.videoUrl)
      ..addListener(() => setState(() {}))
      ..setLooping(true)
      ..initialize().then((_) => _controller.play());
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios_new_rounded, color: GOLDISH),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          automaticallyImplyLeading: true,
          backgroundColor: Colors.black,
          elevation: 0,
        ),
        body:
              _controller.value.isInitialized
                  ? show video
                  : Loading <- never leaves this state

        )
        );
  }
}

My info.plist includes the following lines:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
    </dict>

It works totally fine on android emulator and device. I know that it doest work on IOS emulators, but it also does not work on IOS devices. Every help is welcomed, also recommendations for other video player packages! Thanks in regard.


问:
Is there a way of installing the package PET for installation of gitter and DeadOrAlive in the newest version of R?
```<code>
> install.packages("C:/Users/andyk/Downloads/PET_0.5.1.tar.gz", repos = NULL, type = "source")
‘C:/Users/andyk/AppData/Local/R/win-library/4.2’의 위치에 패키지(들)을 설치합니다.
(왜냐하면 ‘lib’가 지정되지 않았기 때문입니다)
* installing *source* package 'PET' ...
** package 'PET' successfully unpacked and MD5 sums checked
** using staged installation
** libs
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c Hough.c -o Hough.o
Hough.c: In function 'Hough4':
Hough.c:41:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
   41 |   double theta_min;
      |          ^~~~~~~~~
Hough.c:40:38: warning: variable 'y' set but not used [-Wunused-but-set-variable]
   40 |   double *costheta,*sintheta,theta,x,y;
      |                                      ^
Hough.c: In function 'Hough3':
Hough.c:118:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  118 |   double theta_min;
      |          ^~~~~~~~~
Hough.c: In function 'Hough2':
Hough.c:173:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  173 |   double theta_min;
      |          ^~~~~~~~~
Hough.c: In function 'Hough1':
Hough.c:227:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  227 |   double theta_min;
      |          ^~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c PET_init.c -o PET_init.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c amatrix.c -o amatrix.o
amatrix.c: In function 'RegulateMatrix':
amatrix.c:234:10: warning: variable 'tempVv' set but not used [-Wunused-but-set-variable]
  234 |   float *tempVv;
      |          ^~~~~~
amatrix.c: In function 'RegulateL1Matrix':
amatrix.c:289:10: warning: variable 'tempVv' set but not used [-Wunused-but-set-variable]
  289 |   float *tempVv;
      |          ^~~~~~
amatrix.c: In function 'GenerateAMatrixColumn':
amatrix.c:784:9: warning: variable 'onedivsq2' set but not used [-Wunused-but-set-variable]
  784 |   float onedivsq2,psi,pidivDeltaX,costheta,sintheta,of;
      |         ^~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c art.c -o art.o
art.c: In function 'FAST_ART':
art.c:128:10: warning: variable 'tempXv' set but not used [-Wunused-but-set-variable]
  128 |   float *tempXv,*tempBv;
      |          ^~~~~~
art.c: In function 'SLOW_ART':
art.c:239:10: warning: variable 'tempXv' set but not used [-Wunused-but-set-variable]
  239 |   float *tempXv,*tempBv;
      |          ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c calc.c -o calc.o
calc.c: In function 'BackFilter':
calc.c:335:19: warning: variable 'M' set but not used [-Wunused-but-set-variable]
  335 |   int i,m,n,mm,nn,M,N,OldHeight,OldWidth;
      |                   ^
calc.c: In function 'CentralSliceCZ':
calc.c:700:49: warning: variable 'rhomin' set but not used [-Wunused-but-set-variable]
  700 |   float DC,deltatheta,theta,thetaadj,*realtheta,rhomin,deltarho;
      |                                                 ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c cg.c -o cg.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c em.c -o em.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c eval.c -o eval.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c imgtools.c -o imgtools.o
imgtools.c: In function 'ReadPET':
imgtools.c:1005:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1005 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadFIFHeader':
imgtools.c:1148:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1148 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadFIF':
imgtools.c:1222:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1222 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadAnalyze':
imgtools.c:1616:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1616 |   size_t result;
      |          ^~~~~~
imgtools.c:1614:21: warning: variable 'OffSet' set but not used [-Wunused-but-set-variable]
 1614 |   float ScaleFactor,OffSet;
      |                     ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c iradon.c -o iradon.o
iradon.c: In function 'iradon':
iradon.c:271:5: warning: 'spectrum' may be used uninitialized in this function [-Wmaybe-uninitialized]
  271 |     FreeImage(spectrum);
      |     ^~~~~~~~~~~~~~~~~~~
iradon.c: In function 'loadFile':
iradon.c:568:9: warning: 'list' may be used uninitialized in this function [-Wmaybe-uninitialized]
  568 |   return(list);
      |         ^
iradon.c:404:16: warning: 'typeF' may be used uninitialized in this function [-Wmaybe-uninitialized]
  404 |     OutImage = ReadImage(fileName, typeF);
      |                ^~~~~~~~~~~~~~~~~~~~~~~~~~
iradon.c: In function 'writeFile':
iradon.c:684:19: warning: 'N' may be used uninitialized in this function [-Wmaybe-uninitialized]
  684 |         SaveImage=NewFloatImage(fileName, M, N, _RealArray);
      |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iradon.c:684:19: warning: 'M' may be used uninitialized in this function [-Wmaybe-uninitialized]
iradon.c:772:5: warning: 'typeF' may be used uninitialized in this function [-Wmaybe-uninitialized]
  772 |     WriteImage(SaveImage, typeF);
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c it.c -o it.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c itreadargs.c -o itreadargs.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c misc.c -o misc.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradLI.c -o oradLI.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradNN.c -o oradNN.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradSINC.c -o oradSINC.o
oradSINC.c: In function 'radonSINC':
oradSINC.c:52:10: warning: variable 'idx' set but not used [-Wunused-but-set-variable]
   52 |   double idx,mintrig,psi;
      |          ^~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c sparse.c -o sparse.o
sparse.c: In function 'ReadSIFHeader':
sparse.c:607:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
  607 |   size_t result;
      |          ^~~~~~
sparse.c: In function 'ReadSIF':
sparse.c:657:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
  657 |   size_t result;
      |          ^~~~~~
sparse.c: In function 'MeanFilterVector':
sparse.c:1537:13: warning: variable 'area' set but not used [-Wunused-but-set-variable]
 1537 |   float sum,area,*tempVv,*tempNv,*tempKernM;
      |             ^~~~
gcc -shared -s -static-libgcc -o PET.dll tmp.def Hough.o PET_init.o amatrix.o art.o calc.o cg.o em.o eval.o imgtools.o iradon.o it.o itreadargs.o misc.o oradLI.o oradNN.o oradSINC.o sparse.o -LC:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/lib/x64 -LC:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/lib -LC:/PROGRA~1/R/R-42~1.1/bin/x64 -lR
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x610): multiple definition of `DebugNiveau'; iradon.o:iradon.c:(.data+0x0): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x480): multiple definition of `IniFile'; iradon.o:iradon.c:(.bss+0x0): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x598): multiple definition of `multtemp'; iradon.o:iradon.c:(.bss+0x118): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x5a0): multiple definition of `LogFileName'; iradon.o:iradon.c:(.bss+0x120): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x608): multiple definition of `LogFile'; iradon.o:iradon.c:(.bss+0x188): first defined here
collect2.exe: error: ld returned 1 exit status
no DLL was created
ERROR: compilation failed for package 'PET'
* removing 'C:/Users/andyk/AppData/Local/R/win-library/4.2/PET'
Warning in install.packages :
  패키지 ‘C:/Users/andyk/Downloads/PET_0.5.1.tar.gz’의 설치가 0이 아닌 종료상태를 가졌습니다
</code>```

I need the package PET to install gitter and DeadOrAlive. I've tried manually installing with tar. file for PET, using install.packages, and other versions of the package, but none of the methods worked.

Is it not possible to install the package at all, or are there other ways of installing PET to download the subsequent packages.

Body:
> install.packages("C:/Users/andyk/Downloads/PET_0.5.1.tar.gz", repos = NULL, type = "source")
‘C:/Users/andyk/AppData/Local/R/win-library/4.2’의 위치에 패키지(들)을 설치합니다.
(왜냐하면 ‘lib’가 지정되지 않았기 때문입니다)
* installing *source* package 'PET' ...
** package 'PET' successfully unpacked and MD5 sums checked
** using staged installation
** libs
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c Hough.c -o Hough.o
Hough.c: In function 'Hough4':
Hough.c:41:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
   41 |   double theta_min;
      |          ^~~~~~~~~
Hough.c:40:38: warning: variable 'y' set but not used [-Wunused-but-set-variable]
   40 |   double *costheta,*sintheta,theta,x,y;
      |                                      ^
Hough.c: In function 'Hough3':
Hough.c:118:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  118 |   double theta_min;
      |          ^~~~~~~~~
Hough.c: In function 'Hough2':
Hough.c:173:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  173 |   double theta_min;
      |          ^~~~~~~~~
Hough.c: In function 'Hough1':
Hough.c:227:10: warning: variable 'theta_min' set but not used [-Wunused-but-set-variable]
  227 |   double theta_min;
      |          ^~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c PET_init.c -o PET_init.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c amatrix.c -o amatrix.o
amatrix.c: In function 'RegulateMatrix':
amatrix.c:234:10: warning: variable 'tempVv' set but not used [-Wunused-but-set-variable]
  234 |   float *tempVv;
      |          ^~~~~~
amatrix.c: In function 'RegulateL1Matrix':
amatrix.c:289:10: warning: variable 'tempVv' set but not used [-Wunused-but-set-variable]
  289 |   float *tempVv;
      |          ^~~~~~
amatrix.c: In function 'GenerateAMatrixColumn':
amatrix.c:784:9: warning: variable 'onedivsq2' set but not used [-Wunused-but-set-variable]
  784 |   float onedivsq2,psi,pidivDeltaX,costheta,sintheta,of;
      |         ^~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c art.c -o art.o
art.c: In function 'FAST_ART':
art.c:128:10: warning: variable 'tempXv' set but not used [-Wunused-but-set-variable]
  128 |   float *tempXv,*tempBv;
      |          ^~~~~~
art.c: In function 'SLOW_ART':
art.c:239:10: warning: variable 'tempXv' set but not used [-Wunused-but-set-variable]
  239 |   float *tempXv,*tempBv;
      |          ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c calc.c -o calc.o
calc.c: In function 'BackFilter':
calc.c:335:19: warning: variable 'M' set but not used [-Wunused-but-set-variable]
  335 |   int i,m,n,mm,nn,M,N,OldHeight,OldWidth;
      |                   ^
calc.c: In function 'CentralSliceCZ':
calc.c:700:49: warning: variable 'rhomin' set but not used [-Wunused-but-set-variable]
  700 |   float DC,deltatheta,theta,thetaadj,*realtheta,rhomin,deltarho;
      |                                                 ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c cg.c -o cg.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c em.c -o em.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c eval.c -o eval.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c imgtools.c -o imgtools.o
imgtools.c: In function 'ReadPET':
imgtools.c:1005:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1005 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadFIFHeader':
imgtools.c:1148:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1148 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadFIF':
imgtools.c:1222:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1222 |   size_t result;
      |          ^~~~~~
imgtools.c: In function 'ReadAnalyze':
imgtools.c:1616:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
 1616 |   size_t result;
      |          ^~~~~~
imgtools.c:1614:21: warning: variable 'OffSet' set but not used [-Wunused-but-set-variable]
 1614 |   float ScaleFactor,OffSet;
      |                     ^~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c iradon.c -o iradon.o
iradon.c: In function 'iradon':
iradon.c:271:5: warning: 'spectrum' may be used uninitialized in this function [-Wmaybe-uninitialized]
  271 |     FreeImage(spectrum);
      |     ^~~~~~~~~~~~~~~~~~~
iradon.c: In function 'loadFile':
iradon.c:568:9: warning: 'list' may be used uninitialized in this function [-Wmaybe-uninitialized]
  568 |   return(list);
      |         ^
iradon.c:404:16: warning: 'typeF' may be used uninitialized in this function [-Wmaybe-uninitialized]
  404 |     OutImage = ReadImage(fileName, typeF);
      |                ^~~~~~~~~~~~~~~~~~~~~~~~~~
iradon.c: In function 'writeFile':
iradon.c:684:19: warning: 'N' may be used uninitialized in this function [-Wmaybe-uninitialized]
  684 |         SaveImage=NewFloatImage(fileName, M, N, _RealArray);
      |                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iradon.c:684:19: warning: 'M' may be used uninitialized in this function [-Wmaybe-uninitialized]
iradon.c:772:5: warning: 'typeF' may be used uninitialized in this function [-Wmaybe-uninitialized]
  772 |     WriteImage(SaveImage, typeF);
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c it.c -o it.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c itreadargs.c -o itreadargs.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c misc.c -o misc.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradLI.c -o oradLI.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradNN.c -o oradNN.o
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c oradSINC.c -o oradSINC.o
oradSINC.c: In function 'radonSINC':
oradSINC.c:52:10: warning: variable 'idx' set but not used [-Wunused-but-set-variable]
   52 |   double idx,mintrig,psi;
      |          ^~~
gcc  -I"C:/PROGRA~1/R/R-42~1.1/include" -DNDEBUG     -I"C:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/include"     -O2 -Wall  -std=gnu99 -mfpmath=sse -msse2 -mstackrealign  -c sparse.c -o sparse.o
sparse.c: In function 'ReadSIFHeader':
sparse.c:607:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
  607 |   size_t result;
      |          ^~~~~~
sparse.c: In function 'ReadSIF':
sparse.c:657:10: warning: variable 'result' set but not used [-Wunused-but-set-variable]
  657 |   size_t result;
      |          ^~~~~~
sparse.c: In function 'MeanFilterVector':
sparse.c:1537:13: warning: variable 'area' set but not used [-Wunused-but-set-variable]
 1537 |   float sum,area,*tempVv,*tempNv,*tempKernM;
      |             ^~~~
gcc -shared -s -static-libgcc -o PET.dll tmp.def Hough.o PET_init.o amatrix.o art.o calc.o cg.o em.o eval.o imgtools.o iradon.o it.o itreadargs.o misc.o oradLI.o oradNN.o oradSINC.o sparse.o -LC:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/lib/x64 -LC:/RBuildTools/4.2/x86_64-w64-mingw32.static.posix/lib -LC:/PROGRA~1/R/R-42~1.1/bin/x64 -lR
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x610): multiple definition of `DebugNiveau'; iradon.o:iradon.c:(.data+0x0): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x480): multiple definition of `IniFile'; iradon.o:iradon.c:(.bss+0x0): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x598): multiple definition of `multtemp'; iradon.o:iradon.c:(.bss+0x118): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x5a0): multiple definition of `LogFileName'; iradon.o:iradon.c:(.bss+0x120): first defined here
C:\RBuildTools\4.2\x86_64-w64-mingw32.static.posix\bin/ld.exe: it.o:it.c:(.bss+0x608): multiple definition of `LogFile'; iradon.o:iradon.c:(.bss+0x188): first defined here
collect2.exe: error: ld returned 1 exit status
no DLL was created
ERROR: compilation failed for package 'PET'
* removing 'C:/Users/andyk/AppData/Local/R/win-library/4.2/PET'
Warning in install.packages :
  패키지 ‘C:/Users/andyk/Downloads/PET_0.5.1.tar.gz’의 설치가 0이 아닌 종료상태를 가졌습니다

I need the package PET to install gitter and DeadOrAlive. I've tried manually installing with tar. file for PET, using install.packages, and other versions of the package, but none of the methods worked.

Is it not possible to install the package at all, or are there other ways of installing PET to download the subsequent packages.


问:
How to prepare the input for T-SNE transform in pandas?
I am trying to visualize my dataset (which is stored as a Pandas DataFrame) using T-SNE with the following code:

```<code>N = 10000
df_subset = df.sample(n=N, random_state=1)
data_subset = df_subset.values
tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)
tsne_results = tsne.fit_transform(data_subset)
</code>```

However, this gives the following error: "ValueError: setting an array element with a sequence." for the last line of the code above.

The variable data_subset looks like this:

I also tried df_subset.to_numpy() as well, which gave the same error. A single element of the array data_subset looks like this:

Body:
I am trying to visualize my dataset (which is stored as a Pandas DataFrame) using T-SNE with the following code:

N = 10000
df_subset = df.sample(n=N, random_state=1)
data_subset = df_subset.values
tsne = TSNE(n_components=2, verbose=1, perplexity=40, n_iter=300)
tsne_results = tsne.fit_transform(data_subset)

However, this gives the following error: "ValueError: setting an array element with a sequence." for the last line of the code above.

The variable data_subset looks like this:

I also tried df_subset.to_numpy() as well, which gave the same error. A single element of the array data_subset looks like this: