问:
the cdef() gets definition of struct but the wrapper still throws ffi.error of undefined struct/union name
I have a problem in a bigger project but I managed to isolate it into a smallest possible example. Please take a look.

The def.c file that contains a definition of a struct

typedef struct {
  unsigned char data[64];
} somestruct;
```
<p>a <code>build.py</code> file that builds the cffi wrapper</p>
<pre class="lang-py prettyprint-override"><code>import os

from cffi import FFI, VerificationError

basepath = os.path.abspath(os.path.dirname(__file__))

ffi = FFI()

# the def.c is both header and source
with open(basepath + '/def.c', 'rt') as fid:
    _source = fid.read()
    ffi.cdef(_source)

ffi.set_source(
    "some_examples",
    _source,
    extra_compile_args=['-g']
)

ffi.compile()
</code>```

the file run.py that attempts to instantiate an empty struct

from some_examples import ffi, lib

ffi.new('struct somestruct *')
```
<p>How to run</p>
<pre class="lang-bash prettyprint-override"><code>python build.py
python run.py
</code>```

what I get

```<code>Traceback (most recent call last):
  File "run.py", line 3, in <module>
    ffi.new('struct somestruct *')
ffi.error: undefined struct/union name
struct somestruct *
       ^
</code>```

I researched it a bit, this answer was helpful but it indicated that definition must be in cdef() which is the case here. Anyone has some ideas why is somestruct undefined?

Body:
I have a problem in a bigger project but I managed to isolate it into a smallest possible example. Please take a look.

The def.c file that contains a definition of a struct

typedef struct {
  unsigned char data[64];
} somestruct;

a build.py file that builds the cffi wrapper

import os

from cffi import FFI, VerificationError

basepath = os.path.abspath(os.path.dirname(__file__))

ffi = FFI()

# the def.c is both header and source
with open(basepath + '/def.c', 'rt') as fid:
    _source = fid.read()
    ffi.cdef(_source)

ffi.set_source(
    "some_examples",
    _source,
    extra_compile_args=['-g']
)

ffi.compile()

the file run.py that attempts to instantiate an empty struct

from some_examples import ffi, lib

ffi.new('struct somestruct *')

How to run

python build.py
python run.py

what I get

Traceback (most recent call last):
  File "run.py", line 3, in <module>
    ffi.new('struct somestruct *')
ffi.error: undefined struct/union name
struct somestruct *
       ^

I researched it a bit, this answer was helpful but it indicated that definition must be in cdef() which is the case here. Anyone has some ideas why is somestruct undefined?


来源: stackexchange

问:
How to make video responsive like Image component of react?
I'm facing a strange problem while setting width and height of the video tag. I'm using Image component (from next/image), which is setting its height automatically.

It always shows height of 413px even if I use image with 150x150 dimensions. I'm not seeing any absolute height rule in CSS inspector even for parent elements or this Image component.

Actually it is the desired behavior (width/height) of the Image. I'm trying to do the same thing with the video tag. But it shrinks itself down to actual height of the video if video is smaller in height.

Video should not change it's height because it shares same CSS properties and has same container as Image. I'm also using object-fit:cover property.

Code for the component is:

```<code>import React, { useState } from 'react';
import Image from 'next/image';
import { IExclusiveCard } from '../../../typings/types';
import Link from 'next/link';
import useNFTMetadata from '../../../hooks/useNftMetaData';
import { BsFillPlayFill, BsPauseFill } from 'react-icons/bs';

const ExclusiveCard: React.FC<IExclusiveCard> = ({
  id,
  photo_name,
  metadataUri,
  cardInfo,
  cardType,
  cardInfoBg,
  title,
  desc,
  collectionType,
  asset_url,
  thumbnail,
}) => {
  let { data } = useNFTMetadata(metadataUri as string);

  if (!metadataUri?.trim() && thumbnail && asset_url) {
    data = {
      asset_url,
      thumbnail,
    };
  }
  const [videoPaused, setVideoPaused] = useState(true);

  let href = '';

  if (collectionType === 'continuous') {
    href = `/exclusives/${id}/auction`;
  } else if (collectionType === 'editions') {
    href = `/editions/${id}/mint`;
  }

  const image = data?.thumbnail || data?.image || photo_name;
  const description = desc || data?.description || '';

  return (
    <Link href={href}>
      <a className='h-full block'>
        <div
          className="token-card--items h-full w-[382px] md:w-full md:min-w-[216px] md:max-w-[216px] md:h-[317px] lg:w-[290px] laptop-x:w-[300px] laptop-m:w-[350px] desktop-m:w-[350px] rounded-3xl overflow-hidden bg-primary lg:rounded-2xl"
          key={id}
        >
          <div className="token-img-cont-box h-full relative">
            <div className="tokens-img-wrap h-full relative">
              <div className="exclusive--card-img h-full w-full relative md:h-[317px]">
                {/* If thumbnail exists, show video instead of an image  */}

                {!videoPaused && data?.asset_url ? (
                  <video
                    style={{
                      height: '100%',
                      objectFit: 'cover',
                    }}
                    src={data?.asset_url}
                    autoPlay
                    loop
                    muted
                    onEnded={() => setVideoPaused(true)}
                  />
                ) :
                image ? (
                  <Image
                    // src={image}
                    src={"https://picsum.photos/id/1/150/150"}
                    alt="tokens-card-img"
                    className="token-card-img h-full w-full object-cover"
                    width="382px"
                    height="520px"
                  />
                ) : (
                  <div className="slim-nft-card-placeholder-bg rounded-[20px]"></div>
                )}
              </div>
              <div className="tokens-card-top-cont flex justify-end items-start absolute top-0 left-0 p-5 w-full md:p-2">
                <span
                  className={[
                    'card-updates-info  text-fig-15 uppercase text-secondary block  text-center font-primary font-normal rounded-[100%] w-[62px] h-[62px] leading-[62px] laptop-x:text-fig-12 laptop-x:w-[45px] laptop-x:h-[45px] laptop-x:leading-[45px] lg:w-[36px] lg:h-[36px] lg:text-fig-xs lg:leading-[36px]',
                    `bg-${cardInfoBg}`,
                  ].join(' ')}
                >
                  {cardInfo}
                </span>
              </div>
              <div className="token-card-content-box pt-[13px] pb-4 px-6 absolute bottom-0 left-0 z-50 lg:px-4 w-full">
                <h3 className="card-title font-primary font-normal text-fig-32 text-left text-secondary uppercase mb-4  laptop-x:text-fig-24 lg:text-fig-base lg:mb-2">
                  {title || data?.properties?.title}
                </h3>
                <p className="desc mb-8 text-fig-xs text-left text-secondary font-primary font-normal md:text-fig-xs md:mb-2">
                  {/* Truncate desc or data?.description if it is greater than 30 characters */}
                  {description.length > 50
                    ? description.slice(0, 50) + '...'
                    : description}
                </p>
                <div
                  className={`token-cards-bottom flex ${
                    data?.thumbnail ? 'justify-between' : 'justify-end'
                  } w-full`}
                >
                  {data?.thumbnail && (
                    <h3 className="card-type font-primary font-normal text-fig-32 text-right laptop-x:text-fig-24 text-white uppercase lg:text-fig-15 lg:mb-0">
                      {videoPaused ? (
                        <BsFillPlayFill
                          onClick={(ev) => {
                            ev.preventDefault();
                            setVideoPaused(false);
                          }}
                          className="text-4xl"
                        />
                      ) : (
                        <BsPauseFill
                          onClick={(ev) => {
                            ev.preventDefault();
                            setVideoPaused(true);
                          }}
                          className="text-4xl"
                        />
                      )}
                    </h3>
                  )}
                  <h3 className="card-type font-primary font-normal text-fig-32 text-right laptop-x:text-fig-24 text-darkgray uppercase lg:text-fig-15 lg:mb-0">
                    {cardType}
                  </h3>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a>
    </Link>
  );
};

export default ExclusiveCard;

</code>```

I'm not sure what I'm missing here. What should I do to get same size of video like Image when I click play icon?

ContentLicense: CC BY-SA 4.0

Body:
I'm facing a strange problem while setting width and height of the video tag. I'm using Image component (from next/image), which is setting its height automatically.

It always shows height of 413px even if I use image with 150x150 dimensions. I'm not seeing any absolute height rule in CSS inspector even for parent elements or this Image component.

Actually it is the desired behavior (width/height) of the Image. I'm trying to do the same thing with the video tag. But it shrinks itself down to actual height of the video if video is smaller in height.

Video should not change it's height because it shares same CSS properties and has same container as Image. I'm also using object-fit:cover property.

Code for the component is:

import React, { useState } from 'react';
import Image from 'next/image';
import { IExclusiveCard } from '../../../typings/types';
import Link from 'next/link';
import useNFTMetadata from '../../../hooks/useNftMetaData';
import { BsFillPlayFill, BsPauseFill } from 'react-icons/bs';

const ExclusiveCard: React.FC<IExclusiveCard> = ({
  id,
  photo_name,
  metadataUri,
  cardInfo,
  cardType,
  cardInfoBg,
  title,
  desc,
  collectionType,
  asset_url,
  thumbnail,
}) => {
  let { data } = useNFTMetadata(metadataUri as string);

  if (!metadataUri?.trim() && thumbnail && asset_url) {
    data = {
      asset_url,
      thumbnail,
    };
  }
  const [videoPaused, setVideoPaused] = useState(true);

  let href = '';

  if (collectionType === 'continuous') {
    href = `/exclusives/${id}/auction`;
  } else if (collectionType === 'editions') {
    href = `/editions/${id}/mint`;
  }

  const image = data?.thumbnail || data?.image || photo_name;
  const description = desc || data?.description || '';

  return (
    <Link href={href}>

                {/* If thumbnail exists, show video instead of an image  */}

                {!videoPaused && data?.asset_url ? (
                  <video
                    style={{
                      height: '100%',
                      objectFit: 'cover',
                    }}
                    src={data?.asset_url}
                    autoPlay
                    loop
                    muted
                    onEnded={() => setVideoPaused(true)}
                  />
                ) :
                image ? (
                  <Image
                    // src={image}
                    src={"https://picsum.photos/id/1/150/150"}
                    alt="tokens-card-img"
                    className="token-card-img h-full w-full object-cover"
                    width="382px"
                    height="520px"
                  />
                ) : (

                )}

                <span
                  className={[
                    'card-updates-info  text-fig-15 uppercase text-secondary block  text-center font-primary font-normal rounded-[100%] w-[62px] h-[62px] leading-[62px] laptop-x:text-fig-12 laptop-x:w-[45px] laptop-x:h-[45px] laptop-x:leading-[45px] lg:w-[36px] lg:h-[36px] lg:text-fig-xs lg:leading-[36px]',
                    `bg-${cardInfoBg}`,
                  ].join(' ')}
                >
                  {cardInfo}

                  {title || data?.properties?.title}

                  {/* Truncate desc or data?.description if it is greater than 30 characters */}
                  {description.length > 50
                    ? description.slice(0, 50) + '...'
                    : description}

                  {data?.thumbnail && (

                      {videoPaused ? (
                        <BsFillPlayFill
                          onClick={(ev) => {
                            ev.preventDefault();
                            setVideoPaused(false);
                          }}
                          className="text-4xl"
                        />
                      ) : (
                        <BsPauseFill
                          onClick={(ev) => {
                            ev.preventDefault();
                            setVideoPaused(true);
                          }}
                          className="text-4xl"
                        />
                      )}

                  )}

                    {cardType}

    </Link>
  );
};

export default ExclusiveCard;

I'm not sure what I'm missing here. What should I do to get same size of video like Image when I click play icon?


问:
Azure APIM Validate-JWT policy not working with Bearer scheme on custom header?
I have declared the following policy:

```<code><validate-jwt header-name="MyCustomHeader" failed-validation-httpcode="401" require-expiration-time="true" require-scheme="Bearer" require-signed-tokens="true">
   <openid-config url="https://mytentant over here" />
</validate-jwt>
</code>```

The problem is that I always get an error if I my request contains the Bearer keyword before the actual token... if I send the token plain and simple, it works!

Also, if instead of using MyCustomHeader I use the "official" Authorization header, the behavior switches back and the Bearer keyword becomes mandatory

Body:
I have declared the following policy:

<validate-jwt header-name="MyCustomHeader" failed-validation-httpcode="401" require-expiration-time="true" require-scheme="Bearer" require-signed-tokens="true">
   <openid-config url="https://mytentant over here" />
</validate-jwt>

The problem is that I always get an error if I my request contains the Bearer keyword before the actual token... if I send the token plain and simple, it works!

Also, if instead of using MyCustomHeader I use the "official" Authorization header, the behavior switches back and the Bearer keyword becomes mandatory


问:
Create Read-Only MongoDB container read data of the existing MongoDB container
I have running MongoDB as Docker container. Now I want to create one more MongoDB container but read-only and read data from the existing one.

What should I do? I don't use Docker Swarm mode!

I want to have 2 MongoDB container run, the existing is keep running, the new one is read-only and read data from the existing container.

Thanks for reading!


问:
Operands could not be broadcast together with shapes
```<code>data = pd.read_csv('./Book1.csv')
# Read the edgelist of the Wiki Talk network
G = nx.from_pandas_edgelist(data, data.columns[0], data.columns[1])
G = G.subgraph(max(nx.connected_components(G), key=len))
</code>```

ic_seed_set = np.random.choice(G.nodes(), ic_seed_set_size)

Determine the model parameter

ic_threshold = 0.4
g = Graph([[u,v] for (u,v) in G.edges])
def IC(g,S,ic_threshold,ic_num_steps):
"""
Input:  graph object, set of seed nodes, propagation probability
and the number of Monte-Carlo simulations
Output: average number of nodes influenced by the seed nodes
"""

```<code># Loop over the Monte-Carlo Simulations
spread = []
for i in range(ic_num_steps):

    # Simulate propagation process
    new_active, A = S[:], S[:]
    for i in range(len(new_active)) :

        # For each newly active node, find its neighbors that become activated
        new_ones = []
        for node in new_active:

            # Determine neighbors that become infected
            np.random.seed(i)
            success = np.random.uniform(0,1,len(g.neighbors(node,mode="out"))) < ic_threshold
            new_ones += list(np.extract(success, g.neighbors(node,mode="out")))

        new_active = list(set(new_ones) - set(A))

        # Add newly activated nodes to the set of activated nodes
        A = A + new_active

    spread.append(len(A))

return(np.mean(spread))
</code>```

modelpropagation =IC(g,ic_seed_set,ic_threshold,ic_num_steps)

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

i expected list of integer
but in this line >>>   A = A + new_active

```<code>
<ipython-input-24-fc67faf2ae99> in IC(g, S, ic_threshold, ic_num_steps)
     61
     62             # Add newly activated nodes to the set of activated nodes
---> 63             A = A + new_active
     64
     65         spread.append(len(A))

ValueError: operands could not be broadcast together with shapes (5,) (492,)
</code>```

Body:
data = pd.read_csv('./Book1.csv')
# Read the edgelist of the Wiki Talk network
G = nx.from_pandas_edgelist(data, data.columns[0], data.columns[1])
G = G.subgraph(max(nx.connected_components(G), key=len))

ic_seed_set = np.random.choice(G.nodes(), ic_seed_set_size)

Determine the model parameter

ic_threshold = 0.4
g = Graph([[u,v] for (u,v) in G.edges])
def IC(g,S,ic_threshold,ic_num_steps):
"""
Input:  graph object, set of seed nodes, propagation probability
and the number of Monte-Carlo simulations
Output: average number of nodes influenced by the seed nodes
"""

# Loop over the Monte-Carlo Simulations
spread = []
for i in range(ic_num_steps):

    # Simulate propagation process
    new_active, A = S[:], S[:]
    for i in range(len(new_active)) :

        # For each newly active node, find its neighbors that become activated
        new_ones = []
        for node in new_active:

            # Determine neighbors that become infected
            np.random.seed(i)
            success = np.random.uniform(0,1,len(g.neighbors(node,mode="out"))) < ic_threshold
            new_ones += list(np.extract(success, g.neighbors(node,mode="out")))

        new_active = list(set(new_ones) - set(A))

        # Add newly activated nodes to the set of activated nodes
        A = A + new_active

    spread.append(len(A))

return(np.mean(spread))

modelpropagation =IC(g,ic_seed_set,ic_threshold,ic_num_steps)

i expected list of integer
but in this line >>>   A = A + new_active

<ipython-input-24-fc67faf2ae99> in IC(g, S, ic_threshold, ic_num_steps)
     61
     62             # Add newly activated nodes to the set of activated nodes
---> 63             A = A + new_active
     64
     65         spread.append(len(A))

ValueError: operands could not be broadcast together with shapes (5,) (492,)


问:
How to create a function in jS using Github Copilot and running that function in VS Code (OsX)
This is sort of a two-part question. I'm trying to play around with Copilot and used the beginners tutorial to reproduce the code which looks like this.

```<code>// find all images without alternate text
// and give them a red border
function process() {
    var images = "cat_pics.html".getElementsByTagName("img")
    for (var i = 0; i < images.length; i++) {
        var image = images[i]
        if (image.alt == "") {
            image.style.border = "1px solid red"
        }
    }
}
</code>```

There was only one change which was that changed the source of images to a local file.

However I ran this I received an error.

[Running] node "/Users/davidelks/Dropbox/Personal/tempCodeRunnerFile.js"
/bin/sh: node: command not found

```<code>[Done] exited with code=127 in 0.008 seconds
</code>```

The second question is specific to VS Code having switched to it from Sublime. I can see there are powerful tools but how would the debugger to get to the problem?

Body:
This is sort of a two-part question. I'm trying to play around with Copilot and used the beginners tutorial to reproduce the code which looks like this.

// find all images without alternate text
// and give them a red border
function process() {
    var images = "cat_pics.html".getElementsByTagName("img")
    for (var i = 0; i < images.length; i++) {
        var image = images[i]
        if (image.alt == "") {
            image.style.border = "1px solid red"
        }
    }
}

There was only one change which was that changed the source of images to a local file.

However I ran this I received an error.

[Running] node "/Users/davidelks/Dropbox/Personal/tempCodeRunnerFile.js"
/bin/sh: node: command not found

[Done] exited with code=127 in 0.008 seconds

The second question is specific to VS Code having switched to it from Sublime. I can see there are powerful tools but how would the debugger to get to the problem?


问:
Freecodecamp execrise tracker unable to fetch date from data base
Unaable to fetch data from get request : /api/users/:_id/logs
url passed to this request : https://boilerplate-project-exercisetracker.sushilgupta4.repl.co/api/users/63a42aa0beed29d45418f2d5/logs?from=2022-10-10&to=2022-12-30&limit=2

link to my project : https://replit.com/@SushilGupta4/boilerplate-project-exercisetracker

As when I save the data for exercise for particular user the date is saved in the format of 2022-11-05T00:00:00.000+00:00.
But When I recevice date from the user request then convert date to new Date(date) and date is converted in the format of 2022-10-10T00:00:00.000Z

I think if able to change format of either one my code will work. Please look into to code and please tell me how can solve this problem.

This is the project from freecodecamp which i need complete in order to get back-end certificate.
https://www.freecodecamp.org/learn/back-end-development-and-apis/back-end-development-and-apis-projects/exercise-tracker

```<code>const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
require('dotenv').config()

try {
  mongoose.connect(process.env.MANGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
  console.log('db connected')
} catch (err) {
  console.log(err)
}

const personSchema = new mongoose.Schema({
  username: {
    type: String,
    require: [true, 'username must be provided'],
    unique: true
  },
})

const exerciseSchema = new mongoose.Schema({
  userId: {
    type: String,
    require: [true, 'userId must be provided']
  },
  username: {
    type: String,
    require: [true, 'username must be provided']
  },
  description: {
    type: String,
    require: [true, 'desc must be provided']
  },
  duration: {
    type: Number,
    require: [true, 'Duration must be provided']
  },
  date: {
    type: String,
    require: [true, 'date must be provided']
  },
})

const Person = mongoose.model("Person", personSchema)
const Exercise = mongoose.model("Exercise", exerciseSchema)

app.use(cors())
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

app.post('/api/users', function(req, res) {
  const username = req.body.username
  const data = new Person({ username: username })
  data.save((err, data) => {
    if (err) {
      res.json("username already Taken")
    } else {
      res.json({ username: data.username, _id: data._id })
    }
  })

})

app.get('/api/users', (req, res) => {
  Person.find({}, (err, data) => {
    if (!data) {
      res.send("No user")
    } else {
      res.json(data)
    }
  })
})

app.post('/api/users/:_id/exercises', (req, res) => {
  const _id = req.body[':_id']
  const { description, duration, date } = req.body

  console.log(new Date(date).toISOString())
  let formatDate = new Date(date).toISOString()
  console.log("format date" + formatDate)

  Person.findById(_id, (err, data) => {
    if (!data) {
      res.send("User Not found")
    } else {
      const username = data.username
      const addExercise = new Exercise({ userId: _id, username, description, duration, date: formatDate })
      addExercise.save((err, user) => {
        if (err) console.log(err)
        res.json({ username: username, description: user.description, duration: user.duration, date: user.date.toDateString, _id })
      })
    }
  })
})

app.get('/api/users/:_id/logs', (req, res) => {
  const userId = req.params._id
  const _id = userId
  let { from, to, limit } = req.query

  let filter = { userId }
  let dateFilter = {}
  if (from) {
    from = new Date(from)
    from = from.slice(23)
    dateFilter['&gte'] = from
    console.log(from)
  }
  if (to) {
    dateFilter['&lte'] = new Date(to)
  }
  if (from || to) {
    filter.date = dateFilter
  }

  console.log(filter)
  Person.findById({ _id }, (err, data) => {
    if (!data) {
      res.send("userId not found")
    } else {
      console.log("found the id user")
      const username = data.username
      //{date: {$gte: new Date(from), $lte:new Date (to)}}
      Exercise.find(filter).limit(limit).exec((err, data) => {
        console.log("found user exericse")
        if (err) console.log(err)
        //console.log(data)
        let customdata = data.map(items => {
          let formattedDate = new Date(items.date).toDateString()
          return { description: items.description, duration: items.duration, date: formattedDate }
        })
        if (!data) {
          res.json({
            "_id": userId,
            "username": username,
            "count": 0,
            "log": []
          })
        } else {
          console.log("inside")
          res.json({
            "_id": userId,
            "username": username,
            "count": data.length,
            "log": customdata
          })
        }

      })
    }
  })
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

</code>```

I was expecting how can i fetch the data from that get request or how can i change the date format.

Body:
Unaable to fetch data from get request : /api/users/:_id/logs
url passed to this request : https://boilerplate-project-exercisetracker.sushilgupta4.repl.co/api/users/63a42aa0beed29d45418f2d5/logs?from=2022-10-10&to=2022-12-30&limit=2

link to my project : https://replit.com/@SushilGupta4/boilerplate-project-exercisetracker

As when I save the data for exercise for particular user the date is saved in the format of 2022-11-05T00:00:00.000+00:00.
But When I recevice date from the user request then convert date to new Date(date) and date is converted in the format of 2022-10-10T00:00:00.000Z

I think if able to change format of either one my code will work. Please look into to code and please tell me how can solve this problem.

This is the project from freecodecamp which i need complete in order to get back-end certificate.
https://www.freecodecamp.org/learn/back-end-development-and-apis/back-end-development-and-apis-projects/exercise-tracker

const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
require('dotenv').config()

try {
  mongoose.connect(process.env.MANGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
  console.log('db connected')
} catch (err) {
  console.log(err)
}

const personSchema = new mongoose.Schema({
  username: {
    type: String,
    require: [true, 'username must be provided'],
    unique: true
  },
})

const exerciseSchema = new mongoose.Schema({
  userId: {
    type: String,
    require: [true, 'userId must be provided']
  },
  username: {
    type: String,
    require: [true, 'username must be provided']
  },
  description: {
    type: String,
    require: [true, 'desc must be provided']
  },
  duration: {
    type: Number,
    require: [true, 'Duration must be provided']
  },
  date: {
    type: String,
    require: [true, 'date must be provided']
  },
})

const Person = mongoose.model("Person", personSchema)
const Exercise = mongoose.model("Exercise", exerciseSchema)

app.use(cors())
app.use(express.static('public'))
app.use(express.urlencoded({ extended: true }))

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/views/index.html')
});

app.post('/api/users', function(req, res) {
  const username = req.body.username
  const data = new Person({ username: username })
  data.save((err, data) => {
    if (err) {
      res.json("username already Taken")
    } else {
      res.json({ username: data.username, _id: data._id })
    }
  })

})

app.get('/api/users', (req, res) => {
  Person.find({}, (err, data) => {
    if (!data) {
      res.send("No user")
    } else {
      res.json(data)
    }
  })
})

app.post('/api/users/:_id/exercises', (req, res) => {
  const _id = req.body[':_id']
  const { description, duration, date } = req.body

  console.log(new Date(date).toISOString())
  let formatDate = new Date(date).toISOString()
  console.log("format date" + formatDate)

  Person.findById(_id, (err, data) => {
    if (!data) {
      res.send("User Not found")
    } else {
      const username = data.username
      const addExercise = new Exercise({ userId: _id, username, description, duration, date: formatDate })
      addExercise.save((err, user) => {
        if (err) console.log(err)
        res.json({ username: username, description: user.description, duration: user.duration, date: user.date.toDateString, _id })
      })
    }
  })
})

app.get('/api/users/:_id/logs', (req, res) => {
  const userId = req.params._id
  const _id = userId
  let { from, to, limit } = req.query

  let filter = { userId }
  let dateFilter = {}
  if (from) {
    from = new Date(from)
    from = from.slice(23)
    dateFilter['&gte'] = from
    console.log(from)
  }
  if (to) {
    dateFilter['&lte'] = new Date(to)
  }
  if (from || to) {
    filter.date = dateFilter
  }

  console.log(filter)
  Person.findById({ _id }, (err, data) => {
    if (!data) {
      res.send("userId not found")
    } else {
      console.log("found the id user")
      const username = data.username
      //{date: {$gte: new Date(from), $lte:new Date (to)}}
      Exercise.find(filter).limit(limit).exec((err, data) => {
        console.log("found user exericse")
        if (err) console.log(err)
        //console.log(data)
        let customdata = data.map(items => {
          let formattedDate = new Date(items.date).toDateString()
          return { description: items.description, duration: items.duration, date: formattedDate }
        })
        if (!data) {
          res.json({
            "_id": userId,
            "username": username,
            "count": 0,
            "log": []
          })
        } else {
          console.log("inside")
          res.json({
            "_id": userId,
            "username": username,
            "count": data.length,
            "log": customdata
          })
        }

      })
    }
  })
})

const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

I was expecting how can i fetch the data from that get request or how can i change the date format.


问:
Error in constexpr' expansion of 'shader.base::BasicStringPiece<char>::remove_prefix(6)'
```<code>constexpr base::StringPiece StripLambda(base::StringPiece shader) {
  // Must contain at least "[]() {}".
  DCHECK_EQ(shader.substr(0, 6), "[]() {");
  DCHECK_EQ(shader.back(), '}');
  shader.remove_prefix(6);
  shader.remove_suffix(1);

  return shader;
}
</code>```

chromium94/src/components/viz/service/display/shader.cc:29:23: in 'constexpr' expansion of 'shader.base::BasicStringPiece::remove_prefix(6)'
chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type  = 0]' called in a constant expression

chromium94/src/base/check_op.h:184:38: error: call to non-'constexpr' function 'logging::CheckOpResult::CheckOpResult(const char*, char*, char*)'

chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type  = 0]' called in a constant expression

Can anyone help with work around solution?

Can anyone help with work around solution?

Body:
constexpr base::StringPiece StripLambda(base::StringPiece shader) {
  // Must contain at least "[]() {}".
  DCHECK_EQ(shader.substr(0, 6), "[]() {");
  DCHECK_EQ(shader.back(), '}');
  shader.remove_prefix(6);
  shader.remove_suffix(1);

  return shader;
}

chromium94/src/components/viz/service/display/shader.cc:29:23: in 'constexpr' expansion of 'shader.base::BasicStringPiece::remove_prefix(6)'
chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type  = 0]' called in a constant expression

chromium94/src/base/check_op.h:184:38: error: call to non-'constexpr' function 'logging::CheckOpResult::CheckOpResult(const char*, char*, char*)'

chromium94/src/base/check_op.h:157:41: error: 'constexpr logging::CheckOpResult logging::CheckLEImpl(T, U, const char*) [with T = unsigned int; U = unsigned int; typename std::enable_if<(std::is_fundamental<_Tp>::value && std::is_fundamental::value), int>::type  = 0]' called in a constant expression

Can anyone help with work around solution?

Can anyone help with work around solution?


问:
Get values from dynamic dropdown values and show them in a delimited text box on each new dynamic row that is generated in php and jquery
I have a table in which there is a row. The first cell of the row contains a drop-down list, and other rows are generated dynamically in case of an argument. The drop-down list contains an option with two fields from the database, one of which is text and the other is a number. The two are linked to each other. The problem that I am stuck with is that in the table The text and its associated number from the database appear only in the first row in the table, I want to repeat this in the table in the rest of the dynamically generated rows, that each text and its associated value appear in the drop down list

The problem in the image

php code:
`

```<code><td class="td"><select class="form-control select_acount" name="account[]"required>
                            <option value="">--الحساب--</option>
                            <?php
                            $query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
                            $result = mysqli_query($con,$query);
                            $data = array();
                            if($result)
                            {
                              while($row = mysqli_fetch_assoc($result)){
                              $data[] = $row;
                            ?>
                            <?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
                            <?php
                            }
                            } else{
                            }
                            ?>
                            </select>
                          </td>
</code>```

jquery code:

```<code>$('.select_acount').on('change', function() {
   $(this).closest('tr').find('.mount').val($(this).val());
});
</code>```

```<code>var data = <?php echo json_encode($data); ?>;
      var product_dd = "";
          product_dd += '<select class="form-control select_acount" name="account[]"required>';
          product_dd += '<option value="">--الحساب--</option>';
      if(data.length > 0){
        for(let i = 0; i < data.length; i ++) {
          product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
        }
      }
         product_dd += "</select>";

      var i = 0;
      $("#add-btn").click(function() {
        ++i;

        $("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text"  name="description[' + i + ']" class="form-control"  required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount"required></td><td class="td2"><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash" ></i></button></td></tr>');
      });
      $(document).on('click', '.remove-tr', function() {
        $(this).parents('tr').remove();
      });
</code>```

`

Body:
I have a table in which there is a row. The first cell of the row contains a drop-down list, and other rows are generated dynamically in case of an argument. The drop-down list contains an option with two fields from the database, one of which is text and the other is a number. The two are linked to each other. The problem that I am stuck with is that in the table The text and its associated number from the database appear only in the first row in the table, I want to repeat this in the table in the rest of the dynamically generated rows, that each text and its associated value appear in the drop down list

The problem in the image

php code:
`

<select class="form-control select_acount" name="account[]"required>
                            <option value="">--الحساب--</option>
                            <?php
                            $query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
                            $result = mysqli_query($con,$query);
                            $data = array();
                            if($result)
                            {
                              while($row = mysqli_fetch_assoc($result)){
                              $data[] = $row;
                            ?>
                            <?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
                            <?php
                            }
                            } else{
                            }
                            ?>
                            </select>

jquery code:

$('.select_acount').on('change', function() {
   $(this).closest('tr').find('.mount').val($(this).val());
});

var data = <?php echo json_encode($data); ?>;
      var product_dd = "";
          product_dd += '<select class="form-control select_acount" name="account[]"required>';
          product_dd += '<option value="">--الحساب--</option>';
      if(data.length > 0){
        for(let i = 0; i < data.length; i ++) {
          product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
        }
      }
         product_dd += "</select>";

      var i = 0;
      $("#add-btn").click(function() {
        ++i;

        $("#dynamicAddRemove").append('
'+product_dd+'	 <input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required>	 <input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required>	 <input type="text"  name="description[' + i + ']" class="form-control"  required>	  <input type="text" name="mount[' + i + ']" class="form-control mount"required>	<button type="button" name="add" class="btn btn-danger remove-tr"></button>
');
      });
      $(document).on('click', '.remove-tr', function() {
        $(this).parents('tr').remove();
      });

`


问:
If we using upi://pay?pa=upiid@sbi&pn=JOHN BRITAS AK &cu=INR" class="upi-pay1" then App showing unsafe
IF I am using upi://pay?pa=upiid@sbi&pn=JOHN BRITAS AK &cu=INR" class="upi-pay1" to invoke Upi App for Payment, then Payment supported App Showing unsafe Payment and decline that payment.
What should I do about this?

Hey, IF I am using upi://pay?pa=upiid@sbi&pn=JOHN BRITAS AK &cu=INR" class="upi-pay1" to invoke Upi App for Payment, then Payment supported App Showing unsafe Payment and decline that payment.
What should I do about this?


问:
running Service Swagger error " TypeError: Failed to fetch"
I

I have a Asp.Net Core MVC Api, and published as a Windows Service. I have installed the Service locally and tried to run it from Chrome or Vista like this

```<code>http://localhost:5000/swagger/index.html
</code>```

When I execute an Api Endpoint

I have this error

```<code>Failed to fetch.
Possible Reasons:

CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
</code>```

This service has been deployed in several laptop without problems, but I am the only who has problems.. I do not think it is a problem in the Api, though I did some changes following every example I found.

I added in my program.cs

```<code>builder.Services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
                      builder =>
                      {
                          builder.AllowAnyOrigin()
                                 .AllowAnyMethod()
                                 .AllowAnyHeader();
                      }));

.........

app.UseCors("AllowAllOrigins");
</code>```

But still have the same problem.

I do not think it is a Cors or Service problem.

What could be the problem?

Thanks

Body:
I

I have a Asp.Net Core MVC Api, and published as a Windows Service. I have installed the Service locally and tried to run it from Chrome or Vista like this

http://localhost:5000/swagger/index.html

When I execute an Api Endpoint

I have this error

Failed to fetch.
Possible Reasons:

CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.

This service has been deployed in several laptop without problems, but I am the only who has problems.. I do not think it is a problem in the Api, though I did some changes following every example I found.

I added in my program.cs

builder.Services.AddCors(o => o.AddPolicy("AllowAnyOrigin",
                      builder =>
                      {
                          builder.AllowAnyOrigin()
                                 .AllowAnyMethod()
                                 .AllowAnyHeader();
                      }));

.........

app.UseCors("AllowAllOrigins");

But still have the same problem.

I do not think it is a Cors or Service problem.

What could be the problem?

Thanks


问:
How to draw NSAttributedString with .background attributes and insets?
I need to draw in CALayer subclass NSAttributedString with background for every line of text and insets(horizontal and vertical). How to do that?

I am trying this code. But, I can't set insets text insets.

```<code>override func draw(in ctx: CGContext) {
        if let attributedString = nsAttributedString {

            ctx.translateBy(x: 0, y: (bounds.size.height * 1.5) - (stringSize.height / 2))
            ctx.scaleBy(x: 1.0, y: -1.0)

            let path = CGMutablePath()
            path.addRect(bounds)

            let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
            let frame = CTFramesetterCreateFrame(framesetter,
                                                 CFRangeMake(0, attributedString.length),
                                                 path, nil)

            ctx.textMatrix = .identity
            ctx.textPosition = .zero

            CTFrameDraw(frame, ctx)
        }
    }
</code>```

Its should looks like this

Body:
I need to draw in CALayer subclass NSAttributedString with background for every line of text and insets(horizontal and vertical). How to do that?

I am trying this code. But, I can't set insets text insets.

override func draw(in ctx: CGContext) {
        if let attributedString = nsAttributedString {

            ctx.translateBy(x: 0, y: (bounds.size.height * 1.5) - (stringSize.height / 2))
            ctx.scaleBy(x: 1.0, y: -1.0)

            let path = CGMutablePath()
            path.addRect(bounds)

            let framesetter = CTFramesetterCreateWithAttributedString(attributedString)
            let frame = CTFramesetterCreateFrame(framesetter,
                                                 CFRangeMake(0, attributedString.length),
                                                 path, nil)

            ctx.textMatrix = .identity
            ctx.textPosition = .zero

            CTFrameDraw(frame, ctx)
        }
    }

Its should looks like this


问:
i can't close other windows
so i'm trying to make a question asker program that is connected to an access database and i'm having a problem i have a main window and i can't close other windows that i open after this is the code

```<code>import PySimpleGUI as sg
import pypyodbc
import random

sg.theme('darkgrey3')
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\FUAD\Documents\Database9.accdb;')
main_menu = [
    [sg.Text('PROJECT 1',pad=(70,40))],
    [sg.Button('Add question',size=(10,3),key=('add_question'))],
    [sg.Button('ask question',size=(10,3),key = ('-AskQuestion-'))],
    [sg.Button('see all the questions',size=(10,3),key='-SeeAllTheQuestions-')]
 ]

window = sg.Window('project',main_menu)
while True:
 cursor = conn.cursor()
 cursor.execute('select * from Questions')
 questionslist = cursor.fetchall()
 sg.theme('darkblue')

 def see_all_the_questions(delete, set):
     layout = [
         [sg.Text('What you want to do?', key='-text-'), sg.Push(), sg.Button('X', key='-Cancel*SeeQuestions-')],
         [sg.Button('delete', key='-delete-'), sg.Button('set the question', key='-set-'),
          sg.Button('Cancel', key='-cancel-', visible=False)],
         [sg.Listbox(questionslist, s=(50, 25), key='-listbox-', enable_events=True)]
     ]
     window = sg.Window('Question list', layout)

     while True:
         event, values = window.read()
         if event == sg.WIN_CLOSED:
             break
         if event == '-delete-':
             delete, set = True, False
             window['-cancel-'].update(visible=True)
         if event == '-cancel-':
             delete, set = False, False
             window['-cancel-'].update(visible=False)
         if event == '-set-':
             delete, set = False, True
             window['-cancel-'].update(visible=True)
         if event == '-listbox-' and delete == True:
             cursor.execute(f'DELETE FROM Questions WHERE ID in ({values[event][0][0]})')
             cursor.commit()
         if event == '-listbox-' and set == True:
             print('setted')
 **def add_question(question):
     sg.theme('darkbrown')
     layout = [
         [sg.Text('please enter your question'), sg.Push(), sg.Button('X', key='-Exit-')],
         [sg.Input(key='-input-'), sg.Button('-Enter-')],
         [sg.Text('Your question successfully added to questions!', key='sccful', visible=False)]
     ]
     window = sg.Window('question adder', layout)
     while True:
         event, values = window.read()
         if event == sg.WIN_CLOSED:
             break
         if event == '-Enter-' and values['-input-']!='':
             print(questionslist)
             print(questionslist[-1:][0])
             question = (questionslist[-1:][0][0]+1,values['-input-'])
             cursor.execute('''
                         INSERT INTO Questions VALUES(?,?)''',question)
             cursor.commit()
             break**

 event,values = window.read()
 if event == sg.WIN_CLOSED:
      break
 if event == '-SeeAllTheQuestions-':
     see_all_the_questions(False,False)
 if event == 'add_question':
     add_question('')
</code>```

in bold part of the code i'm trying to get information from user and when the user hits the enter i want to close that window but it just isn't what can i do

i tried to close the window

Title: i can't close other windows

Body:
so i'm trying to make a question asker program that is connected to an access database and i'm having a problem i have a main window and i can't close other windows that i open after this is the code

import PySimpleGUI as sg
import pypyodbc
import random

sg.theme('darkgrey3')
conn = pypyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\FUAD\Documents\Database9.accdb;')
main_menu = [
    [sg.Text('PROJECT 1',pad=(70,40))],
    [sg.Button('Add question',size=(10,3),key=('add_question'))],
    [sg.Button('ask question',size=(10,3),key = ('-AskQuestion-'))],
    [sg.Button('see all the questions',size=(10,3),key='-SeeAllTheQuestions-')]
 ]

window = sg.Window('project',main_menu)
while True:
 cursor = conn.cursor()
 cursor.execute('select * from Questions')
 questionslist = cursor.fetchall()
 sg.theme('darkblue')

 def see_all_the_questions(delete, set):
     layout = [
         [sg.Text('What you want to do?', key='-text-'), sg.Push(), sg.Button('X', key='-Cancel*SeeQuestions-')],
         [sg.Button('delete', key='-delete-'), sg.Button('set the question', key='-set-'),
          sg.Button('Cancel', key='-cancel-', visible=False)],
         [sg.Listbox(questionslist, s=(50, 25), key='-listbox-', enable_events=True)]
     ]
     window = sg.Window('Question list', layout)

     while True:
         event, values = window.read()
         if event == sg.WIN_CLOSED:
             break
         if event == '-delete-':
             delete, set = True, False
             window['-cancel-'].update(visible=True)
         if event == '-cancel-':
             delete, set = False, False
             window['-cancel-'].update(visible=False)
         if event == '-set-':
             delete, set = False, True
             window['-cancel-'].update(visible=True)
         if event == '-listbox-' and delete == True:
             cursor.execute(f'DELETE FROM Questions WHERE ID in ({values[event][0][0]})')
             cursor.commit()
         if event == '-listbox-' and set == True:
             print('setted')
 **def add_question(question):
     sg.theme('darkbrown')
     layout = [
         [sg.Text('please enter your question'), sg.Push(), sg.Button('X', key='-Exit-')],
         [sg.Input(key='-input-'), sg.Button('-Enter-')],
         [sg.Text('Your question successfully added to questions!', key='sccful', visible=False)]
     ]
     window = sg.Window('question adder', layout)
     while True:
         event, values = window.read()
         if event == sg.WIN_CLOSED:
             break
         if event == '-Enter-' and values['-input-']!='':
             print(questionslist)
             print(questionslist[-1:][0])
             question = (questionslist[-1:][0][0]+1,values['-input-'])
             cursor.execute('''
                         INSERT INTO Questions VALUES(?,?)''',question)
             cursor.commit()
             break**

 event,values = window.read()
 if event == sg.WIN_CLOSED:
      break
 if event == '-SeeAllTheQuestions-':
     see_all_the_questions(False,False)
 if event == 'add_question':
     add_question('')

in bold part of the code i'm trying to get information from user and when the user hits the enter i want to close that window but it just isn't what can i do

i tried to close the window


问:
How can I implement nested comments in a post of react-native same as facebook

How can I implement nested comments in a post of react-native same as
facebook

anyone if know the functionality or any git repo please share with me


问:
Click X, Y coordinates of any text in any image and click it
I'm trying to click text on the screen in any program, sometimes is in text format, sometimes image, and appearance varies (so pyautogui wasn't helpful) and I'm using pytesseract.  And I've got it working except that I can't find the dictionary entry.  Manually searching the dictionary content, I find it--so pytesseract is doing it's job.  But my for loop doesn't.  What am I doing wrong?

```<code>import time
from PIL import ImageGrab  # for taking screenshots
import pytesseract  # for OCR
from pytesseract import Output  # for specifying the output type of image_to_boxes
import pyautogui  # for clicking on the screen

# Set the path to the Tesseract OCR engine (needed for Windows)
pytesseract.pytesseract.tesseract_cmd = (r"C:\...\Tesseract-OCR\tesseract")

while True:  # loop indefinitely
    # Take a screenshot and convert it to grayscale
    screenshot = ImageGrab.grab()
    screenshot_gray = screenshot.convert('L')

    # Extract the bounding boxes for the text in the screenshot
    data = pytesseract.image_to_boxes(screenshot_gray, output_type=Output.DICT)

    # Print the contents of the data dictionary
    print(data)

    # Iterate through the bounding boxes
22  for i in range(len(data['text'])):
        # Check if the text of the current bounding box is "Hello World"
        if data['text'][i] == "Hello World":
            # Calculate the x and y coordinates of the center of the bounding box
            x = (data['left'][i] + data['right'][i]) / 2
            y = (data['top'][i] + data['bottom'][i]) / 2
            # Click the location
            pyautogui.click(x, y)
            print("Clicked at", x, y)
            break  # stop looping through the bounding boxes
</code>```

I receive the following error. But the "Hello World" was found by pytesseract and exists in the dictionary when I run it.

```<code>line 22, in <module>
    for i in range(len(data['text'])):
KeyError: 'text'
</code>```

I labeled line 22 above for clarity

Body:
I'm trying to click text on the screen in any program, sometimes is in text format, sometimes image, and appearance varies (so pyautogui wasn't helpful) and I'm using pytesseract.  And I've got it working except that I can't find the dictionary entry.  Manually searching the dictionary content, I find it--so pytesseract is doing it's job.  But my for loop doesn't.  What am I doing wrong?

import time
from PIL import ImageGrab  # for taking screenshots
import pytesseract  # for OCR
from pytesseract import Output  # for specifying the output type of image_to_boxes
import pyautogui  # for clicking on the screen

# Set the path to the Tesseract OCR engine (needed for Windows)
pytesseract.pytesseract.tesseract_cmd = (r"C:\...\Tesseract-OCR\tesseract")

while True:  # loop indefinitely
    # Take a screenshot and convert it to grayscale
    screenshot = ImageGrab.grab()
    screenshot_gray = screenshot.convert('L')

    # Extract the bounding boxes for the text in the screenshot
    data = pytesseract.image_to_boxes(screenshot_gray, output_type=Output.DICT)

    # Print the contents of the data dictionary
    print(data)

    # Iterate through the bounding boxes
22  for i in range(len(data['text'])):
        # Check if the text of the current bounding box is "Hello World"
        if data['text'][i] == "Hello World":
            # Calculate the x and y coordinates of the center of the bounding box
            x = (data['left'][i] + data['right'][i]) / 2
            y = (data['top'][i] + data['bottom'][i]) / 2
            # Click the location
            pyautogui.click(x, y)
            print("Clicked at", x, y)
            break  # stop looping through the bounding boxes

I receive the following error. But the "Hello World" was found by pytesseract and exists in the dictionary when I run it.

line 22, in <module>
    for i in range(len(data['text'])):
KeyError: 'text'

I labeled line 22 above for clarity


问:
Trying to create custom data type in Typescript
I am trying to make custom datatype in typescript names as email so we can use email

as datatype so we can validate. and i came up with this code.

```<code>type Email = string & { __email: void } & RegExp;
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

let a:Email = 'sdf@gmail.com';
</code>```

But I don't know what i do wrong this not working and showing me error.

```<code>Type 'string' is not assignable to type 'Email'.
  Type 'string' is not assignable to type '{ __email: void; }'.ts(2322)
</code>```

So how i can solve this?

Body:
I am trying to make custom datatype in typescript names as email so we can use email

as datatype so we can validate. and i came up with this code.

type Email = string & { __email: void } & RegExp;
const emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

let a:Email = 'sdf@gmail.com';

But I don't know what i do wrong this not working and showing me error.

Type 'string' is not assignable to type 'Email'.
  Type 'string' is not assignable to type '{ __email: void; }'.ts(2322)

So how i can solve this?


问:
dotCover on TeamCity stop working without any error
I have configured dotCover on my build on TeamCity. But sometimes it just stops working. There is no error. Just I don't have any new entries in the log. It ends with a timeout (timeout is configured for the whole build, not some dotcover timeout).
Part of the log of one of a failed build

! 14:55:14     Starting test execution, please wait...
14:55:14     Starting test execution, please wait...
14:55:14     Starting test execution, please wait...
14:55:14     A total of 1 test files matched the specified pattern.
14:55:14     Starting test execution, please wait...
14:55:14     A total of 1 test files matched the specified pattern.
14:55:14     Starting test execution, please wait...
14:55:14     A total of 1 test files matched the specified pattern.
14:55:15     A total of 1 test files matched the specified pattern.
14:55:15     A total of 1 test files matched the specified pattern.
15:01:37     The build MyApp::Build and Test #1.6.3-rc.3224 {buildId=634051} has been running for more than 8 minutes. Terminating...
15:01:37     Execution timeout

Previously it happens also in the middle of running tests. Today, after the dotcover update I tried to verify this problem. In 30 builds it happens once. But sometimes it is more frequent (I don't have enough old data to verify it).

I updated dotCover to 2022.2.4 Cross-Platform (the newest Cross-Platform version available on TeamCity). I'm using TeamCity 2021.2.1 (build 99602) (I'm a little scared about updating it).
I have the newest version of xUnit (2.4.2)
As a temporary solution, I configured a retry build on any error (I'm wondering if there is a possibility to retry only on timeout).


Title: What caused the invalid virtual address in linux kernel

Body:
Update: the virtual address is invalid address, not null pointer.

=======================================================

Invalid virtual address problem happened in my project, but I did not modify the code, some information as below:

[ 1150.456387] Unable to handle kernel paging request at virtual address 0000000000010000
[ 1150.456393] Mem abort info:
[ 1150.456395]   ESR = 0x96000005
[ 1150.456398]   EC = 0x25: DABT (current EL), IL = 32 bits
[ 1150.456400]   SET = 0, FnV = 0
[ 1150.456402]   EA = 0, S1PTW = 0
[ 1150.456404]   FSC = 0x05: level 1 translation fault
[ 1150.456407] Data abort info:
[ 1150.456409]   ISV = 0, ISS = 0x00000005
[ 1150.456411]   CM = 0, WnR = 0
[ 1150.456413] user pgtable: 4k pages, 39-bit VAs, pgdp=00000008e7572000
[ 1150.456415] [0000000000010000] pgd=0000000000000000, p4d=0000000000000000, pud=0000000000000000
[ 1150.456676] Internal error: Oops: 96000005 [#1] PREEMPT SMP
[ 1150.456802] Skip md ftrace buffer dump for: 0xa00f50

[ 1150.457154] pc : percpu_ref_get_many+0x2c/0x104
[ 1150.457164] lr : percpu_ref_get_many+0x2c/0x104
[ 1150.457167] sp : ffffffc02e513a20
[ 1150.457168] x29: ffffffc02e513a20 x28: ffffffef9324a000 x27: fffffffe00000008
[ 1150.457171] x26: fffffffe00000000 x25: 0000008000000000 x24: ffffff88661d3800
[ 1150.457175] x23: 0000000000000000 x22: ffffff8970f94408 x21: 0000000000000001
[ 1150.457178] x20: 0000000000010000 x19: 0000000000000001 x18: ffffffc01ce1b078
[ 1150.457181] x17: 430e0000071d4992 x16: 0001400000000000 x15: 000000008e83ddb6
[ 1150.457184] x14: 00000000ab032363 x13: 00000000d860b6cd x12: ffffff88661d4230
[ 1150.457187] x11: ffffffef93f46de8 x10: 0000000000000018 x9 : 0000000000000080
[ 1150.457190] x8 : 00000000000000c0 x7 : 0000000000000000 x6 : ffffffef910a04c0
[ 1150.457192] x5 : 0000000000000000 x4 : 0000000000000000 x3 : 0000000000000002
[ 1150.457195] x2 : 0000000000000000 x1 : ffffffef92f6e370 x0 : 0000000000000005
[ 1150.457198] Call trace:
[ 1150.457199]  percpu_ref_get_many+0x2c/0x104
[ 1150.457202]  refill_obj_stock.llvm.3785610425212570905+0xa8/0x24c
[ 1150.457208]  memcg_slab_free_hook+0x138/0x1a8
[ 1150.457212]  kmem_cache_free+0x14c/0x378
[ 1150.457214]  unlink_anon_vmas+0x60/0x1e0
[ 1150.457217]  free_pgtables+0x54/0x190
[ 1150.457219]  unmap_region+0xfc/0x148
[ 1150.457223]  __do_munmap+0x588/0x79c
[ 1150.457225]  __vm_munmap.llvm.11919687734878218350+0x88/0x174
[ 1150.457228]  __arm64_sys_munmap+0x44/0x5c
[ 1150.457231]  invoke_syscall+0x60/0x150
[ 1150.457235]  el0_svc_common.llvm.8274709215075016746+0xc8/0x114
[ 1150.457237]  do_el0_svc+0x28/0xa0
[ 1150.457239]  el0_svc+0x28/0x90
[ 1150.457243]  el0t_64_sync_handler+0x88/0xec
[ 1150.457246]  el0t_64_sync+0x1b4/0x1b8
[ 1150.457250] Code: 9402597f b0014e20 91196000 97fb46b8 (f8bfc289)

I parsed the information with the tool crash. The invalid address problem happened on the line percpu_ptr = READ_ONCE(ref->percpu_count_ptr); as below:

/*
 * Internal helper.  Don't use outside percpu-refcount proper.  The
 * function doesn't return the pointer and let the caller test it for NULL
 * because doing so forces the compiler to generate two conditional
 * branches as it can't assume that @ref->percpu_count is not NULL.
 */
static inline bool __ref_is_percpu(struct percpu_ref *ref,
                      unsigned long __percpu **percpu_countp)
{
    unsigned long percpu_ptr;

    /*
     * The value of @ref->percpu_count_ptr is tested for
     * !__PERCPU_REF_ATOMIC, which may be set asynchronously, and then
     * used as a pointer.  If the compiler generates a separate fetch
     * when using it as a pointer, __PERCPU_REF_ATOMIC may be set in
     * between contaminating the pointer value, meaning that
     * READ_ONCE() is required when fetching it.
     *
     * The dependency ordering from the READ_ONCE() pairs
     * with smp_store_release() in __percpu_ref_switch_to_percpu().
     */
    percpu_ptr = READ_ONCE(ref->percpu_count_ptr);

    /*
     * Theoretically, the following could test just ATOMIC; however,
     * then we'd have to mask off DEAD separately as DEAD may be
     * visible without ATOMIC if we race with percpu_ref_kill().  DEAD
     * implies ATOMIC anyway.  Test them together.
     */
    if (unlikely(percpu_ptr & __PERCPU_REF_ATOMIC_DEAD))
        return false;

    *percpu_countp = (unsigned long __percpu *)percpu_ptr;
    return true;
}

Another case happend on line if (unlikely(percpu_ptr & __PERCPU_REF_ATOMIC_DEAD)).

pointer variable ref comes from an address &objcg->refcnt as blow:

static inline void obj_cgroup_get(struct obj_cgroup *objcg)
{
    percpu_ref_get(&objcg->refcnt);
}

So it cann't be invalid. Why did invalid address problem happened?


问:
Two Independent Axis Barplot in R
I'm trying to create a barplot that was two independent Y axis, as a way to lookup the count of contratcs and the amount value of the count on PowerBi.

x axis - Year/Month timeline
y axis - Amount of Contracts Values
y2 axis - Count of Contracts

The point is that the graph must be done as barplot and I have to show it on PowerBi. But PowerBi don't offer a bar/bar plot type in their visuals, just bar/line thats it's not cool to use for what I need.

I found a way to do the graph using a private visual from xViz but I'm also trying to on R Studio to put inside the PowerBi later.

In the end the graph should be like that:

I tryed to use ggplot2 with sec.axis() but in that way the second axis works as a transformation of the first as:

```<code>data_long <- melt(data)
plot <- ggplot(data_long,aes(Group.1,value,fill = variable)) +
geom_col(,position = "dodge")+
scale_y_continuous(sec.axis = sec_axis(~./100000, name="Contracts"))
</code>```

the problem is that the number of contracts are very small relation of the amount value of then, what makes the graph on R been shown like that:

Can someone help me with that issue?

Title: Two Independent Axis Barplot in R

Body:
I'm trying to create a barplot that was two independent Y axis, as a way to lookup the count of contratcs and the amount value of the count on PowerBi.

x axis - Year/Month timeline
y axis - Amount of Contracts Values
y2 axis - Count of Contracts

The point is that the graph must be done as barplot and I have to show it on PowerBi. But PowerBi don't offer a bar/bar plot type in their visuals, just bar/line thats it's not cool to use for what I need.

I found a way to do the graph using a private visual from xViz but I'm also trying to on R Studio to put inside the PowerBi later.

In the end the graph should be like that:

I tryed to use ggplot2 with sec.axis() but in that way the second axis works as a transformation of the first as:

data_long <- melt(data)
plot <- ggplot(data_long,aes(Group.1,value,fill = variable)) +
geom_col(,position = "dodge")+
scale_y_continuous(sec.axis = sec_axis(~./100000, name="Contracts"))

the problem is that the number of contracts are very small relation of the amount value of then, what makes the graph on R been shown like that:

Can someone help me with that issue?


问:
EMR multiple primary nodes cluster hive/thrift transport exception
We have an issue with migrating the spark job from single master to multi master EMR cluster.
Multiple jobs which are using hive were successfully migrated to the new cluster, but only one keeps failing despite it works fine in the single master node cluster.

ERROR Client: Application diagnostics message: User class threw exception: org.apache.spark.sql.AnalysisException: org.apache.hadoop.hive.ql.metadata.HiveException: org.apache.thrift.transport.TTransportException;
at org.apache.spark.sql.hive.HiveExternalCatalog.withClient(HiveExternalCatalog.scala:127)
at org.apache.spark.sql.hive.HiveExternalCatalog.doListPartitions(HiveExternalCatalog.scala:1226)
at org.apache.spark.sql.hive.HiveExternalCatalog.listPartitionLocations(HiveExternalCatalog.scala:1211)
at org.apache.spark.sql.catalyst.catalog.ExternalCatalogWithListener.listPartitionLocations(ExternalCatalogWithListener.scala:246)
at org.apache.spark.sql.catalyst.catalog.SessionCatalog.listPartitionLocationsOptimized(SessionCatalog.scala:960)
at org.apache.spark.sql.catalyst.catalog.SessionCatalog.listPartitionLocations(SessionCatalog.scala:941)
at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:102)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.executeCollect(commands.scala:115)
at org.apache.spark.sql.Dataset$$anonfun$6.apply(Dataset.scala:196)
at org.apache.spark.sql.Dataset$$anonfun$6.apply(Dataset.scala:196)
at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3390)
at org.apache.spark.sql.execution.SQLExecution$.org$apache$spark$sql$execution$SQLExecution$$executeQuery$1(SQLExecution.scala:83)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1$$anonfun$apply$1.apply(SQLExecution.scala:94)
at org.apache.spark.sql.execution.QueryExecutionMetrics$.withMetrics(QueryExecutionMetrics.scala:141)
at org.apache.spark.sql.execution.SQLExecution$.org$apache$spark$sql$execution$SQLExecution$$withMetrics(SQLExecution.scala:178)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:93)
at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:200)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:92)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$withAction(Dataset.scala:3389)
at org.apache.spark.sql.Dataset.(Dataset.scala:196)
at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:81)
at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:650)

The job is failing while we are doing insert into external table with partitions.

"""insert into table {tableName} partition ({part1}, {part2}) select {columns} from {view}"""

```<code>

- We've checked hive configurations between old and new clusters -  no significant differences.
- We are able to connect to hive and do any command from the terminal on that cluster.
- All the jobs are using the same metastore.
- We tried to increase metastore timeout - no luck.
- We tried to run this job from another master node - same result.

Any suggestions?
</code>```

Body:
We have an issue with migrating the spark job from single master to multi master EMR cluster.
Multiple jobs which are using hive were successfully migrated to the new cluster, but only one keeps failing despite it works fine in the single master node cluster.

ERROR Client: Application diagnostics message: User class threw exception: org.apache.spark.sql.AnalysisException: org.apache.hadoop.hive.ql.metadata.HiveException: org.apache.thrift.transport.TTransportException;
at org.apache.spark.sql.hive.HiveExternalCatalog.withClient(HiveExternalCatalog.scala:127)
at org.apache.spark.sql.hive.HiveExternalCatalog.doListPartitions(HiveExternalCatalog.scala:1226)
at org.apache.spark.sql.hive.HiveExternalCatalog.listPartitionLocations(HiveExternalCatalog.scala:1211)
at org.apache.spark.sql.catalyst.catalog.ExternalCatalogWithListener.listPartitionLocations(ExternalCatalogWithListener.scala:246)
at org.apache.spark.sql.catalyst.catalog.SessionCatalog.listPartitionLocationsOptimized(SessionCatalog.scala:960)
at org.apache.spark.sql.catalyst.catalog.SessionCatalog.listPartitionLocations(SessionCatalog.scala:941)
at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:102)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
at org.apache.spark.sql.execution.command.DataWritingCommandExec.executeCollect(commands.scala:115)
at org.apache.spark.sql.Dataset$$anonfun$6.apply(Dataset.scala:196)
at org.apache.spark.sql.Dataset$$anonfun$6.apply(Dataset.scala:196)
at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3390)
at org.apache.spark.sql.execution.SQLExecution$.org$apache$spark$sql$execution$SQLExecution$$executeQuery$1(SQLExecution.scala:83)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1$$anonfun$apply$1.apply(SQLExecution.scala:94)
at org.apache.spark.sql.execution.QueryExecutionMetrics$.withMetrics(QueryExecutionMetrics.scala:141)
at org.apache.spark.sql.execution.SQLExecution$.org$apache$spark$sql$execution$SQLExecution$$withMetrics(SQLExecution.scala:178)
at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:93)
at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:200)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:92)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$withAction(Dataset.scala:3389)
at org.apache.spark.sql.Dataset.(Dataset.scala:196)
at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:81)
at org.apache.spark.sql.SparkSession.sql(SparkSession.scala:650)

The job is failing while we are doing insert into external table with partitions.

"""insert into table {tableName} partition ({part1}, {part2}) select {columns} from {view}"""

- We've checked hive configurations between old and new clusters -  no significant differences.
- We are able to connect to hive and do any command from the terminal on that cluster.
- All the jobs are using the same metastore.
- We tried to increase metastore timeout - no luck.
- We tried to run this job from another master node - same result.

Any suggestions?


问:
App working when test on device but crash when downloaded from App Store
i made app with swift and Xcode using Wordpress Website to fetch data. i am using rest api to fetch data from Website, my app is working great on test device but when i upload it on app store and then it crashes, i found this error in my Xcode - organizer

this is how i implement searchbar

```<code>@IBOutlet weak var searchBar: UISearchBar!
</code>```

in viewdid

```<code>  searchBar.delegate = self

extension StatusViewController: UISearchBarDelegate {

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    self.searchBar.showsCancelButton = true
    self.collectionView.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    self.searchBar.text = ""
    self.searchBar.showsCancelButton = false
    self.searchBar.endEditing(true)
    self.dismiss(animated: true, completion: nil)
    SVProgressHUD.show()
    sortBy = ""
    page = 1
    self.fetchPostData { (posts) in
        self.newsData = posts }
    self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    print("searchText \(searchText)")

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    print("searchTextclicked \(String(describing: searchBar.text))")

    sortBy = "&search=" + searchBar.text!
    page = 1
     self.fetchPostData { (posts) in
         self.newsData = posts }
    self.collectionView.isUserInteractionEnabled = false
    SVProgressHUD.show()
     self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
     refreshControl.endRefreshing()
    self.searchBar.endEditing(true)

}
</code>```

}

please can you tell me the issue ?

Body:
i made app with swift and Xcode using Wordpress Website to fetch data. i am using rest api to fetch data from Website, my app is working great on test device but when i upload it on app store and then it crashes, i found this error in my Xcode - organizer

this is how i implement searchbar

@IBOutlet weak var searchBar: UISearchBar!

in viewdid

  searchBar.delegate = self

extension StatusViewController: UISearchBarDelegate {

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    self.searchBar.showsCancelButton = true
    self.collectionView.reloadData()
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    self.searchBar.text = ""
    self.searchBar.showsCancelButton = false
    self.searchBar.endEditing(true)
    self.dismiss(animated: true, completion: nil)
    SVProgressHUD.show()
    sortBy = ""
    page = 1
    self.fetchPostData { (posts) in
        self.newsData = posts }
    self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    print("searchText \(searchText)")

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    print("searchTextclicked \(String(describing: searchBar.text))")

    sortBy = "&search=" + searchBar.text!
    page = 1
     self.fetchPostData { (posts) in
         self.newsData = posts }
    self.collectionView.isUserInteractionEnabled = false
    SVProgressHUD.show()
     self.collectionView.setContentOffset(CGPoint(x:0,y:0), animated: true)
     refreshControl.endRefreshing()
    self.searchBar.endEditing(true)

}

}

please can you tell me the issue ?


问:
TypeError: E is not a function Vite.js React.js
I'm facing the following problem. After building the project and starting production server I got TypeError: E is not a functionenter image description here

The problem is on desktop version only, so I thought it could be something with useMediaQuery hook from react-responsive and removed it's usage from project. The error is not thrown now, but I still need to use useMediaQuery. What can be the problem with this hook and how can I solve it?

Here's an example of useMediaQuery usage

```<code>import React from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import { useMediaQuery } from 'react-responsive'

export const TrustBlock = (): JSX.Element => {
    const isMobile = useMediaQuery({ query: '(max-width: 650px)' })
    const isTablet = useMediaQuery({ query: '(max-width: 1200px)' })
    return (
        <div className='container'>
                <Swiper spaceBetween={20} slidesPerView={isMobile ? 1 : isTablet ? 3 : 4} navigation loop>

                </Swiper>
        </div>
    )
}
</code>```

Body:
I'm facing the following problem. After building the project and starting production server I got TypeError: E is not a functionenter image description here

The problem is on desktop version only, so I thought it could be something with useMediaQuery hook from react-responsive and removed it's usage from project. The error is not thrown now, but I still need to use useMediaQuery. What can be the problem with this hook and how can I solve it?

Here's an example of useMediaQuery usage

import React from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import { useMediaQuery } from 'react-responsive'

export const TrustBlock = (): JSX.Element => {
    const isMobile = useMediaQuery({ query: '(max-width: 650px)' })
    const isTablet = useMediaQuery({ query: '(max-width: 1200px)' })
    return (

                <Swiper spaceBetween={20} slidesPerView={isMobile ? 1 : isTablet ? 3 : 4} navigation loop>

                </Swiper>

    )
}


问:
How to use package specific typescript paths in a typescript monorepo?
Lets say the following folder structure is present. The frontend directly imports a type from the backend (via workspace:) to use tRPC. The backend does not transpile into javascript, rather is directly imported in the frontend. This is done because you want to have the routes type updated live in both the frontend and the backend.

```<code>ui
    frontend
        src
            utils
            pages
        tsconfig.json
        package.json
        vite.config.js

services
    backend
        src
            utils
            routes
        package.json
        tsconfig.json
</code>```

To keep paths clean, typescript paths are used in both the frontend and in the backend.

Ex. in the frontend, the following property is used in the backend compilerOptions:

```<code>    "paths": {
      "@utils/*": ["src/utils/*"],
      "@routes/*": ["src/routes/*"]
    }
</code>```

Everything works just using vite without running tsc. But if type checking is wanted (running tsc && vite in the frontend directory), it just outputs ../../services/backend/src/x Cannot find module '@utils/x' or its corresponding type declarations.

Supposedly this is because it uses the tsconfig in the folder where tsc is ran from, which in this case is frontend. What is needed is to make it use the tsconfig.json present in the backend for typechecking there?

Body:
Lets say the following folder structure is present. The frontend directly imports a type from the backend (via workspace:) to use tRPC. The backend does not transpile into javascript, rather is directly imported in the frontend. This is done because you want to have the routes type updated live in both the frontend and the backend.

ui
    frontend
        src
            utils
            pages
        tsconfig.json
        package.json
        vite.config.js

services
    backend
        src
            utils
            routes
        package.json
        tsconfig.json

To keep paths clean, typescript paths are used in both the frontend and in the backend.

Ex. in the frontend, the following property is used in the backend compilerOptions:

    "paths": {
      "@utils/*": ["src/utils/*"],
      "@routes/*": ["src/routes/*"]
    }

Everything works just using vite without running tsc. But if type checking is wanted (running tsc && vite in the frontend directory), it just outputs ../../services/backend/src/x Cannot find module '@utils/x' or its corresponding type declarations.

Supposedly this is because it uses the tsconfig in the folder where tsc is ran from, which in this case is frontend. What is needed is to make it use the tsconfig.json present in the backend for typechecking there?


问:
Ag-Grid rowSpan and autoHeight
We've encouterred a problem where we need to use rowSpan and autoHeight (or any kind of dynamic height) for a cell in tandem.

According to the docs, autoHeigth is not supported when using rowSpan: https://www.ag-grid.com/archive/27.1.0/react-data-grid/row-spanning/#constraints-with-row-spanning

Our scenario:
We have a grid, where the first column is a "grouping" column, and the next columns are for "children" properties. E.g.: United States has 4 athletes, so the first column would span 4 rows, and the others 1. The issue is, we need to show more information in the first column, and it works ok if there are 2 or more "children" - the information fits in the cell, but when there is only 1 "child", the 1st column only spans 1 row and the information's does not fit. Some kind of mechanism is needed to make the row higher when, let's say rowSpan is less than 2.

Here's the a simple plunker to represent the scenario: https://plnkr.co/edit/lSO9tOKPfsBmrzPC

As seen in the screenshot, the cell contents do not fit, on row 5 (2 based on the 1 column rowSpan)

Since autoHeight is not supported when using rowSpan, has anyone encountered a similar scenario and has a suggestion for a workaround for dynamic height?

Title: Ag-Grid rowSpan and autoHeight


问:
How to append to list in python module written in rust?
I am writing a python model for heavy calculations in rust using the pyo3 bindings. However, for a rust struct with a variable containing an empty list I cannot append to that variable in python.

Does anybody know how to do this? See below for a MWE ( that I cannot get to work ):

I have a rust file called lib.rs:

// lib.rs

use pyo3::prelude::*;
use std::vec::Vec;

#[pyclass(subclass)]
pub struct TestClass {
    #[pyo3(get)]
    pub id: i32,
    #[pyo3(get, set)]
    pub test_list: Vec<f32>
}

#[pymethods]
impl TestClass {
    #[new]
    pub fn new(id: i32) -> TestClass {
        TestClass{
            id,
            test_list: Vec::new()
        }
    }
}

/// A Python module implemented in Rust.
#[pymodule]
fn test_rust(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<TestClass>()?;
    Ok(())
}
```
<p>This library is build using the <code>maturin</code> package. When I initiate the <code>TestClass</code> in python that works as expected. However, when I want to append to the class attribute <code>test_list</code> this is not happening. <code>test_list</code> still is an empty list. See for an example below:</p>
<pre class="lang-python prettyprint-override"><code>from test_rust import TestClass

foo = TestClass(1)

print(foo.test_list) # output: []
foo.test_list.append(2.3)
print(foo.test_list) # output: [] - expected: [2.3]
</code>```

The pyo3 documentation stated that the types Vec<T> and list[T] are accepted. However, this does not work.

Any help would be very much appreciated.

Body:
I am writing a python model for heavy calculations in rust using the pyo3 bindings. However, for a rust struct with a variable containing an empty list I cannot append to that variable in python.

Does anybody know how to do this? See below for a MWE ( that I cannot get to work ):

I have a rust file called lib.rs:

// lib.rs

use pyo3::prelude::*;
use std::vec::Vec;

#[pyclass(subclass)]
pub struct TestClass {
    #[pyo3(get)]
    pub id: i32,
    #[pyo3(get, set)]
    pub test_list: Vec<f32>
}

#[pymethods]
impl TestClass {
    #[new]
    pub fn new(id: i32) -> TestClass {
        TestClass{
            id,
            test_list: Vec::new()
        }
    }
}

/// A Python module implemented in Rust.
#[pymodule]
fn test_rust(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<TestClass>()?;
    Ok(())
}

This library is build using the maturin package. When I initiate the TestClass in python that works as expected. However, when I want to append to the class attribute test_list this is not happening. test_list still is an empty list. See for an example below:

from test_rust import TestClass

foo = TestClass(1)

print(foo.test_list) # output: []
foo.test_list.append(2.3)
print(foo.test_list) # output: [] - expected: [2.3]

The pyo3 documentation stated that the types Vec<T> and list[T] are accepted. However, this does not work.

Any help would be very much appreciated.


问:
TimeoutError Installing Pyqt6 Package
As I mentioned above, this is the error that is occurring on Cmd panel:

```<code>"ERROR: Exception:
Traceback (most recent call last):
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 437, in _error_catcher
    yield
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 560, in read
    data = self._fp_read(amt) if not fp_closed else b""
           ^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 526, in _fp_read
    return self._fp.read(amt) if amt is not None else self._fp.read()
           ^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 90, in read
    data = self.__fp.read(amt)
           ^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\http\client.py", line 465, in read
    s = self.fp.read(amt)
        ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\socket.py", line 706, in readinto
    return self._sock.recv_into(b)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\ssl.py", line 1278, in recv_into
    return self.read(nbytes, buffer)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\ssl.py", line 1134, in read
    return self._sslobj.read(len, buffer)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\python interpreter\Lib\site-packages\pip\_internal\cli\base_command.py", line 160, in exc_logging_wrapper
    status = run_func(*args)
             ^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\cli\req_command.py", line 247, in wrapper
    return func(self, options, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\commands\install.py", line 400, in run
    requirement_set = resolver.resolve(
                      ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 92, in resolve
    result = self._result = resolver.resolve(
                            ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 481, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 348, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria
    if not criterion.candidates:
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 151, in __bool__
    return bool(self._sequence)
           ^^^^^^^^^^^^^^^^^^^"
</code>```

I wrote this command to download the package :

```<code>C:\Windows\system32>pip install PyQt6
Collecting PyQt6
  Downloading PyQt6-6.4.0-cp37-abi3-win_amd64.whl (6.4 MB)
     ------- -------------------------------- 1.2/6.4 MB 3.6 kB/s eta 0:24:04
</code>```

If there is no way to solve this problem, how can I download this package without using pip or command line?

Title: TimeoutError Installing Pyqt6 Package

Body:
As I mentioned above, this is the error that is occurring on Cmd panel:

"ERROR: Exception:
Traceback (most recent call last):
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 437, in _error_catcher
    yield
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 560, in read
    data = self._fp_read(amt) if not fp_closed else b""
           ^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\urllib3\response.py", line 526, in _fp_read
    return self._fp.read(amt) if amt is not None else self._fp.read()
           ^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 90, in read
    data = self.__fp.read(amt)
           ^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\http\client.py", line 465, in read
    s = self.fp.read(amt)
        ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\socket.py", line 706, in readinto
    return self._sock.recv_into(b)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\ssl.py", line 1278, in recv_into
    return self.read(nbytes, buffer)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\ssl.py", line 1134, in read
    return self._sslobj.read(len, buffer)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\python interpreter\Lib\site-packages\pip\_internal\cli\base_command.py", line 160, in exc_logging_wrapper
    status = run_func(*args)
             ^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\cli\req_command.py", line 247, in wrapper
    return func(self, options, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\commands\install.py", line 400, in run
    requirement_set = resolver.resolve(
                      ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 92, in resolve
    result = self._result = resolver.resolve(
                            ^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 481, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 348, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria
    if not criterion.candidates:
  File "D:\python interpreter\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 151, in __bool__
    return bool(self._sequence)
           ^^^^^^^^^^^^^^^^^^^"

I wrote this command to download the package :

C:\Windows\system32>pip install PyQt6
Collecting PyQt6
  Downloading PyQt6-6.4.0-cp37-abi3-win_amd64.whl (6.4 MB)
     ------- -------------------------------- 1.2/6.4 MB 3.6 kB/s eta 0:24:04

If there is no way to solve this problem, how can I download this package without using pip or command line?